code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
module Acquire.Net (PortNumber, runServer, runPlayer, runNewGame, listGames, module Acquire.Net.Types) where
import Acquire.Net.Game
import Acquire.Net.Player
import Acquire.Net.Server
import Acquire.Net.Types
|
abailly/hsgames
|
chinese/src/Chinese/Net.hs
|
apache-2.0
| 364 | 0 | 5 | 83 | 57 | 39 | 18 | 8 | 0 |
{-# LANGUAGE OverloadedStrings,
ScopedTypeVariables,
GADTs,
MultiWayIf #-}
module Main (main) where
import Control.Monad (foldM, forM, void)
import Data.Map (Map)
import qualified Data.Map as Map
import qualified Data.IntMap as IntMap
import qualified Data.Set as Set
import Control.Concurrent (forkIO)
import Control.Concurrent.STM
import qualified Data.ByteString.Char8 as BS8
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.Lazy.Char8 as LBS8
import qualified Data.ByteString.Lazy.Builder as Builder
import System.Environment (getArgs)
import System.Random (randomRIO)
import Network.Socket (SockAddr(SockAddrInet), inet_addr)
import Control.Lens hiding (Index)
import qualified Data.Binary as B
import Data.Conduit
import qualified Data.Conduit.List as CL
import qualified Data.Conduit.Network.UDP as CNU
import qualified Data.Streaming.Network as SN
import qualified Data.Streaming.Network.Internal as SNI
import Network.Kontiki.Raft
( Command(..), Config(..), Entry(..), Event(..),
Message, NodeId, SomeState, Index, index0, succIndex, unIndex)
import qualified Network.Kontiki.Raft as Raft
import Data.Kontiki.MemLog (Log, runMemLog)
import qualified Data.Kontiki.MemLog as MemLog
import Data.STM.RollingQueue (RollingQueue)
import qualified Data.STM.RollingQueue as RollingQueue
import qualified Data.Conduit.RollingQueue as CRQ
import Control.STM.Timer (Timer)
import qualified Control.STM.Timer as Timer
type Value = (NodeId, Int)
nodes :: Map NodeId ((String, Int))
nodes = Map.fromList [ ("node0", ("127.0.0.1", 4000))
, ("node1", ("127.0.0.1", 4001))
, ("node2", ("127.0.0.1", 4002))
]
config :: Config
config = Config { _configNodeId = "unknown"
, _configNodes = Set.fromList $ Map.keys nodes
, _configElectionTimeout = 10000 * 1000
, _configHeartbeatTimeout = 5000 * 1000
}
data PlumbingState = PS { psElectionTimer :: Timer
, psHeartbeatTimer :: Timer
, psMessages :: RollingQueue (Event Value)
, psChannels :: Map NodeId (RollingQueue (Message Value))
, psLog :: Log Value
, psCommitIndex :: Index
}
queueSize :: Int
queueSize = 1024
newPlumbingState :: Map NodeId (RollingQueue (Message Value)) -> IO PlumbingState
newPlumbingState channels = do
et <- Timer.newIO
ht <- Timer.newIO
q <- RollingQueue.newIO queueSize
return $ PS { psElectionTimer = et
, psHeartbeatTimer = ht
, psMessages = q
, psChannels = channels
, psLog = MemLog.empty
, psCommitIndex = index0
}
handleCommand :: PlumbingState -> Command Value -> IO PlumbingState
handleCommand s c = case c of
CBroadcast m -> do
putStrLn $ "CBroadcast: " ++ show m
atomically $ mapM_ (flip RollingQueue.write m) (Map.elems $ psChannels s)
return s
CSend n m -> do
putStrLn $ "CSend: " ++ show n ++ " -> " ++ show m
case Map.lookup n (psChannels s) of
Nothing -> putStrLn "Unknown node?!"
Just q -> atomically $ RollingQueue.write q m
return s
CResetElectionTimeout a b -> do
t <- randomRIO (a, b)
putStrLn $ "Reset election timeout: " ++ show t
Timer.reset (psElectionTimer s) t
return s
CResetHeartbeatTimeout a -> do
putStrLn $ "Reset heartbeat timeout: " ++ show a
Timer.reset (psHeartbeatTimer s) a
return s
CLog b -> do
let m = LBS8.unpack $ Builder.toLazyByteString b
putStrLn $ "Log: " ++ m
return s
CTruncateLog i -> do
putStrLn $ "Truncate: " ++ show i
let l = psLog s
i' = fromIntegral $ unIndex i
l' = IntMap.filterWithKey (\k _ -> k <= i') l
return $ s { psLog = l' }
CLogEntries es -> do
putStrLn $ "Log entries: " ++ show es
let l = psLog s
l' = foldr (\e -> MemLog.insert (fromIntegral $ unIndex $ eIndex e) e) l es
return $ s { psLog = l' }
CSetCommitIndex i' -> do
let i = psCommitIndex s
putStrLn $ "New commit index, to commit: " ++ entriesToCommit i i'
return $ s { psCommitIndex = i' }
entriesToCommit :: Index -> Index -> String
entriesToCommit prev new =
if | new < prev -> error "Committed entries could not be reverted"
| new == prev -> "nothing"
| new == next -> "entry " ++ show new
| otherwise -> "entries " ++ show next ++ " to " ++ show new
where
next = succIndex prev
handleCommands :: PlumbingState -> [Command Value] -> IO PlumbingState
handleCommands = foldM handleCommand
run :: Config -> SomeState -> PlumbingState -> IO ()
run config' s ps = do
putStrLn "Awaiting event"
event <- atomically $ do
(const EElectionTimeout `fmap` Timer.await (psElectionTimer ps))
`orElse` (const EHeartbeatTimeout `fmap` Timer.await (psHeartbeatTimer ps))
`orElse` (fst `fmap` RollingQueue.read (psMessages ps))
putStrLn $ "Got event: " ++ show (event :: Event Value)
putStrLn $ "Input state: " ++ show s
let (s', cs) = runMemLog (Raft.handle config' s event) (psLog ps)
putStrLn $ "Output state: " ++ show s'
ps' <- handleCommands ps cs
ps'' <- case s' of
Raft.WrapState (Raft.Leader ls) -> do
let l = psLog ps'
size = IntMap.size l
(_, m) = if size /= 0
then IntMap.findMax l
else (0, Entry { eTerm = Raft.term0
, eIndex = Raft.index0
, eValue = (config' ^. Raft.configNodeId, 0)
})
e = Entry { eTerm = ls ^. Raft.lCurrentTerm
, eIndex = Raft.succIndex (eIndex m)
, eValue = (config' ^. Raft.configNodeId, size)
}
l' = IntMap.insert (fromIntegral $ unIndex $ eIndex e) e l
return $ ps' { psLog = l' }
_ -> return ps'
putStrLn $ "Log: " ++ show (map (\(k, v) -> (k, eValue v)) $ IntMap.toAscList $ psLog ps'')
run config' s' ps''
makeChannel :: NodeId -> String -> Int -> IO (RollingQueue (Message Value))
makeChannel nn h p = do
(sock, _) <- SN.getSocketUDP h p
q <- RollingQueue.newIO queueSize
addr <- inet_addr h
let r = SockAddrInet (toEnum p) addr
void $ forkIO $ do
CRQ.sourceRollingQueue q $= CL.map (\m -> (nn, m))
=$= CL.map B.encode
=$= CL.map LBS.toStrict
=$= CL.map (\m -> CNU.Message { CNU.msgData = m
, CNU.msgSender = r
})
$$ CNU.sinkToSocket sock
return q
main :: IO ()
main = do
[self] <- map BS8.pack `fmap` getArgs
let config' = config { _configNodeId = self }
let s0 = Raft.initialState
(s, cs) = Raft.restore config' s0
others = Map.filterWithKey (\k _ -> k /= self) nodes
chans <- forM (Map.toList others) $ \(n, (h, p)) -> makeChannel self h p >>= \c -> return (n, c)
ps <- newPlumbingState (Map.fromList chans)
let (_, p) = (Map.!) nodes self
sock <- SN.bindPortUDP (toEnum p) SNI.HostIPv4
void $ forkIO $ do
CNU.sourceSocket sock 4096 $= CL.map (B.decode . LBS.fromStrict . CNU.msgData)
=$= CL.map (uncurry EMessage)
$$ CRQ.sinkRollingQueue (psMessages ps)
-- TODO Handle resubmit
ps' <- handleCommands ps cs
run config' s ps'
|
NicolasT/kontiki
|
bin/udp.hs
|
bsd-3-clause
| 8,074 | 0 | 22 | 2,719 | 2,490 | 1,316 | 1,174 | 175 | 9 |
import Text.JSON
import Network.RPC.JSON
import System.Exit
main = do
case (decode test1 :: Result JSRequest) of
Ok _ -> exitWith ExitSuccess
test1 =
"{\"method\":\"feed.add\",\"params\":{\"uri\":\"http://rss.slashdot.org/Slashdot/slashdot\"},\"version\":\"1.1\" }"
|
sof/json
|
tests/Unit.hs
|
bsd-3-clause
| 288 | 0 | 10 | 47 | 58 | 30 | 28 | 8 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Network.Wai.Handler.WebSockets
( websocketsOr
, websocketsApp
, isWebSocketsReq
, getRequestHead
, runWebSockets
) where
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as BC
import qualified Data.ByteString.Lazy as BL
import qualified Data.CaseInsensitive as CI
import Network.HTTP.Types (status500)
import qualified Network.Wai as Wai
import qualified Network.WebSockets as WS
import qualified Network.WebSockets.Connection as WS
import qualified Network.WebSockets.Stream as WS
--------------------------------------------------------------------------------
-- | Returns whether or not the given 'Wai.Request' is a WebSocket request.
isWebSocketsReq :: Wai.Request -> Bool
isWebSocketsReq req =
fmap CI.mk (lookup "upgrade" $ Wai.requestHeaders req) == Just "websocket"
--------------------------------------------------------------------------------
-- | Upgrade a @websockets@ 'WS.ServerApp' to a @wai@ 'Wai.Application'. Uses
-- the given backup 'Wai.Application' to handle 'Wai.Request's that are not
-- WebSocket requests.
--
-- @
-- websocketsOr opts ws_app backup_app = \\req send_response ->
-- __case__ 'websocketsApp' opts ws_app req __of__
-- 'Nothing' -> backup_app req send_response
-- 'Just' res -> send_response res
-- @
--
-- For example, below is an 'Wai.Application' that sends @"Hello, client!"@ to
-- each connected client.
--
-- @
-- app :: 'Wai.Application'
-- app = 'websocketsOr' 'WS.defaultConnectionOptions' wsApp backupApp
-- __where__
-- wsApp :: 'WS.ServerApp'
-- wsApp pending_conn = do
-- conn <- 'WS.acceptRequest' pending_conn
-- 'WS.sendTextData' conn ("Hello, client!" :: 'Data.Text.Text')
--
-- backupApp :: 'Wai.Application'
-- backupApp = 'Wai.respondLBS' 'Network.HTTP.Types.status400' [] "Not a WebSocket request"
-- @
websocketsOr :: WS.ConnectionOptions
-> WS.ServerApp
-> Wai.Application
-> Wai.Application
websocketsOr opts app backup req sendResponse =
case websocketsApp opts app req of
Nothing -> backup req sendResponse
Just res -> sendResponse res
--------------------------------------------------------------------------------
-- | Handle a single @wai@ 'Wai.Request' with the given @websockets@
-- 'WS.ServerApp'. Returns 'Nothing' if the 'Wai.Request' is not a WebSocket
-- request, 'Just' otherwise.
--
-- Usually, 'websocketsOr' is more convenient.
websocketsApp :: WS.ConnectionOptions
-> WS.ServerApp
-> Wai.Request
-> Maybe Wai.Response
websocketsApp opts app req
| isWebSocketsReq req =
Just $ flip Wai.responseRaw backup $ \src sink ->
runWebSockets opts req' app src sink
| otherwise = Nothing
where
req' = getRequestHead req
backup = Wai.responseLBS status500 [("Content-Type", "text/plain")]
"The web application attempted to send a WebSockets response, but WebSockets are not supported by your WAI handler."
--------------------------------------------------------------------------------
getRequestHead :: Wai.Request -> WS.RequestHead
getRequestHead req = WS.RequestHead
(Wai.rawPathInfo req `BC.append` Wai.rawQueryString req)
(Wai.requestHeaders req)
(Wai.isSecure req)
--------------------------------------------------------------------------------
-- | Internal function to run the WebSocket io-streams using the conduit library.
runWebSockets :: WS.ConnectionOptions
-> WS.RequestHead
-> (WS.PendingConnection -> IO a)
-> IO ByteString
-> (ByteString -> IO ())
-> IO a
runWebSockets opts req app src sink = do
stream <- WS.makeStream
(do
bs <- src
return $ if BC.null bs then Nothing else Just bs)
(\mbBl -> case mbBl of
Nothing -> return ()
Just bl -> mapM_ sink (BL.toChunks bl))
let pc = WS.PendingConnection
{ WS.pendingOptions = opts
, WS.pendingRequest = req
, WS.pendingOnAccept = \_ -> return ()
, WS.pendingStream = stream
}
app pc
|
rgrinberg/wai
|
wai-websockets/Network/Wai/Handler/WebSockets.hs
|
mit
| 4,435 | 0 | 17 | 1,123 | 687 | 383 | 304 | 64 | 3 |
module Paper.Haskell2.All(haskell2) where
import System.Process.Extra
import System.FilePath
import Paper.Haskell2.Stage1
import Paper.Haskell2.Stage2
import Paper.Haskell2.Stage3
haskell2 :: FilePath -> [FilePath] -> IO ()
haskell2 obj files = mapM_ f files
where
f file = do
putStrLn $ "Checking " ++ takeBaseName file
src <- readFile file
let dest = obj </> takeFileName file
res = stage3 dest $ stage2 $ stage1 file src
mapM_ (uncurry writeFile) res
system_ $ "runghc -i" ++ obj ++ " " ++ fst (head res)
|
saep/neil
|
src/Paper/Haskell2/All.hs
|
bsd-3-clause
| 601 | 0 | 14 | 171 | 190 | 96 | 94 | 15 | 1 |
--
-- Copyright (c) 2011 Citrix Systems, Inc.
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--
{-# LANGUAGE GADTs #-}
module UpdateMgr.DbReqHandler where
import UpdateMgr.DbReq
import Rpc.Core
import Db (dbMaybeRead,dbWrite,dbRm,dbList)
handleDbReq :: (MonadRpc e m) => DbReq r -> m r
handleDbReq (DbMaybeRead p) = dbMaybeRead p
handleDbReq (DbWrite p v) = dbWrite p v
handleDbReq (DbRm p) = dbRm p
handleDbReq (DbList p) = dbList p
|
crogers1/manager
|
updatemgr/UpdateMgr/DbReqHandler.hs
|
gpl-2.0
| 1,110 | 0 | 7 | 197 | 149 | 86 | 63 | 10 | 1 |
module E2 where
--Any type/data constructor name declared in this module can be renamed.
--Any type variable can be renamed.
--Rename type Constructor 'BTree' to 'MyBTree'
data BTree a = Empty | T a (BTree a) (BTree a)
deriving Show
buildtree :: Ord a => [a] -> BTree a
buildtree [] = Empty
buildtree (x:xs) = snd (insert x (buildtree xs))
insert :: Ord a => a -> BTree a -> (Int, BTree a)
insert val (T val1 Empty Empty) = (42, T val1 Empty Empty)
newPat_1 = Empty
f :: String -> String
f newPat_2@((x : xs)) = newPat_2
main :: BTree Int
main = buildtree [3,1,2]
|
kmate/HaRe
|
old/testing/asPatterns/E2.hs
|
bsd-3-clause
| 589 | 0 | 9 | 133 | 228 | 123 | 105 | 13 | 1 |
{-# Language QuantifiedConstraints #-}
{-# Language StandaloneDeriving #-}
{-# Language DataKinds #-}
{-# Language TypeOperators #-}
{-# Language GADTs #-}
{-# Language KindSignatures #-}
{-# Language FlexibleInstances #-}
{-# Language UndecidableInstances #-}
{-# Language MultiParamTypeClasses #-}
{-# Language RankNTypes #-}
{-# Language ConstraintKinds #-}
module T14735 where
import Data.Kind
data D c where
D :: c => D c
newtype a :- b = S (a => D b)
class C1 a b
class C2 a b
instance C1 a b => C2 a b
class (forall xx. f xx) => Limit f
instance (forall xx. f xx) => Limit f
impl :: Limit (C1 a) :- Limit (C2 a)
impl = S D
|
sdiehl/ghc
|
testsuite/tests/typecheck/should_compile/T14735.hs
|
bsd-3-clause
| 642 | 0 | 8 | 126 | 173 | 94 | 79 | -1 | -1 |
{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}
{-# LANGUAGE KindSignatures #-}
module T7903 where
instance Eq (((->) a :: * -> *) b)
instance (Ord b) => Ord (((->) a) b)
|
urbanslug/ghc
|
testsuite/tests/typecheck/should_compile/T7903.hs
|
bsd-3-clause
| 177 | 2 | 10 | 30 | 67 | 37 | 30 | 5 | 0 |
module Safetails where
safetail :: Eq a => [a] -> [a]
safetail xs = if xs == [] then [] else tail xs
safetail' :: Eq a => [a] -> [a]
safetail' xs
| xs == [] = []
| otherwise = tail xs
|
kaveet/haskell-snippets
|
modules/lists/Safetails.hs
|
mit
| 191 | 0 | 9 | 51 | 109 | 56 | 53 | 7 | 2 |
module ParserAux where
import Text.Megaparsec
import Text.Megaparsec.String
import qualified Text.Megaparsec.Lexer as L
spacey :: Parser ()
spacey = L.space (spaceChar >> return ()) (L.skipLineComment "--") (L.skipBlockComment "{-" "-}")
lexeme = L.lexeme spacey
symbol = L.symbol spacey
many1 p = do
v <- p
vs <- many p
return $ v : vs
name = lexeme $ do
c <- letterChar
cs <- many (letterChar <|> digitChar)
return $ c : cs
num = lexeme (many1 digitChar)
paren = between (symbol "(") (symbol ")")
bracey = between (symbol "{") (symbol "}")
dot = symbol "."
commaSep x = sepBy1 x (symbol ",")
tries :: [Parser a] -> Parser a
tries = choice . map try
|
clarissalittler/pi-calculus
|
ParserAux.hs
|
mit
| 690 | 0 | 11 | 153 | 293 | 148 | 145 | 23 | 1 |
module ParserState2
( Parser
, ParserT
, ParserState (..)
, FuncTable
, initParserState
, nextLabel
, newFunc
, lookupFunc
) where
import qualified Data.Map as M
import Control.Monad.State
import Lexer (Token)
type FuncTable = M.Map [Char] [Char]
data ParserState = ParserState
{ parserFuncTable :: FuncTable
, parserFinalFuncTable :: FuncTable
, parserLabelCursor :: Int
}
type ParserT m a = StateT ParserState m a
type Parser a = ParserT IO a
initParserState finalFuncTable = ParserState
{ parserFuncTable = M.fromList [("input", "read"), ("output", "write")]
, parserFinalFuncTable = finalFuncTable
, parserLabelCursor = 0
}
nextLabel :: Monad m => ParserT m [Char]
nextLabel = do
oldState <- get
let
oldLabel = parserLabelCursor oldState
newLabel = oldLabel + 1
newState = oldState { parserLabelCursor = newLabel }
put newState
return $ "label_" ++ show newLabel
newFunc :: Monad m => [Char] -> ParserT m [Char]
newFunc name = do
oldState <- get
let
oldTable = parserFuncTable oldState
if M.member name oldTable
then
fail $ "function " ++ name ++ " redefined"
else do
newLabel <- nextLabel
oldState' <- get
let
newTable = M.insert name newLabel oldTable
newState = oldState' {parserFuncTable = newTable}
put newState
return newLabel
lookupFunc :: Monad m => [Char] -> ParserT m [Char]
lookupFunc name = do
state <- get
return $ case M.lookup name (parserFinalFuncTable state) of
Just label -> label
Nothing -> "UnknownFunc" ++ name
|
CindyLinz/Talk-HappyMonadFix-Easy-NPassCompiler
|
ParserState2.hs
|
mit
| 1,586 | 0 | 14 | 376 | 492 | 263 | 229 | 53 | 2 |
module ADT where
-- data Bool = True | False --
data RGB = RGB Int Int Int -- это констуктор значений. Первое слово RGB -> это имя констуктора
red = RGB 255 0 0
-- Optional!
-- data Maybee a = Just a | Nothing
data T -- Вполне себе валидный тип
-- Функция принимающая что угодно и возвращающая что угодно, но строго в рамках своей области определения
frst :: (a,b) -> a
frst (x, _) = x
fromMaybe :: Maybe a -> a -> a
fromMaybe (Just x) _ = x
fromMaybe Nothing y = y
f :: a -> Int
f a = 5
-- f :: a -> b -- Так нельзя, так как функции чистые. А b -> не определено
data List a = Nil | Cons a (List a)
data NonEmpty a = NonEmpty a (List a)
data Tree a = Leaf | Node a (Tree a) (Tree a)
data Tree' a = Leaf' a | Node' (Tree' a) (Tree' a)
-- len :: List a -> Int
-- len Nil = 0
-- elen (Cons _ tail) = 1 + len tail -- _ -> это мы отбрасываем голову списка
-- Type классы. Хочется диспечиризацию по значению, но так же и по типу
class Sizeable t where
len :: t -> Int
instance Sizeable () where
len () = 0
instance Sizeable (List a) where
len Nil = 0
len (Cons _ tail) = 1 + len tail
foo :: Sizeable t => t -> Int
foo x = 2 * len x
-- Можно автоматически определять имплементации для некоторых тайп классов
data Fruit = Apple | Orange | Lemon
deriving (Ord, Eq)
-- А вот так можно определить JSON
data Json
= Null
| Bool Bool
| Number Float
| String String
| List [Json]
| Object [(String, Json)]
main = frst (5, 3)
|
aquatir/remember_java_api
|
code-sample-haskell/typed_fp_basics_cource/01_algebraic_data_structures/code.hs
|
mit
| 1,845 | 0 | 8 | 384 | 426 | 237 | 189 | -1 | -1 |
{- arch-tag: HVFS tests main file
Copyright (C) 2004-2011 John Goerzen <[email protected]>
All rights reserved.
For license and copyright information, see the file LICENSE
-}
module HVFStest(tests) where
import Test.HUnit
import System.IO.HVIO
import System.IO.HVFS
import System.IO.HVFS.InstanceHelpers
import System.IO.HVFS.Combinators
import Test.HUnit.Tools
import System.IO
import System.IO.Error
import Control.Exception
import System.FilePath (pathSeparator)
sep = map (\c -> if c == '/' then pathSeparator else c)
ioeq :: (Show a, Eq a) => a -> IO a -> Assertion
ioeq exp inp = do x <- inp
exp @=? x
testTree = [("test.txt", MemoryFile "line1\nline2\n"),
("file2.txt", MemoryFile "line3\nline4\n"),
("emptydir", MemoryDirectory []),
("dir1", MemoryDirectory
[("file3.txt", MemoryFile "line5\n"),
("test.txt", MemoryFile "subdir test"),
("dir2", MemoryDirectory [])
]
)
]
test_nice_slice =
let f exp fp' = TestLabel fp $ TestCase $ exp @=? nice_slice fp
where
fp = sep fp'
in [
f [] "/"
,f ["foo", "bar"] "/foo/bar"
--,f [] "."
]
test_content =
let f exp fp' = TestLabel fp $ TestCase $
do x <- newMemoryVFS testTree
h <- vOpen x fp ReadMode
case h of
HVFSOpenEncap h2 -> exp `ioeq` vGetContents h2
where
fp = sep fp'
in
[
f "line1\nline2\n" "test.txt",
f "line1\nline2\n" "/test.txt",
f "line5\n" "dir1/file3.txt",
f "subdir test" "/dir1/test.txt"
]
test_chroot =
let f msg testfunc = TestLabel msg $ TestCase $
do x <- newMemoryVFS testTree
vSetCurrentDirectory x (sep "/emptydir")
y <- newHVFSChroot x (sep "/dir1")
testfunc y
in
[
f "root" (\x -> ["file3.txt", "test.txt", "dir2"]
`ioeq` vGetDirectoryContents x (sep "/"))
,f "cwd" (\x -> sep "/" `ioeq` vGetCurrentDirectory x)
,f "dir2" (\x -> [] `ioeq` vGetDirectoryContents x (sep "/dir2"))
,f "dot" (\x -> ["file3.txt", "test.txt", "dir2"]
`ioeq` vGetDirectoryContents x ".")
,f "cwd tests" $
(\x -> do a <- vGetDirectoryContents x (sep "/")
["file3.txt", "test.txt", "dir2"] @=? a
vSetCurrentDirectory x (sep "/dir2")
cwd <- vGetCurrentDirectory x
sep "/dir2" @=? cwd
y <- vGetDirectoryContents x "."
[] @=? y
vSetCurrentDirectory x ".."
sep "/" `ioeq` vGetCurrentDirectory x
--vSetCurrentDirectory x ".."
--"/" `ioeq` vGetCurrentDirectory x
)
--,f "test.txt" (\x -> "subdir test" `ioeq`
-- (vOpen x "/test.txt" ReadMode >>= vGetContents))
]
test_structure =
let f msg testfunc = TestLabel msg $ TestCase $ do x <- newMemoryVFS testTree
testfunc x
in
[
f "root" (\x -> ["test.txt", "file2.txt", "emptydir", "dir1"]
`ioeq` vGetDirectoryContents x (sep ("/")))
,f "dot" (\x -> ["test.txt", "file2.txt", "emptydir", "dir1"]
`ioeq` vGetDirectoryContents x ".")
,f "dot2" (\x -> ["file3.txt", "test.txt", "dir2"]
`ioeq` do vSetCurrentDirectory x (sep "./dir1")
vGetDirectoryContents x ".")
,f "emptydir" (\x -> [] `ioeq` vGetDirectoryContents x (sep "/emptydir"))
,f "dir1" (\x -> ["file3.txt", "test.txt", "dir2"] `ioeq`
vGetDirectoryContents x "/dir1")
,f (sep "dir1/dir2") (\x -> [] `ioeq` vGetDirectoryContents x (sep "/dir1/dir2"))
,f "relative tests" (\x ->
do vSetCurrentDirectory x "dir1"
[] `ioeq` vGetDirectoryContents x "dir2"
)
]
tests = TestList [TestLabel "nice_slice" (TestList test_nice_slice)
,TestLabel "structure" (TestList test_structure)
,TestLabel "content" (TestList test_content)
,TestLabel "chroot" (TestList test_chroot)
]
|
haskellbr/missingh
|
missingh-all/testsrc/HVFStest.hs
|
mit
| 4,635 | 0 | 16 | 1,793 | 1,205 | 632 | 573 | 85 | 2 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.VTTCue
(js_newVTTCue, newVTTCue, js_getCueAsHTML, getCueAsHTML,
js_setVertical, setVertical, js_getVertical, getVertical,
js_setSnapToLines, setSnapToLines, js_getSnapToLines,
getSnapToLines, js_setLine, setLine, js_getLine, getLine,
js_setPosition, setPosition, js_getPosition, getPosition,
js_setSize, setSize, js_getSize, getSize, js_setAlign, setAlign,
js_getAlign, getAlign, js_setText, setText, js_getText, getText,
js_setRegionId, setRegionId, js_getRegionId, getRegionId, VTTCue,
castToVTTCue, gTypeVTTCue)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe
"new window[\"VTTCue\"]($1, $2, $3)" js_newVTTCue ::
Double -> Double -> JSString -> IO VTTCue
-- | <https://developer.mozilla.org/en-US/docs/Web/API/VTTCue Mozilla VTTCue documentation>
newVTTCue ::
(MonadIO m, ToJSString text) =>
Double -> Double -> text -> m VTTCue
newVTTCue startTime endTime text
= liftIO (js_newVTTCue startTime endTime (toJSString text))
foreign import javascript unsafe "$1[\"getCueAsHTML\"]()"
js_getCueAsHTML :: VTTCue -> IO (Nullable DocumentFragment)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/VTTCue.getCueAsHTML Mozilla VTTCue.getCueAsHTML documentation>
getCueAsHTML :: (MonadIO m) => VTTCue -> m (Maybe DocumentFragment)
getCueAsHTML self
= liftIO (nullableToMaybe <$> (js_getCueAsHTML (self)))
foreign import javascript unsafe "$1[\"vertical\"] = $2;"
js_setVertical :: VTTCue -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/VTTCue.vertical Mozilla VTTCue.vertical documentation>
setVertical :: (MonadIO m, ToJSString val) => VTTCue -> val -> m ()
setVertical self val
= liftIO (js_setVertical (self) (toJSString val))
foreign import javascript unsafe "$1[\"vertical\"]" js_getVertical
:: VTTCue -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/VTTCue.vertical Mozilla VTTCue.vertical documentation>
getVertical ::
(MonadIO m, FromJSString result) => VTTCue -> m result
getVertical self
= liftIO (fromJSString <$> (js_getVertical (self)))
foreign import javascript unsafe "$1[\"snapToLines\"] = $2;"
js_setSnapToLines :: VTTCue -> Bool -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/VTTCue.snapToLines Mozilla VTTCue.snapToLines documentation>
setSnapToLines :: (MonadIO m) => VTTCue -> Bool -> m ()
setSnapToLines self val = liftIO (js_setSnapToLines (self) val)
foreign import javascript unsafe "($1[\"snapToLines\"] ? 1 : 0)"
js_getSnapToLines :: VTTCue -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/VTTCue.snapToLines Mozilla VTTCue.snapToLines documentation>
getSnapToLines :: (MonadIO m) => VTTCue -> m Bool
getSnapToLines self = liftIO (js_getSnapToLines (self))
foreign import javascript unsafe "$1[\"line\"] = $2;" js_setLine ::
VTTCue -> Double -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/VTTCue.line Mozilla VTTCue.line documentation>
setLine :: (MonadIO m) => VTTCue -> Double -> m ()
setLine self val = liftIO (js_setLine (self) val)
foreign import javascript unsafe "$1[\"line\"]" js_getLine ::
VTTCue -> IO Double
-- | <https://developer.mozilla.org/en-US/docs/Web/API/VTTCue.line Mozilla VTTCue.line documentation>
getLine :: (MonadIO m) => VTTCue -> m Double
getLine self = liftIO (js_getLine (self))
foreign import javascript unsafe "$1[\"position\"] = $2;"
js_setPosition :: VTTCue -> Double -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/VTTCue.position Mozilla VTTCue.position documentation>
setPosition :: (MonadIO m) => VTTCue -> Double -> m ()
setPosition self val = liftIO (js_setPosition (self) val)
foreign import javascript unsafe "$1[\"position\"]" js_getPosition
:: VTTCue -> IO Double
-- | <https://developer.mozilla.org/en-US/docs/Web/API/VTTCue.position Mozilla VTTCue.position documentation>
getPosition :: (MonadIO m) => VTTCue -> m Double
getPosition self = liftIO (js_getPosition (self))
foreign import javascript unsafe "$1[\"size\"] = $2;" js_setSize ::
VTTCue -> Double -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/VTTCue.size Mozilla VTTCue.size documentation>
setSize :: (MonadIO m) => VTTCue -> Double -> m ()
setSize self val = liftIO (js_setSize (self) val)
foreign import javascript unsafe "$1[\"size\"]" js_getSize ::
VTTCue -> IO Double
-- | <https://developer.mozilla.org/en-US/docs/Web/API/VTTCue.size Mozilla VTTCue.size documentation>
getSize :: (MonadIO m) => VTTCue -> m Double
getSize self = liftIO (js_getSize (self))
foreign import javascript unsafe "$1[\"align\"] = $2;" js_setAlign
:: VTTCue -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/VTTCue.align Mozilla VTTCue.align documentation>
setAlign :: (MonadIO m, ToJSString val) => VTTCue -> val -> m ()
setAlign self val = liftIO (js_setAlign (self) (toJSString val))
foreign import javascript unsafe "$1[\"align\"]" js_getAlign ::
VTTCue -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/VTTCue.align Mozilla VTTCue.align documentation>
getAlign :: (MonadIO m, FromJSString result) => VTTCue -> m result
getAlign self = liftIO (fromJSString <$> (js_getAlign (self)))
foreign import javascript unsafe "$1[\"text\"] = $2;" js_setText ::
VTTCue -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/VTTCue.text Mozilla VTTCue.text documentation>
setText :: (MonadIO m, ToJSString val) => VTTCue -> val -> m ()
setText self val = liftIO (js_setText (self) (toJSString val))
foreign import javascript unsafe "$1[\"text\"]" js_getText ::
VTTCue -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/VTTCue.text Mozilla VTTCue.text documentation>
getText :: (MonadIO m, FromJSString result) => VTTCue -> m result
getText self = liftIO (fromJSString <$> (js_getText (self)))
foreign import javascript unsafe "$1[\"regionId\"] = $2;"
js_setRegionId :: VTTCue -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/VTTCue.regionId Mozilla VTTCue.regionId documentation>
setRegionId :: (MonadIO m, ToJSString val) => VTTCue -> val -> m ()
setRegionId self val
= liftIO (js_setRegionId (self) (toJSString val))
foreign import javascript unsafe "$1[\"regionId\"]" js_getRegionId
:: VTTCue -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/VTTCue.regionId Mozilla VTTCue.regionId documentation>
getRegionId ::
(MonadIO m, FromJSString result) => VTTCue -> m result
getRegionId self
= liftIO (fromJSString <$> (js_getRegionId (self)))
|
manyoo/ghcjs-dom
|
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/VTTCue.hs
|
mit
| 7,614 | 128 | 10 | 1,169 | 1,822 | 997 | 825 | 108 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Y2021.M02.D23.Exercise where
{--
Name matching is the name of the game for today's Haskell problem.
You have a set of named wikidata wineries in "column A" and a set of named
graph wineries in "column B." You've already done the exact name-matches, now
how do we know which wineries in column A are the wineries in column B.
One way to do that is to by-hand pair the candidates. I had a CEO once that
wanted to do name matches by-hand over thousands of articles, to base-line
our name-matching algorithm.
The operative phrase there is 'I HAD a CEO ONCE.'
The problem with by-hand matching is that it entails writing no software, so
you have (no joke) three secretaries working over 72 hours to come up with a
schedule for 100 people.
Or, you could do like me, and write the software that does the matching for
them in 1 second and prints out the schedule in PDF.
Then, like me, sell them that software.
The other, insidious, problem with by-hand matching is that is error-prone
because human beings are fatigue-prone, so, not only do you have to by-hand
name-match, but then you need to by-hand verify the by-hand name-matching.
Convert those hours into a bill, and you begin to see the immediate benefits
of a software solution.
Okay, so, today, let's use the double-metaphone name-matching algorithm. The one
I'm selecting to use here is written in Python.
For example: The Al Este winery in Argentina encodes as:
$ python metaphone.py Al Este
('ALST', '')
The repository is here:
https://github.com/oubiwann/metaphone
So, first we need to send a winery to metaphone and get back the encoding:
--}
import Data.Aeson hiding (KeyValue)
import Data.Set (Set)
import Data.Text (Text)
import System.Process
-- for the bonus problem:
import Y2021.M01.D29.Solution hiding (toPair) -- Namei
import Y2021.M02.D22.Solution (wineriesWIP, NeoWinery(NeoWinery))
import Y2021.M01.D21.Solution (Idx, IxWineries)
import Y2021.M01.D22.Solution -- for wineries
import Data.Aeson.WikiDatum (Name)
doubleMetaphone :: Text -> IO (String, String)
doubleMetaphone winery = undefined
{--
Now, 16K+ wineries called one-by-one ... 'may' be a pain? But let's use
today's Haskell exercise to interoperate with other systems. Call the
doubleMetaphone with at least one winery and show the result.
(That, of course, means you have the double-metaphone installed, so do that.
You'll also have to automate the double-metaphone application so you can call
it and get a result (writing a very simple __main__ function worked for me.)
That's it! That's today's Haskell exercise. DOIT! TOIT!
--}
{-- BONUS -------------------------------------------------------
All right, all right! A little bonus.
Output one of the winery-sets as names to a file, one winery per line.
I'll write a python script to scan that file and return the double-metaphone
encodings for each line.
--}
todaysDir :: FilePath
todaysDir = "Y2021/M02/D23/"
{-- ... but wait (see bonus-bonus-bonus below)
wineriesFile :: Namei a => FilePath -> Set a -> IO ()
wineriesFile outputFile wineries = undefined
>>> graphEndpoint >>= wineriesWIP (wineriesDir ++ wineriesJSON)
fromList [...]
>>> let (wikiws, graphws) = it
>>> (Set.size wikiws, Set.size graphws)
(481,16836)
>>> wineriesFile (todaysDir ++ "wiki-wineries.txt") wikiws
>>> wineriesFile (todaysDir ++ "graph-wineries.txt") graphws
-- BONUS-BONUS --------------------------------------------------
OR! You could just save out resulting file as el JSONerific.
--}
data KeyValue a b = KV a b
deriving (Eq, Ord, Show)
instance (ToJSON a, ToJSON b) => ToJSON (KeyValue a b) where
toJSON (KV a b) = undefined
data Metaphone = Meta (String, String)
deriving (Eq, Ord, Show)
instance ToJSON Metaphone where
toJSON (Meta (a,b)) = undefined
data IxKeyValue a b = IxKV Idx (KeyValue a b)
deriving (Eq, Ord, Show)
instance (ToJSON a, ToJSON b) => ToJSON (IxKeyValue a b) where
toJSON (IxKV ix kv) = undefined
toKV :: (Name, Idx) -> IO (IxKeyValue Name Metaphone)
toKV (n, ix) = undefined
{-- BONUS-BONUS-BONUS!! ----------------------------------------
I noticed a lot of QNames for Names in the wiki-winery data-set and a lot
of duplicates (triplicates, ... megalons (???)) in the graph-winery data-set
for their names. We don't need to process QNames nor (re)process multiples
for winery names, so filter all those out. ... but we also need to preserve
the index of these wineries, as well.
--}
instance Indexed Winery where
ix _ = 0
instance Indexed NeoWinery where
ix neo = undefined
removeQNames :: Indexed a => Namei a => Set a -> IxWineries
removeQNames = undefined
-- show that removeQNames 'automagically' removes duplicate names.
-- So, the updated wineriesFile is now:
wineriesFile :: Indexed a => Namei a => FilePath -> Set a -> IO ()
wineriesFile = undefined
-- show that removeQNames 'automagically' removes duplicate names.
|
geophf/1HaskellADay
|
exercises/HAD/Y2021/M02/D23/Exercise.hs
|
mit
| 4,958 | 0 | 10 | 858 | 516 | 292 | 224 | -1 | -1 |
{-# LANGUAGE DeriveGeneric, DeriveDataTypeable,
MultiParamTypeClasses #-}
module Syntax where
import Unbound.Generics.LocallyNameless
import GHC.Generics (Generic)
import Data.Typeable (Typeable)
type TName = Name Term
data Ty
= TyNat
| TyBool
| TyTop
| TyBot
| TyUnit
| TyString
| TyFloat
| TyRecord [(String, Ty)]
| TyArr Ty Ty
deriving (Show, Eq, Generic, Typeable)
data Term
= TmVar TName
| TmTrue
| TmFalse
| TmSucc Term
| TmPred Term
| TmZero
| TmIsZero Term
| TmError
| TmString String
| TmFloat Double
| TmFloatTimes Term Term
| TmAscription [String] String
| TmApp Term Term
| TmAbs (Bind (TName, Embed [String]) Term)
| TmLet (Bind (TName, Embed Term) Term)
| TmIf Term Term Term
| TmFix Term
| TmRecord [(String, Term)]
| TmProj Term String
deriving (Show, Generic, Typeable)
instance Alpha Term
instance Alpha Ty
instance Subst Term Term where
isvar (TmVar x) = Just (SubstName x)
isvar _ = Nothing
instance Subst Term Ty
|
kellino/TypeSystems
|
fullSub/Syntax.hs
|
mit
| 1,087 | 0 | 11 | 304 | 336 | 191 | 145 | 45 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Yesod.Form.I18n.Dutch where
import Yesod.Form.Types (FormMessage (..))
import Data.Monoid (mappend)
import Data.Text (Text)
dutchFormMessage :: FormMessage -> Text
dutchFormMessage (MsgInvalidInteger t) = "Ongeldig aantal: " `Data.Monoid.mappend` t
dutchFormMessage (MsgInvalidNumber t) = "Ongeldig getal: " `mappend` t
dutchFormMessage (MsgInvalidEntry t) = "Ongeldige invoer: " `mappend` t
dutchFormMessage MsgInvalidTimeFormat = "Ongeldige tijd, het juiste formaat is (UU:MM[:SS])"
dutchFormMessage MsgInvalidDay = "Ongeldige datum, het juiste formaat is (JJJJ-MM-DD)"
dutchFormMessage (MsgInvalidUrl t) = "Ongeldige URL: " `mappend` t
dutchFormMessage (MsgInvalidEmail t) = "Ongeldig e-mail adres: " `mappend` t
dutchFormMessage (MsgInvalidHour t) = "Ongeldig uur: " `mappend` t
dutchFormMessage (MsgInvalidMinute t) = "Ongeldige minuut: " `mappend` t
dutchFormMessage (MsgInvalidSecond t) = "Ongeldige seconde: " `mappend` t
dutchFormMessage MsgCsrfWarning = "Bevestig het indienen van het formulier, dit als veiligheidsmaatregel tegen \"cross-site request forgery\" aanvallen."
dutchFormMessage MsgValueRequired = "Verplicht veld"
dutchFormMessage (MsgInputNotFound t) = "Geen invoer gevonden: " `mappend` t
dutchFormMessage MsgSelectNone = "<Geen>"
dutchFormMessage (MsgInvalidBool t) = "Ongeldige waarheidswaarde: " `mappend` t
dutchFormMessage MsgBoolYes = "Ja"
dutchFormMessage MsgBoolNo = "Nee"
dutchFormMessage MsgDelete = "Verwijderen?"
dutchFormMessage (MsgInvalidHexColorFormat t) = "Ongeldige kleur, moet de hexadecimale indeling #rrggbb hebben: " `mappend` t
|
yesodweb/yesod
|
yesod-form/Yesod/Form/I18n/Dutch.hs
|
mit
| 1,702 | 0 | 7 | 271 | 340 | 189 | 151 | 25 | 1 |
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE CPP #-}
--------------------------------------------------------------------
-- |
-- Copyright : © Oleg Grenrus 2014
-- License : MIT
-- Maintainer: Oleg Grenrus <[email protected]>
-- Stability : experimental
-- Portability: non-portable
--
--------------------------------------------------------------------
module Data.Algebra.Boolean.DNF.Set (
DNF(..),
fromDoubleList,
toDoubleList,
fromNNF,
module Data.Algebra.Boolean.NormalForm
) where
import Prelude hiding ((||),(&&),not,and,or,any,all)
#if !MIN_VERSION_base(4,11,0)
import Data.Monoid
#endif
import Data.Typeable (Typeable)
import Data.Foldable (Foldable)
import Control.DeepSeq (NFData(rnf))
import Data.Set (Set)
import qualified Data.Set as Set
import Data.List (sortBy, foldl')
import Data.Function (on)
import Data.Algebra.Boolean.NormalForm
import Data.Algebra.Boolean.Negable hiding (not)
import qualified Data.Algebra.Boolean.Negable as Negable
import Data.Algebra.Boolean.NNF.Tree
import Data.Algebra.Boolean
-- | Boolean formula in Disjunction Normal Form
--
-- <<doc-formulae/dnf.svg>>
newtype DNF a = DNF { unDNF :: Set (Set a) }
deriving (Eq, Ord, Show, Read, Foldable, Typeable)
instance CoBoolean1 DNF where
toBooleanWith f = any (all f) . unDNF
instance CoBoolean a => CoBoolean (DNF a) where
toBoolean = toBooleanWith toBoolean
toDoubleList :: DNF a -> [[a]]
toDoubleList = map Set.toList . Set.toList . unDNF
fromDoubleList :: (Ord a) => [[a]] -> DNF a
fromDoubleList = DNF . Set.fromList . map Set.fromList
dnfNot :: (Ord a, Negable a) => DNF a -> DNF a
dnfNot = all or . map (map $ toNormalForm . Negable.not) . toDoubleList
instance (Ord a, Negable a) => Negable (DNF a) where
not = dnfNot
instance (Ord a, Negable a) => Boolean (DNF a) where
true = DNF $ Set.singleton Set.empty
false = DNF Set.empty
(DNF a) || (DNF b) = DNF (a <> b)
(DNF a) && (DNF b) = DNF $ Set.fromList [a' <> b' | a' <- Set.toList a, b' <- Set.toList b ]
not = dnfNot
fromLeft :: Either a b -> a
fromLeft (Left x) = x
fromLeft _ = error "fromLeft called on Right value"
optimize :: Ord a => Set (Set a) -> Set (Set a)
optimize = Set.fromList . f . sortBy (compare `on` Set.size) . Set.toList
where f conj = foldl' g conj conj
g conj item = filter (not . Set.isProperSubsetOf item) conj
fromNNF :: (Ord a, Negable a) => NNF a -> DNF a
fromNNF = toBooleanWith toNormalForm
instance NormalForm DNF where
type NFConstraint DNF a = (Negable a, Ord a)
toNormalForm = DNF . Set.singleton . Set.singleton
simplify f = DNF . optimize . q . h . Set.map g . Set.map (Set.map f') . unDNF
where f' x = case f x of
Just b -> Right b
Nothing -> Left x
h :: Ord a => Set (Either a Bool) -> Either (Set a) Bool
h disj | Right True `Set.member` disj = Right True
| Set.null l = Right False
| otherwise = Left l
where l = Set.mapMonotonic fromLeft $ fst $ Set.split (Right minBound) disj
g :: Ord a => Set (Either a Bool) -> Either (Set a) Bool
g conj | Right False `Set.member` conj = Right False
| Set.null l = Right True
| otherwise = Left l
where l = Set.mapMonotonic fromLeft $ fst $ Set.split (Right minBound) conj
q :: Either (Set (Set a)) Bool -> Set (Set a)
q (Right True) = Set.singleton Set.empty
q (Right False) = Set.empty
q (Left x) = x
fromFreeBoolean = fromNNF . toBooleanWith toNormalForm
instance NFData a => NFData (DNF a) where
rnf (DNF xss) = rnf xss
|
phadej/boolean-normal-forms
|
src/Data/Algebra/Boolean/DNF/Set.hs
|
mit
| 3,961 | 0 | 13 | 1,095 | 1,373 | 719 | 654 | 77 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE PatternGuards #-}
-- | A sqlite backend for persistent.
--
-- Note: If you prepend @WAL=off @ to your connection string, it will disable
-- the write-ahead log. For more information, see
-- <https://github.com/yesodweb/persistent/issues/363>.
module Database.Persist.Sqlite
( withSqlitePool
, withSqliteConn
, createSqlitePool
, module Database.Persist.Sql
, SqliteConf (..)
, runSqlite
, wrapConnection
) where
import Database.Persist.Sql
import qualified Database.Sqlite as Sqlite
import Control.Monad.IO.Class (MonadIO (..))
import Control.Monad.Logger (NoLoggingT, runNoLoggingT, MonadLogger)
import Data.IORef
import qualified Data.Map as Map
import Control.Monad.Trans.Control (control)
import Data.Acquire (Acquire, mkAcquire, with)
import qualified Control.Exception as E
import Data.Text (Text)
import Data.Aeson
import Data.Aeson.Types (modifyFailure)
import qualified Data.Text as T
import Data.Conduit
import qualified Data.Conduit.List as CL
import Control.Applicative
import Data.Int (Int64)
import Data.Monoid ((<>))
import Control.Monad.Trans.Control (MonadBaseControl)
import Control.Monad.Trans.Resource (ResourceT, runResourceT)
import Control.Monad (when)
createSqlitePool :: (MonadIO m, MonadLogger m, MonadBaseControl IO m) => Text -> Int -> m ConnectionPool
createSqlitePool s = createSqlPool $ open' s
withSqlitePool :: (MonadBaseControl IO m, MonadIO m, MonadLogger m)
=> Text
-> Int -- ^ number of connections to open
-> (ConnectionPool -> m a) -> m a
withSqlitePool s = withSqlPool $ open' s
withSqliteConn :: (MonadBaseControl IO m, MonadIO m, MonadLogger m)
=> Text -> (SqlBackend -> m a) -> m a
withSqliteConn = withSqlConn . open'
open' :: Text -> LogFunc -> IO SqlBackend
open' connStr logFunc = do
let (connStr', enableWal) = case () of
()
| Just cs <- T.stripPrefix "WAL=on " connStr -> (cs, True)
| Just cs <- T.stripPrefix "WAL=off " connStr -> (cs, False)
| otherwise -> (connStr, True)
conn <- Sqlite.open connStr'
wrapConnectionWal enableWal conn logFunc
-- | Wrap up a raw 'Sqlite.Connection' as a Persistent SQL 'Connection'.
--
-- Since 1.1.5
wrapConnection :: Sqlite.Connection -> LogFunc -> IO SqlBackend
wrapConnection = wrapConnectionWal True
-- | Allow control of WAL settings when wrapping
wrapConnectionWal :: Bool -- ^ enable WAL?
-> Sqlite.Connection
-> LogFunc
-> IO SqlBackend
wrapConnectionWal enableWal conn logFunc = do
when enableWal $ do
-- Turn on the write-ahead log
-- https://github.com/yesodweb/persistent/issues/363
turnOnWal <- Sqlite.prepare conn "PRAGMA journal_mode=WAL;"
_ <- Sqlite.step turnOnWal
Sqlite.reset conn turnOnWal
Sqlite.finalize turnOnWal
smap <- newIORef $ Map.empty
return SqlBackend
{ connPrepare = prepare' conn
, connStmtMap = smap
, connInsertSql = insertSql'
, connClose = Sqlite.close conn
, connMigrateSql = migrate'
, connBegin = helper "BEGIN"
, connCommit = helper "COMMIT"
, connRollback = ignoreExceptions . helper "ROLLBACK"
, connEscapeName = escape
, connNoLimit = "LIMIT -1"
, connRDBMS = "sqlite"
, connLimitOffset = decorateSQLWithLimitOffset "LIMIT -1"
, connLogFunc = logFunc
}
where
helper t getter = do
stmt <- getter t
_ <- stmtExecute stmt []
stmtReset stmt
ignoreExceptions = E.handle (\(_ :: E.SomeException) -> return ())
-- | A convenience helper which creates a new database connection and runs the
-- given block, handling @MonadResource@ and @MonadLogger@ requirements. Note
-- that all log messages are discarded.
--
-- Since 1.1.4
runSqlite :: (MonadBaseControl IO m, MonadIO m)
=> Text -- ^ connection string
-> SqlPersistT (NoLoggingT (ResourceT m)) a -- ^ database action
-> m a
runSqlite connstr = runResourceT
. runNoLoggingT
. withSqliteConn connstr
. runSqlConn
prepare' :: Sqlite.Connection -> Text -> IO Statement
prepare' conn sql = do
stmt <- Sqlite.prepare conn sql
return Statement
{ stmtFinalize = Sqlite.finalize stmt
, stmtReset = Sqlite.reset conn stmt
, stmtExecute = execute' conn stmt
, stmtQuery = withStmt' conn stmt
}
insertSql' :: EntityDef -> [PersistValue] -> InsertSqlResult
insertSql' ent vals =
case entityPrimary ent of
Just _ ->
ISRManyKeys sql vals
where sql = T.concat
[ "INSERT INTO "
, escape $ entityDB ent
, "("
, T.intercalate "," $ map (escape . fieldDB) $ entityFields ent
, ") VALUES("
, T.intercalate "," (map (const "?") $ entityFields ent)
, ")"
]
Nothing ->
ISRInsertGet ins sel
where
sel = T.concat
[ "SELECT "
, escape $ fieldDB (entityId ent)
, " FROM "
, escape $ entityDB ent
, " WHERE _ROWID_=last_insert_rowid()"
]
ins = T.concat
[ "INSERT INTO "
, escape $ entityDB ent
, if null (entityFields ent)
then " VALUES(null)"
else T.concat
[ "("
, T.intercalate "," $ map (escape . fieldDB) $ entityFields ent
, ") VALUES("
, T.intercalate "," (map (const "?") $ entityFields ent)
, ")"
]
]
execute' :: Sqlite.Connection -> Sqlite.Statement -> [PersistValue] -> IO Int64
execute' conn stmt vals = flip finally (liftIO $ Sqlite.reset conn stmt) $ do
Sqlite.bind stmt vals
_ <- Sqlite.step stmt
Sqlite.changes conn
withStmt'
:: MonadIO m
=> Sqlite.Connection
-> Sqlite.Statement
-> [PersistValue]
-> Acquire (Source m [PersistValue])
withStmt' conn stmt vals = do
_ <- mkAcquire
(Sqlite.bind stmt vals >> return stmt)
(Sqlite.reset conn)
return pull
where
pull = do
x <- liftIO $ Sqlite.step stmt
case x of
Sqlite.Done -> return ()
Sqlite.Row -> do
cols <- liftIO $ Sqlite.columns stmt
yield cols
pull
showSqlType :: SqlType -> Text
showSqlType SqlString = "VARCHAR"
showSqlType SqlInt32 = "INTEGER"
showSqlType SqlInt64 = "INTEGER"
showSqlType SqlReal = "REAL"
showSqlType (SqlNumeric precision scale) = T.concat [ "NUMERIC(", T.pack (show precision), ",", T.pack (show scale), ")" ]
showSqlType SqlDay = "DATE"
showSqlType SqlTime = "TIME"
showSqlType SqlDayTime = "TIMESTAMP"
showSqlType SqlBlob = "BLOB"
showSqlType SqlBool = "BOOLEAN"
showSqlType (SqlOther t) = t
migrate' :: [EntityDef]
-> (Text -> IO Statement)
-> EntityDef
-> IO (Either [Text] [(Bool, Text)])
migrate' allDefs getter val = do
let (cols, uniqs, _) = mkColumns allDefs val
let newSql = mkCreateTable False def (filter (not . safeToRemove val . cName) cols, uniqs)
stmt <- getter "SELECT sql FROM sqlite_master WHERE type='table' AND name=?"
oldSql' <- with (stmtQuery stmt [PersistText $ unDBName table]) ($$ go)
case oldSql' of
Nothing -> return $ Right [(False, newSql)]
Just oldSql -> do
if oldSql == newSql
then return $ Right []
else do
sql <- getCopyTable allDefs getter val
return $ Right sql
where
def = val
table = entityDB def
go = do
x <- CL.head
case x of
Nothing -> return Nothing
Just [PersistText y] -> return $ Just y
Just y -> error $ "Unexpected result from sqlite_master: " ++ show y
-- | Check if a column name is listed as the "safe to remove" in the entity
-- list.
safeToRemove :: EntityDef -> DBName -> Bool
safeToRemove def (DBName colName)
= any (elem "SafeToRemove" . fieldAttrs)
$ filter ((== DBName colName) . fieldDB)
$ entityFields def
getCopyTable :: [EntityDef]
-> (Text -> IO Statement)
-> EntityDef
-> IO [(Bool, Text)]
getCopyTable allDefs getter def = do
stmt <- getter $ T.concat [ "PRAGMA table_info(", escape table, ")" ]
oldCols' <- with (stmtQuery stmt []) ($$ getCols)
let oldCols = map DBName $ filter (/= "id") oldCols' -- need to update for table id attribute ?
let newCols = filter (not . safeToRemove def) $ map cName cols
let common = filter (`elem` oldCols) newCols
let id_ = fieldDB (entityId def)
return [ (False, tmpSql)
, (False, copyToTemp $ id_ : common)
, (common /= filter (not . safeToRemove def) oldCols, dropOld)
, (False, newSql)
, (False, copyToFinal $ id_ : newCols)
, (False, dropTmp)
]
where
getCols = do
x <- CL.head
case x of
Nothing -> return []
Just (_:PersistText name:_) -> do
names <- getCols
return $ name : names
Just y -> error $ "Invalid result from PRAGMA table_info: " ++ show y
table = entityDB def
tableTmp = DBName $ unDBName table <> "_backup"
(cols, uniqs, _) = mkColumns allDefs def
cols' = filter (not . safeToRemove def . cName) cols
newSql = mkCreateTable False def (cols', uniqs)
tmpSql = mkCreateTable True def { entityDB = tableTmp } (cols', uniqs)
dropTmp = "DROP TABLE " <> escape tableTmp
dropOld = "DROP TABLE " <> escape table
copyToTemp common = T.concat
[ "INSERT INTO "
, escape tableTmp
, "("
, T.intercalate "," $ map escape common
, ") SELECT "
, T.intercalate "," $ map escape common
, " FROM "
, escape table
]
copyToFinal newCols = T.concat
[ "INSERT INTO "
, escape table
, " SELECT "
, T.intercalate "," $ map escape newCols
, " FROM "
, escape tableTmp
]
mkCreateTable :: Bool -> EntityDef -> ([Column], [UniqueDef]) -> Text
mkCreateTable isTemp entity (cols, uniqs) =
case entityPrimary entity of
Just pdef ->
T.concat
[ "CREATE"
, if isTemp then " TEMP" else ""
, " TABLE "
, escape $ entityDB entity
, "("
, T.drop 1 $ T.concat $ map sqlColumn cols
, ", PRIMARY KEY "
, "("
, T.intercalate "," $ map (escape . fieldDB) $ compositeFields pdef
, ")"
, ")"
]
Nothing -> T.concat
[ "CREATE"
, if isTemp then " TEMP" else ""
, " TABLE "
, escape $ entityDB entity
, "("
, escape $ fieldDB (entityId entity)
, " "
, showSqlType $ fieldSqlType $ entityId entity
," PRIMARY KEY"
, mayDefault $ defaultAttribute $ fieldAttrs $ entityId entity
, T.concat $ map sqlColumn cols
, T.concat $ map sqlUnique uniqs
, ")"
]
mayDefault :: Maybe Text -> Text
mayDefault def = case def of
Nothing -> ""
Just d -> " DEFAULT " <> d
sqlColumn :: Column -> Text
sqlColumn (Column name isNull typ def _cn _maxLen ref) = T.concat
[ ","
, escape name
, " "
, showSqlType typ
, if isNull then " NULL" else " NOT NULL"
, mayDefault def
, case ref of
Nothing -> ""
Just (table, _) -> " REFERENCES " <> escape table
]
sqlUnique :: UniqueDef -> Text
sqlUnique (UniqueDef _ cname cols _) = T.concat
[ ",CONSTRAINT "
, escape cname
, " UNIQUE ("
, T.intercalate "," $ map (escape . snd) cols
, ")"
]
escape :: DBName -> Text
escape (DBName s) =
T.concat [q, T.concatMap go s, q]
where
q = T.singleton '"'
go '"' = "\"\""
go c = T.singleton c
-- | Information required to connect to a sqlite database
data SqliteConf = SqliteConf
{ sqlDatabase :: Text
, sqlPoolSize :: Int
} deriving Show
instance FromJSON SqliteConf where
parseJSON v = modifyFailure ("Persistent: error loadomg Sqlite conf: " ++) $
flip (withObject "SqliteConf") v $ \o -> SqliteConf
<$> o .: "database"
<*> o .: "poolsize"
instance PersistConfig SqliteConf where
type PersistConfigBackend SqliteConf = SqlPersistT
type PersistConfigPool SqliteConf = ConnectionPool
createPoolConfig (SqliteConf cs size) = runNoLoggingT $ createSqlitePool cs size -- FIXME
runPool _ = runSqlPool
loadConfig = parseJSON
finally :: MonadBaseControl IO m
=> m a -- ^ computation to run first
-> m b -- ^ computation to run afterward (even if an exception was raised)
-> m a
finally a sequel = control $ \runInIO ->
E.finally (runInIO a)
(runInIO sequel)
{-# INLINABLE finally #-}
|
jcristovao/persistent
|
persistent-sqlite/Database/Persist/Sqlite.hs
|
mit
| 13,367 | 0 | 20 | 4,154 | 3,699 | 1,925 | 1,774 | 329 | 5 |
module Errors where
import Control.Monad.Error
import Data.Word
import Text.HTML.TagSoup
import Types
import TCP (Port)
data StatsError
= CannotParseTagContent Payload
| CodingError String
| FragmentationError
| HTTPError Payload Payload
| IncompleteCapture Word32 Word32 -- wire length, capture length
| MoreRequestsInConversation
| NoAttribute (Tag Payload) Payload
| NoSuchTag Int (Tag Payload) -- number of aparitions
| OtherError String
| UnacceptableEncoding Payload Payload
| UndefinedLayer3Protocol
| UnexpectedHTTPRequest Payload
| UnhandledHTMLRequest TaggedHeaderRequest
| UnhandledParseIP
| UnhandledParseTCP
| UnknownPortPair Port Port
instance Error StatsError where
strMsg = OtherError
instance Show StatsError where
show (CannotParseTagContent p) = concat ["# Text ", show p, " doesn't have the required format"]
show (CodingError s) = concat ["# Coding error: ", s, "!"]
show (HTTPError u r) = concat ["# Request to ", show u, " failed ", show r]
show (IncompleteCapture wl cl) = "# Incomplete capture: " ++ show (wl, cl)
show (NoAttribute tag attrib) = concat ["# No attribute ", show attrib, " of tag ", show tag]
show (NoSuchTag n t) = concat ["# Tag ", show t, " not found at least ", show n, " times"]
show (OtherError s) = s
show (UnacceptableEncoding h h1) = concat ["# Unacceptable encoding ", show h, " / ", show h1]
show (UnexpectedHTTPRequest t) = "# Unknown/unexpected request " ++ show t
show (UnhandledHTMLRequest thr) = "# Don't know to parse " ++ show thr
show (UnknownPortPair sp dp) = "# Unknown port pair " ++ show (sp, dp)
show FragmentationError = "# Unable to handle fragmentation at IP level"
show MoreRequestsInConversation = "# One request only assumption failed"
show UndefinedLayer3Protocol = "# Undefined layer 3 proto"
show UnhandledParseIP = "# Unhandled parseIP case"
show UnhandledParseTCP = "# Unhandled parseTCP case"
type StatsM = Either StatsError
|
mihaimaruseac/petulant-octo-avenger
|
src/Errors.hs
|
mit
| 1,974 | 0 | 8 | 363 | 522 | 280 | 242 | 43 | 0 |
{-# OPTIONS_GHC -Wwarn #-} -- I anticipate rewriting this, no point fixing warnings
module Database.Siege.Flushable where
import Control.Concurrent.MVar
import Data.IORef
data FVar a = FVar (MVar a) (IORef (a, a, IO ())) (MVar ())
-- make it possible to fail a flush
newFVar :: s -> IO (FVar s)
newFVar s = do
m0 <- newMVar s
m1 <- newIORef (s, s, return ())
m2 <- newEmptyMVar
return $ FVar m0 m1 m2
modifyFVar :: (s -> IO (s, IO (), a)) -> FVar s -> IO a
modifyFVar op (FVar m i b) = do
v <- takeMVar m
(v', after, out) <- op v
atomicModifyIORef i (\(_, c, act) -> ((v', c, act >> after), ()))
putMVar m v'
_ <- tryPutMVar b ()
return out
readFVar :: FVar s -> IO s
readFVar (FVar _ i _) = do
(_, v, _) <- readIORef i
return v
flushFVar :: (s -> IO a) -> FVar s -> IO a
flushFVar op (FVar _ i b) = do
takeMVar b
(v, act) <- atomicModifyIORef i (\(v, c, act) -> ((v, c, return ()), (v, act)))
out <- op v
atomicModifyIORef i (\(v', _, act') -> ((v', v, act'), ()))
act
return out
|
DanielWaterworth/siege
|
src/Database/Siege/Flushable.hs
|
mit
| 1,025 | 0 | 14 | 248 | 551 | 285 | 266 | 31 | 1 |
module NetHack.Data.MonsterInstance
(MonsterInstance(),
MonsterAttributes(),
monsterNameTrim,
monsterByName,
newMonsterInstance,
freshMonsterInstance,
defaultMonsterAttributes,
monsterByAppearance,
setAttributes,
isHostile,
respectsElbereth)
where
import qualified Data.Map as M
import Data.Foldable(foldl')
import NetHack.Data.Appearance
import Control.Monad
import qualified Data.ByteString.Char8 as B
import qualified NetHack.Imported.MonsterData as MD
import qualified Regex as R
import qualified Terminal.Data as T
data MonsterAttributes = MonsterAttributes
{ peaceful :: Maybe Bool,
tame :: Maybe Bool } deriving(Eq, Show)
data MonsterInstance = MonsterInstance MD.Monster MonsterAttributes
deriving(Eq, Show)
-- | 'isHostile' returns Just True if the monster is definitely hostile,
-- Just False if the monster is definitely peaceful (or tame) and Nothing
-- if hostility is not known.
isHostile :: MonsterInstance -> Maybe Bool
isHostile (MonsterInstance _ ma) = fmap not (peacefulness |^| tameness)
where
peacefulness = peaceful ma
tameness = tame ma
(|^|) = liftM2 (||)
newMonsterInstance :: MD.Monster -> MonsterAttributes -> MonsterInstance
newMonsterInstance = MonsterInstance
defaultMonsterAttributes = MonsterAttributes Nothing Nothing
mdCToTermAttributes :: MD.Color -> T.Attributes
mdCToTermAttributes MD.Black = T.newAttributes T.Blue T.Black False False
mdCToTermAttributes MD.Red = T.newAttributes T.Red T.Black False False
mdCToTermAttributes MD.Green = T.newAttributes T.Green T.Black False False
mdCToTermAttributes MD.Brown = T.newAttributes T.Yellow T.Black False False
mdCToTermAttributes MD.Blue = T.newAttributes T.Blue T.Black False False
mdCToTermAttributes MD.Magenta = T.newAttributes T.Magenta T.Black False False
mdCToTermAttributes MD.Cyan = T.newAttributes T.Cyan T.Black False False
mdCToTermAttributes MD.Gray = T.newAttributes T.White T.Black False False
mdCToTermAttributes MD.Orange = T.newAttributes T.Red T.Black True False
mdCToTermAttributes MD.BrightGreen = T.newAttributes T.Green T.Black True False
mdCToTermAttributes MD.Yellow = T.newAttributes T.Yellow T.Black True False
mdCToTermAttributes MD.BrightBlue = T.newAttributes T.Blue T.Black True False
mdCToTermAttributes MD.BrightMagenta = T.newAttributes T.Magenta T.Black True False
mdCToTermAttributes MD.BrightCyan = T.newAttributes T.Cyan T.Black True False
mdCToTermAttributes MD.White = T.newAttributes T.White T.Black True False
freshMonsterInstance mon =
newMonsterInstance mon defaultMonsterAttributes
monsterSymbolTuning :: Char -> Char
monsterSymbolTuning ' ' = '8' -- ghosts
monsterSymbolTuning '\'' = '7' -- golems
monsterSymbolTuning ch = ch
tunedMoSymbol :: MD.Monster -> Char
tunedMoSymbol = monsterSymbolTuning . MD.moSymbol
monsterMapByString :: M.Map String [MD.Monster]
monsterMapByString =
foldl' (\map name -> let Just mon = MD.monster name
symb = [tunedMoSymbol mon]
in M.insert symb
(case M.lookup symb map of
Nothing -> [mon]
Just oldlist -> mon:oldlist)
map)
M.empty
MD.allMonsterNames
monsterMapByStringLookup :: String -> [MD.Monster]
monsterMapByStringLookup str =
case M.lookup str monsterMapByString of
Nothing -> []
Just l -> l
monsterByName :: String -> Maybe MD.Monster
monsterByName str = MD.monster $ B.pack str
monsterByAppearance :: Appearance -> [MD.Monster]
monsterByAppearance (str, attributes) =
foldl accumulateMonsters [] $ monsterMapByStringLookup str
where
accumulateMonsters accum mons =
if (mdCToTermAttributes . MD.moColor $ mons) == attributes &&
[tunedMoSymbol mons] == str
then mons:accum
else accum
monsterNameTrim :: String -> (String, MonsterAttributes)
monsterNameTrim monsname = peacefulness monsname
where
peacefulness monsname =
case R.match "^peaceful (.+)$" monsname of
Just rest -> tameness rest True
Nothing -> tameness monsname False
tameness monsname peaceful =
case R.match "^tame (.+)$" monsname of
Just rest -> coyoteness rest (peaceful, True)
Nothing -> coyoteness monsname (peaceful, False)
coyoteness monsname attrs =
case R.match "^(.+) \\- .+$" monsname of
Just rest -> nameness rest attrs
Nothing -> nameness monsname attrs
nameness monsname (peaceful, tame) =
case R.match "^(.+) called .+$" monsname of
Just rest -> (rest, MonsterAttributes (Just peaceful) (Just tame))
Nothing -> (monsname, MonsterAttributes (Just peaceful) (Just tame))
setAttributes :: MonsterInstance -> MonsterAttributes -> MonsterInstance
setAttributes (MonsterInstance mon _) newAttrs = MonsterInstance mon newAttrs
class ElberethQueryable a where
respectsElbereth :: a -> Bool
instance ElberethQueryable MonsterInstance where
respectsElbereth (MonsterInstance mon _) = respectsElbereth mon
instance ElberethQueryable MD.Monster where
respectsElbereth mon
| tunedMoSymbol mon == '@' = False
| tunedMoSymbol mon == 'A' = False
| B.unpack (MD.moName mon) == "minotaur" = False
| B.unpack (MD.moName mon) == "shopkeeper" = False
| B.unpack (MD.moName mon) == "Death" = False
| B.unpack (MD.moName mon) == "Pestilence" = False
| B.unpack (MD.moName mon) == "Famine" = False
| otherwise = True
instance ElberethQueryable ((Int, Int), MonsterInstance) where
respectsElbereth (_, mi) = respectsElbereth mi
|
Noeda/Megaman
|
src/NetHack/Data/MonsterInstance.hs
|
mit
| 5,832 | 0 | 15 | 1,316 | 1,599 | 817 | 782 | 123 | 5 |
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableInstances #-}
{-# OPTIONS_GHC -Wno-missing-pattern-synonym-signatures #-}
module Clingo.Internal.Types
(
IOSym (..),
ClingoSetting (..),
ClingoT(..),
runClingoT,
mapClingoT,
Clingo,
runClingo,
liftC,
askC,
mkClingo,
freeClingo,
Signed (..),
Symbol (..),
Signature (..),
Literal (..),
WeightedLiteral (..),
rawWeightedLiteral,
fromRawWeightedLiteral,
ExternalType (..),
rawExtT,
fromRawExtT,
HeuristicType (..),
rawHeuT,
fromRawHeuT,
negateLiteral,
AspifLiteral (..),
Atom (..),
Model (..),
Location (..),
rawLocation,
freeRawLocation,
fromRawLocation,
SolveResult (..),
rawSolveResult,
fromRawSolveResult,
SolveMode (..),
fromRawSolveMode,
pattern SolveModeAsync,
pattern SolveModeYield,
Solver (..),
exhausted,
wrapCBLogger,
Statistics (..),
ProgramBuilder (..),
Configuration (..),
Backend (..),
SymbolicAtoms (..),
TheoryAtoms (..),
TruthValue (..),
pattern TruthFree,
pattern TruthFalse,
pattern TruthTrue,
negateTruth,
IOPropagator (..),
rawPropagator,
PropagateCtrl (..),
PropagateInit (..),
AMVTree (..)
)
where
import Control.DeepSeq
import Control.Applicative
import Control.Monad.Catch
import Control.Monad.Except
import Control.Monad.Fail
import Control.Monad.IO.Class
import Control.Monad.Reader
import Control.Monad.State
import Control.Monad.Writer
import Data.Text (Text, pack)
import Data.Bits
import Data.Hashable
import Foreign
import Foreign.C
import GHC.Generics
import qualified Clingo.Raw as Raw
import Clingo.Internal.Utils
import Numeric.Natural
-- | A monad that serves as witness that data registered with a running solver
-- still exists and can be used.
newtype IOSym s a = IOSym { iosym :: IO a }
deriving (Functor, Applicative, Monad, MonadMask, MonadThrow
, MonadCatch, MonadIO, MonadFix, MonadPlus, MonadFail, Alternative )
-- | The 'Clingo' monad provides a base monad for computations utilizing the
-- clingo answer set solver. It uses an additional type parameter to ensure that
-- values that are managed by the solver can not leave scope.
newtype ClingoT m s a = Clingo { clingo :: ReaderT Raw.Control m a }
deriving (Functor, Applicative, Monad, MonadMask, MonadThrow
, MonadCatch, MonadIO, MonadFix, MonadPlus, MonadFail, Alternative)
mapClingoT :: (m a -> n b) -> ClingoT m s a -> ClingoT n s b
mapClingoT f (Clingo k) = Clingo (mapReaderT f k)
type Clingo s a = ClingoT IO s a
instance MonadState st m => MonadState st (ClingoT m s) where
get = liftC get
put = liftC . put
state = liftC . state
instance MonadError e m => MonadError e (ClingoT m s) where
throwError = liftC . throwError
catchError (Clingo k) f = Clingo $ catchError k (clingo <$> f)
instance MonadReader r m => MonadReader r (ClingoT m s) where
ask = liftC ask
local f (Clingo (ReaderT k)) = Clingo (ReaderT $ \ctrl -> local f (k ctrl))
instance MonadWriter w m => MonadWriter w (ClingoT m s) where
writer = liftC . writer
listen (Clingo k) = Clingo (listen k)
pass (Clingo k) = Clingo (pass k)
-- | Run a clingo computation from an explicit handle. The handle must be
-- cleaned up manually afterwards, or on failure!
runClingoT :: Raw.Control -> ClingoT m s a -> m a
runClingoT ctrl a = runReaderT (clingo a) ctrl
runClingo :: Raw.Control -> Clingo s a -> IO a
runClingo ctrl k = runClingoT ctrl k
-- | A version of 'lift' for 'ClingoT'. Due to the additional @s@ parameter,
-- which must occur after the @m@ to define 'MonadSymbol' and 'MonadModel'
-- instances, 'ClingoT' cannot implement 'MonadTrans'.
liftC :: Monad m => m a -> ClingoT m s a
liftC k = Clingo (lift k)
{-# INLINE liftC #-}
-- | Get the control handle from the 'Clingo' monad. Arbitrarily unsafe things
-- can be done with this!
askC :: Monad m => ClingoT m s Raw.Control
askC = Clingo ask
-- | Data type to encapsulate the settings for clingo.
data ClingoSetting = ClingoSetting
{ clingoArgs :: [String]
, clingoLogger :: Maybe (ClingoWarning -> Text -> IO ())
, msgLimit :: Natural }
-- | Wrapper function to create a raw handle. Arbitrarily unsafe things can be
-- done with this! Note that the handle must be freed after you are done with it!
mkClingo :: MonadIO m => ClingoSetting -> m Raw.Control
mkClingo settings = liftIO $ do
let argc = length (clingoArgs settings)
argv <- liftIO $ mapM newCString (clingoArgs settings)
ctrl <- marshal1 $ \x ->
withArray argv $ \argvArr -> do
logCB <- maybe (pure nullFunPtr) wrapCBLogger
(clingoLogger settings)
let argv' = case clingoArgs settings of
[] -> nullPtr
_ -> argvArr
Raw.controlNew argv' (fromIntegral argc)
logCB nullPtr (fromIntegral . msgLimit $ settings) x
liftIO $ mapM_ free argv
pure ctrl
freeClingo :: MonadIO m => Raw.Control -> m ()
freeClingo = Raw.controlFree
data Symbol s = Symbol
{ rawSymbol :: Raw.Symbol
, symType :: Raw.SymbolType
, symHash :: Integer
, symNum :: Maybe Integer
, symName :: Maybe Text
, symString :: Maybe Text
, symArgs :: [Symbol s]
, symPretty :: Text
}
deriving (Generic)
instance NFData (Symbol s)
instance Eq (Symbol s) where
a == b = toBool (Raw.symbolIsEqualTo (rawSymbol a) (rawSymbol b))
instance Ord (Symbol s) where
a <= b = toBool (Raw.symbolIsLessThan (rawSymbol a) (rawSymbol b))
instance Hashable (Symbol s) where
hashWithSalt s sym = hashWithSalt s (symHash sym)
class Signed a where
positive :: a -> Bool
positive = not . negative
negative :: a -> Bool
negative = not . positive
instance Signed Bool where
positive x = x
data Signature s = Signature
{ rawSignature :: Raw.Signature
, sigArity :: Natural
, sigName :: Text
, sigHash :: Integer
}
instance Eq (Signature s) where
a == b = toBool (Raw.signatureIsEqualTo (rawSignature a) (rawSignature b))
instance Ord (Signature s) where
a <= b = toBool (Raw.signatureIsLessThan (rawSignature a) (rawSignature b))
instance Signed (Signature s) where
positive = toBool . Raw.signatureIsPositive . rawSignature
negative = toBool . Raw.signatureIsNegative . rawSignature
instance Hashable (Signature s) where
hashWithSalt s sig = hashWithSalt s (sigHash sig)
newtype Literal s = Literal { rawLiteral :: Raw.Literal }
deriving (Ord, Show, Eq, NFData, Generic)
instance Hashable (Literal s)
instance Signed (Literal s) where
positive = (> 0) . rawLiteral
negative = (< 0) . rawLiteral
data WeightedLiteral s = WeightedLiteral (Literal s) Integer
deriving (Eq, Show, Ord, Generic)
instance Hashable (WeightedLiteral s)
instance NFData (WeightedLiteral s)
rawWeightedLiteral :: WeightedLiteral s -> Raw.WeightedLiteral
rawWeightedLiteral (WeightedLiteral l w) =
Raw.WeightedLiteral (rawLiteral l) (fromIntegral w)
fromRawWeightedLiteral :: Raw.WeightedLiteral -> WeightedLiteral s
fromRawWeightedLiteral (Raw.WeightedLiteral l w) =
WeightedLiteral (Literal l) (fromIntegral w)
data ExternalType = ExtFree | ExtTrue | ExtFalse | ExtRelease
deriving (Show, Eq, Ord, Enum, Read, Generic)
instance Hashable ExternalType
rawExtT :: ExternalType -> Raw.ExternalType
rawExtT ExtFree = Raw.ExternalFree
rawExtT ExtTrue = Raw.ExternalTrue
rawExtT ExtFalse = Raw.ExternalFalse
rawExtT ExtRelease = Raw.ExternalRelease
fromRawExtT :: Raw.ExternalType -> ExternalType
fromRawExtT Raw.ExternalFree = ExtFree
fromRawExtT Raw.ExternalTrue = ExtTrue
fromRawExtT Raw.ExternalFalse = ExtFalse
fromRawExtT Raw.ExternalRelease = ExtRelease
fromRawExtT _ = error "unknown external_type"
data HeuristicType = HeuristicLevel | HeuristicSign | HeuristicFactor
| HeuristicInit | HeuristicTrue | HeuristicFalse
deriving (Show, Eq, Ord, Enum, Read, Generic)
instance Hashable HeuristicType
rawHeuT :: HeuristicType -> Raw.HeuristicType
rawHeuT HeuristicLevel = Raw.HeuristicLevel
rawHeuT HeuristicSign = Raw.HeuristicSign
rawHeuT HeuristicFactor = Raw.HeuristicFactor
rawHeuT HeuristicInit = Raw.HeuristicInit
rawHeuT HeuristicTrue = Raw.HeuristicTrue
rawHeuT HeuristicFalse = Raw.HeuristicFalse
fromRawHeuT :: Raw.HeuristicType -> HeuristicType
fromRawHeuT Raw.HeuristicLevel = HeuristicLevel
fromRawHeuT Raw.HeuristicSign = HeuristicSign
fromRawHeuT Raw.HeuristicFactor = HeuristicFactor
fromRawHeuT Raw.HeuristicInit = HeuristicInit
fromRawHeuT Raw.HeuristicTrue = HeuristicTrue
fromRawHeuT Raw.HeuristicFalse = HeuristicFalse
fromRawHeuT _ = error "unknown heuristic_type"
negateLiteral :: Literal s -> Literal s
negateLiteral (Literal a) = Literal (negate a)
newtype AspifLiteral s = AspifLiteral { rawAspifLiteral :: Raw.Literal }
deriving (Ord, Show, Eq, NFData, Generic)
instance Hashable (AspifLiteral s)
instance Signed (AspifLiteral s) where
positive = (> 0) . rawAspifLiteral
negative = (< 0) . rawAspifLiteral
newtype Atom s = Atom { rawAtom :: Raw.Atom }
deriving (Show, Ord, Eq, NFData, Generic)
instance Hashable (Atom s)
newtype Model s = Model Raw.Model
data Location = Location
{ locBeginFile :: FilePath
, locEndFile :: FilePath
, locBeginLine :: Natural
, locEndLine :: Natural
, locBeginCol :: Natural
, locEndCol :: Natural }
deriving (Eq, Show, Ord)
rawLocation :: Location -> IO Raw.Location
rawLocation l = Raw.Location
<$> newCString (locBeginFile l)
<*> newCString (locEndFile l)
<*> pure (fromIntegral (locBeginLine l))
<*> pure (fromIntegral (locEndLine l))
<*> pure (fromIntegral (locBeginCol l))
<*> pure (fromIntegral (locEndCol l))
freeRawLocation :: Raw.Location -> IO ()
freeRawLocation l = do
free (Raw.locBeginFile l)
free (Raw.locEndFile l)
fromRawLocation :: Raw.Location -> IO Location
fromRawLocation l = Location
<$> peekCString (Raw.locBeginFile l)
<*> peekCString (Raw.locEndFile l)
<*> pure (fromIntegral . Raw.locBeginLine $ l)
<*> pure (fromIntegral . Raw.locEndLine $ l)
<*> pure (fromIntegral . Raw.locBeginCol $ l)
<*> pure (fromIntegral . Raw.locEndCol $ l)
data SolveResult = Satisfiable Bool | Unsatisfiable Bool | Interrupted
deriving (Eq, Show, Read, Generic)
instance NFData SolveResult
instance Hashable SolveResult
exhausted :: SolveResult -> Bool
exhausted (Satisfiable b) = b
exhausted (Unsatisfiable b) = b
exhausted _ = False
rawSolveResult :: SolveResult -> Raw.SolveResult
rawSolveResult (Satisfiable e) =
Raw.ResultSatisfiable .|. if e then Raw.ResultExhausted else zeroBits
rawSolveResult (Unsatisfiable e) =
Raw.ResultUnsatisfiable .|. if e then Raw.ResultExhausted else zeroBits
rawSolveResult Interrupted = Raw.ResultInterrupted
fromRawSolveResult :: Raw.SolveResult -> SolveResult
fromRawSolveResult r
| r == Raw.ResultSatisfiable .|. Raw.ResultExhausted = Satisfiable True
| r == Raw.ResultSatisfiable = Satisfiable False
| r == Raw.ResultUnsatisfiable .|. Raw.ResultExhausted = Unsatisfiable True
| r == Raw.ResultUnsatisfiable = Unsatisfiable False
| r == Raw.ResultInterrupted = Interrupted
| otherwise = error "Malformed clingo_solve_result_bitset_t"
newtype SolveMode = SolveMode { rawSolveMode :: Raw.SolveMode }
deriving (Eq, Show, Read, Ord)
fromRawSolveMode :: Raw.SolveMode -> SolveMode
fromRawSolveMode = SolveMode
newtype Solver s = Solver Raw.SolveHandle
pattern SolveModeAsync = SolveMode Raw.SolveModeAsync
pattern SolveModeYield = SolveMode Raw.SolveModeYield
wrapCBLogger :: MonadIO m
=> (ClingoWarning -> Text -> IO ())
-> m (FunPtr (Raw.Logger ()))
wrapCBLogger f = liftIO $ Raw.mkCallbackLogger go
where go :: Raw.ClingoWarning -> CString -> Ptr () -> IO ()
go w str _ = peekCString str >>= \cstr ->
f (ClingoWarning w) (pack cstr)
newtype Statistics s = Statistics Raw.Statistics
newtype ProgramBuilder s = ProgramBuilder Raw.ProgramBuilder
newtype Configuration s = Configuration Raw.Configuration
newtype Backend s = Backend Raw.Backend
newtype SymbolicAtoms s = SymbolicAtoms Raw.SymbolicAtoms
newtype TheoryAtoms s = TheoryAtoms Raw.TheoryAtoms
newtype TruthValue = TruthValue { rawTruthValue :: Raw.TruthValue }
deriving (Eq, Show, Ord)
pattern TruthFree = TruthValue Raw.TruthFree
pattern TruthFalse = TruthValue Raw.TruthFalse
pattern TruthTrue = TruthValue Raw.TruthTrue
negateTruth :: TruthValue -> TruthValue
negateTruth TruthFree = TruthFree
negateTruth TruthTrue = TruthFalse
negateTruth TruthFalse = TruthTrue
negateTruth _ = error "negateTruth: Invalid TruthValue"
data IOPropagator s = IOPropagator
{ propagatorInit :: Maybe (PropagateInit s -> IO ())
, propagatorPropagate :: Maybe (PropagateCtrl s -> [Literal s] -> IO ())
, propagatorUndo :: Maybe (PropagateCtrl s -> [Literal s] -> IO ())
, propagatorCheck :: Maybe (PropagateCtrl s -> IO ())
}
rawPropagator :: MonadIO m => IOPropagator s -> m (Raw.Propagator ())
rawPropagator p = Raw.Propagator <$> wrapCBInit (propagatorInit p)
<*> wrapCBProp (propagatorPropagate p)
<*> wrapCBUndo (propagatorUndo p)
<*> wrapCBCheck (propagatorCheck p)
wrapCBInit :: MonadIO m
=> Maybe (PropagateInit s -> IO ())
-> m (FunPtr (Raw.CallbackPropagatorInit ()))
wrapCBInit Nothing = pure nullFunPtr
wrapCBInit (Just f) = liftIO $ Raw.mkCallbackPropagatorInit go
where go :: Raw.PropagateInit -> Ptr () -> IO Raw.CBool
go c _ = reraiseIO $ f (PropagateInit c)
wrapCBProp :: MonadIO m
=> Maybe (PropagateCtrl s -> [Literal s] -> IO ())
-> m (FunPtr (Raw.CallbackPropagatorPropagate ()))
wrapCBProp Nothing = pure nullFunPtr
wrapCBProp (Just f) = liftIO $ Raw.mkCallbackPropagatorPropagate go
where go :: Raw.PropagateControl -> Ptr Raw.Literal -> CSize -> Ptr ()
-> IO Raw.CBool
go c lits len _ =
reraiseIO $ do
ls <- map Literal <$> peekArray (fromIntegral len) lits
f (PropagateCtrl c) ls
wrapCBUndo :: MonadIO m
=> Maybe (PropagateCtrl s -> [Literal s] -> IO ())
-> m (FunPtr (Raw.CallbackPropagatorUndo ()))
wrapCBUndo = wrapCBProp
wrapCBCheck :: MonadIO m
=> Maybe (PropagateCtrl s -> IO ())
-> m (FunPtr (Raw.CallbackPropagatorCheck ()))
wrapCBCheck Nothing = pure nullFunPtr
wrapCBCheck (Just f) = liftIO $ Raw.mkCallbackPropagatorCheck go
where go :: Raw.PropagateControl -> Ptr () -> IO Raw.CBool
go c _ = reraiseIO $ f (PropagateCtrl c)
newtype PropagateCtrl s = PropagateCtrl Raw.PropagateControl
newtype PropagateInit s = PropagateInit Raw.PropagateInit
class AMVTree t where
atArray :: Int -> t v -> Maybe (t v)
atMap :: Text -> t v -> Maybe (t v)
value :: t v -> Maybe v
|
tsahyt/clingo-haskell
|
src/Clingo/Internal/Types.hs
|
mit
| 15,418 | 0 | 21 | 3,350 | 4,644 | 2,436 | 2,208 | 363 | 3 |
{-# LANGUAGE OverloadedStrings #-}
import System.IO
import System.Environment
import System.Process
import Control.Monad
import Control.Concurrent.Async
import qualified Data.ByteString as B
splitSize = 20 * 1024 * 1024 -- 128 Mega Bytes
download :: String -> String -> IO ()
download url fname = do
system $ "curl -sI " ++ url ++
" | awk '/Content-Length/ { print $2 }' > /tmp/hacurl"
fileSize <- fmap (read) $ readFile $ "/tmp/hacurl" :: IO Int
putStrLn $ "Filesize: " ++ show fileSize
let splits = ((fromIntegral fileSize) / (fromIntegral splitSize))
rs = ceiling splits
putStrLn $ "Number of splits: " ++ (show rs)
mapConcurrently (\x -> download' url x fileSize fname) [1..rs]
combine rs fname
download' :: String -> Int -> Int -> String -> IO ()
download' url n tot fname = do
system $ "curl -s -o \"" ++ fname ++ "." ++ (show n) ++
"\" --range " ++ start ++ "-" ++ end ++ " " ++ url
return ()
where
start = show $ (n - 1) * splitSize
end = let size = (n * splitSize - 1)
in show $ if size > tot then tot else size
combine :: Int -> String -> IO ()
combine n fname = do
let xs = map (\x -> aux x) [1..n]
all <- foldr (aux') (return "") xs
B.writeFile fname all
where aux x = B.readFile $ fname ++ "." ++ (show x)
aux' :: IO B.ByteString -> IO B.ByteString -> IO B.ByteString
aux' s1 s2 = liftM2 B.append s1 s2
main = do
ar <- fmap head $ getArgs
let fileName = reverse $ takeWhile (/= '/') $ reverse ar
download ar fileName
|
hlambda/Downloader
|
down.hs
|
gpl-2.0
| 1,560 | 1 | 16 | 407 | 612 | 303 | 309 | 39 | 2 |
{-# LANGUAGE DeriveDataTypeable #-}
module Keystone.Web.Role.Types
where
import Data.Data (Typeable)
data RoleCreateRequest = RoleCreateRequest
{ description :: Maybe String
, name :: String
, enabled :: Maybe Bool
} deriving (Show, Read, Eq, Ord, Typeable)
|
VictorDenisov/keystone
|
src/Keystone/Web/Role/Types.hs
|
gpl-2.0
| 375 | 0 | 9 | 152 | 75 | 44 | 31 | 8 | 0 |
module Main where
import Counting (sumToN)
main :: IO ()
main =
let
numbers = [1..100]
squares = map (^2) numbers
squareSum = (sumToN 100)^2
sumSquares = sum squares
in
print $ squareSum - sumSquares
|
liefswanson/projectEuler
|
app/p1/q6/Main.hs
|
gpl-2.0
| 250 | 0 | 11 | 85 | 88 | 48 | 40 | 10 | 1 |
module Tests.GADTHigherOrder where
import QFeldspar.MyPrelude
import QFeldspar.Expression.GADTHigherOrder
import QFeldspar.Variable.Typed
import QFeldspar.Conversion as E
import QFeldspar.Expression.Conversions.Evaluation.GADTHigherOrder ()
import qualified QFeldspar.Expression.GADTValue as FGV
import QFeldspar.Type.GADT hiding (Int)
import QFeldspar.Environment.Typed
dbl :: Exp '[Word32 -> Word32 -> Word32] (Word32 -> Word32)
dbl = Abs (\ x -> Prm Zro (x `Ext` (x `Ext` Emp)))
compose :: (Type ta , Type tb , Type tc) =>
Exp r ((tb -> tc) -> ((ta -> tb) -> (ta -> tc)))
compose = Abs (\ g -> Abs (\ f -> Abs
(\ x -> App g (App f x))))
four :: Exp '[Word32 -> Word32 -> Word32] Word32
four = App (App (App compose dbl) dbl) (Int 1)
test :: Bool
test = case runNamM (cnv ( four
, Ext (FGV.Exp (+)
:: FGV.Exp (Word32 -> Word32 -> Word32))
Emp)) of
Rgt (FGV.Exp x) -> x == 4
Lft _ -> False
|
shayan-najd/QFeldspar
|
Tests/GADTHigherOrder.hs
|
gpl-3.0
| 999 | 0 | 16 | 255 | 402 | 225 | 177 | -1 | -1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- SJC: is it possible to move this to the prototype part of ampersand? I mean,
-- do functions like plugFields and plug-path really need to be here?
-- perhaps we can at least move the largest part?
module Database.Design.Ampersand.FSpec.Plug
(Plugable(..), PlugInfo(..)
,SqlField(..)
,SqlFieldUsage(..)
,SqlType(..)
,showSQL
,plugpath
,tblcontents
,fldauto
,PlugSQL(..)
)
where
import Database.Design.Ampersand.ADL1
import Database.Design.Ampersand.Classes (fullContents,atomsOf,Relational(..))
import Database.Design.Ampersand.Basics
import Data.List
import GHC.Exts (sortWith)
import Database.Design.Ampersand.FSpec.FSpec
import Prelude hiding (Ordering(..))
fatal :: Int -> String -> a
fatal = fatalMsg "FSpec.Plug"
----------------------------------------------
--Plug
----------------------------------------------
--TODO151210 -> define what a plug is and what it should do
--Plugs are of the class Object just like Activities(??? => PHP plug isn't an instance of Object)
--An Object is an entity to do things with like reading, updating, creating,deleting.
--A Interface is an Object using only Plugs for reading and writing data; a Plug is a data service maintaining the rules for one object:
-- + GEN Interface,Plug ISA Object
-- + cando::Operation*Object
-- + uses::Interface*Plug [TOT].
-- + maintains::Plug*Rule.
-- + signals::Interface*SignalRule.
--
--Plugs can currently be implemented in PHP or SQL.
--type Plugs = [Plug]
--data Plug = PlugSql PlugSQL | PlugPhp PlugPHP deriving (Show,Eq)
class (Named p, Eq p, Show p) => Plugable p where
makePlug :: PlugInfo -> p
instance Plugable PlugSQL where
makePlug (InternalPlug p) = p
makePlug (ExternalPlug _) = fatal 112 "external plug is not Plugable"
----------------------------------------------
--PlugSQL
----------------------------------------------
--TblSQL, BinSQL, and ScalarSQL hold different entities. See their definition FSpec.hs
-- all kernel fields can be related to an imaginary concept ID for the plug (a SqlField with type=SQLID)
-- i.e. For all kernel fields k1,k2, where concept k1=A, concept k2=B, fldexpr k1=r~, fldexpr k2=s~
-- You can imagine :
-- - a relation value::ID->A[INJ] or value::ID->A[INJ,SUR]
-- - a relation value::ID->B[INJ] or value::ID->B[INJ,SUR]
-- such that s~=value~;value;r~ and r~=value~;value;s~
-- because value is at least uni,tot,inj, all NULL in k0 imply NULL in k1 xor v.v.
-- if value also sur then all NULL in k0 imply NULL in k1 and v.v.
-- Without such an ID, the surjective or total property between any two kernel fields is required.
-- Because you can imagine an ID concept the surjective or total property between two kernel field has become a design choice.
--
-- With or without ID we choose to keep kernel = A closure of concepts A,B for which there exists a r::A->B[INJ] instead of r::A*B[UNI,INJ]
-- By making this choice:
-- - nice database table size
-- - we do not need the imaginary concept ID (and relation value::ID->A[INJ] or value::ID->A[INJ,SUR]), because:
-- with ID -> there will always be one or more kernel field k1 such that (value;(fldexpr k1)~)[UNI,INJ,TOT,SUR].
-- any of those k1 can serve as ID of the plug (a.k.a. concept p / source p)
-- without ID -> any of those k1 can still serve as ID of the plug (a.k.a. concept p / source p)
-- In other words, the imaginary concept is never needed
-- because there always is an existing one with the correct properties by definition of kernel.
-- Implementation without optional ID:
-- -> fldexpr of some kernel field k1 will be r~
-- k1 holds the target of r~
-- the source of r~ is a kernel concept too
-- r~ may be I
-- -> fldexpr of some attMor field a1 will be s
-- a1 holds the target of s
-- the source of s is a kernel concept
-- -> sqlRelFields r = (r,k1,a1) (or (r,k1,k2)) in mLkpTbl
-- is used to generate SQL code and PHP-objects without needing the ID field.
-- The ID field can be ignored and does not have to be generated because r=(fldexpr k1)~;(fldexpr a1)
-- You could generate the ID-field with autonum if you want, because it will not be used
-- -> TODO151210 -> sqlRelFields e where e is not in mLkpTbl
-- option1) Generate the ID field (see entityfield)
-- sqlRelFields e = (e, idfld;k1, idfld;a1) where e=(fldexpr k1)~;value~;value;(fldexpr a1)
-- remark: binary tables can be binary tables without kernels, but with ID field
-- (or from a different perspective: ID is the only kernel field)
-- sqlRelFields r = (r,idfld/\r;r~,idfld;m1) where r = (idfld/\r;r~)~;idfld;(fldexpr m1)
-- (sqlRelFields r~ to get the target of r)
-- (scalar tables can of course also have an ID field)
-- option2) sqlRelFields e = (e, k1;k2;..kn, a1)
-- where e=(fldexpr kn)~;..;(fldexpr k2)~;(fldexpr k1)~;(fldexpr k1)(fldexpr k2);..;(fldexpr kn);(fldexpr a1)
-- If I am right the function isTrue tries to support sqlRelFields e by ignoring the type error in kn;a1.
-- That is wrong!
--the entityfield is not implemented as part of the data type PlugSQL
--It is a constant which may or may not be used (you may always imagine it)
--TODO151210 -> generate the entityfield if options = --autoid -p
--REMARK151210 -> one would expect I[entityconcept p],
-- but any p (as instance of Object) has one always existing concept p suitable to replace entityconcept p.
-- concept p and entityconcept p are related uni,tot,inj,sur.
--the entity stored in a plug is an imaginary concept, that is uni,tot,inj,sur with (concept p)
--REMARK: there is a (concept p) because all kernel fields are related SUR with (concept p)
--Maintain rule: Object ObjectDef = Object (makeUserDefinedSqlPlug :: ObjectDef -> PlugSQL)
--TODO151210 -> Build a check which checks this rule for userdefined/showADL generated plugs(::[ObjectDef])
--TODO151210 -> The ObjectDef of a BinSQL plug for relation r is that:
-- 1) SQLPLUG mybinplug: r , or
-- 2) SQLPLUG labelforsourcem : I /\ r;r~ --(or just I if r is TOT)
-- = [labelfortargetm : r]
-- The first option has been implemented in instance ObjectPlugSQL i.e. attributes=[], ctx=ERel r _
instance Object PlugSQL where
concept p = case p of
TblSQL{mLkpTbl = []} -> fatal 263 $ "empty lookup table for plug "++name p++"."
TblSQL{} -> --TODO151210-> deze functieimplementatie zou beter moeten matchen met onderstaande beschrijving
-- nu wordt aangenomen dat de source van het 1e rel in mLkpTbl de source van de plug is.
--a relation between kernel concepts r::A*B is at least [UNI,INJ]
--to be able to point out one concept to be the source we are looking for one without NULLs in its field
-- i.e. there is a concept A such that
-- for all kernel field expr (s~)::B*C[UNI,INJ]:
-- s~ is total and there exists an expr::A*B[UNI,INJ,TOT,SUR] (possibly A=B => I[A][UNI,INJ,TOT,SUR])
--If A is such a concept,
-- and A is not B,
-- and there exist an expr::A*B[UNI,INJ,TOT,SUR]
--then (concept PlugSQL{}) may be A or B
--REMARK -> (source p) used to be implemented as (source . fldexpr . head . fields) p. That is different!
head [source r |(r,_,_)<-mLkpTbl p]
BinSQL{} -> source (mLkp p) --REMARK151210 -> the concept is actually ID such that I[ID]=I[source r]/\r;r~
ScalarSQL{} -> cLkp p
-- Usually source a==concept p. Otherwise, the attribute computation is somewhat more complicated. See ADL2FSpec for explanation about kernels.
attributes p@TblSQL{}
= [ Obj (fldname tFld) -- objnm
(Origin "This object is generated by attributes (Object PlugSQL)") -- objpos
(if source a==concept p then a else f (source a) [[a]]) -- objctx
Nothing
Nothing
[] -- objats and objstrs
| (a,_,tFld)<-mLkpTbl p]
where
f c mms
= case sortWith length stop of
[] -> f c mms' -- a path from c to a is not found (yet), so add another step to the recursion
(hd:_) -> case hd of
[] -> fatal 201 "Empty head should be impossible."
_ -> case [(l,r) | (l,r)<-zip (init hd) (tail hd), target l/=source r] of
[] -> foldr1 (.:.) hd -- pick the shortest path and turn it into an expression.
lrs -> fatal 204 ("illegal compositions " ++show lrs)
where
mms' = if [] `elem` mms
then fatal 295 "null in mms."
else [a:ms | ms<-mms, (a,_,_)<-mLkpTbl p, target a==source (head ms)]
stop = if [] `elem` mms'
then fatal 298 "null in mms'."
else [ms | ms<-mms', source (head ms)==c] -- contains all found paths from c to a
attributes _ = [] --no attributes for BinSQL and ScalarSQL
contextOf p@BinSQL{} = mLkp p
contextOf p = EDcI (concept p)
fldauto::SqlField->Bool -- is the field auto increment?
fldauto f = (fldtype f==SQLId) && not (fldnull f) && flduniq f -- && isIdent (fldexpr f)
showSQL :: SqlType -> String
showSQL (SQLChar n) = "CHAR("++show n++")"
showSQL (SQLBlob ) = "BLOB"
showSQL (SQLPass ) = "VARCHAR(255)"
showSQL (SQLSingle ) = "FLOAT" -- todo
showSQL (SQLDouble ) = "FLOAT"
showSQL (SQLText ) = "TEXT"
showSQL (SQLuInt n) = "INT("++show n++") UNSIGNED"
showSQL (SQLsInt n) = "INT("++show n++")"
showSQL (SQLId ) = "INT"
showSQL (SQLVarchar n) = "VARCHAR("++show n++")"
showSQL (SQLBool ) = "BOOLEAN"
-- Every kernel field is a key, kernel fields are in cLkpTbl or the column of ScalarSQL (which has one column only)
-- isPlugIndex refers to UNIQUE key -- TODO: this is wrong
--isPlugIndex may contain NULL, but their key (the entityfield of the plug) must be unique for a kernel field (isPlugIndex=True)
--the field that is isIdent and isPlugIndex (i.e. concept plug), or any similar (uni,inj,sur,tot) field is also UNIQUE key
--IdentityDefs define UNIQUE key (fld1,fld2,..,fldn)
--REMARK -> a kernel field does not have to be in cLkpTbl, in that cast there is another kernel field that is
-- thus I must check whether fldexpr isUni && isInj && isSur
isPlugIndex :: PlugSQL->SqlField->Bool
isPlugIndex plug f =
case plug of
ScalarSQL{} -> sqlColumn plug==f
BinSQL{} --mLkp is not uni or inj by definition of BinSQL, if mLkp total then the (fldexpr srcfld)=I/\r;r~=I i.e. a key for this plug
| isUni(mLkp plug) || isInj(mLkp plug) -> fatal 366 "BinSQL may not store a univalent or injective rel, use TblSQL instead."
| otherwise -> False --binary does not have key, but I could do a SELECT DISTINCT iff f==fst(columns plug) && (isTot(mLkp plug))
TblSQL{} -> elem f (fields plug) && isUni(fldexpr f) && isInj(fldexpr f) && isSur(fldexpr f)
composeCheck :: Expression -> Expression -> Expression
composeCheck l r
= if target l/=source r then fatal 316 ("\nl: "++show l++"with target "++show (target l)++"\nl: "++show r++"with source "++show (source r)) else
l .:. r
--composition from srcfld to trgfld, if there is an expression for that
plugpath :: PlugSQL -> SqlField -> SqlField -> Maybe Expression
plugpath p srcfld trgfld =
case p of
BinSQL{}
| srcfld==trgfld -> let tm=mLkp p --(note: mLkp p is the relation from fst to snd column of BinSQL)
in if srcfld==fst(columns p)
then Just$ tm .:. flp tm --domain of r
else Just$ flp tm .:. tm --codomain of r
| srcfld==fst(columns p) && trgfld==snd(columns p) -> Just$ fldexpr trgfld
| trgfld==fst(columns p) && srcfld==snd(columns p) -> Just$ flp(fldexpr srcfld)
| otherwise -> fatal 444 $ "BinSQL has only two fields:"++show(fldname srcfld,fldname trgfld,name p)
ScalarSQL{}
| srcfld==trgfld -> Just$ fldexpr trgfld
| otherwise -> fatal 447 $ "scalarSQL has only one field:"++show(fldname srcfld,fldname trgfld,name p)
TblSQL{}
| srcfld==trgfld && isPlugIndex p trgfld -> Just$ EDcI (target (fldexpr trgfld))
| srcfld==trgfld && not(isPlugIndex p trgfld) -> Just$ composeCheck (flp (fldexpr srcfld)) (fldexpr trgfld) --codomain of r of morAtt
| (not . null) (paths srcfld trgfld)
-> case head (paths srcfld trgfld) of
[] -> fatal 338 ("Empty head (paths srcfld trgfld) should be impossible.")
ps -> Just$ foldr1 composeCheck ps
--bijective kernel fields, which are bijective with ID of plug have fldexpr=I[X].
--thus, path closures of these kernel fields are disjoint (path closure=set of fields reachable by paths),
-- because these kernel fields connect to themselves by r=I[X] (i.e. end of path).
--connect two paths over I[X] (I[X];srce)~;(I[X];trge) => filter I[X] => srcpath~;trgpath
| (not.null) (pathsoverIs srcfld trgfld) -> Just$ foldr1 composeCheck (head (pathsoverIs srcfld trgfld))
| (not.null) (pathsoverIs trgfld srcfld) -> Just$ flp (foldr1 composeCheck (head (pathsoverIs trgfld srcfld)))
| otherwise -> Nothing
--paths from s to t by connecting r from mLkpTbl
--the (r,srcfld,trgfld) from mLkpTbl form paths longer paths if connected: (trgfld m1==srcfld m2) => (m1;m2,srcfld m1,trgfld m2)
where
paths s t = [e |(e,es,et)<-eLkpTbl p,s==es,t==et]
--paths from I to field t
pathsfromIs t = [(e,es,et) |(e,es,et)<-eLkpTbl p,et==t,not (null e),isIdent(head e)]
--paths from s to t over I[X]
pathsoverIs s t = [flpsrce++tail trge
|(srce,srces,_)<-pathsfromIs s
,(trge,trges,_)<-pathsfromIs t
,srces==trges, let flpsrce = (map flp.reverse.tail) srce]
--the expression LkpTbl of a plug is the transitive closure of the mLkpTbl of the plug
--Warshall's transitive closure algorithm clos1 :: (Eq a) => [(a,a)] -> [(a,a)] is extended to combine paths i.e. r++r'
--[Expression] implies a 'composition' from a kernel SqlField to another SqlField
--use plugpath to get the Expression from srcfld to trgfld
--plugpath also combines expressions with head I like (I;tail1)~;(I;tail2) <=> tail1;tail2
eLkpTbl::PlugSQL -> [([Expression],SqlField,SqlField)]
eLkpTbl p = clos1 [([r],s,t)|(r,s,t)<-mLkpTbl p]
where
clos1 :: [([Expression],SqlField,SqlField)] -> [([Expression],SqlField,SqlField)] -- e.g. a list of SqlField pairs
clos1 xs
= foldl f xs (nub (map (\(_,x,_)->x) xs) `isc` nub (map (\(_,_,x)->x) xs))
where
f q x = q `uni` [( r++r' , a, b') | (r ,a, b) <- q, b == x, (r', a', b') <- q, a' == x]
-- | tblcontents is meant to compute the contents of an entity table.
-- It yields a list of records. Values in the records may be absent, which is why Maybe String is used rather than String.
type TblRecord = [Maybe String]
tblcontents :: [A_Gen] -> [Population] -> PlugSQL -> [TblRecord]
tblcontents gs udp plug
= case plug of
ScalarSQL{} -> [[Just x] | x<-atomsOf gs udp (cLkp plug)]
BinSQL{} -> [[(Just . srcPaire) p,(Just . trgPaire) p] |p<-fullContents gs udp (mLkp plug)]
TblSQL{} ->
--TODO15122010 -> remove the assumptions (see comment data PlugSQL)
--fields are assumed to be in the order kernel+other,
--where NULL in a kernel field implies NULL in the following kernel fields
--and the first field is unique and not null
--(r,s,t)<-mLkpTbl: s is assumed to be in the kernel, fldexpr t is expected to hold r or (flp r), s and t are assumed to be different
case fields plug of
[] -> fatal 593 "no fields in plug."
f:fs -> transpose
( map Just cAtoms
: [case fExp of
EDcI c -> [ if a `elem` atomsOf gs udp c then Just a else Nothing | a<-cAtoms ]
_ -> [ (lkp a . fullContents gs udp) fExp | a<-cAtoms ]
| fld<-fs, let fExp=fldexpr fld
]
)
where
cAtoms = (atomsOf gs udp . source . fldexpr) f
lkp a pairs
= case [ p | p<-pairs, a==srcPaire p ] of
[] -> Nothing
[p] -> Just (trgPaire p)
ps -> fatal 428 ("(this could happen when using --dev flag, when there are violations)\n"++
"Looking for: '"++a++"'.\n"++
"Multiple values in one field: \n"++
" [ "++intercalate "\n , " (map show ps)++"\n ]")
|
DanielSchiavini/ampersand
|
src/Database/Design/Ampersand/FSpec/Plug.hs
|
gpl-3.0
| 17,884 | 0 | 24 | 5,263 | 3,007 | 1,614 | 1,393 | 143 | 8 |
{-# LANGUAGE DeriveDataTypeable #-}
module Raft.Protocol
( initRaft
, Command(..)
)
where
import Prelude hiding (log)
import System.Random.MWC
import System.Directory
import System.IO
import Control.Concurrent
import Control.Concurrent.MVar
import Control.Monad hiding (forM_)
import Control.Applicative
import Control.Distributed.Process
import Control.Distributed.Process.Node hiding (newLocalNode)
import Control.Distributed.Process.Backend.SimpleLocalnet
import Control.Distributed.Process.Serializable
import Control.Distributed.Process.Internal.Types
import Data.Binary
import Data.Typeable
import Data.List
import Data.Foldable (forM_)
import qualified Data.IntMap.Strict as IntMap
import qualified Data.Map.Strict as Map
-- | Type renaming to make things clearer.
type Term = Int
type Index = Int
type Log a = IntMap.IntMap (LogEntry a)
data ServerRole = Follower | Candidate | Leader deriving (Show, Read, Eq)
-- | Wrapper around state transition rule. Derive Typeable and Binary
-- so that we can serialize it.
newtype Command a = Command a deriving (Show, Read, Eq, Typeable)
instance (Binary a) => Binary (Command a) where
put (Command a) = put a
get = Command <$> get
-- | An entry in a log. Also serializable.
data LogEntry a = LogEntry
{ termReceived :: !Term
, applied :: !Bool
, command :: !(Command a)
} deriving (Show, Read, Eq, Typeable)
instance (Binary a) => Binary (LogEntry a) where
put (LogEntry a b c) = put a >> put b >> put c
get = LogEntry <$> get <*> get <*> get
-- | Data structure for appendEntriesRPC. Is serializable.
data AppendEntriesMsg a = AppendEntriesMsg
{ aeSender :: !ProcessId -- ^ Sender's process id
, aeTerm :: !Term -- ^ Leader's term
, leaderId :: !NodeId -- ^ Leader's Id
, prevLogIndex :: !Index -- ^ Log entry index right before new ones
, prevLogTerm :: !Term -- ^ Term of the previous log entry
, entries :: !(Log a) -- ^ Log entries to store, [] for heartbeat
, leaderCommit :: !Index -- ^ Leader's commit index
} deriving (Show, Eq, Typeable)
instance (Binary a) => Binary (AppendEntriesMsg a) where
put (AppendEntriesMsg a b c d e f g) =
put a >> put b >> put c >> put d >> put e >> put f >> put g
get = AppendEntriesMsg <$> get <*> get <*> get <*> get <*> get <*> get <*> get
-- | Data structure for the response to appendEntriesRPC. Is serializable.
data AppendEntriesResponseMsg = AppendEntriesResponseMsg
{ aerSender :: !ProcessId -- ^ Sender's process id
, aerTerm :: !Term -- ^ Current term to update leader
, aerMatchIndex :: !Index -- ^ Index of highest log entry replicated
, success :: !Bool -- ^ Did follower contain a matching entry?
} deriving (Show, Eq, Typeable)
instance Binary AppendEntriesResponseMsg where
put (AppendEntriesResponseMsg a b c d) = put a >> put b >> put c >> put d
get = AppendEntriesResponseMsg <$> get <*> get <*> get <*> get
-- | Data structure for requestVoteRPC. Is serializable.
data RequestVoteMsg = RequestVoteMsg
{ rvSender :: !ProcessId -- ^ Sender's process id
, rvTerm :: !Term -- ^ Candidate's term
, candidateId :: !NodeId -- ^ Candidate requesting vote
, lastLogIndex :: !Index -- ^ Index of candidate's last log entry
, lastLogTerm :: !Term -- ^ Term of candidate's last log entry
} deriving (Show, Eq, Typeable)
instance Binary RequestVoteMsg where
put (RequestVoteMsg a b c d e) =
put a >> put b >> put c >> put d >> put e
get = RequestVoteMsg <$> get <*> get <*> get <*> get <*> get
-- | Data structure for the response to requestVoteRPC. Is serializable.
data RequestVoteResponseMsg = RequestVoteResponseMsg
{ rvrSender :: !ProcessId -- ^ Sender's process id
, rvrTerm :: !Term -- ^ Current term to update leader
, voteGranted :: !Bool -- ^ Did candidate receive vote?
} deriving (Show, Eq, Typeable)
instance Binary RequestVoteResponseMsg where
put (RequestVoteResponseMsg a b c) =
put a >> put b >> put c
get = RequestVoteResponseMsg <$> get <*> get <*> get
-- | Hack to allow us to process arbitrary messages from the mailbox
data RpcMessage a
= RpcNothing
| RpcWhereIsReply WhereIsReply
| RpcProcessMonitorNotification ProcessMonitorNotification
| RpcAppendEntriesMsg (AppendEntriesMsg a)
| RpcAppendEntriesResponseMsg AppendEntriesResponseMsg
| RpcRequestVoteMsg RequestVoteMsg
| RpcRequestVoteResponseMsg RequestVoteResponseMsg
| RpcCommandMsg (Command a)
| RpcStateMsg Bool
-- | These wrapping functions return the message in an RPCMsg type.
recvSay :: String -> Process (RpcMessage a)
recvSay a = say a >> return RpcNothing
recvEcho :: (ProcessId, String) -> Process (RpcMessage a)
recvEcho (pid, a) = send pid a >> return RpcNothing
recvWhereIsReply :: WhereIsReply -> Process (RpcMessage a)
recvWhereIsReply a = return $ RpcWhereIsReply a
recvProcessMonitorNotification :: ProcessMonitorNotification
-> Process (RpcMessage a)
recvProcessMonitorNotification a = return $ RpcProcessMonitorNotification a
recvAppendEntriesMsg :: AppendEntriesMsg a -> Process (RpcMessage a)
recvAppendEntriesMsg a = return $ RpcAppendEntriesMsg a
recvAppendEntriesResponseMsg :: AppendEntriesResponseMsg
-> Process (RpcMessage a)
recvAppendEntriesResponseMsg a = return $ RpcAppendEntriesResponseMsg a
recvRequestVoteMsg :: RequestVoteMsg -> Process (RpcMessage a)
recvRequestVoteMsg a = return $ RpcRequestVoteMsg a
recvRequestVoteResponseMsg :: RequestVoteResponseMsg -> Process (RpcMessage a)
recvRequestVoteResponseMsg a = return $ RpcRequestVoteResponseMsg a
recvCommandMsg :: Command a -> Process (RpcMessage a)
recvCommandMsg a = return $ RpcCommandMsg a
recvStateMsg :: Bool -> Process (RpcMessage a)
recvStateMsg a = return $ RpcStateMsg a
-- | This is the process's local view of the entire cluster. Information
-- stored in this data structure should only be modified by the main thread.
data ClusterState = ClusterState
{ backend :: !Backend -- ^ Backend for the topology
, numNodes :: !Int -- ^ Number of nodes in the topology
, selfNodeId :: !NodeId -- ^ nodeId of current server
, nodeIds :: ![NodeId] -- ^ List of nodeIds in the topology
, peers :: ![NodeId] -- ^ nodeIds \\ [selfNodeId]
, mainPid :: !ProcessId -- ^ ProcessId of the master thread
, raftPid :: !ProcessId -- ^ ProcessId of the thread running Raft
, clientPid :: !ProcessId -- ^ ProcessId of the state thread
, delayPid :: !ProcessId -- ^ ProcessId of the delay thread
, randomGen :: GenIO -- ^ Random generator for random events
, identifier :: !Int -- ^ Identifier
}
-- | Creates a new cluster.
newCluster :: Backend -> [LocalNode] -> Int -> Process ClusterState
newCluster backend nodes identifier = do
selfPid <- getSelfPid
randomGen <- liftIO createSystemRandom
return ClusterState {
backend = backend
, numNodes = length nodes
, selfNodeId = processNodeId selfPid
, nodeIds = localNodeId <$> nodes
, peers = (localNodeId <$> nodes) \\ [processNodeId selfPid]
, mainPid = selfPid
, raftPid = nullProcessId (processNodeId selfPid)
, clientPid = nullProcessId (processNodeId selfPid)
, delayPid = nullProcessId (processNodeId selfPid)
, randomGen = randomGen
, identifier = identifier
}
-- | This is state that is volatile and can be modified by multiple threads
-- concurrently. This state will always be passed to the threads in an MVar.
data RaftState a = RaftState
{ leader :: !(Maybe NodeId) -- ^ Current leader of Raft
, state :: !ServerRole -- ^ Follower, Candidate, Leader
, currentTerm :: !Term -- ^ Current election term
, votedFor :: !(Maybe NodeId) -- ^ Voted node for leader
, log :: !(Log a) -- ^ Contains log entries
, commitIndex :: !Index -- ^ Highest entry committed
, lastApplied :: !Index -- ^ Highest entry applied
, nextIndexMap :: Map.Map NodeId Index -- ^ Next entry to send
, matchIndexMap :: Map.Map NodeId Index -- ^ Highest entry replicated
, voteCount :: !Int -- ^ Number votes received
, active :: !Bool -- ^ Is Raft active on this node?
}
-- | Creates a new RaftState.
newRaftState :: [LocalNode] -> RaftState a
newRaftState nodes = RaftState {
leader = Nothing
, state = Follower
, currentTerm = 0
, votedFor = Nothing
, log = IntMap.empty
, commitIndex = 0
, lastApplied = 0
, nextIndexMap = Map.fromList $ zip (localNodeId <$> nodes) [1, 1..]
, matchIndexMap = Map.fromList $ zip (localNodeId <$> nodes) [0, 0..]
, voteCount = 0
, active = True
}
-- | Helper Functions
stepDown :: RaftState a -> Term -> RaftState a
stepDown raftState newTerm =
raftState { currentTerm = newTerm
, state = Follower
, votedFor = Nothing
, voteCount = 0
}
logTerm :: Log a -> Index -> Term
logTerm log index
| index < 1 = 0
| index > IntMap.size log = 0
| otherwise = termReceived (log IntMap.! index)
-- | Handle Request Vote request from peer
handleRequestVoteMsg :: ClusterState
-> MVar (RaftState a)
-> RequestVoteMsg
-> Process ()
handleRequestVoteMsg c mr msg = do
(t, g) <- liftIO $ modifyMVarMasked mr $ \r -> handleMsg c r msg
send (rvSender msg) (RequestVoteResponseMsg (raftPid c) t g)
where
handleMsg :: ClusterState
-> RaftState a
-> RequestVoteMsg
-> IO (RaftState a, (Term, Bool))
handleMsg c r
msg@(RequestVoteMsg sender term candidateId lastLogIndex lastLogTerm)
| term > rCurrentTerm = handleMsg c (stepDown r term) msg
| term < rCurrentTerm = return (r, (rCurrentTerm, False))
| rVotedFor `elem` [Nothing, Just candidateId]
, lastLogTerm > rLastLogTerm ||
lastLogTerm == rLastLogTerm && lastLogIndex >= rLogSize
= return (r { votedFor = Just candidateId }, (term, True))
| otherwise = return (r, (rCurrentTerm, False))
where
rLog = log r
rLogSize = IntMap.size rLog
rVotedFor = votedFor r
rCurrentTerm = currentTerm r
rLastLogTerm = logTerm (log r) rLogSize
-- | Handle Request Vote response from peer
handleRequestVoteResponseMsg :: ClusterState
-> MVar (RaftState a)
-> RequestVoteResponseMsg
-> Process ()
handleRequestVoteResponseMsg c mr msg =
liftIO $ modifyMVarMasked_ mr $ \r -> handleMsg c r msg
where
handleMsg :: ClusterState
-> RaftState a
-> RequestVoteResponseMsg
-> IO (RaftState a)
handleMsg c r msg@(RequestVoteResponseMsg sender term granted)
| term > rCurrentTerm = handleMsg c (stepDown r term) msg
| rState == Candidate
, rCurrentTerm == term
, granted
= return r { voteCount = rVoteCount + 1 }
| otherwise = return r
where
rState = state r
rCurrentTerm = currentTerm r
rVoteCount = voteCount r
-- | Handle Append Entries request from peer
handleAppendEntriesMsg :: ClusterState
-> MVar (RaftState a)
-> AppendEntriesMsg a
-> Process ()
handleAppendEntriesMsg c mr msg = do
(t, g, i) <- liftIO $ modifyMVarMasked mr $ \r -> handleMsg c r msg
--say "Received append entries msg"
--say $ show t ++ " " ++ show i ++" "++ show g
send (aeSender msg) (AppendEntriesResponseMsg (raftPid c) t i g)
where
handleMsg :: ClusterState
-> RaftState a
-> AppendEntriesMsg a
-> IO (RaftState a, (Term, Bool, Index))
handleMsg c r
msg@(AppendEntriesMsg
sender term leaderId prevLogIndex prevLogTerm entries leaderCommit)
| term > rCurrentTerm = handleMsg c (stepDown r term) msg
| term < rCurrentTerm = return (r, (rCurrentTerm, False, 0))
| prevLogIndex == 0 ||
(prevLogIndex <= rLogSize &&
logTerm (log r) prevLogIndex == prevLogTerm) = do
let rLog' = appendLog rLog entries prevLogIndex
index = prevLogIndex + IntMap.size entries
r' = r {
log = rLog'
, commitIndex = min leaderCommit index
, leader = Just $ processNodeId sender
, state = Follower
}
return (r', (rCurrentTerm, True, index))
| otherwise = return (r {
leader = Just $ processNodeId sender
, state = Follower
} , (rCurrentTerm, False, 0))
where
rLog = log r
rLogSize = IntMap.size rLog
rVotedFor = votedFor r
rCurrentTerm = currentTerm r
rLastLogTerm = logTerm (log r) rLogSize
appendLog :: Log a -> Log a -> Index -> Log a
appendLog dstLog srcLog prevLogIndex
| IntMap.null srcLog = dstLog
| logTerm dstLog index /= termReceived headSrcLog =
appendLog (IntMap.insert index headSrcLog initDstLog) tailSrcLog index
| otherwise = appendLog dstLog tailSrcLog index
where
index = prevLogIndex + 1
((_, headSrcLog), tailSrcLog) = IntMap.deleteFindMin srcLog
initDstLog
| prevLogIndex < IntMap.size dstLog =
IntMap.filterWithKey (\k _ -> k <= prevLogIndex) dstLog
| otherwise = dstLog
-- | Handle Append Entries response from peer.
handleAppendEntriesResponseMsg :: ClusterState
-> MVar (RaftState a)
-> AppendEntriesResponseMsg
-> Process ()
handleAppendEntriesResponseMsg c mr msg =
liftIO $ modifyMVarMasked_ mr $ \r -> handleMsg c r msg
where
handleMsg :: ClusterState
-> RaftState a
-> AppendEntriesResponseMsg
-> IO (RaftState a)
handleMsg c r msg@(AppendEntriesResponseMsg sender term matchIndex success)
| term > rCurrentTerm = handleMsg c (stepDown r term) msg
| rState == Leader
, rCurrentTerm == term
= if success
then return r {
matchIndexMap = Map.insert peer matchIndex rMatchIndexMap
, nextIndexMap = Map.insert peer (matchIndex + 1) rNextIndexMap
}
else return r {
nextIndexMap = Map.insert peer (max 1 $ rNextIndex - 1) rNextIndexMap
}
| otherwise = return r
where
peer = processNodeId sender
rState = state r
rCurrentTerm = currentTerm r
rMatchIndexMap = matchIndexMap r
rNextIndexMap = nextIndexMap r
rNextIndex = rNextIndexMap Map.! peer
-- | Handle command message from a client. If leader, write to log. Else
-- forward to leader. If there is no leader...send back to self
handleCommandMsg :: Serializable a
=> ClusterState
-> MVar (RaftState a)
-> Command a
-> Process ()
handleCommandMsg c mr msg = do
(forwardMsg, leader) <- liftIO $ modifyMVarMasked mr $ \r -> handleMsg c r msg
case leader of
Nothing -> when forwardMsg $ void (nsend "client" msg)
Just l -> when forwardMsg $ void (nsendRemote l "client" msg)
where
handleMsg :: ClusterState
-> RaftState a
-> Command a
-> IO (RaftState a, (Bool, Maybe NodeId))
handleMsg c r msg
| state r /= Leader = return (r, (True, leader r))
| otherwise = do
let key = 1 + IntMap.size (log r)
entry = LogEntry {
termReceived = currentTerm r
, applied = False
, command = msg
}
return ( r { log = IntMap.insert key entry (log r) }, (False, leader r))
-- | Applies entries in the log to state machine.
applyLog :: Show a => ClusterState -> MVar (RaftState a) -> Process ()
applyLog c mr = do
finished <- liftIO $ modifyMVarMasked mr $ \r ->
if lastApplied r >= commitIndex r
then return (r, True)
else
let lastApplied' = succ . lastApplied $ r
entry = log r IntMap.! lastApplied'
entry' = entry { applied = True }
fname = "tmp/" ++ show (identifier c) ++ ".csv"
Command cm = command entry
line = show (termReceived entry) ++ "," ++ show cm
in do
withFile fname AppendMode $ \h -> do
hPutStrLn h line >> hFlush h
return (r {
lastApplied = lastApplied'
, log = IntMap.insert lastApplied' entry' (log r)
}, False)
-- Loop until finish applying all
--l <- liftIO $ withMVarMasked mr $ \r -> return $ log r
--say $ show (IntMap.size l)
unless finished $ applyLog c mr
-- | This thread starts a new election.
electionThread :: ClusterState -> MVar (RaftState a) -> Process ()
electionThread c mr = do
-- Die when parent does
link $ mainPid c
-- Update raftState and create (Maybe RequestVoteMsg)
msg <- liftIO $ modifyMVarMasked mr $ \r ->
if state r == Leader
then return (r, Nothing)
else
let r' = r { state = Candidate
, votedFor = Just $ selfNodeId c
, currentTerm = 1 + currentTerm r
, voteCount = 1
, matchIndexMap = Map.fromList $ zip (nodeIds c) [0, 0..]
, nextIndexMap = Map.fromList $ zip (nodeIds c) [1, 1..]
}
msg = RequestVoteMsg
{ rvSender = raftPid c
, rvTerm = currentTerm r'
, candidateId = selfNodeId c
, lastLogIndex = IntMap.size $ log r
, lastLogTerm = logTerm (log r) (IntMap.size $ log r)
}
in return (r', Just msg)
case msg of
-- New election started, send RequestVoteMsg to all peers
Just m -> mapM_ (\x -> nsendRemote x "server" m) $ peers c
-- We were already leader, do nothing
Nothing -> return ()
return ()
-- | This thread starts the election timer if it is not killed before then.
delayThread :: ClusterState -> MVar (RaftState a) -> Int -> Process ()
delayThread c mr t = do
-- Die when parent does
link $ mainPid c
-- Delay for t ns
liftIO $ threadDelay t
-- Spawn thread that starts election
active <- liftIO $ withMVarMasked mr $ \r-> return $ active r
when active $ spawnLocal (electionThread c mr) >> return ()
-- | This thread only performs work when the server is the leader.
leaderThread :: (Show a, Serializable a)
=> ClusterState -> MVar (RaftState a) -> Int -> Process ()
leaderThread c mr u = do
-- Die when parent does
link $ mainPid c
active <- liftIO $ withMVarMasked mr $ \r-> return $ active r
unless active (liftIO (threadDelay 10000) >> leaderThread c mr u)
-- Delay u ns to main update rate
liftIO $ threadDelay u
-- Create AppendEntries
msgsM <- liftIO $ modifyMVarMasked mr $ \r -> handleLeader c r
-- Send them if they were created
forM_ msgsM (mapM_ (\ (n, m) -> nsendRemote n "server" m))
-- Advance commit index
liftIO $ modifyMVarMasked_ mr $ \r -> do
let n = filter (\v -> logTerm (log r) v == currentTerm r)
[commitIndex r + 1 .. IntMap.size $ log r]
pred :: Index -> Bool
pred v = numNodes c `div` 2 <
Map.size (Map.filter (>=v) $ matchIndexMap r) + 1
ns = filter pred n
if state r == Leader && not (null ns)
then return r { commitIndex = head ns }
else return r
-- Loop forever
leaderThread c mr u
where
handleLeader :: ClusterState
-> RaftState a
-> IO (RaftState a, Maybe [(NodeId, AppendEntriesMsg a)])
handleLeader c r
| state r == Leader = return $ foldr (\n (r', Just a) ->
let r'MatchIndexMap = matchIndexMap r'
r'NextIndexMap = nextIndexMap r'
r'Log = log r'
r'LogSize = IntMap.size r'Log
r'NextIndex = r'NextIndexMap Map.! n
r'LastIndex = r'LogSize
r'MatchIndex = r'MatchIndexMap Map.! n
in
let msg = AppendEntriesMsg {
aeSender = raftPid c
, aeTerm = currentTerm r'
, leaderId = selfNodeId c
, prevLogIndex = r'NextIndex - 1
, prevLogTerm = logTerm r'Log $ r'NextIndex - 1
, entries = IntMap.filterWithKey (\k _ -> k >= r'NextIndex) r'Log
, leaderCommit = commitIndex r'
}
r'' = r' {
nextIndexMap = Map.insert n r'LastIndex r'NextIndexMap
}
in (r', Just $ (n, msg):a)
) (r, Just []) (peers c)
| otherwise = return (r, Nothing)
-- | This thread handles commands from clients and forwards them
-- to the leader.
clientThread :: Serializable a => ClusterState -> MVar (RaftState a) -> Process ()
clientThread c mr = do
-- Die when parent does
link $ mainPid c
(RpcCommandMsg m) <- receiveWait [ match recvCommandMsg ]
handleCommandMsg c mr m
-- loop forever
clientThread c mr
-- | This thread listens from the main program and halts and continues
-- the node (in order to test Raft).
stateThread :: ClusterState -> MVar (RaftState a) -> Process ()
stateThread c mr = do
msg <- receiveWait [ match recvStateMsg ]
case msg of
RpcStateMsg True -> do
-- Enable RaftThread
liftIO $ modifyMVarMasked_ mr $ \r -> return r { active = True }
-- Get registry values of server and client
raftReg <- whereis "server"
clientReg <- whereis "client"
-- register them
case raftReg of
Nothing -> register "server" $ raftPid c
_ -> reregister "server" $ raftPid c
case clientReg of
Nothing -> register "client" $ clientPid c
_ -> reregister "client" $ clientPid c
RpcStateMsg False -> do
-- Disable RaftThread
liftIO $ modifyMVarMasked_ mr $ \r -> return r { active = False }
-- Get registry values of server and client
raftReg <- whereis "server"
clientReg <- whereis "client"
-- Unregister them
case raftReg of
Nothing -> return ()
_ -> unregister "server"
case clientReg of
Nothing -> return ()
_ -> unregister "client"
-- Loop forever
stateThread c mr
-- | Main loop of the program.
raftThread :: (Show a, Serializable a) => ClusterState -> MVar (RaftState a) -> Process ()
raftThread c mr = do
-- Die when parent does
link $ mainPid c
active <- liftIO $ withMVarMasked mr $ \r-> return $ active r
unless active (liftIO (threadDelay 10000) >> raftThread c mr)
-- Choose election timeout between 150ms and 600ms
timeout <- liftIO (uniformR (150000, 300000) (randomGen c) :: IO Int)
-- Update cluster with raftPid
selfPid <- getSelfPid
let c' = c { raftPid = selfPid }
-- Restart election delay thread
kill (delayPid c') "restart"
delayPid <- spawnLocal $ delayThread c' mr timeout
let c'' = c' { delayPid = delayPid }
-- Block for RPC Messages
msg <- receiveWait
[ match recvAppendEntriesMsg
, match recvAppendEntriesResponseMsg
, match recvRequestVoteMsg
, match recvRequestVoteResponseMsg ]
-- Handle RPC Message
case msg of
RpcAppendEntriesMsg m -> handleAppendEntriesMsg c'' mr m
RpcAppendEntriesResponseMsg m -> handleAppendEntriesResponseMsg c'' mr m
RpcRequestVoteMsg m -> handleRequestVoteMsg c'' mr m
RpcRequestVoteResponseMsg m -> handleRequestVoteResponseMsg c'' mr m
other@_ -> return ()
-- Update if become leader
s <- liftIO $ modifyMVarMasked mr $ \r ->
case state r of
Candidate -> if voteCount r > numNodes c'' `div` 2
then return (r {
state = Leader
, leader = Just $ selfNodeId c''
, nextIndexMap = Map.fromList $
zip (nodeIds c'') $ repeat $ 1 + IntMap.size (log r)
}, True)
else return (r, False)
other@_ -> return (r, False)
t <- liftIO $ withMVarMasked mr $ \r -> return $ currentTerm r
when s $ say $ "I am leader of term: " ++ show t
-- Advance state machine
applyLog c'' mr
-- Loop Forever
raftThread c'' mr
initRaft :: Backend -> [LocalNode] -> Int -> Process ()
initRaft backend nodes identifier = do
say "Hi!"
-- Initialize state
c <- newCluster backend nodes identifier
mr <- liftIO . newMVar $ (newRaftState nodes :: RaftState String)
let fname = "tmp/" ++ show identifier ++ ".csv"
line = "term,command"
liftIO $ withFile fname AppendMode $ \h -> do
hPutStrLn h line >> hFlush h
-- Start process for handling messages and register it
raftPid <- spawnLocal $ raftThread c mr
raftReg <- whereis "server"
case raftReg of
Nothing -> register "server" raftPid
_ -> reregister "server" raftPid
-- Update raftPid
let c' = c { raftPid = raftPid }
-- Start leader thread
leaderPid <- spawnLocal $ leaderThread c' mr 50000
-- Start client thread and register it
clientPid <- spawnLocal $ clientThread c' mr
clientReg <- whereis "client"
case clientReg of
Nothing -> register "client" clientPid
_ -> reregister "client" clientPid
let c'' = c' { clientPid = clientPid }
-- Start state thread and register it
statePid <- spawnLocal $ stateThread c'' mr
stateReg <- whereis "state"
case stateReg of
Nothing -> register "state" statePid
_ -> reregister "state" statePid
-- Kill this process if raftThread dies
link raftPid
link leaderPid
link clientPid
link statePid
-- Hack to block
x <- receiveWait []
return ()
|
mwlow/raft-haskell
|
src/Raft/Protocol.hs
|
gpl-3.0
| 28,009 | 0 | 24 | 9,521 | 7,054 | 3,606 | 3,448 | 596 | 7 |
-- |
-- Copyright : (c) 2010-2012 Simon Meier, Benedikt Schmidt
-- contributing in 2019: Robert Künnemann, Johannes Wocker
-- License : GPL v3 (see LICENSE)
--
-- Maintainer : Simon Meier <[email protected]>
-- Portability : portable
--
-- Parsing Proofs
module Theory.Text.Parser.Proof (
startProofSkeleton
, diffProofSkeleton
)
where
import Prelude hiding (id, (.))
import Data.Foldable (asum)
import qualified Data.Map as M
-- import Data.Monoid hiding (Last)
import Control.Applicative hiding (empty, many, optional)
import Control.Category
import Text.Parsec hiding ((<|>))
import Theory
import Theory.Text.Parser.Token
import Theory.Text.Parser.Fact
import Theory.Text.Parser.Term
import Theory.Text.Parser.Formula
-- | Parse a node premise.
nodePrem :: Parser NodePrem
nodePrem = parens ((,) <$> nodevar
<*> (comma *> fmap (PremIdx . fromIntegral) natural))
-- | Parse a node conclusion.
nodeConc :: Parser NodeConc
nodeConc = parens ((,) <$> nodevar
<*> (comma *> fmap (ConcIdx .fromIntegral) natural))
-- | Parse a goal.
goal :: Parser Goal
goal = asum
[ premiseGoal
, actionGoal
, chainGoal
, disjSplitGoal
, eqSplitGoal
]
where
actionGoal = do
fa <- try (fact llit <* opAt)
i <- nodevar
return $ ActionG i fa
premiseGoal = do
(fa, v) <- try ((,) <$> fact llit <*> opRequires)
i <- nodevar
return $ PremiseG (i, v) fa
chainGoal = ChainG <$> (try (nodeConc <* opChain)) <*> nodePrem
disjSplitGoal = (DisjG . Disj) <$> sepBy1 guardedFormula (symbol "∥")
eqSplitGoal = try $ do
symbol_ "splitEqs"
parens $ (SplitG . SplitId . fromIntegral) <$> natural
-- | Parse a proof method.
proofMethod :: Parser ProofMethod
proofMethod = asum
[ symbol "sorry" *> pure (Sorry Nothing)
, symbol "simplify" *> pure Simplify
, symbol "solve" *> (SolveGoal <$> parens goal)
, symbol "contradiction" *> pure (Contradiction Nothing)
, symbol "induction" *> pure Induction
]
-- | Start parsing a proof skeleton.
-- | If the first step of the proof is a SOLVED, mark it as an inavalid proof step.
-- | If that is not the case, call proofSkeleton
startProofSkeleton :: Parser ProofSkeleton
startProofSkeleton =
solvedProof <|> otherProof
where
solvedProof = symbol "SOLVED" *> error "SOLVED without a proof was found."
otherProof = proofSkeleton
-- | Parse a proof skeleton.
proofSkeleton :: Parser ProofSkeleton
proofSkeleton =
solvedProof <|> finalProof <|> interProof
where
solvedProof =
symbol "SOLVED" *> pure (LNode (ProofStep Solved ()) M.empty)
finalProof = do
method <- symbol "by" *> proofMethod
return (LNode (ProofStep method ()) M.empty)
interProof = do
method <- proofMethod
cases <- (sepBy oneCase (symbol "next") <* symbol "qed") <|>
((return . (,) "") <$> proofSkeleton )
return (LNode (ProofStep method ()) (M.fromList cases))
oneCase = (,) <$> (symbol "case" *> identifier) <*> proofSkeleton
-- | Parse a proof method.
diffProofMethod :: Parser DiffProofMethod
diffProofMethod = asum
[ symbol "sorry" *> pure (DiffSorry Nothing)
, symbol "rule-equivalence" *> pure DiffRuleEquivalence
, symbol "backward-search" *> pure DiffBackwardSearch
, symbol "step" *> (DiffBackwardSearchStep <$> parens proofMethod)
, symbol "ATTACK" *> pure DiffAttack
]
-- | Parse a diff proof skeleton.
diffProofSkeleton :: Parser DiffProofSkeleton
diffProofSkeleton =
solvedProof <|> finalProof <|> interProof
where
solvedProof =
symbol "MIRRORED" *> pure (LNode (DiffProofStep DiffMirrored ()) M.empty)
finalProof = do
method <- symbol "by" *> diffProofMethod
return (LNode (DiffProofStep method ()) M.empty)
interProof = do
method <- diffProofMethod
cases <- (sepBy oneCase (symbol "next") <* symbol "qed") <|>
((return . (,) "") <$> diffProofSkeleton )
return (LNode (DiffProofStep method ()) (M.fromList cases))
oneCase = (,) <$> (symbol "case" *> identifier) <*> diffProofSkeleton
|
tamarin-prover/tamarin-prover
|
lib/theory/src/Theory/Text/Parser/Proof.hs
|
gpl-3.0
| 4,442 | 1 | 16 | 1,231 | 1,146 | 602 | 544 | 87 | 1 |
module Language.Mulang.Analyzer.ExpectationsAnalyzer (
analyseExpectations) where
import Data.Maybe (fromMaybe)
import Language.Mulang.Ast (Expression)
import Language.Mulang.Analyzer.Analysis (Expectation, QueryResult, ExpectationResult(..))
import Language.Mulang.Analyzer.ExpectationsCompiler (compileExpectation)
analyseExpectations :: Expression -> Maybe [Expectation] -> [QueryResult]
analyseExpectations content = map (analyseExpectation content) . (fromMaybe [])
analyseExpectation :: Expression -> Expectation -> QueryResult
analyseExpectation ast e = (query, ExpectationResult e (inspection ast))
where (query, inspection) = compileExpectation e
|
mumuki/mulang
|
src/Language/Mulang/Analyzer/ExpectationsAnalyzer.hs
|
gpl-3.0
| 665 | 0 | 8 | 67 | 176 | 101 | 75 | 11 | 1 |
{-# LANGUAGE JavaScriptFFI #-}
module Estuary.WebDirt.Foreign where
import GHC.IORef
import qualified GHCJS.Prim as Prim
import qualified GHCJS.Types as T
import qualified GHCJS.Foreign as F
import GHCJS.Foreign.Internal
import GHCJS.Marshal.Pure
foreign import javascript unsafe
"$r = new WebDirt('WebDirt/sampleMap.json','Dirt/samples',null, function() {console.log('callback from WebDirt constructor completed');});"
newWebDirt :: IO (T.JSVal)
foreign import javascript unsafe "try { $1.queue({sample_name: 'cp', sample_n:0}) } catch(e) {console.log(e)} " webDirtTestMessage ::T.JSVal->IO (T.JSVal)
foreign import javascript unsafe
"try { $1.queue({whenPosix: $2, sample_name: $3, sample_n: $4})} catch(e) { console.log(e)} "
playSample':: T.JSVal -> T.JSVal -> T.JSVal -> T.JSVal -> IO()
playSample :: T.JSVal -> Double -> String -> Int -> IO ()
playSample webDirt when sampleName sampleN = playSample' webDirt (pToJSVal when) (Prim.toJSString sampleName) (pToJSVal sampleN)
|
Moskau/estuary
|
Estuary/WebDirt/Foreign.hs
|
gpl-3.0
| 1,014 | 14 | 8 | 149 | 215 | 119 | 96 | 15 | 1 |
{-# LANGUAGE PatternGuards #-}
-- | The contents of the \"PART REAL_GUITAR\", \"PART REAL_GUITAR_22\",
-- \"PART REAL_BASS\", and \"PART REAL_BASS_22\" tracks.
module Data.Rhythm.RockBand.Lex.ProGuitar where
import Data.Rhythm.RockBand.Common
import qualified Sound.MIDI.File.Event as E
import qualified Sound.MIDI.File.Event.Meta as M
import qualified Sound.MIDI.Message.Channel as C
import qualified Sound.MIDI.Message.Channel.Voice as V
import qualified Data.Rhythm.MIDI as MIDI
import Data.Rhythm.Time
import Data.Rhythm.Event
import Data.Rhythm.Parser
import qualified Numeric.NonNegative.Class as NN
import Data.Char (isSpace)
import Data.List (stripPrefix, sort)
import Data.Maybe (listToMaybe)
import qualified Data.EventList.Relative.TimeBody as RTB
import Data.Rhythm.Guitar
instance Long Length where
match (DiffEvent d0 (Slide _)) (DiffEvent d1 (Slide _)) = d0 == d1
match (DiffEvent d0 (PartialChord _)) (DiffEvent d1 (PartialChord _)) =
d0 == d1
match (DiffEvent d0 (UnknownBFlat _ _)) (DiffEvent d1 (UnknownBFlat _ _)) =
d0 == d1
match x y = x == y
type T = Event Length Point
data Point
= TrainerGtr Trainer
| TrainerBass Trainer
| HandPosition GtrFret
| ChordRoot V.Pitch -- ^ Valid pitches are 4 (E) to 15 (D#).
| ChordName Difficulty String
deriving (Eq, Ord, Show)
data Length
= Trill
| Tremolo
| BRE
| Overdrive
| Solo
| NoChordNames
| SlashChords
| BlackChordSwitch -- ^ I *think* this swaps between (e.g.) F# and Gb chords.
| DiffEvent Difficulty DiffEvent
deriving (Eq, Ord, Show)
data DiffEvent
= Note SixString GtrFret NoteType
| ForceHOPO
| Slide SlideType
| Arpeggio
| PartialChord StrumArea
| UnknownBFlat C.Channel V.Velocity
| AllFrets
deriving (Eq, Ord, Show)
data NoteType
= NormalNote
| ArpeggioForm
| Bent
| Muted
| Tapped
| Harmonic
| PinchHarmonic
deriving (Eq, Ord, Show, Read, Enum, Bounded)
data SlideType = NormalSlide | ReversedSlide
deriving (Eq, Ord, Show, Read, Enum, Bounded)
data StrumArea = High | Mid | Low
deriving (Eq, Ord, Show, Read, Enum, Bounded)
parse :: (NN.C a) => Parser (MIDI.T a) (Maybe (T a))
parse = get >>= \x -> case x of
Length len n@(MIDI.Note ch p vel) -> case V.fromPitch p of
i | 4 <= i && i <= 15 -> single $ Point $ ChordRoot p
16 -> single $ Length len SlashChords
17 -> single $ Length len NoChordNames
18 -> single $ Length len BlackChordSwitch
i | let (oct, k) = quotRem i 12
, elem oct [2,4,6,8]
, let makeDiff = single . Length len . DiffEvent (toEnum $ quot oct 2 - 1)
-> case k of
6 -> makeDiff ForceHOPO
7 -> case C.fromChannel ch of
0 -> makeDiff $ Slide NormalSlide
11 -> makeDiff $ Slide ReversedSlide
ch' -> warn w >> makeDiff (Slide NormalSlide) where
w = "Slide marker (pitch " ++ show i ++
") has unknown channel " ++ show ch'
8 -> makeDiff Arpeggio
9 -> case C.fromChannel ch of
13 -> makeDiff $ PartialChord High
14 -> makeDiff $ PartialChord Mid
15 -> makeDiff $ PartialChord Low
ch' -> warn w >> makeDiff (PartialChord Mid) where
w = "Partial chord marker (pitch " ++ show i ++
") has unknown channel " ++ show ch'
10 -> makeDiff $ UnknownBFlat ch vel
11 -> makeDiff AllFrets
_ -> makeDiff $ Note nstr nfret ntyp where
nstr = toEnum k
nfret = fromIntegral $ V.fromVelocity vel - 100
ntyp = toEnum $ C.fromChannel ch
108 -> single $ Point $ HandPosition $ fromIntegral $ V.fromVelocity vel - 100
115 -> single $ Length len Solo
116 -> single $ Length len Overdrive
120 -> single $ Length len BRE
121 -> return Nothing
122 -> return Nothing
123 -> return Nothing
124 -> return Nothing
125 -> return Nothing
126 -> single $ Length len Tremolo
127 -> single $ Length len Trill
_ -> unrecognized n
Point (E.MetaEvent txt@(M.TextEvent str)) -> case readTrainer str of
Just (t, "pg") -> single $ Point $ TrainerGtr t
Just (t, "pb") -> single $ Point $ TrainerBass t
_ -> case readChordName str of
Nothing -> unrecognized txt
Just (diff, name) -> single $ Point $ ChordName diff name
Point p -> unrecognized p
where single = return . Just
unparse :: T Beats -> [MIDI.T Beats]
unparse (Point x) = case x of
TrainerGtr t -> [text $ showTrainer t "pg"]
TrainerBass t -> [text $ showTrainer t "pb"]
HandPosition f -> [blip $ V.toPitch $ fromIntegral f + 100]
ChordRoot p -> [blip p]
ChordName diff str -> [text $ showChordName diff str]
where text = Point . E.MetaEvent . M.TextEvent
unparse (Length len x) = case x of
SlashChords -> [note 16]
NoChordNames -> [note 17]
BlackChordSwitch -> [note 18]
Solo -> [note 115]
Overdrive -> [note 116]
BRE -> map note [120 .. 125]
Tremolo -> [note 126]
Trill -> [note 127]
DiffEvent diff evt -> [Length len $ MIDI.Note ch p vel] where
ch = case evt of
Note _ _ typ -> toEnum $ fromEnum typ
Slide typ -> toEnum $ fromEnum typ * 11
PartialChord area -> toEnum $ fromEnum area + 13
UnknownBFlat c _ -> c
_ -> toEnum 0
p = V.toPitch $ diffOffset + case evt of
Note str _ _ -> fromEnum str
ForceHOPO -> 6
Slide _ -> 7
Arpeggio -> 8
PartialChord _ -> 9
UnknownBFlat _ _ -> 10
AllFrets -> 11
vel = case evt of
Note _ frt _ -> V.toVelocity $ fromIntegral frt + 100
UnknownBFlat _ v -> v
_ -> V.toVelocity 96
diffOffset = (fromEnum diff + 1) * 24
where note = Length len . standardNote . V.toPitch
readChordName :: String -> Maybe (Difficulty, String)
readChordName str
| Just (x:xs) <- stripPrefix "[chrd" str
, elem x "0123"
, let diff = toEnum $ read [x]
, Just name <- stripSuffix "]" $ dropWhile isSpace xs
= Just (diff, name)
| otherwise = Nothing
showChordName :: Difficulty -> String -> String
showChordName d ch = "[chrd" ++ show (fromEnum d) ++ " " ++ ch ++ "]"
-- | Generates a fret number for each note or chord.
autoHandPosition :: (NN.C t) => RTB.T t DiffEvent -> RTB.T t GtrFret
autoHandPosition = RTB.mapMaybe getFret . RTB.collectCoincident where
getFret :: [DiffEvent] -> Maybe GtrFret
getFret evts = listToMaybe $ sort
[f | Note _ f _ <- evts, f /= 0]
|
mtolly/rhythm
|
src/Data/Rhythm/RockBand/Lex/ProGuitar.hs
|
gpl-3.0
| 6,368 | 0 | 25 | 1,610 | 2,339 | 1,194 | 1,145 | 170 | 33 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Books.Bookshelves.Volumes.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves volumes in a specific bookshelf for the specified user.
--
-- /See:/ <https://developers.google.com/books/docs/v1/getting_started Books API Reference> for @books.bookshelves.volumes.list@.
module Network.Google.Resource.Books.Bookshelves.Volumes.List
(
-- * REST Resource
BookshelvesVolumesListResource
-- * Creating a Request
, bookshelvesVolumesList
, BookshelvesVolumesList
-- * Request Lenses
, bvlUserId
, bvlShelf
, bvlSource
, bvlStartIndex
, bvlMaxResults
, bvlShowPreOrders
) where
import Network.Google.Books.Types
import Network.Google.Prelude
-- | A resource alias for @books.bookshelves.volumes.list@ method which the
-- 'BookshelvesVolumesList' request conforms to.
type BookshelvesVolumesListResource =
"books" :>
"v1" :>
"users" :>
Capture "userId" Text :>
"bookshelves" :>
Capture "shelf" Text :>
"volumes" :>
QueryParam "source" Text :>
QueryParam "startIndex" (Textual Word32) :>
QueryParam "maxResults" (Textual Word32) :>
QueryParam "showPreorders" Bool :>
QueryParam "alt" AltJSON :> Get '[JSON] Volumes
-- | Retrieves volumes in a specific bookshelf for the specified user.
--
-- /See:/ 'bookshelvesVolumesList' smart constructor.
data BookshelvesVolumesList = BookshelvesVolumesList'
{ _bvlUserId :: !Text
, _bvlShelf :: !Text
, _bvlSource :: !(Maybe Text)
, _bvlStartIndex :: !(Maybe (Textual Word32))
, _bvlMaxResults :: !(Maybe (Textual Word32))
, _bvlShowPreOrders :: !(Maybe Bool)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'BookshelvesVolumesList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'bvlUserId'
--
-- * 'bvlShelf'
--
-- * 'bvlSource'
--
-- * 'bvlStartIndex'
--
-- * 'bvlMaxResults'
--
-- * 'bvlShowPreOrders'
bookshelvesVolumesList
:: Text -- ^ 'bvlUserId'
-> Text -- ^ 'bvlShelf'
-> BookshelvesVolumesList
bookshelvesVolumesList pBvlUserId_ pBvlShelf_ =
BookshelvesVolumesList'
{ _bvlUserId = pBvlUserId_
, _bvlShelf = pBvlShelf_
, _bvlSource = Nothing
, _bvlStartIndex = Nothing
, _bvlMaxResults = Nothing
, _bvlShowPreOrders = Nothing
}
-- | ID of user for whom to retrieve bookshelf volumes.
bvlUserId :: Lens' BookshelvesVolumesList Text
bvlUserId
= lens _bvlUserId (\ s a -> s{_bvlUserId = a})
-- | ID of bookshelf to retrieve volumes.
bvlShelf :: Lens' BookshelvesVolumesList Text
bvlShelf = lens _bvlShelf (\ s a -> s{_bvlShelf = a})
-- | String to identify the originator of this request.
bvlSource :: Lens' BookshelvesVolumesList (Maybe Text)
bvlSource
= lens _bvlSource (\ s a -> s{_bvlSource = a})
-- | Index of the first element to return (starts at 0)
bvlStartIndex :: Lens' BookshelvesVolumesList (Maybe Word32)
bvlStartIndex
= lens _bvlStartIndex
(\ s a -> s{_bvlStartIndex = a})
. mapping _Coerce
-- | Maximum number of results to return
bvlMaxResults :: Lens' BookshelvesVolumesList (Maybe Word32)
bvlMaxResults
= lens _bvlMaxResults
(\ s a -> s{_bvlMaxResults = a})
. mapping _Coerce
-- | Set to true to show pre-ordered books. Defaults to false.
bvlShowPreOrders :: Lens' BookshelvesVolumesList (Maybe Bool)
bvlShowPreOrders
= lens _bvlShowPreOrders
(\ s a -> s{_bvlShowPreOrders = a})
instance GoogleRequest BookshelvesVolumesList where
type Rs BookshelvesVolumesList = Volumes
type Scopes BookshelvesVolumesList =
'["https://www.googleapis.com/auth/books"]
requestClient BookshelvesVolumesList'{..}
= go _bvlUserId _bvlShelf _bvlSource _bvlStartIndex
_bvlMaxResults
_bvlShowPreOrders
(Just AltJSON)
booksService
where go
= buildClient
(Proxy :: Proxy BookshelvesVolumesListResource)
mempty
|
rueshyna/gogol
|
gogol-books/gen/Network/Google/Resource/Books/Bookshelves/Volumes/List.hs
|
mpl-2.0
| 4,951 | 0 | 19 | 1,214 | 744 | 430 | 314 | 106 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.StorageGateway.DeleteVolume
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | This operation delete the specified gateway volume that you previously
-- created using the 'CreateStorediSCSIVolume' API. For gateway-stored volumes,
-- the local disk that was configured as the storage volume is not deleted. You
-- can reuse the local disk to create another storage volume.
--
-- Before you delete a gateway volume, make sure there are no iSCSI connections
-- to the volume you are deleting. You should also make sure there is no
-- snapshot in progress. You can use the Amazon Elastic Compute Cloud (Amazon
-- EC2) API to query snapshots on the volume you are deleting and check the
-- snapshot status. For more information, go to <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSnapshots.html DescribeSnapshots> in the /AmazonElastic Compute Cloud API Reference/.
--
-- In the request, you must provide the Amazon Resource Name (ARN) of the
-- storage volume you want to delete.
--
-- <http://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DeleteVolume.html>
module Network.AWS.StorageGateway.DeleteVolume
(
-- * Request
DeleteVolume
-- ** Request constructor
, deleteVolume
-- ** Request lenses
, dvVolumeARN
-- * Response
, DeleteVolumeResponse
-- ** Response constructor
, deleteVolumeResponse
-- ** Response lenses
, dvrVolumeARN
) where
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.StorageGateway.Types
import qualified GHC.Exts
newtype DeleteVolume = DeleteVolume
{ _dvVolumeARN :: Text
} deriving (Eq, Ord, Read, Show, Monoid, IsString)
-- | 'DeleteVolume' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dvVolumeARN' @::@ 'Text'
--
deleteVolume :: Text -- ^ 'dvVolumeARN'
-> DeleteVolume
deleteVolume p1 = DeleteVolume
{ _dvVolumeARN = p1
}
-- | The Amazon Resource Name (ARN) of the volume. Use the 'ListVolumes' operation
-- to return a list of gateway volumes.
dvVolumeARN :: Lens' DeleteVolume Text
dvVolumeARN = lens _dvVolumeARN (\s a -> s { _dvVolumeARN = a })
newtype DeleteVolumeResponse = DeleteVolumeResponse
{ _dvrVolumeARN :: Maybe Text
} deriving (Eq, Ord, Read, Show, Monoid)
-- | 'DeleteVolumeResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dvrVolumeARN' @::@ 'Maybe' 'Text'
--
deleteVolumeResponse :: DeleteVolumeResponse
deleteVolumeResponse = DeleteVolumeResponse
{ _dvrVolumeARN = Nothing
}
-- | The Amazon Resource Name (ARN) of the storage volume that was deleted. It is
-- the same ARN you provided in the request.
dvrVolumeARN :: Lens' DeleteVolumeResponse (Maybe Text)
dvrVolumeARN = lens _dvrVolumeARN (\s a -> s { _dvrVolumeARN = a })
instance ToPath DeleteVolume where
toPath = const "/"
instance ToQuery DeleteVolume where
toQuery = const mempty
instance ToHeaders DeleteVolume
instance ToJSON DeleteVolume where
toJSON DeleteVolume{..} = object
[ "VolumeARN" .= _dvVolumeARN
]
instance AWSRequest DeleteVolume where
type Sv DeleteVolume = StorageGateway
type Rs DeleteVolume = DeleteVolumeResponse
request = post "DeleteVolume"
response = jsonResponse
instance FromJSON DeleteVolumeResponse where
parseJSON = withObject "DeleteVolumeResponse" $ \o -> DeleteVolumeResponse
<$> o .:? "VolumeARN"
|
dysinger/amazonka
|
amazonka-storagegateway/gen/Network/AWS/StorageGateway/DeleteVolume.hs
|
mpl-2.0
| 4,434 | 0 | 9 | 909 | 460 | 284 | 176 | 55 | 1 |
{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -XGeneralizedNewtypeDeriving #-}
module Internal.Types where
import Control.Monad.Except
import Control.Monad.State.Strict
import qualified Data.Map as Map
import Data.IORef
import qualified TclObj as T
import qualified EventMgr as Evt
import Control.Applicative
import Util
import TclErr
import TclChan
class Runnable t where
evalTcl :: t -> TclM T.TclObj
newtype TclM a = TclM { unTclM :: ExceptT Err (StateT TclState IO) a }
deriving (MonadState TclState, MonadIO, Applicative, Functor, Monad, MonadError Err)
-- instance Alternative TclM where
-- instance Exception (TclM Err) where
data Namespace = TclNS
{ nsName :: BString
, nsCmds :: !CmdMap
, nsFrame :: !FrameRef
, nsExport :: [BString]
, nsParent :: Maybe NSRef
, nsChildren :: Map.Map BString NSRef
, nsPath :: [NSRef]
, nsPathLinks :: [NSRef]
, nsUnknown :: Maybe BString
}
type FrameRef = IORef TclFrame
type NSRef = IORef Namespace
type UpMap = Map.Map BString (FrameRef,BString)
data TclFrame = TclFrame
{ frVars :: !VarMap
, upMap :: !UpMap
, frNS :: NSRef
, frTag :: !Int
, frInfo :: [T.TclObj]
}
type TclStack = [FrameRef]
data Interp = Interp { interpState :: IORef TclState }
type InterpMap = Map.Map BString Interp
data TclState = TclState
{ interpSafe :: Bool
, tclChans :: ChanMap
, tclInterps :: InterpMap
, tclEvents :: Evt.EventMgr T.TclObj
, tclStack :: !TclStack
, tclHidden :: CmdMap
, tclGlobalNS :: !NSRef
, tclCmdCount :: !Int
, tclCmdWatchers :: [IO ()]
}
type TclCmd = [T.TclObj] -> TclM T.TclObj
type CmdRef = IORef TclCmdObj
data TclCmdObj = TclCmdObj
{ cmdName :: BString
, cmdOrigNS :: Maybe NSRef
, cmdParent :: Maybe CmdRef
, cmdKids :: [CmdRef]
, cmdCore :: !CmdCore
}
cmdIsProc cmd = case cmdCore cmd of
ProcCore {} -> True
_ -> False
cmdIsEnsem cmd = case cmdCore cmd of
EnsemCore {} -> True
_ -> False
type ArgSpec = Either BString (BString,T.TclObj)
type ArgList = [ArgSpec]
newtype ParamList = ParamList (BString, Bool, ArgList)
data CmdCore
= CmdCore !TclCmd
| EnsemCore { ensemName :: BString
, ensemCmd :: TclCmd
}
| ProcCore { procBody :: BString
, procArgs :: !ParamList
, procAction :: !(TclM T.TclObj)
}
type ProcKey = BString
data CmdMap = CmdMap
{ cmdMapEpoch :: !Int
, unCmdMap :: !(Map.Map ProcKey CmdRef)
}
type TclArray = Map.Map BString T.TclObj
data TclVar
= ScalarVar !T.TclObj
| ArrayVar TclArray
| Undefined
deriving (Eq,Show)
type TraceCB = Maybe (IO ())
type VarMap = Map.Map BString (TraceCB,TclVar)
runTclM :: TclM a -> TclState -> IO (Either Err a, TclState)
runTclM = runStateT . runExceptT . unTclM
execTclM c e = do
(r,s) <- runTclM c e
case r of
Right _ -> return s
Left e -> error (show e)
|
tolysz/hiccup
|
Internal/Types.hs
|
lgpl-2.1
| 3,018 | 0 | 12 | 799 | 911 | 518 | 393 | 122 | 2 |
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
--------------------------------------------------------------------------------
{-| Module : Window
Copyright : (c) Daan Leijen 2003
License : wxWindows
Maintainer : [email protected]
Stability : provisional
Portability : portable
Exports default instances for generic windows.
* Instances: 'Textual', 'Literate', 'Dimensions', 'Colored', 'Visible',
'Child', 'Sized', 'Parent', 'Help', 'Bordered',
'Able', 'Tipped', 'Identity', 'Styled', 'Reactive', 'Paint'.
-}
--------------------------------------------------------------------------------
module Graphics.UI.WX.Window
( -- * Window
Window, window, refit, refitMinimal, rootParent, frameParent, tabTraversal
-- * ScrolledWindow
, ScrolledWindow, scrolledWindow, scrollRate
-- * Internal
, initialWindow, initialContainer
, initialIdentity, initialStyle, initialText
, initialFullRepaintOnResize, initialClipChildren
) where
import Graphics.UI.WXCore
import Graphics.UI.WX.Types
import Graphics.UI.WX.Attributes
import Graphics.UI.WX.Layout
import Graphics.UI.WX.Classes
import Graphics.UI.WX.Events
{--------------------------------------------------------------------------------
ScrolledWindow
--------------------------------------------------------------------------------}
-- | A scrollable window. Use 'virtualSize' and 'scrollRate' to set the scrollbar
-- behaviour.
--
-- * Attributes: 'scrollRate'
--
-- * Instances: 'Textual', 'Literate', 'Dimensions', 'Colored', 'Visible', 'Child',
-- 'Able', 'Tipped', 'Identity', 'Styled', 'Reactive', 'Paint'.
--
scrolledWindow :: Window a -> [Prop (ScrolledWindow ())] -> IO (ScrolledWindow ())
scrolledWindow parent props
= feed2 props 0 $
initialContainer $ \id rect -> \props style ->
do sw <- scrolledWindowCreate parent id rect style
set sw props
return sw
-- | The horizontal and vertical scroll rate of scrolled window. Use @0@ to disable
-- scrolling in that direction.
scrollRate :: Attr (ScrolledWindow a) Size
scrollRate
= newAttr "scrollRate" getter setter
where
getter sw
= do p <- scrolledWindowGetScrollPixelsPerUnit sw
return (sizeFromPoint p)
setter sw size
= scrolledWindowSetScrollRate sw (sizeW size) (sizeH size)
{--------------------------------------------------------------------------------
Plain window
--------------------------------------------------------------------------------}
-- | Create a plain window. Can be used to define custom controls for example.
--
-- * Attributes: 'rootParent', 'frameParent', 'tabTraversal'
--
-- * Instances: 'Textual', 'Literate', 'Dimensions', 'Colored', 'Visible', 'Child',
-- 'Able', 'Tipped', 'Identity', 'Styled', 'Reactive', 'Paint'.
window :: Window a -> [Prop (Window ())] -> IO (Window ())
window parent props
= feed2 props 0 $
initialWindow $ \id rect -> \props flags ->
do w <- windowCreate parent id rect flags
set w props
return w
{--------------------------------------------------------------------------------
Properties
--------------------------------------------------------------------------------}
-- | Helper function that retrieves initial window settings, including
-- |identity|, |style|, and |area| (or |position| and |outerSize|).
initialWindow :: (Id -> Rect -> [Prop (Window w)] -> Style -> a) -> [Prop (Window w)] -> Style -> a
initialWindow cont
= initialIdentity $ \id ->
initialArea $ \rect ->
initialStyle $
initialBorder $
cont id rect
-- | Helper function that retrieves initial window settings, including |clipChildren|
-- and |fullRepaintOnResize|.
initialContainer :: (Id -> Rect -> [Prop (Window w)] -> Style -> a) -> [Prop (Window w)] -> Style -> a
initialContainer cont
= initialWindow $ \id rect ->
initialFullRepaintOnResize $
initialClipChildren $
cont id rect
instance Able (Window a) where
enabled
= newAttr "enabled" windowIsEnabled setter
where
setter w enable
| enable = unitIO $ windowEnable w
| otherwise = unitIO $ windowDisable w
instance Textual (Window a) where
text
= reflectiveAttr "text" getter setter
where
getter w
= fst (getset w)
setter w x
= snd (getset w) x
getset w
= ifInstanceOf w classComboBox
(\cb -> (comboBoxGetValue cb, \s -> do comboBoxClear cb; comboBoxAppend cb s)) $
ifInstanceOf w classTextCtrl
(\tc -> (textCtrlGetValue tc, \s -> do textCtrlChangeValue tc s)) $
(windowGetLabel w,windowSetLabel w)
appendText w s
= ifInstanceOf w classComboBox
(\cb -> comboBoxAppend cb s) $
ifInstanceOf w classTextCtrl
(\tc -> textCtrlAppendText tc s)
(set w [text :~ (++s)])
-- | Retrieve the initial title from the |text| attribute.
initialText :: Textual w => (String -> [Prop w] -> a) -> [Prop w] -> a
initialText cont props
= withProperty text "" cont props
instance Dimensions (Window a) where
outerSize
= newAttr "size" windowGetSize setSize
where
setSize w sz
= windowSetSize w (rect (pt (-1) (-1)) sz) wxSIZE_USE_EXISTING
area
= newAttr "area" windowGetRect setArea
where
setArea w rect
= windowSetSize w rect wxSIZE_USE_EXISTING
bestSize
= readAttr "bestSize" windowGetEffectiveMinSize
position
= newAttr "position" windowGetPosition windowMove
clientSize
= newAttr "clientSize" windowGetClientSize windowSetClientSize
virtualSize
= newAttr "virtualSize" windowGetVirtualSize windowSetVirtualSize
instance Sized (Window a) where
size = outerSize
-- | Retrieve the initial creation area from the |area|, or the |position| and
-- |outerSize| properties.
initialArea :: Dimensions w => (Rect -> [Prop w] -> a) -> [Prop w] -> a
initialArea cont props
= case findProperty area rectNull props of
Just (rect,props') -> cont rect props'
Nothing
-> case findProperty position pointNull props of
Just (p,props') -> case findProperty outerSize sizeNull props of
Just (sz,props'') -> cont (rect p sz) props''
Nothing -> cont (rect p sizeNull) props'
Nothing -> case findProperty outerSize sizeNull props of
Just (sz,props') -> cont (rect pointNull sz) props'
Nothing -> cont rectNull props
instance Colored (Window a) where
bgcolor
= newAttr "bgcolor" windowGetBackgroundColour (\w x -> do{ windowSetBackgroundColour w x; return ()})
color
= newAttr "color" windowGetForegroundColour (\w x -> do windowSetForegroundColour w x; return ())
instance Literate (Window a) where
font
= newAttr "font" getter setter
where
getter w
= ifInstanceOf w classTextCtrl
(\textCtrl -> bracket (textCtrlGetDefaultStyle textCtrl)
(textAttrDelete)
(\attr -> do hasFont <- textAttrHasFont attr
if (hasFont)
then getFont (textAttrGetFont attr)
else getFont (windowGetFont w)))
(getFont (windowGetFont w))
where
getFont io
= bracket io fontDelete fontGetFontStyle
setter w info
= ifInstanceOf w classTextCtrl
(\textCtrl -> bracket (textAttrCreateDefault)
(textAttrDelete)
(\attr -> withFontStyle info $ \fnt ->
do textAttrSetFont attr fnt
textCtrlSetDefaultStyle textCtrl attr
return ()))
(withFontStyle info $ \fnt ->
do windowSetFont w fnt
return ())
textColor
= newAttr "textcolor" getter setter
where
getter w
= ifInstanceOf w classTextCtrl
(\textCtrl -> bracket (textCtrlGetDefaultStyle textCtrl)
(textAttrDelete)
(\attr -> do hasColor <- textAttrHasTextColour attr
if (hasColor) then textAttrGetTextColour attr
else get w color))
(get w color)
setter w c
= ifInstanceOf w classTextCtrl
(\textCtrl -> bracket (textAttrCreateDefault)
(textAttrDelete)
(\attr -> do textAttrSetTextColour attr c
textCtrlSetDefaultStyle textCtrl attr
return ()))
(set w [color := c])
textBgcolor
= newAttr "textbgcolor" getter setter
where
getter w
= ifInstanceOf w classTextCtrl
(\textCtrl -> bracket (textCtrlGetDefaultStyle textCtrl)
(textAttrDelete)
(\attr -> do hasColor <- textAttrHasBackgroundColour attr
if (hasColor) then textAttrGetBackgroundColour attr
else get w bgcolor))
(get w bgcolor)
setter w c
= ifInstanceOf w classTextCtrl
(\textCtrl -> bracket (textAttrCreateDefault)
(textAttrDelete)
(\attr -> do textAttrSetBackgroundColour attr c
textCtrlSetDefaultStyle textCtrl attr
return ()))
(set w [bgcolor := c])
instance Visible (Window a) where
visible
= newAttr "visible" windowIsShown setVisible
where
setVisible w vis
= if vis
then do{ windowShow w; windowRaise w }
else unitIO (windowHide w)
refresh w
= windowRefresh w True
fullRepaintOnResize
= reflectiveAttr "fullRepaintOnResize" getFlag setFlag
where
getFlag w
= do s <- get w style
return (not (bitsSet wxNO_FULL_REPAINT_ON_RESIZE s))
setFlag w repaint
= set w [style :~ \stl -> if repaint
then stl .-. wxNO_FULL_REPAINT_ON_RESIZE
else stl .+. wxNO_FULL_REPAINT_ON_RESIZE]
instance Parent (Window a) where
children
= readAttr "children" windowChildren
clipChildren
= reflectiveAttr "clipChildren" getFlag setFlag
where
getFlag w
= do s <- get w style
return (bitsSet wxCLIP_CHILDREN s)
setFlag w clip
= set w [style :~ \stl -> if clip
then stl .+. wxCLIP_CHILDREN
else stl .-. wxCLIP_CHILDREN]
-- | Helper function that transforms the style accordding
-- to the 'fullRepaintOnResize' flag in of the properties
initialFullRepaintOnResize :: Visible w => ([Prop w] -> Style -> a) -> [Prop w] -> Style -> a
initialFullRepaintOnResize
= withStylePropertyNot fullRepaintOnResize wxNO_FULL_REPAINT_ON_RESIZE
-- | Helper function that transforms the style accordding
-- to the 'clipChildren' flag out of the properties
initialClipChildren :: Parent w => ([Prop w] -> Style -> a) -> [Prop w] -> Style -> a
initialClipChildren
= withStyleProperty clipChildren wxCLIP_CHILDREN
instance Child (Window a) where
parent
= readAttr "parent" windowGetParent
-- | Ensure that a widget is refitted inside a window when
-- its size changes, for example when the 'text' of a
-- 'staticText' control changes. (calls 'windowReFit')
refit :: Window a -> IO ()
refit w
= windowReFit w
-- | Ensure that a widget is refitted inside a window when
-- its size changes, for example when the 'text' of a
-- 'staticText' control changes. Always resizes the
-- window to its minimal acceptable size. (calls 'windowReFitMinimal')
refitMinimal :: Window a -> IO ()
refitMinimal w
= windowReFitMinimal w
-- | The ultimate root parent of the widget.
rootParent :: ReadAttr (Window a) (Window ())
rootParent
= readAttr "rootParent" windowGetRootParent
-- | The parent frame or dialog of a widget.
frameParent :: ReadAttr (Window a) (Window ())
frameParent
= readAttr "frameParent" windowGetFrameParent
-- | Enable (or disable) tab-traversal. (= wxTAB_TRAVERSAL)
tabTraversal :: Attr (Window a) Bool
tabTraversal
= newAttr "tabTraversal" getter setter
where
getter w
= do st <- get w style
return (bitsSet wxTAB_TRAVERSAL st)
setter w enable
= set w [style :~ \stl -> if enable then stl .+. wxTAB_TRAVERSAL else stl .-. wxTAB_TRAVERSAL]
instance Identity (Window a) where
identity
= reflectiveAttr "identity" windowGetId windowSetId
-- | Helper function that retrieves the initial |identity|.
initialIdentity :: Identity w => (Id -> [Prop w] -> a) -> [Prop w] -> a
initialIdentity
= withProperty identity idAny
instance Styled (Window a) where
style
= reflectiveAttr "style" windowGetWindowStyleFlag windowSetWindowStyleFlag
-- | Helper function that retrieves the initial |style|.
initialStyle :: Styled w => ([Prop w] -> Style -> a) -> [Prop w] -> Style -> a
initialStyle cont props stl
= withProperty style stl (\stl' props' -> cont props' stl') props
instance Tipped (Window a) where
tooltip
= newAttr "tooltip" windowGetToolTip windowSetToolTip
{-
instance Help (Window a) where
help
= newAttr "help" windowSetHelpText windowGetHelpText
-}
{--------------------------------------------------------------------------------
Borders
--------------------------------------------------------------------------------}
instance Bordered (Window a) where
border
= reflectiveAttr "border" getter setter
where
getter w
= do st <- get w style
return (fromBitMask st)
setter w b
= set w [style :~ \stl -> setBitMask b stl]
initialBorder cont props style
= case filterProperty border props of
(PropValue x, ps) -> cont ps (setBitMask x style)
(PropModify f, ps) -> cont ps (setBitMask (f (fromBitMask style)) style)
(PropNone, ps) -> cont ps style
{--------------------------------------------------------------------------------
Events
--------------------------------------------------------------------------------}
instance Reactive (Window a) where
mouse = newEvent "mouse" windowGetOnMouse (\w h -> windowOnMouse w True h)
keyboard = newEvent "keyboard" windowGetOnKeyChar (windowOnKeyChar)
closing = newEvent "closing" windowGetOnClose windowOnClose
idle = newEvent "idle" windowGetOnIdle windowOnIdle
resize = newEvent "resize" windowGetOnSize windowOnSize
focus = newEvent "focus" windowGetOnFocus windowOnFocus
activate = newEvent "activate" windowGetOnActivate windowOnActivate
instance Paint (Window a) where
paint = newEvent "paint" windowGetOnPaint (\w h -> windowOnPaint w h)
paintRaw = newEvent "paintRaw" windowGetOnPaintRaw (\w h -> windowOnPaintRaw w h)
repaint w = windowRefresh w False
|
ekmett/wxHaskell
|
wx/src/Graphics/UI/WX/Window.hs
|
lgpl-2.1
| 15,573 | 0 | 19 | 4,469 | 3,438 | 1,750 | 1,688 | 273 | 5 |
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module: SwiftNav.SBP.System
-- Copyright: Copyright (C) 2015 Swift Navigation, Inc.
-- License: LGPL-3
-- Maintainer: Mark Fine <[email protected]>
-- Stability: experimental
-- Portability: portable
--
-- Standardized system messages from Swift Navigation devices.
module SwiftNav.SBP.System where
import BasicPrelude
import Control.Lens
import Control.Monad.Loops
import Data.Aeson.TH (defaultOptions, deriveJSON, fieldLabelModifier)
import Data.Binary
import Data.Binary.Get
import Data.Binary.IEEE754
import Data.Binary.Put
import Data.ByteString
import Data.ByteString.Lazy hiding (ByteString)
import Data.Int
import Data.Word
import SwiftNav.SBP.Encoding
import SwiftNav.SBP.TH
import SwiftNav.SBP.Types
msgStartup :: Word16
msgStartup = 0xFF00
-- | SBP class for message MSG_STARTUP (0xFF00).
--
-- The system start-up message is sent once on system start-up. It notifies the
-- host or other attached devices that the system has started and is now ready
-- to respond to commands or configuration requests.
data MsgStartup = MsgStartup
{ _msgStartup_reserved :: Word32
-- ^ Reserved
} deriving ( Show, Read, Eq )
instance Binary MsgStartup where
get = do
_msgStartup_reserved <- getWord32le
return MsgStartup {..}
put MsgStartup {..} = do
putWord32le _msgStartup_reserved
$(deriveSBP 'msgStartup ''MsgStartup)
$(deriveJSON defaultOptions {fieldLabelModifier = fromMaybe "_msgStartup_" . stripPrefix "_msgStartup_"}
''MsgStartup)
$(makeLenses ''MsgStartup)
msgHeartbeat :: Word16
msgHeartbeat = 0xFFFF
-- | SBP class for message MSG_HEARTBEAT (0xFFFF).
--
-- The heartbeat message is sent periodically to inform the host or other
-- attached devices that the system is running. It is used to monitor system
-- malfunctions. It also contains status flags that indicate to the host the
-- status of the system and whether it is operating correctly. Currently, the
-- expected heartbeat interval is 1 sec. The system error flag is used to
-- indicate that an error has occurred in the system. To determine the source
-- of the error, the remaining error flags should be inspected.
data MsgHeartbeat = MsgHeartbeat
{ _msgHeartbeat_flags :: Word32
-- ^ Status flags
} deriving ( Show, Read, Eq )
instance Binary MsgHeartbeat where
get = do
_msgHeartbeat_flags <- getWord32le
return MsgHeartbeat {..}
put MsgHeartbeat {..} = do
putWord32le _msgHeartbeat_flags
$(deriveSBP 'msgHeartbeat ''MsgHeartbeat)
$(deriveJSON defaultOptions {fieldLabelModifier = fromMaybe "_msgHeartbeat_" . stripPrefix "_msgHeartbeat_"}
''MsgHeartbeat)
$(makeLenses ''MsgHeartbeat)
|
swift-nav/libsbp
|
haskell/src/SwiftNav/SBP/System.hs
|
lgpl-3.0
| 2,725 | 0 | 11 | 460 | 432 | 243 | 189 | -1 | -1 |
--função simples de média
mediaDeDoisNumeros numero1 numero2 = (numero1 + numero2) / 2
resultadoDaMediaDeDoisNumeros = mediaDeDoisNumeros 2 5
resultadoDaMediaDeDoisNumeros_UsandoInfixNotation = 2 `mediaDeDoisNumeros` 5
resultadoDaMediaDaMedia = (2 `mediaDeDoisNumeros` 5) `mediaDeDoisNumeros` 10
--verificação de um número
ehMultiploDeCincoOuTres numero = (numero `mod` 3) == 0 || (numero `mod` 5) == 0
resultadoDeVerificacao_Verdadeiro = ehMultiploDeCincoOuTres(15)
resultadoDeVerificacao_Falso = ehMultiploDeCincoOuTres(7)
escreveUmResutadoDeVerificacao x = if ehMultiploDeCincoOuTres x
then "O número é multiplo de 3 ou 5"
else "O número não é multiplo de 3 ou 5"
--monta uma lista de numeros 0 a 100 que passam pela verificação
numerosDeZeroACem = [1..100]
numerosMultiplosDeCioncoOuTres = [x | x <- numerosDeZeroACem , ehMultiploDeCincoOuTres x]
--verifica se o nome contem na lista, usando funções com assinaturas de tipos
listaDeJogadores = ["Jobson","Kleiston","Ronaldo","Suelinton"]
temCraqueNaLista :: [String] -> Bool
temCraqueNaLista lista = "Ronaldo" `elem` lista
resultadoDeCraque = temCraqueNaLista listaDeJogadores
--remove vogais de uma string
removerVogais :: String -> String
removerVogais texto = [x | x <- texto, not (x `elem` "aeiouAEIOU")]
resultadoDeRemoverVogais = removerVogais "Olha esse é um texto com um monte de vogais!"
--junta 2 listas em 1
listaDeNumeros_A = [10,20,30,40,50]
listaDeNumeros_B = [8, 13, 18]
juntaDuasListas :: Eq a => [a] -> [a] -> [a]
juntaDuasListas lista1 [] = lista1
juntaDuasListas lista1 (elementoLista2:lista2) | elementoLista2 `elem` lista1 = juntaDuasListas lista1 lista2
| otherwise = juntaDuasListas (lista1 ++ [elementoLista2]) lista2
resultadoDeJuncaoDeDuasListas = listaDeNumeros_A `juntaDuasListas` listaDeNumeros_B
--printa algum resultado
main = print resultadoDeJuncaoDeDuasListas
|
leonardi-tutorials/tutorial-haskell
|
Main.hs
|
apache-2.0
| 1,969 | 0 | 9 | 334 | 437 | 247 | 190 | 27 | 2 |
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell, OverloadedStrings, DeriveDataTypeable #-}
import System.Console.CmdArgs.FromHelp
import System.Console.CmdArgs hiding (cmdArgsHelp)
import System.Environment (getArgs)
{-printHelp :: Annotate Ann -> IO ()-}
{-printHelp a = print =<< (cmdArgs_ a :: IO FromHelpArgs)-}
{-
main :: IO ()
main = print =<< processArgs [cmdArgsHelp|
-}
mkCmdArgs [fromHelp|
The sample program
sample [COMMAND] ... [OPTIONS]
Common flags
-? --help Display help message
-V --version Print version information
-w --whom=GUY
sample hello [OPTIONS]
-t --top Top of the Morning to you!
sample goodbye [OPTIONS]
-s --sianara
-c --ciao
|]
main :: IO ()
main = do
print defaultHello
print defaultGoodbye
args <- getArgs
if "--help" `elem` args || "-?" `elem` args
-- helpContents and default.. are references generated by mkCmdArgs
then putStrLn sampleHelpContents
else print =<< cmdArgs (modes [defaultHello, defaultGoodbye])
{-
dist/build/test/test goodbye -s sucker
Hello {top = "", whom = ""}
Goodbye {whom = "", sianara = "", ciao = ""}
Goodbye {whom = "", sianara = "sucker", ciao = ""}
-}
|
gregwebs/ParseHelp.hs
|
test/Help.hs
|
bsd-2-clause
| 1,189 | 0 | 12 | 230 | 130 | 74 | 56 | 14 | 2 |
module Database.SqlServer.Definition.FullTextStopList
(
FullTextStopList
) where
import Database.SqlServer.Definition.Identifier
import Database.SqlServer.Definition.Entity
import Test.QuickCheck
import Text.PrettyPrint
import Control.Monad
data FullTextStopList = FullTextStopList
{
stoplistName :: RegularIdentifier
, sourceStopList :: Maybe (Maybe FullTextStopList)
}
instance Arbitrary FullTextStopList where
arbitrary = do
x <- arbitrary
y <- frequency [(50, return Nothing), (50,arbitrary)]
return (FullTextStopList x y)
instance Entity FullTextStopList where
name = stoplistName
toDoc f = maybe empty toDoc (join (sourceStopList f)) $+$
text "CREATE FULLTEXT STOPLIST" <+>
renderName f <+>
maybe (text ";") (\q -> text "FROM" <+>
maybe (text "SYSTEM STOPLIST;\n") (\x -> renderRegularIdentifier (stoplistName x) <> text ";\n") q <>
text "GO\n") (sourceStopList f)
|
SuperDrew/sql-server-gen
|
src/Database/SqlServer/Definition/FullTextStopList.hs
|
bsd-2-clause
| 1,025 | 0 | 18 | 257 | 273 | 144 | 129 | 24 | 0 |
--
-- Copyright (c) 2013, Carl Joachim Svenn
-- All rights reserved.
--
-- 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.
--
-- 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.
--
module GUI.Widget.BorderWidget
(
BorderWidget,
makeBorderWidget,
makeBorderWidgetSize,
) where
import MyPrelude
import GUI.Widget
import GUI.Widget.Output
import GUI.Widget.Helpers
import GUI.Widget.ChildWidget
data BorderWidget a =
BorderWidget
{
borderChild :: !(ChildWidget a),
borderSize :: !Float
}
instance Widget BorderWidget where
widgetShape = borderShape
widgetBegin = borderBegin
widgetEatInput = borderEatInput
widgetIterate = borderIterate
--------------------------------------------------------------------------------
-- Widget structure
borderShape :: GUIData -> GUIState -> BorderWidget a -> GUIShape
borderShape gd gs = \border ->
let size = borderSize border
GUIShape wth hth = widgetShape gd gs (borderChild border)
in GUIShape (2.0 * size + wth) (2.0 * size + hth)
borderBegin :: GUIData -> GUIState -> BorderWidget a -> IO (BorderWidget a)
borderBegin gd gs border = do
child' <- widgetBegin gd gs (borderChild border)
return border { borderChild = child' }
borderEatInput :: GUIData -> GUIState -> BorderWidget a -> WidgetInput -> BorderWidget a
borderEatInput gd gs border wi =
let gs' = gdgsPlusPos gd gs (GUIPos (borderSize border) (borderSize border))
in border { borderChild = widgetEatInput gd gs' (borderChild border) wi }
borderIterate :: GUIData -> GUIState -> BorderWidget a -> a -> IO (BorderWidget a, a)
borderIterate gd gs border a = do
gs' <- plusPos gd gs (GUIPos (borderSize border) (borderSize border))
-- draw FillTexBack before children
gs'' <- useTexFillTexStencil gd gs' 0 (guidataFillTexBack gd)
(guidataBorderWidgetStencil gd) 0
let shape = widgetShape gd gs'' (borderChild border)
draw24ShapeAddSize gd gs'' shape (borderSize border)
gs''' <- useFillTex gd gs'' (guidataFillTexMid gd)
gs'''' <- incDepth gd gs'''
-- iterate child
(child', a') <- widgetIterate gd gs'''' (borderChild border) a
resetDepth gd gs
useTexStencil gd gs'''' 0 (guidataBorderWidgetStencil gd) 0
draw24ShapeAddSize gd gs'''' shape (borderSize border)
-- reset GUIState
resetFillTex gd gs
resetPos gd gs
return (border { borderChild = child' }, a')
--------------------------------------------------------------------------------
-- make
makeBorderWidgetSize :: Widget w => GUIData -> Float -> w a -> BorderWidget a
makeBorderWidgetSize gd size = \child ->
BorderWidget
{
borderChild = makeChildWidget gd child,
borderSize = size
}
makeBorderWidget :: Widget w => GUIData -> w a -> BorderWidget a
makeBorderWidget gd = \child ->
makeBorderWidgetSize gd size child
where
size = 0.02 -- ^ default size
|
karamellpelle/MEnv
|
source/GUI/Widget/BorderWidget.hs
|
bsd-2-clause
| 4,281 | 0 | 13 | 963 | 827 | 428 | 399 | 61 | 1 |
module Drasil.GlassBR.DataDefs (aspRat, dataDefs, dimLL, qDefns, glaTyFac,
hFromt, loadDF, nonFL, risk, standOffDis, strDisFac, tolPre, tolStrDisFac,
eqTNTWDD, probOfBreak, calofCapacity, calofDemand, pbTolUsr, qRef) where
import Control.Lens ((^.))
import Language.Drasil
import Language.Drasil.Code (asVC')
import Prelude hiding (log, exp, sqrt)
import Theory.Drasil (DataDefinition, dd, mkQuantDef)
import Database.Drasil (Block(Parallel))
import Utils.Drasil
import Data.Drasil.Concepts.Documentation (datum, user)
import Data.Drasil.Concepts.Math (parameter)
import Data.Drasil.Concepts.PhysicalProperties (dimension)
import Data.Drasil.Citations (campidelli)
import Drasil.GlassBR.Assumptions (assumpSV, assumpLDFC)
import Drasil.GlassBR.Concepts (annealed, fullyT, glass, heatS)
import Drasil.GlassBR.Figures (demandVsSDFig, dimlessloadVsARFig)
import Drasil.GlassBR.ModuleDefs (interpY, interpZ)
import Drasil.GlassBR.References (astm2009, beasonEtAl1998)
import Drasil.GlassBR.Unitals (actualThicknesses, aspectRatio, charWeight,
demand, demandq, dimlessLoad, eqTNTWeight, gTF, glassType, glassTypeCon,
glassTypeFactors, lDurFac, lRe, loadDur, loadSF, minThick, modElas, nomThick,
nominalThicknesses, nonFactorL, pbTol, plateLen, plateWidth, probBr, riskFun,
sdfTol, sdx, sdy, sdz, sflawParamK, sflawParamM, standOffDist, stressDistFac,
tNT, tolLoad)
----------------------
-- DATA DEFINITIONS --
----------------------
dataDefs :: [DataDefinition]
dataDefs = [risk, hFromt, loadDF, strDisFac, nonFL, glaTyFac,
dimLL, tolPre, tolStrDisFac, standOffDis, aspRat, eqTNTWDD, probOfBreak,
calofCapacity, calofDemand]
qDefns :: [Block QDefinition]
qDefns = Parallel hFromtQD {-DD2-} [glaTyFacQD {-DD6-}] : --can be calculated on their own
map (flip Parallel []) [dimLLQD {-DD7-}, strDisFacQD {-DD4-}, riskQD {-DD1-},
tolStrDisFacQD {-DD9-}, tolPreQD {-DD8-}, nonFLQD {-DD5-}]
--DD1--
riskEq :: Expr
riskEq = sy sflawParamK /
(sy plateLen * sy plateWidth) $^ (sy sflawParamM - 1) *
(sy modElas * square (sy minThick)) $^ sy sflawParamM
* sy lDurFac * exp (sy stressDistFac)
-- FIXME [4] !!!
riskQD :: QDefinition
riskQD = mkQuantDef riskFun riskEq
risk :: DataDefinition
risk = dd riskQD
[makeCite astm2009, makeCiteInfo beasonEtAl1998 $ Equation [4, 5],
makeCiteInfo campidelli $ Equation [14]]
Nothing "riskFun" [aGrtrThanB, hRef, ldfRef, jRef]
--DD2--
hFromtEq :: Relation
hFromtEq = (1/1000) * incompleteCase (zipWith hFromtHelper
actualThicknesses nominalThicknesses)
hFromtHelper :: Double -> Double -> (Expr, Relation)
hFromtHelper result condition = (dbl result, sy nomThick $= dbl condition)
hFromtQD :: QDefinition
hFromtQD = mkQuantDef minThick hFromtEq
hFromt :: DataDefinition
hFromt = dd hFromtQD [makeCite astm2009] Nothing "minThick" [hMin]
--DD3-- (#749)
loadDFEq :: Expr
loadDFEq = (sy loadDur / 60) $^ (sy sflawParamM / 16)
loadDFQD :: QDefinition
loadDFQD = mkQuantDef lDurFac loadDFEq
loadDF :: DataDefinition
loadDF = dd loadDFQD [makeCite astm2009] Nothing "loadDurFactor"
[stdVals [loadDur, sflawParamM], ldfConst]
--DD4--
strDisFacEq :: Expr
-- strDisFacEq = apply (sy stressDistFac)
-- [sy dimlessLoad, sy aspectRatio]
strDisFacEq = apply (asVC' interpZ) [Str "SDF.txt", sy aspectRatio, sy dimlessLoad]
strDisFacQD :: QDefinition
strDisFacQD = mkQuantDef stressDistFac strDisFacEq
strDisFac :: DataDefinition
strDisFac = dd strDisFacQD [makeCite astm2009] Nothing "stressDistFac"
[interpolating stressDistFac dimlessloadVsARFig, arRef, qHtRef]
--DD5--
nonFLEq :: Expr
nonFLEq = (sy tolLoad * sy modElas * sy minThick $^ 4) /
square (sy plateLen * sy plateWidth)
nonFLQD :: QDefinition
nonFLQD = mkQuantDef nonFactorL nonFLEq
nonFL :: DataDefinition
nonFL = dd nonFLQD [makeCite astm2009] Nothing "nFL"
[qHtTlTolRef, stdVals [modElas], hRef, aGrtrThanB]
--DD6--
glaTyFacEq :: Expr
glaTyFacEq = incompleteCase (zipWith glaTyFacHelper glassTypeFactors $ map (getAccStr . snd) glassType)
glaTyFacHelper :: Integer -> String -> (Expr, Relation)
glaTyFacHelper result condition = (int result, sy glassTypeCon $= str condition)
glaTyFacQD :: QDefinition
glaTyFacQD = mkQuantDef gTF glaTyFacEq
glaTyFac :: DataDefinition
glaTyFac = dd glaTyFacQD [makeCite astm2009] Nothing "gTF"
[anGlass, ftGlass, hsGlass]
--DD7--
dimLLEq :: Expr
dimLLEq = (sy demand * square (sy plateLen * sy plateWidth))
/ (sy modElas * (sy minThick $^ 4) * sy gTF)
dimLLQD :: QDefinition
dimLLQD = mkQuantDef dimlessLoad dimLLEq
dimLL :: DataDefinition
dimLL = dd dimLLQD [makeCite astm2009, makeCiteInfo campidelli $ Equation [7]] Nothing "dimlessLoad"
[qRef, aGrtrThanB, stdVals [modElas], hRef, gtfRef]
--DD8--
tolPreEq :: Expr
--tolPreEq = apply (sy tolLoad) [sy sdfTol, (sy plateLen) / (sy plateWidth)]
tolPreEq = apply (asVC' interpY) [Str "SDF.txt", sy aspectRatio, sy sdfTol]
tolPreQD :: QDefinition
tolPreQD = mkQuantDef tolLoad tolPreEq
tolPre :: DataDefinition
tolPre = dd tolPreQD [makeCite astm2009] Nothing "tolLoad"
[interpolating tolLoad dimlessloadVsARFig, arRef, jtolRef]
--DD9--
tolStrDisFacEq :: Expr
tolStrDisFacEq = ln (ln (1 / (1 - sy pbTol))
* ((sy plateLen * sy plateWidth) $^ (sy sflawParamM - 1) /
(sy sflawParamK * (sy modElas *
square (sy minThick)) $^ sy sflawParamM * sy lDurFac)))
tolStrDisFacQD :: QDefinition
tolStrDisFacQD = mkQuantDef sdfTol tolStrDisFacEq
tolStrDisFac :: DataDefinition
tolStrDisFac = dd tolStrDisFacQD [makeCite astm2009] Nothing "sdfTol"
[pbTolUsr, aGrtrThanB, stdVals [sflawParamM, sflawParamK, mkUnitary modElas],
hRef, ldfRef]
--DD10--
standOffDisEq :: Expr
standOffDisEq = sqrt (sy sdx $^ 2 + sy sdy $^ 2 + sy sdz $^ 2)
standOffDisQD :: QDefinition
standOffDisQD = mkQuantDef standOffDist standOffDisEq
standOffDis :: DataDefinition
standOffDis = dd standOffDisQD [makeCite astm2009] Nothing "standOffDist" []
--DD11--
aspRatEq :: Expr
aspRatEq = sy plateLen / sy plateWidth
aspRatQD :: QDefinition
aspRatQD = mkQuantDef aspectRatio aspRatEq
aspRat :: DataDefinition
aspRat = dd aspRatQD [makeCite astm2009] Nothing "aspectRatio" [aGrtrThanB]
--DD12--
eqTNTWEq :: Expr
eqTNTWEq = sy charWeight * sy tNT
eqTNTWQD :: QDefinition
eqTNTWQD = mkQuantDef eqTNTWeight eqTNTWEq
eqTNTWDD :: DataDefinition
eqTNTWDD = dd eqTNTWQD [makeCite astm2009] Nothing "eqTNTW" []
--DD13--
probOfBreakEq :: Expr
probOfBreakEq = 1 - exp (negate (sy risk))
probOfBreakQD :: QDefinition
probOfBreakQD = mkQuantDef probBr probOfBreakEq
probOfBreak :: DataDefinition
probOfBreak = dd probOfBreakQD (map makeCite [astm2009, beasonEtAl1998]) Nothing "probOfBreak" [riskRef]
--DD14--
calofCapacityEq :: Expr
calofCapacityEq = sy nonFL * sy glaTyFac * sy loadSF
calofCapacityQD :: QDefinition
calofCapacityQD = mkQuantDef lRe calofCapacityEq
calofCapacity :: DataDefinition
calofCapacity = dd calofCapacityQD [makeCite astm2009] Nothing "calofCapacity"
[lrCap, nonFLRef, gtfRef]
--DD15--
calofDemandEq :: Expr
calofDemandEq = apply (asVC' interpY) [Str "TSD.txt", sy standOffDist, sy eqTNTWeight]
calofDemandQD :: QDefinition
calofDemandQD = mkQuantDef demand calofDemandEq
calofDemand :: DataDefinition
calofDemand = dd calofDemandQD [makeCite astm2009] Nothing "calofDemand" [calofDemandDesc]
--Additional Notes--
calofDemandDesc :: Sentence
calofDemandDesc =
foldlSent [ch demand `sC` EmptyS `sOr` phrase demandq `sC` EmptyS `isThe`
(demandq ^. defn), S "obtained from", makeRef2S demandVsSDFig,
S "by interpolation using", phrase standOffDist, sParen (ch standOffDist)
`sAnd` ch eqTNTWeight, S "as" +:+. plural parameter, ch eqTNTWeight,
S "is defined in" +:+. makeRef2S eqTNTWDD, ch standOffDist `isThe`
phrase standOffDist, S "as defined in", makeRef2S standOffDis]
aGrtrThanB :: Sentence
aGrtrThanB = ch plateLen `sAnd` ch plateWidth `sAre` (plural dimension `ofThe` S "plate") `sC`
S "where" +:+. sParen (E (sy plateLen $>= sy plateWidth))
anGlass :: Sentence
anGlass = getAcc annealed `sIs` phrase annealed +:+. phrase glass
ftGlass :: Sentence
ftGlass = getAcc fullyT `sIs` phrase fullyT +:+. phrase glass
hMin :: Sentence
hMin = ch nomThick `sIs` S "a function that maps from the nominal thickness"
+:+. (sParen (ch minThick) `toThe` phrase minThick)
hsGlass :: Sentence
hsGlass = getAcc heatS `sIs` phrase heatS +:+. phrase glass
ldfConst :: Sentence
ldfConst = ch lDurFac `sIs` S "assumed to be constant" +:+. fromSource assumpLDFC
lrCap :: Sentence
lrCap = ch lRe +:+. S "is also called capacity"
pbTolUsr :: Sentence
pbTolUsr = ch pbTol `sIs` S "entered by the" +:+. phrase user
qRef :: Sentence
qRef = ch demand `isThe` (demandq ^. defn) `sC` S "as given in" +:+. makeRef2S calofDemand
arRef, gtfRef, hRef, jRef, jtolRef, ldfRef, nonFLRef, qHtRef, qHtTlTolRef, riskRef :: Sentence
arRef = definedIn aspRat
gtfRef = definedIn glaTyFac
hRef = definedIn' hFromt (S "and is based on the nominal thicknesses")
jRef = definedIn strDisFac
jtolRef = definedIn tolStrDisFac
ldfRef = definedIn loadDF
nonFLRef = definedIn nonFL
qHtRef = definedIn dimLL
qHtTlTolRef = definedIn tolPre
riskRef = definedIn risk
--- Helpers
interpolating :: (HasUID s, HasSymbol s, Referable f, HasShortName f) => s -> f -> Sentence
interpolating s f = foldlSent [ch s `sIs` S "obtained by interpolating from",
plural datum, S "shown" `sIn` makeRef2S f]
stdVals :: (HasSymbol s, HasUID s) => [s] -> Sentence
stdVals s = foldlList Comma List (map ch s) +:+ sent +:+. makeRef2S assumpSV
where sent = case s of [ ] -> error "stdVals needs quantities"
[_] -> S "comes from"
(_:_) -> S "come from"
|
JacquesCarette/literate-scientific-software
|
code/drasil-example/Drasil/GlassBR/DataDefs.hs
|
bsd-2-clause
| 9,696 | 0 | 18 | 1,536 | 2,973 | 1,635 | 1,338 | 195 | 3 |
-- | Parses OCaml cil_types.mli file and generates an equivalent CIL.hs file and a supporting Frama-C plugin (-dumpcil).
module Main (main) where
import Data.Char
import Data.List hiding (group)
import System.Process
import Text.ParserCombinators.Poly.Plain
import Text.Printf
main :: IO ()
main = do
f <- readFile "cil_types.mli"
writeFile "cil_types_nocomments.mli" $ decomment f
let types = parseOCaml f
system "mkdir -p install-dumpcil-plugin"
writeFile "install-dumpcil-plugin/Makefile" $ dumpcilMakefile
writeFile "install-dumpcil-plugin/dump_cil.ml" $ dumpcilPlugin types
writeFile "CIL.hs" $ haskellCIL types
-- OCaml type types.
-- Type definitions.
data TypeDef
= Sum [(String, [TypeApply])]
| Record [(String, TypeApply)]
| Alias TypeApply
deriving (Show, Eq)
--- Type definition name with parameters.
data TypeName = TypeName String [String] deriving (Show, Eq)
-- Type references. Either type applications or tuples.
data TypeApply
= TypeApply VarPar [TypeApply]
| TypeApplyGroup TypeApply
deriving (Show, Eq)
-- Type variables or parameters.
data VarPar = Var String | Par String deriving (Show, Eq)
cap :: String -> String
cap [] = []
cap (a:b) = toUpper a : b
isAlias :: TypeDef -> Bool
isAlias (Alias _) = True
isAlias _ = False
-- Haskell CIL module generation.
haskellCIL :: [(TypeName, TypeDef)] -> String
haskellCIL types = unlines
[ "-- | A Haskell interface to OCaml's CIL library, via Frama-C, providing both a simplied C AST and the ACSL specification language."
, "module Language.CIL"
, " ( parseC"
, " , debugParseC"
, " , installPlugin"
, " , Exn (..)"
, " , Position (..)"
, " , Int64 (..)"
, unlines [ printf " , %-26s %s" (cap name) (if isAlias t then "" else "(..)") | (TypeName name _, t) <- types ]
, " )"
, " where"
, ""
, "import System.Exit"
, "import System.Process"
-- , "import Text.Parse"
, ""
, "-- | Parse a C compilation unit (file)."
, "parseC :: FilePath -> IO File"
, "parseC file = do"
, " (exitCode, out, err) <- readProcessWithExitCode \"frama-c\" [\"-dumpcil\", file] \"\""
, " let code = unlines $ tail $ lines out"
, " case exitCode of"
, " ExitSuccess -> return $ read code"
, " ExitFailure _ -> putStrLn err >> exitWith exitCode"
, ""
, "-- | Prints output from frama-c -dumpcil."
, "debugParseC :: FilePath -> IO ()"
, "debugParseC file = do"
, " (exitCode, out, err) <- readProcessWithExitCode \"frama-c\" [\"-dumpcil\", file] \"\""
, " putStrLn out"
, ""
-- {-
-- case exitCode of
-- ExitSuccess -> case runParser parse code of
-- (Left s, a) -> putStrLn ("parse error: " ++ s ++ "\n" ++ code ++ "\n" ++ a) >> exitFailure
-- (Right f, _) -> return f
-- ExitFailure _ -> putStrLn err >> exitWith exitCode
-- -}
, " -- | Installs Frama-C '-dumpcil' plugin. Creates 'install-dumpcil-pluging' directory, deposits a Makefile and dump_cil.ml, then runs 'make' and 'make install'."
, "installPlugin :: IO ()"
, "installPlugin = do"
, " putStrLn \"creating install-dumpcil-plugin directory for plugin compiling and installation ...\""
, " system \"mkdir -p install-dumpcil-plugin\""
, " writeFile \"install-dumpcil-plugin/Makefile\" " ++ show dumpcilMakefile
, " writeFile \"install-dumpcil-plugin/dump_cil.ml\" " ++ show (dumpcilPlugin types)
, " putStrLn \"running 'make' to compile dumpcil plugin ...\""
, " system \"cd install-dumpcil-plugin && make\""
, " putStrLn \"running 'make install' to install dumpcil plugin ...\""
, " system \"cd install-dumpcil-plugin && make install\""
, " return ()"
, ""
, "data Exn = Exn " ++ derives
, "data Position = Position FilePath Int Int " ++ derives
, "data Int64 = Int64 " ++ derives
, ""
, unlines [ printf "%s %s %s = %s %s" (if isAlias t then "type" else "data") (cap name) (intercalate " " params) (fType name t) (if isAlias t then "" else derives) | (TypeName name params, t) <- types ]
]
where
derives = "deriving (Show, Read, Eq) {-! derive : Parse !-}"
fType :: String -> TypeDef -> String
fType name t = case t of
Sum constructors -> intercalate " | " [ constructorName name ++ concat [ " " ++ group (fTypeApply t) | t <- args ] | (name, args) <- constructors ]
Record fields -> printf "%s { %s }" (cap name) $ intercalate ", " [ printf "%s :: %s" field (fTypeApply tr) | (field, tr) <- fields ]
Alias tr -> fTypeApply tr
fTypeApply :: TypeApply -> String
fTypeApply a = case a of
TypeApply a [] -> name a
TypeApply (Var "list") [a] -> "[" ++ fTypeApply a ++ "]"
TypeApply (Var "option") [a] -> "Maybe " ++ group (fTypeApply a)
TypeApply (Var "ref") [a] -> fTypeApply a
TypeApply (Var "tuple") args -> group $ intercalate ", " (map fTypeApply args)
TypeApply a args -> name a ++ concat [ " (" ++ fTypeApply t ++ ")" | t <- args ]
TypeApplyGroup a -> fTypeApply a
where
name (Var n) = cap n
name (Par n) = n
constructorName :: String -> String
constructorName a = case a of
"Block" -> "Block'"
"True" -> "True'"
"False" -> "False'"
"Nothing" -> "Nothing'"
a -> cap a
-- Frama-C 'dumpcil' plugin generation.
dumpcilPlugin :: [(TypeName, TypeDef)] -> String
dumpcilPlugin types = unlines
[ "open Ast"
, "open Cil_types"
, "open File"
, "open Lexing"
, "open List"
, "open String"
, "open Int64"
, "open Char"
, ""
, "let string a = \"\\\"\" ^ a ^ \"\\\"\" (* XXX Doesn't handle '\\' or '\"' chars in string. *)"
, "let position t = \"Position \\\"\" ^ t.pos_fname ^ \"\\\" \" ^ string_of_int t.pos_lnum ^ \" \" ^ string_of_int (t.pos_cnum - t.pos_bol + 1)"
, "let bool a = if a then \"True\" else \"False\""
, "let char = Char.escaped"
, "let int = string_of_int"
, "let int64 = Int64.to_string"
, "let float = string_of_float"
, ""
, "let rec " ++ intercalate "\nand " (map fType types)
, ""
, "let run () ="
, " File.init_from_cmdline ();"
, " print_endline (file (Ast.get ()))"
, ""
, "module Self ="
, " Plugin.Register"
, " (struct"
, " let name = \"dumpcil\""
, " let shortname = \"dumpcil\""
, " let descr = \"Dumps CIL and ACSL to stdout to be read by Haskell CIL.\""
, " end);;"
, ""
, "module Enabled ="
, " Self.False"
, " (struct"
, " let option_name = \"-dumpcil\""
, " let descr = \"Dumps CIL and ACSL to stdout to be read by Haskell CIL.\""
, " end);;"
, ""
, "let () = Db.Main.extend (fun () -> if Enabled.get () then run ())"
]
where
fType :: (TypeName, TypeDef) -> String
fType (TypeName name args, m) = name ++ concatMap (" " ++) args ++ " m = " ++ case m of -- Parametric types are passed formating functions for each of the parameters.
Sum constructors -> function (map constructor constructors) ++ " m"
Record fields -> "\"" ++ cap name ++ " { " ++ intercalate ", " (map field fields) ++ " }\""
Alias m -> fTypeApply m ++ " m"
constructor :: (String, [TypeApply]) -> (String, String)
constructor (name, []) = (name, show $ cap name)
constructor (name, [m]) = (name ++ " m1", show (constructorName name) ++ " ^ \" \" ^ " ++ fTypeApply m ++ " m1")
constructor (name, args) = (name ++ " " ++ group (intercalate ", " [ "m" ++ show i | i <- [1 .. length args] ]), show (constructorName name) ++ concat [ " ^ \" \" ^ " ++ metaGroup (fTypeApply m ++ " m" ++ show i) | (m, i) <- zip args [1..] ])
field :: (String, TypeApply) -> String
field (name, t) = name ++ " = " ++ "\" ^ " ++ fTypeApply t ++ " m." ++ name ++ " ^ \""
-- Returns an OCaml function :: Data -> String
fTypeApply :: TypeApply -> String
fTypeApply m = case m of
TypeApply (Var "exn") [] -> "(fun _ -> \"Exn\")"
TypeApply m [] -> name m -- Vars are top level functions, Params should be functions passed in and thus in scope.
TypeApply (Var "list") [m] -> function [("m", "\"[ \" ^ concat \", \" (map " ++ group (fTypeApply m) ++ " m) ^ \" ]\"")]
TypeApply (Var "option") [m] -> function [("None", show "Nothing"), ("Some m", show "Just " ++ " ^ " ++ metaGroup (fTypeApply m ++ " m"))]
TypeApply (Var "ref") [m] -> function [("m", metaGroup (fTypeApply m ++ " (!m)"))]
TypeApply (Var "tuple") args -> function [(group $ intercalate ", " [ "m" ++ show i | i <- [1 .. length args] ], metaGroup $ intercalate " ^ \", \" ^ " [ metaGroup (fTypeApply m ++ " m" ++ show i) | (m, i) <- zip args [1..] ])]
TypeApply m args -> function [("m", metaGroup (name m ++ concat [ " " ++ function [("m", metaGroup (fTypeApply arg ++ " m"))] | arg <- args ] ++ " m"))]
TypeApplyGroup a -> fTypeApply a
where
name (Var n) = n
name (Par n) = n
function :: [(String, String)] -> String
function matches = group $ "function " ++ intercalate " | " [ a ++ " -> " ++ b | (a, b) <- matches ]
group :: String -> String
group a = "(" ++ a ++ ")"
metaGroup :: String -> String
metaGroup a = group $ "\"(\" ^ " ++ a ++ " ^ \")\""
-- | Makefile used to install the dumpcil plugin.
dumpcilMakefile :: String
dumpcilMakefile = unlines
[ "FRAMAC_SHARE :=$(shell frama-c.byte -print-path)"
, "FRAMAC_LIBDIR :=$(shell frama-c.byte -print-libpath)"
, "PLUGIN_NAME = Dumpcil"
, "PLUGIN_CMO = dump_cil"
, "include $(FRAMAC_SHARE)/Makefile.dynamic"
]
-- Lexing.
data Token
= Type
| Of
| Eq
| Pipe
| Colon
| SemiColon
| Star
| Comma
| ParenLeft
| ParenRight
| BraceLeft
| BraceRight
| Constructor String
| Variable String
| Parameter String
deriving (Show, Eq)
lexer :: String -> [Token]
lexer = map t . filter (/= "mutable") . filter (not . null) . concatMap split . words . decomment
where
split :: String -> [String]
split a = case break isSym a of
(word, []) -> [word]
(word, (a:b)) -> [word, [a]] ++ split b
isSym = flip elem "=|;:*,(){}"
t :: String -> Token
t a = case a of
"type" -> Type
"and" -> Type
"of" -> Of
"=" -> Eq
"|" -> Pipe
":" -> Colon
";" -> SemiColon
"*" -> Star
"," -> Comma
"(" -> ParenLeft
")" -> ParenRight
"{" -> BraceLeft
"}" -> BraceRight
'\'':a -> Parameter a
a | elem '.' a -> t $ tail $ dropWhile (/= '.') a
a:b | isUpper a -> Constructor (a : b)
| otherwise -> Variable (a : b)
a -> error $ "unexpected string: " ++ a
decomment :: String -> String
decomment = decomment' 0
where
decomment' :: Int -> String -> String
decomment' n "" | n == 0 = ""
| otherwise = error "reached end of file without closing comment"
decomment' n ('(':'*':a) = " " ++ decomment' (n + 1) a
decomment' n ('*':')':a) | n > 0 = " " ++ decomment' (n - 1) a
| otherwise = error "unexpected closing comment"
decomment' n (a:b) = (if n > 0 && a /= '\n' then ' ' else a) : decomment' n b
-- Parsing.
type OCaml a = Parser Token a
parseOCaml :: String -> [(TypeName, TypeDef)]
parseOCaml a = case runParser (many typeDef `discard` eof) $ lexer a of
(Left msg, remaining) -> error $ msg ++ "\nremaining tokens: " ++ show (take 30 $ remaining) ++ " ..."
(Right a, []) -> a
(Right _, remaining) -> error $ "parsed, but with remaining tokens: " ++ show remaining
tok :: Token -> OCaml ()
tok a = satisfy (== a) >> return ()
parameter :: OCaml String
parameter = do
a <- satisfy (\ a -> case a of { Parameter _ -> True; _ -> False })
case a of
Parameter s -> return s
_ -> undefined
constructor :: OCaml String
constructor = do
a <- satisfy (\ a -> case a of { Constructor _ -> True; _ -> False })
case a of
Constructor s -> return s
_ -> undefined
variable :: OCaml String
variable = do
a <- satisfy (\ a -> case a of { Variable _ -> True; _ -> False })
case a of
Variable s -> return s
_ -> undefined
typeDef :: OCaml (TypeName, TypeDef)
typeDef = do { tok Type; n <- typeName; tok Eq; e <- typeExpr; return (n, e) }
typeName :: OCaml TypeName
typeName = oneOf
[ do { tok ParenLeft; a <- parameter; b <- many1 (tok Comma >> parameter); tok ParenRight; n <- variable; return $ TypeName n $ a : b }
, do { p <- parameter; n <- variable; return $ TypeName n [p] }
, do { n <- variable; return $ TypeName n [] }
]
varPars :: OCaml [VarPar]
varPars = do { a <- varPar; b <- many varPar; return $ a : b }
where
varPar :: OCaml VarPar
varPar = oneOf [variable >>= return . Var, parameter >>= return . Par]
typeApply :: OCaml TypeApply
typeApply = oneOf
[ do { tok ParenLeft; a <- varPars; b <- many1 (tok Comma >> varPars); tok ParenRight; c <- varPars; return $ TypeApplyGroup $ apply (map (apply []) (a : b)) c }
, do { tok ParenLeft; a <- typeApply; tok ParenRight; b <- varPars; return $ TypeApplyGroup $ apply [a] b }
, do { tok ParenLeft; a <- typeApply; tok ParenRight; return $ TypeApplyGroup a }
-- XXX Need to prevent nested tuples.
, do { a <- varPars; b <- many1 (tok Star >> typeApply); return $ TypeApply (Var "tuple") $ flattenTuples $ apply [] a : b }
, do { a <- varPars; return $ apply [] a }
]
where
apply :: [TypeApply] -> [VarPar] -> TypeApply
apply _ [] = error "typeApply: no type to apply to"
apply args [a] = TypeApply a args
apply args (a:b) = apply [(apply args [a])] b
flattenTuples :: [TypeApply] -> [TypeApply]
flattenTuples = concatMap flattenTuple
flattenTuple :: TypeApply -> [TypeApply]
flattenTuple (TypeApply (Var "tuple") args) = args
flattenTuple a = [a]
typeExpr :: OCaml TypeDef
typeExpr = oneOf
[ recordType >>= return . Record
, sumType >>= return . Sum
, typeApply >>= return . Alias
]
recordType :: OCaml [(String, TypeApply)]
recordType = do { tok BraceLeft; f <- recordField; fs <- many (tok SemiColon >> recordField); optional $ tok SemiColon; tok BraceRight; return $ f : fs }
recordField :: OCaml (String, TypeApply)
recordField = do { n <- variable; tok Colon; t <- typeApply; return (n, t) }
sumType :: OCaml [(String, [TypeApply])]
sumType = do { optional (tok Pipe); a <- sumConstructor; b <- many (tok Pipe >> sumConstructor); return $ a : b }
sumConstructor :: OCaml (String, [TypeApply])
sumConstructor = oneOf
[ do { n <- constructor; tok Of; a <- typeApply; return (n, detuple a) }
, do { n <- constructor; return (n, []) }
]
where
detuple :: TypeApply -> [TypeApply]
detuple (TypeApply (Var "tuple") args) = args
detuple a = [a]
|
tomahawkins/cil
|
attic/GenCIL.hs
|
bsd-3-clause
| 14,544 | 0 | 26 | 3,572 | 4,616 | 2,419 | 2,197 | 307 | 18 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Numeral.HE.Rules
( rules
) where
import Data.Maybe
import Data.String
import Data.Text (Text)
import Prelude
import qualified Data.Text as Text
import Duckling.Dimensions.Types
import Duckling.Numeral.Helpers
import Duckling.Numeral.Types (NumeralData (..))
import Duckling.Regex.Types
import Duckling.Types
import qualified Duckling.Numeral.Types as TNumeral
ruleInteger5 :: Rule
ruleInteger5 = Rule
{ name = "integer 4"
, pattern =
[ regex "(ארבע(ה)?)"
]
, prod = \_ -> integer 4
}
ruleIntersectNumerals :: Rule
ruleIntersectNumerals = Rule
{ name = "intersect numbers"
, pattern =
[ Predicate hasGrain
, Predicate $ and . sequence [not . isMultipliable, isPositive]
]
, prod = \tokens -> case tokens of
(Token Numeral NumeralData{TNumeral.value = val1, TNumeral.grain = Just g}:
Token Numeral NumeralData{TNumeral.value = val2}:
_) | (10 ** fromIntegral g) > val2 -> double $ val1 + val2
_ -> Nothing
}
ruleIntersectWithAnd :: Rule
ruleIntersectWithAnd = Rule
{ name = "intersect (with and)"
, pattern =
[ Predicate hasGrain
, regex "ו"
, Predicate isMultipliable
]
, prod = \tokens -> case tokens of
(Token Numeral NumeralData{TNumeral.value = val1, TNumeral.grain = Just g}:
_:
Token Numeral NumeralData{TNumeral.value = val2}:
_) | (10 ** fromIntegral g) > val2 -> double $ val1 + val2
_ -> Nothing
}
ruleCompositeTens :: Rule
ruleCompositeTens = Rule
{ name = "integer 21..99"
, pattern =
[ oneOf [ 20, 30..90 ]
, numberBetween 1 10
]
, prod = \tokens -> case tokens of
(Token Numeral NumeralData{TNumeral.value = tens}:
Token Numeral NumeralData{TNumeral.value = units}:
_) -> double $ tens + units
_ -> Nothing
}
ruleCompositeTensWithAnd :: Rule
ruleCompositeTensWithAnd = Rule
{ name = "integer 21..99 (with and)"
, pattern =
[ oneOf [ 20, 30..90 ]
, regex "ו"
, numberBetween 1 10
]
, prod = \tokens -> case tokens of
(Token Numeral NumeralData{TNumeral.value = tens}:
_:
Token Numeral NumeralData{TNumeral.value = units}:
_) -> double $ tens + units
_ -> Nothing
}
ruleNumeralsPrefixWithNegativeOrMinus :: Rule
ruleNumeralsPrefixWithNegativeOrMinus = Rule
{ name = "numbers prefix with -, negative or minus"
, pattern =
[ regex "-|מינוס"
, Predicate isPositive
]
, prod = \tokens -> case tokens of
(_:Token Numeral nd:_) -> double (TNumeral.value nd * (-1))
_ -> Nothing
}
ruleInteger10 :: Rule
ruleInteger10 = Rule
{ name = "integer 9"
, pattern =
[ regex "(תשע(ה)?)"
]
, prod = \_ -> integer 9
}
ruleInteger15 :: Rule
ruleInteger15 = Rule
{ name = "integer (20..90)"
, pattern =
[ regex "(עשרים|שלושים|ארבעים|חמישים|שישים|שבעים|שמונים|תשעים)"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) -> case match of
"עשרים" -> integer 20
"שלושים" -> integer 30
"ארבעים" -> integer 40
"חמישים" -> integer 50
"שישים" -> integer 60
"שבעים" -> integer 70
"שמונים" -> integer 80
"תשעים" -> integer 90
_ -> Nothing
_ -> Nothing
}
ruleDecimalNumeral :: Rule
ruleDecimalNumeral = Rule
{ name = "decimal number"
, pattern =
[ regex "(\\d*\\.\\d+)"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) -> parseDecimal True match
_ -> Nothing
}
ruleInteger3 :: Rule
ruleInteger3 = Rule
{ name = "integer 2"
, pattern =
[ regex "(שתיים|שניים)"
]
, prod = \_ -> integer 2
}
ruleSingle :: Rule
ruleSingle = Rule
{ name = "single"
, pattern =
[ regex "יחיד"
]
, prod = \_ -> integer 1
}
ruleInteger13 :: Rule
ruleInteger13 = Rule
{ name = "integer 12"
, pattern =
[ regex "(שניים עשר|תרי עשר)"
]
, prod = \_ -> integer 12
}
ruleMultiply :: Rule
ruleMultiply = Rule
{ name = "compose by multiplication"
, pattern =
[ dimension Numeral
, numberWith TNumeral.multipliable id
]
, prod = \tokens -> case tokens of
(token1:token2:_) -> multiply token1 token2
_ -> Nothing
}
ruleInteger6 :: Rule
ruleInteger6 = Rule
{ name = "integer 5"
, pattern =
[ regex "(חמ(ש|ישה))"
]
, prod = \_ -> integer 5
}
rulePowersOfTen :: Rule
rulePowersOfTen = Rule
{ name = "powers of tens"
, pattern =
[ regex "(מא(ה|ות)|אל(ף|פים)|מיליו(ן|נים))"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) -> case Text.toLower match of
"מאה" ->
double 1e2 >>= withGrain 2 >>= withMultipliable
"מאות" ->
double 1e2 >>= withGrain 2 >>= withMultipliable
"אלף" ->
double 1e3 >>= withGrain 3 >>= withMultipliable
"אלפים" ->
double 1e3 >>= withGrain 3 >>= withMultipliable
"מיליון" ->
double 1e6 >>= withGrain 6 >>= withMultipliable
"מיליונים" ->
double 1e6 >>= withGrain 6 >>= withMultipliable
_ -> Nothing
_ -> Nothing
}
ruleInteger7 :: Rule
ruleInteger7 = Rule
{ name = "integer 6"
, pattern =
[ regex "(שש(ה)?)"
]
, prod = \_ -> integer 6
}
ruleInteger14 :: Rule
ruleInteger14 = Rule
{ name = "integer 11..19"
, pattern =
[ numberBetween 1 10
, numberWith TNumeral.value (== 10)
]
, prod = \tokens -> case tokens of
(Token Numeral NumeralData{TNumeral.value = v1}:
Token Numeral NumeralData{TNumeral.value = v2}:
_) -> double $ v1 + v2
_ -> Nothing
}
ruleInteger8 :: Rule
ruleInteger8 = Rule
{ name = "integer 7"
, pattern =
[ regex "(שבע(ה)?)"
]
, prod = \_ -> integer 7
}
ruleCouple :: Rule
ruleCouple = Rule
{ name = "couple"
, pattern =
[ regex "זוג( של)?"
]
, prod = \_ -> integer 2
}
ruleInteger16 :: Rule
ruleInteger16 = Rule
{ name = "integer 101..999"
, pattern =
[ oneOf [300, 600, 500, 100, 800, 200, 900, 700, 400]
, numberBetween 1 100
]
, prod = \tokens -> case tokens of
(Token Numeral NumeralData{TNumeral.value = v1}:
Token Numeral NumeralData{TNumeral.value = v2}:
_) -> double $ v1 + v2
_ -> Nothing
}
ruleInteger9 :: Rule
ruleInteger9 = Rule
{ name = "integer 8"
, pattern =
[ regex "(שמונה)"
]
, prod = \_ -> integer 8
}
ruleInteger :: Rule
ruleInteger = Rule
{ name = "integer 0"
, pattern =
[ regex "(אפס|כלום)"
]
, prod = \_ -> integer 0
}
ruleInteger4 :: Rule
ruleInteger4 = Rule
{ name = "integer 3"
, pattern =
[ regex "(שלוש(ה)?)"
]
, prod = \_ -> integer 3
}
ruleInteger2 :: Rule
ruleInteger2 = Rule
{ name = "integer 1"
, pattern =
[ regex "(אחד|אחת)"
]
, prod = \_ -> integer 1
}
ruleInteger11 :: Rule
ruleInteger11 = Rule
{ name = "integer 10"
, pattern =
[ regex "(עשר(ה)?)"
]
, prod = \_ -> integer 10
}
ruleNumeralDotNumeral :: Rule
ruleNumeralDotNumeral = Rule
{ name = "number dot number"
, pattern =
[ dimension Numeral
, regex "נקודה"
, Predicate $ not . hasGrain
]
, prod = \tokens -> case tokens of
(Token Numeral nd1:_:Token Numeral nd2:_) ->
double $ TNumeral.value nd1 + decimalsToDouble (TNumeral.value nd2)
_ -> Nothing
}
ruleCommas :: Rule
ruleCommas = Rule
{ name = "comma-separated numbers"
, pattern =
[ regex "(\\d+(,\\d\\d\\d)+(\\.\\d+)?)"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) ->
parseDouble (Text.replace "," Text.empty match) >>= double
_ -> Nothing
}
ruleHalf :: Rule
ruleHalf = Rule
{ name = "half"
, pattern =
[ regex "חצי"
]
, prod = \_ -> double 0.5
}
rules :: [Rule]
rules =
[ ruleCommas
, ruleCompositeTens
, ruleCompositeTensWithAnd
, ruleCouple
, ruleDecimalNumeral
, ruleInteger
, ruleInteger10
, ruleInteger11
, ruleInteger13
, ruleInteger14
, ruleInteger15
, ruleInteger16
, ruleInteger2
, ruleInteger3
, ruleInteger4
, ruleInteger5
, ruleInteger6
, ruleInteger7
, ruleInteger8
, ruleInteger9
, ruleIntersectNumerals
, ruleIntersectWithAnd
, ruleMultiply
, ruleNumeralDotNumeral
, ruleNumeralsPrefixWithNegativeOrMinus
, rulePowersOfTen
, ruleSingle
, ruleHalf
]
|
facebookincubator/duckling
|
Duckling/Numeral/HE/Rules.hs
|
bsd-3-clause
| 9,005 | 0 | 18 | 2,455 | 2,574 | 1,440 | 1,134 | 289 | 10 |
{-# LANGUAGE JavaScriptFFI, TypeSynonymInstances, OverloadedStrings, FlexibleInstances #-}
module Famous.Core.Basic where
import GHCJS.Foreign
import GHCJS.Marshal
import GHCJS.Types
import qualified JavaScript.Object as Obj
import JavaScript.Object.Internal as Obj
import qualified Data.Map as Map
import Control.Monad (forM_)
import Data.Text
import Data.JSString
type FamoObj a = JSRef
type Options v = Map.Map JSString v
instance ToJSRef v => ToJSRef (Options v) where
toJSRef m = do
o <- Obj.create
forM_ (Map.toList m) $ \(k, v) -> do v' <- toJSRef v
Obj.setProp k v' o
return $ jsref o
-- | Size Mode
data SizeMode = SMAbsolute
| SMRelative
| SMRender
sizeMode2Text :: SizeMode -> JSString
sizeMode2Text SMAbsolute = "absolute"
sizeMode2Text SMRelative = "relative"
sizeMode2Text SMRender = "render"
|
manyoo/ghcjs-famous
|
src/Famous/Core/Basic.hs
|
bsd-3-clause
| 903 | 0 | 13 | 209 | 234 | 130 | 104 | 26 | 1 |
module Samsum ( findBetween ) where
import Data.Char
sumByDigits :: [Int] -> Int
sumByDigits xs = sum $ map charToInt $ concatMap show xs
where
charToInt = \c -> ord c - ord '0'
infiniteSeq :: Int -> Int -> [Int]
infiniteSeq incr from = if from <= 0
then []
else from : infiniteSeq incr (incr + from)
subsets :: [a] -> [[a]]
subsets xs = tail $ scanl (flip (:)) [] xs
findSeqsBySum :: Int -> [Int] -> [[Int]]
findSeqsBySum s xs = takeWhile sumEquals $ dropWhile sumNoGreaterThan $ subsets xs
where
sumEquals ys = sumByDigits ys == s
sumNoGreaterThan ys = sumByDigits ys < s
findBetween :: Int -> Int -> [(Int, Int)]
findBetween min max = map firstAndLast $ concatMap findOne directions
where
directions = [ ([min .. max], 1),
(reverse [ min .. (max - 1) ], -1) ]
sum' = sumByDigits [ min .. max ]
findOne (xs, incr) = concatMap (findSeqsBySum sum') $ map (infiniteSeq incr) xs
firstAndLast xs = (head xs, last xs)
|
hackle/hscripting
|
src/Samsum.hs
|
bsd-3-clause
| 1,314 | 0 | 12 | 571 | 421 | 224 | 197 | 22 | 2 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
The @Inst@ type: dictionaries or method instances
-}
{-# LANGUAGE CPP, MultiWayIf, TupleSections #-}
module Inst (
deeplySkolemise,
topInstantiate, topInstantiateInferred, deeplyInstantiate,
instCall, instDFunType, instStupidTheta,
newWanted, newWanteds,
tcInstBinders, tcInstBindersX,
newOverloadedLit, mkOverLit,
newClsInst,
tcGetInsts, tcGetInstEnvs, getOverlapFlag,
tcExtendLocalInstEnv,
instCallConstraints, newMethodFromName,
tcSyntaxName,
-- Simple functions over evidence variables
tyCoVarsOfWC,
tyCoVarsOfCt, tyCoVarsOfCts,
) where
#include "HsVersions.h"
import {-# SOURCE #-} TcExpr( tcPolyExpr, tcSyntaxOp )
import {-# SOURCE #-} TcUnify( unifyType, unifyKind, noThing )
import FastString
import HsSyn
import TcHsSyn
import TcRnMonad
import TcEnv
import TcEvidence
import InstEnv
import TysWiredIn ( heqDataCon, coercibleDataCon )
import CoreSyn ( isOrphan )
import FunDeps
import TcMType
import Type
import TcType
import HscTypes
import Class( Class )
import MkId( mkDictFunId )
import Id
import Name
import Var ( EvVar, mkTyVar )
import DataCon
import TyCon
import VarEnv
import PrelNames
import SrcLoc
import DynFlags
import Util
import Outputable
import qualified GHC.LanguageExtensions as LangExt
import Control.Monad( unless )
import Data.Maybe( isJust )
{-
************************************************************************
* *
Creating and emittind constraints
* *
************************************************************************
-}
newMethodFromName :: CtOrigin -> Name -> TcRhoType -> TcM (HsExpr TcId)
-- Used when Name is the wired-in name for a wired-in class method,
-- so the caller knows its type for sure, which should be of form
-- forall a. C a => <blah>
-- newMethodFromName is supposed to instantiate just the outer
-- type variable and constraint
newMethodFromName origin name inst_ty
= do { id <- tcLookupId name
-- Use tcLookupId not tcLookupGlobalId; the method is almost
-- always a class op, but with -XRebindableSyntax GHC is
-- meant to find whatever thing is in scope, and that may
-- be an ordinary function.
; let ty = piResultTy (idType id) inst_ty
(theta, _caller_knows_this) = tcSplitPhiTy ty
; wrap <- ASSERT( not (isForAllTy ty) && isSingleton theta )
instCall origin [inst_ty] theta
; return (mkHsWrap wrap (HsVar (noLoc id))) }
{-
************************************************************************
* *
Deep instantiation and skolemisation
* *
************************************************************************
Note [Deep skolemisation]
~~~~~~~~~~~~~~~~~~~~~~~~~
deeplySkolemise decomposes and skolemises a type, returning a type
with all its arrows visible (ie not buried under foralls)
Examples:
deeplySkolemise (Int -> forall a. Ord a => blah)
= ( wp, [a], [d:Ord a], Int -> blah )
where wp = \x:Int. /\a. \(d:Ord a). <hole> x
deeplySkolemise (forall a. Ord a => Maybe a -> forall b. Eq b => blah)
= ( wp, [a,b], [d1:Ord a,d2:Eq b], Maybe a -> blah )
where wp = /\a.\(d1:Ord a).\(x:Maybe a)./\b.\(d2:Ord b). <hole> x
In general,
if deeplySkolemise ty = (wrap, tvs, evs, rho)
and e :: rho
then wrap e :: ty
and 'wrap' binds tvs, evs
ToDo: this eta-abstraction plays fast and loose with termination,
because it can introduce extra lambdas. Maybe add a `seq` to
fix this
-}
deeplySkolemise
:: TcSigmaType
-> TcM ( HsWrapper
, [TyVar] -- all skolemised variables
, [EvVar] -- all "given"s
, TcRhoType)
deeplySkolemise ty
| Just (arg_tys, tvs, theta, ty') <- tcDeepSplitSigmaTy_maybe ty
= do { ids1 <- newSysLocalIds (fsLit "dk") arg_tys
; (subst, tvs1) <- tcInstSkolTyVars tvs
; ev_vars1 <- newEvVars (substThetaUnchecked subst theta)
; (wrap, tvs2, ev_vars2, rho) <-
deeplySkolemise (substTyAddInScope subst ty')
; return ( mkWpLams ids1
<.> mkWpTyLams tvs1
<.> mkWpLams ev_vars1
<.> wrap
<.> mkWpEvVarApps ids1
, tvs1 ++ tvs2
, ev_vars1 ++ ev_vars2
, mkFunTys arg_tys rho ) }
| otherwise
= return (idHsWrapper, [], [], ty)
-- | Instantiate all outer type variables
-- and any context. Never looks through arrows.
topInstantiate :: CtOrigin -> TcSigmaType -> TcM (HsWrapper, TcRhoType)
-- if topInstantiate ty = (wrap, rho)
-- and e :: ty
-- then wrap e :: rho (that is, wrap :: ty "->" rho)
topInstantiate = top_instantiate True
-- | Instantiate all outer 'Invisible' binders
-- and any context. Never looks through arrows or specified type variables.
-- Used for visible type application.
topInstantiateInferred :: CtOrigin -> TcSigmaType
-> TcM (HsWrapper, TcSigmaType)
-- if topInstantiate ty = (wrap, rho)
-- and e :: ty
-- then wrap e :: rho
topInstantiateInferred = top_instantiate False
top_instantiate :: Bool -- True <=> instantiate *all* variables
-- False <=> instantiate only the invisible ones
-> CtOrigin -> TcSigmaType -> TcM (HsWrapper, TcRhoType)
top_instantiate inst_all orig ty
| not (null binders && null theta)
= do { let (inst_bndrs, leave_bndrs) = span should_inst binders
(inst_theta, leave_theta)
| null leave_bndrs = (theta, [])
| otherwise = ([], theta)
in_scope = mkInScopeSet (tyCoVarsOfType ty)
empty_subst = mkEmptyTCvSubst in_scope
inst_tvs = map (binderVar "top_inst") inst_bndrs
; (subst, inst_tvs') <- mapAccumLM newMetaTyVarX empty_subst inst_tvs
; let inst_theta' = substTheta subst inst_theta
sigma' = substTy subst (mkForAllTys leave_bndrs $
mkFunTys leave_theta rho)
; wrap1 <- instCall orig (mkTyVarTys inst_tvs') inst_theta'
; traceTc "Instantiating"
(vcat [ text "all tyvars?" <+> ppr inst_all
, text "origin" <+> pprCtOrigin orig
, text "type" <+> ppr ty
, text "theta" <+> ppr theta
, text "leave_bndrs" <+> ppr leave_bndrs
, text "with" <+> ppr inst_tvs'
, text "theta:" <+> ppr inst_theta' ])
; (wrap2, rho2) <-
if null leave_bndrs
-- account for types like forall a. Num a => forall b. Ord b => ...
then top_instantiate inst_all orig sigma'
-- but don't loop if there were any un-inst'able tyvars
else return (idHsWrapper, sigma')
; return (wrap2 <.> wrap1, rho2) }
| otherwise = return (idHsWrapper, ty)
where
(binders, phi) = tcSplitNamedPiTys ty
(theta, rho) = tcSplitPhiTy phi
should_inst bndr
| inst_all = True
| otherwise = binderVisibility bndr == Invisible
deeplyInstantiate :: CtOrigin -> TcSigmaType -> TcM (HsWrapper, TcRhoType)
-- Int -> forall a. a -> a ==> (\x:Int. [] x alpha) :: Int -> alpha
-- In general if
-- if deeplyInstantiate ty = (wrap, rho)
-- and e :: ty
-- then wrap e :: rho
-- That is, wrap :: ty "->" rho
deeplyInstantiate orig ty
| Just (arg_tys, tvs, theta, rho) <- tcDeepSplitSigmaTy_maybe ty
= do { (subst, tvs') <- newMetaTyVars tvs
; ids1 <- newSysLocalIds (fsLit "di") (substTysUnchecked subst arg_tys)
; let theta' = substThetaUnchecked subst theta
; wrap1 <- instCall orig (mkTyVarTys tvs') theta'
; traceTc "Instantiating (deeply)" (vcat [ text "origin" <+> pprCtOrigin orig
, text "type" <+> ppr ty
, text "with" <+> ppr tvs'
, text "args:" <+> ppr ids1
, text "theta:" <+> ppr theta'
, text "subst:" <+> ppr subst ])
; (wrap2, rho2) <- deeplyInstantiate orig (substTyUnchecked subst rho)
; return (mkWpLams ids1
<.> wrap2
<.> wrap1
<.> mkWpEvVarApps ids1,
mkFunTys arg_tys rho2) }
| otherwise = return (idHsWrapper, ty)
{-
************************************************************************
* *
Instantiating a call
* *
************************************************************************
Note [Handling boxed equality]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The solver deals entirely in terms of unboxed (primitive) equality.
There should never be a boxed Wanted equality. Ever. But, what if
we are calling `foo :: forall a. (F a ~ Bool) => ...`? That equality
is boxed, so naive treatment here would emit a boxed Wanted equality.
So we simply check for this case and make the right boxing of evidence.
-}
----------------
instCall :: CtOrigin -> [TcType] -> TcThetaType -> TcM HsWrapper
-- Instantiate the constraints of a call
-- (instCall o tys theta)
-- (a) Makes fresh dictionaries as necessary for the constraints (theta)
-- (b) Throws these dictionaries into the LIE
-- (c) Returns an HsWrapper ([.] tys dicts)
instCall orig tys theta
= do { dict_app <- instCallConstraints orig theta
; return (dict_app <.> mkWpTyApps tys) }
----------------
instCallConstraints :: CtOrigin -> TcThetaType -> TcM HsWrapper
-- Instantiates the TcTheta, puts all constraints thereby generated
-- into the LIE, and returns a HsWrapper to enclose the call site.
instCallConstraints orig preds
| null preds
= return idHsWrapper
| otherwise
= do { evs <- mapM go preds
; traceTc "instCallConstraints" (ppr evs)
; return (mkWpEvApps evs) }
where
go pred
| Just (Nominal, ty1, ty2) <- getEqPredTys_maybe pred -- Try short-cut #1
= do { co <- unifyType noThing ty1 ty2
; return (EvCoercion co) }
-- Try short-cut #2
| Just (tc, args@[_, _, ty1, ty2]) <- splitTyConApp_maybe pred
, tc `hasKey` heqTyConKey
= do { co <- unifyType noThing ty1 ty2
; return (EvDFunApp (dataConWrapId heqDataCon) args [EvCoercion co]) }
| otherwise
= emitWanted orig pred
instDFunType :: DFunId -> [DFunInstType]
-> TcM ( [TcType] -- instantiated argument types
, TcThetaType ) -- instantiated constraint
-- See Note [DFunInstType: instantiating types] in InstEnv
instDFunType dfun_id dfun_inst_tys
= do { (subst, inst_tys) <- go emptyTCvSubst dfun_tvs dfun_inst_tys
; return (inst_tys, substTheta subst dfun_theta) }
where
(dfun_tvs, dfun_theta, _) = tcSplitSigmaTy (idType dfun_id)
go :: TCvSubst -> [TyVar] -> [DFunInstType] -> TcM (TCvSubst, [TcType])
go subst [] [] = return (subst, [])
go subst (tv:tvs) (Just ty : mb_tys)
= do { (subst', tys) <- go (extendTvSubstAndInScope subst tv ty)
tvs
mb_tys
; return (subst', ty : tys) }
go subst (tv:tvs) (Nothing : mb_tys)
= do { (subst', tv') <- newMetaTyVarX subst tv
; (subst'', tys) <- go subst' tvs mb_tys
; return (subst'', mkTyVarTy tv' : tys) }
go _ _ _ = pprPanic "instDFunTypes" (ppr dfun_id $$ ppr dfun_inst_tys)
----------------
instStupidTheta :: CtOrigin -> TcThetaType -> TcM ()
-- Similar to instCall, but only emit the constraints in the LIE
-- Used exclusively for the 'stupid theta' of a data constructor
instStupidTheta orig theta
= do { _co <- instCallConstraints orig theta -- Discard the coercion
; return () }
{-
************************************************************************
* *
Instantiating Kinds
* *
************************************************************************
-}
---------------------------
-- | This is used to instantiate binders when type-checking *types* only.
-- See also Note [Bidirectional type checking]
tcInstBinders :: [TyBinder] -> TcM (TCvSubst, [TcType])
tcInstBinders = tcInstBindersX emptyTCvSubst Nothing
-- | This is used to instantiate binders when type-checking *types* only.
-- The @VarEnv Kind@ gives some known instantiations.
-- See also Note [Bidirectional type checking]
tcInstBindersX :: TCvSubst -> Maybe (VarEnv Kind)
-> [TyBinder] -> TcM (TCvSubst, [TcType])
tcInstBindersX subst mb_kind_info bndrs
= do { (subst, args) <- mapAccumLM (tcInstBinderX mb_kind_info) subst bndrs
; traceTc "instantiating tybinders:"
(vcat $ zipWith (\bndr arg -> ppr bndr <+> text ":=" <+> ppr arg)
bndrs args)
; return (subst, args) }
-- | Used only in *types*
tcInstBinderX :: Maybe (VarEnv Kind)
-> TCvSubst -> TyBinder -> TcM (TCvSubst, TcType)
tcInstBinderX mb_kind_info subst binder
| Just tv <- binderVar_maybe binder
= case lookup_tv tv of
Just ki -> return (extendTvSubstAndInScope subst tv ki, ki)
Nothing -> do { (subst', tv') <- newMetaTyVarX subst tv
; return (subst', mkTyVarTy tv') }
-- This is the *only* constraint currently handled in types.
| Just (mk, role, k1, k2) <- get_pred_tys_maybe substed_ty
= do { let origin = TypeEqOrigin { uo_actual = k1
, uo_expected = mkCheckExpType k2
, uo_thing = Nothing }
; co <- case role of
Nominal -> unifyKind noThing k1 k2
Representational -> emitWantedEq origin KindLevel role k1 k2
Phantom -> pprPanic "tcInstBinderX Phantom" (ppr binder)
; arg' <- mk co k1 k2
; return (subst, arg') }
| isPredTy substed_ty
= do { let (env, tidy_ty) = tidyOpenType emptyTidyEnv substed_ty
; addErrTcM (env, text "Illegal constraint in a type:" <+> ppr tidy_ty)
-- just invent a new variable so that we can continue
; u <- newUnique
; let name = mkSysTvName u (fsLit "dict")
; return (subst, mkTyVarTy $ mkTyVar name substed_ty) }
| otherwise
= do { ty <- newFlexiTyVarTy substed_ty
; return (subst, ty) }
where
substed_ty = substTy subst (binderType binder)
lookup_tv tv = do { env <- mb_kind_info -- `Maybe` monad
; lookupVarEnv env tv }
-- handle boxed equality constraints, because it's so easy
get_pred_tys_maybe ty
| Just (r, k1, k2) <- getEqPredTys_maybe ty
= Just (\co _ _ -> return $ mkCoercionTy co, r, k1, k2)
| Just (tc, [_, _, k1, k2]) <- splitTyConApp_maybe ty
= if | tc `hasKey` heqTyConKey
-> Just (mkHEqBoxTy, Nominal, k1, k2)
| otherwise
-> Nothing
| Just (tc, [_, k1, k2]) <- splitTyConApp_maybe ty
= if | tc `hasKey` eqTyConKey
-> Just (mkEqBoxTy, Nominal, k1, k2)
| tc `hasKey` coercibleTyConKey
-> Just (mkCoercibleBoxTy, Representational, k1, k2)
| otherwise
-> Nothing
| otherwise
= Nothing
-------------------------------
-- | This takes @a ~# b@ and returns @a ~~ b@.
mkHEqBoxTy :: TcCoercion -> Type -> Type -> TcM Type
-- monadic just for convenience with mkEqBoxTy
mkHEqBoxTy co ty1 ty2
= return $
mkTyConApp (promoteDataCon heqDataCon) [k1, k2, ty1, ty2, mkCoercionTy co]
where k1 = typeKind ty1
k2 = typeKind ty2
-- | This takes @a ~# b@ and returns @a ~ b@.
mkEqBoxTy :: TcCoercion -> Type -> Type -> TcM Type
mkEqBoxTy co ty1 ty2
= do { eq_tc <- tcLookupTyCon eqTyConName
; let [datacon] = tyConDataCons eq_tc
; hetero <- mkHEqBoxTy co ty1 ty2
; return $ mkTyConApp (promoteDataCon datacon) [k, ty1, ty2, hetero] }
where k = typeKind ty1
-- | This takes @a ~R# b@ and returns @Coercible a b@.
mkCoercibleBoxTy :: TcCoercion -> Type -> Type -> TcM Type
-- monadic just for convenience with mkEqBoxTy
mkCoercibleBoxTy co ty1 ty2
= do { return $
mkTyConApp (promoteDataCon coercibleDataCon)
[k, ty1, ty2, mkCoercionTy co] }
where k = typeKind ty1
{-
************************************************************************
* *
Literals
* *
************************************************************************
-}
{-
In newOverloadedLit we convert directly to an Int or Integer if we
know that's what we want. This may save some time, by not
temporarily generating overloaded literals, but it won't catch all
cases (the rest are caught in lookupInst).
-}
newOverloadedLit :: HsOverLit Name
-> ExpRhoType
-> TcM (HsOverLit TcId)
newOverloadedLit
lit@(OverLit { ol_val = val, ol_rebindable = rebindable }) res_ty
| not rebindable
-- all built-in overloaded lits are tau-types, so we can just
-- tauify the ExpType
= do { res_ty <- expTypeToType res_ty
; dflags <- getDynFlags
; case shortCutLit dflags val res_ty of
-- Do not generate a LitInst for rebindable syntax.
-- Reason: If we do, tcSimplify will call lookupInst, which
-- will call tcSyntaxName, which does unification,
-- which tcSimplify doesn't like
Just expr -> return (lit { ol_witness = expr, ol_type = res_ty
, ol_rebindable = False })
Nothing -> newNonTrivialOverloadedLit orig lit
(mkCheckExpType res_ty) }
| otherwise
= newNonTrivialOverloadedLit orig lit res_ty
where
orig = LiteralOrigin lit
-- Does not handle things that 'shortCutLit' can handle. See also
-- newOverloadedLit in TcUnify
newNonTrivialOverloadedLit :: CtOrigin
-> HsOverLit Name
-> ExpRhoType
-> TcM (HsOverLit TcId)
newNonTrivialOverloadedLit orig
lit@(OverLit { ol_val = val, ol_witness = HsVar (L _ meth_name)
, ol_rebindable = rebindable }) res_ty
= do { hs_lit <- mkOverLit val
; let lit_ty = hsLitType hs_lit
; (_, fi') <- tcSyntaxOp orig (mkRnSyntaxExpr meth_name)
[synKnownType lit_ty] res_ty $
\_ -> return ()
; let L _ witness = nlHsSyntaxApps fi' [nlHsLit hs_lit]
; res_ty <- readExpType res_ty
; return (lit { ol_witness = witness
, ol_type = res_ty
, ol_rebindable = rebindable }) }
newNonTrivialOverloadedLit _ lit _
= pprPanic "newNonTrivialOverloadedLit" (ppr lit)
------------
mkOverLit :: OverLitVal -> TcM HsLit
mkOverLit (HsIntegral src i)
= do { integer_ty <- tcMetaTy integerTyConName
; return (HsInteger src i integer_ty) }
mkOverLit (HsFractional r)
= do { rat_ty <- tcMetaTy rationalTyConName
; return (HsRat r rat_ty) }
mkOverLit (HsIsString src s) = return (HsString src s)
{-
************************************************************************
* *
Re-mappable syntax
Used only for arrow syntax -- find a way to nuke this
* *
************************************************************************
Suppose we are doing the -XRebindableSyntax thing, and we encounter
a do-expression. We have to find (>>) in the current environment, which is
done by the rename. Then we have to check that it has the same type as
Control.Monad.(>>). Or, more precisely, a compatible type. One 'customer' had
this:
(>>) :: HB m n mn => m a -> n b -> mn b
So the idea is to generate a local binding for (>>), thus:
let then72 :: forall a b. m a -> m b -> m b
then72 = ...something involving the user's (>>)...
in
...the do-expression...
Now the do-expression can proceed using then72, which has exactly
the expected type.
In fact tcSyntaxName just generates the RHS for then72, because we only
want an actual binding in the do-expression case. For literals, we can
just use the expression inline.
-}
tcSyntaxName :: CtOrigin
-> TcType -- Type to instantiate it at
-> (Name, HsExpr Name) -- (Standard name, user name)
-> TcM (Name, HsExpr TcId) -- (Standard name, suitable expression)
-- USED ONLY FOR CmdTop (sigh) ***
-- See Note [CmdSyntaxTable] in HsExpr
tcSyntaxName orig ty (std_nm, HsVar (L _ user_nm))
| std_nm == user_nm
= do rhs <- newMethodFromName orig std_nm ty
return (std_nm, rhs)
tcSyntaxName orig ty (std_nm, user_nm_expr) = do
std_id <- tcLookupId std_nm
let
-- C.f. newMethodAtLoc
([tv], _, tau) = tcSplitSigmaTy (idType std_id)
sigma1 = substTyWith [tv] [ty] tau
-- Actually, the "tau-type" might be a sigma-type in the
-- case of locally-polymorphic methods.
addErrCtxtM (syntaxNameCtxt user_nm_expr orig sigma1) $ do
-- Check that the user-supplied thing has the
-- same type as the standard one.
-- Tiresome jiggling because tcCheckSigma takes a located expression
span <- getSrcSpanM
expr <- tcPolyExpr (L span user_nm_expr) sigma1
return (std_nm, unLoc expr)
syntaxNameCtxt :: HsExpr Name -> CtOrigin -> Type -> TidyEnv
-> TcRn (TidyEnv, SDoc)
syntaxNameCtxt name orig ty tidy_env
= do { inst_loc <- getCtLocM orig (Just TypeLevel)
; let msg = vcat [ text "When checking that" <+> quotes (ppr name)
<+> text "(needed by a syntactic construct)"
, nest 2 (text "has the required type:"
<+> ppr (tidyType tidy_env ty))
, nest 2 (pprCtLoc inst_loc) ]
; return (tidy_env, msg) }
{-
************************************************************************
* *
Instances
* *
************************************************************************
-}
getOverlapFlag :: Maybe OverlapMode -> TcM OverlapFlag
-- Construct the OverlapFlag from the global module flags,
-- but if the overlap_mode argument is (Just m),
-- set the OverlapMode to 'm'
getOverlapFlag overlap_mode
= do { dflags <- getDynFlags
; let overlap_ok = xopt LangExt.OverlappingInstances dflags
incoherent_ok = xopt LangExt.IncoherentInstances dflags
use x = OverlapFlag { isSafeOverlap = safeLanguageOn dflags
, overlapMode = x }
default_oflag | incoherent_ok = use (Incoherent "")
| overlap_ok = use (Overlaps "")
| otherwise = use (NoOverlap "")
final_oflag = setOverlapModeMaybe default_oflag overlap_mode
; return final_oflag }
tcGetInsts :: TcM [ClsInst]
-- Gets the local class instances.
tcGetInsts = fmap tcg_insts getGblEnv
newClsInst :: Maybe OverlapMode -> Name -> [TyVar] -> ThetaType
-> Class -> [Type] -> TcM ClsInst
newClsInst overlap_mode dfun_name tvs theta clas tys
= do { (subst, tvs') <- freshenTyVarBndrs tvs
-- Be sure to freshen those type variables,
-- so they are sure not to appear in any lookup
; let tys' = substTys subst tys
theta' = substTheta subst theta
dfun = mkDictFunId dfun_name tvs' theta' clas tys'
-- Substituting in the DFun type just makes sure that
-- we are using TyVars rather than TcTyVars
-- Not sure if this is really the right place to do so,
-- but it'll do fine
; oflag <- getOverlapFlag overlap_mode
; let inst = mkLocalInstance dfun oflag tvs' clas tys'
; dflags <- getDynFlags
; warnIf (Reason Opt_WarnOrphans)
(isOrphan (is_orphan inst) && wopt Opt_WarnOrphans dflags)
(instOrphWarn inst)
; return inst }
instOrphWarn :: ClsInst -> SDoc
instOrphWarn inst
= hang (text "Orphan instance:") 2 (pprInstanceHdr inst)
$$ text "To avoid this"
$$ nest 4 (vcat possibilities)
where
possibilities =
text "move the instance declaration to the module of the class or of the type, or" :
text "wrap the type with a newtype and declare the instance on the new type." :
[]
tcExtendLocalInstEnv :: [ClsInst] -> TcM a -> TcM a
-- Add new locally-defined instances
tcExtendLocalInstEnv dfuns thing_inside
= do { traceDFuns dfuns
; env <- getGblEnv
; (inst_env', cls_insts') <- foldlM addLocalInst
(tcg_inst_env env, tcg_insts env)
dfuns
; let env' = env { tcg_insts = cls_insts'
, tcg_inst_env = inst_env' }
; setGblEnv env' thing_inside }
addLocalInst :: (InstEnv, [ClsInst]) -> ClsInst -> TcM (InstEnv, [ClsInst])
-- Check that the proposed new instance is OK,
-- and then add it to the home inst env
-- If overwrite_inst, then we can overwrite a direct match
addLocalInst (home_ie, my_insts) ispec
= do {
-- Load imported instances, so that we report
-- duplicates correctly
-- 'matches' are existing instance declarations that are less
-- specific than the new one
-- 'dups' are those 'matches' that are equal to the new one
; isGHCi <- getIsGHCi
; eps <- getEps
; tcg_env <- getGblEnv
-- In GHCi, we *override* any identical instances
-- that are also defined in the interactive context
-- See Note [Override identical instances in GHCi]
; let home_ie'
| isGHCi = deleteFromInstEnv home_ie ispec
| otherwise = home_ie
-- If we're compiling sig-of and there's an external duplicate
-- instance, silently ignore it (that's the instance we're
-- implementing!) NB: we still count local duplicate instances
-- as errors.
-- See Note [Signature files and type class instances]
global_ie | isJust (tcg_sig_of tcg_env) = emptyInstEnv
| otherwise = eps_inst_env eps
inst_envs = InstEnvs { ie_global = global_ie
, ie_local = home_ie'
, ie_visible = tcVisibleOrphanMods tcg_env }
-- Check for inconsistent functional dependencies
; let inconsistent_ispecs = checkFunDeps inst_envs ispec
; unless (null inconsistent_ispecs) $
funDepErr ispec inconsistent_ispecs
-- Check for duplicate instance decls.
; let (_tvs, cls, tys) = instanceHead ispec
(matches, _, _) = lookupInstEnv False inst_envs cls tys
dups = filter (identicalClsInstHead ispec) (map fst matches)
; unless (null dups) $
dupInstErr ispec (head dups)
; return (extendInstEnv home_ie' ispec, ispec : my_insts) }
{-
Note [Signature files and type class instances]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Instances in signature files do not have an effect when compiling:
when you compile a signature against an implementation, you will
see the instances WHETHER OR NOT the instance is declared in
the file (this is because the signatures go in the EPS and we
can't filter them out easily.) This is also why we cannot
place the instance in the hi file: it would show up as a duplicate,
and we don't have instance reexports anyway.
However, you might find them useful when typechecking against
a signature: the instance is a way of indicating to GHC that
some instance exists, in case downstream code uses it.
Implementing this is a little tricky. Consider the following
situation (sigof03):
module A where
instance C T where ...
module ASig where
instance C T
When compiling ASig, A.hi is loaded, which brings its instances
into the EPS. When we process the instance declaration in ASig,
we should ignore it for the purpose of doing a duplicate check,
since it's not actually a duplicate. But don't skip the check
entirely, we still want this to fail (tcfail221):
module ASig where
instance C T
instance C T
Note that in some situations, the interface containing the type
class instances may not have been loaded yet at all. The usual
situation when A imports another module which provides the
instances (sigof02m):
module A(module B) where
import B
See also Note [Signature lazy interface loading]. We can't
rely on this, however, since sometimes we'll have spurious
type class instances in the EPS, see #9422 (sigof02dm)
************************************************************************
* *
Errors and tracing
* *
************************************************************************
-}
traceDFuns :: [ClsInst] -> TcRn ()
traceDFuns ispecs
= traceTc "Adding instances:" (vcat (map pp ispecs))
where
pp ispec = hang (ppr (instanceDFunId ispec) <+> colon)
2 (ppr ispec)
-- Print the dfun name itself too
funDepErr :: ClsInst -> [ClsInst] -> TcRn ()
funDepErr ispec ispecs
= addClsInstsErr (text "Functional dependencies conflict between instance declarations:")
(ispec : ispecs)
dupInstErr :: ClsInst -> ClsInst -> TcRn ()
dupInstErr ispec dup_ispec
= addClsInstsErr (text "Duplicate instance declarations:")
[ispec, dup_ispec]
addClsInstsErr :: SDoc -> [ClsInst] -> TcRn ()
addClsInstsErr herald ispecs
= setSrcSpan (getSrcSpan (head sorted)) $
addErr (hang herald 2 (pprInstances sorted))
where
sorted = sortWith getSrcLoc ispecs
-- The sortWith just arranges that instances are dislayed in order
-- of source location, which reduced wobbling in error messages,
-- and is better for users
|
GaloisInc/halvm-ghc
|
compiler/typecheck/Inst.hs
|
bsd-3-clause
| 31,342 | 8 | 17 | 9,673 | 5,667 | 2,960 | 2,707 | 417 | 7 |
-- | An example of how AJAX can be done in Fay. This module Demo.actually
-- imports the real SharedTypes and Client.API modules used to run
-- this IDE. So any requests you make are actual real requests to
-- the server. You can inspect their source in the “Internal
-- modules” section on this page.
module Demo.AJAX where
import SharedTypes
import Client.API
import Language.Fay.JQuery
import Language.Fay.Prelude
main =
ready $ do
body <- select "body"
ul <- select "<ul></ul>" >>= appendTo body
let tell name = select "<li></li>" >>= appendTo ul >>= setText name
call ProjectModules $ \(ModuleList modules) -> forM_ modules tell
call LibraryModules $ \(ModuleList modules) -> forM_ modules tell
|
faylang/fay-server
|
modules/project/Demo/AJAX.hs
|
bsd-3-clause
| 738 | 0 | 13 | 147 | 148 | 74 | 74 | 12 | 1 |
-- | Module Main embodies all modules, also have some helper functions to A*.
module Main where
import AStar
import Hyrule
import Renderer
import Parser
import Data.Array
import Data.Foldable (find)
import Data.List (nub)
import qualified Data.Map.Strict as Map
import Data.Maybe (fromJust)
findObject :: Object -> Area -> Maybe Position
findObject obj area = fst <$> find (\(_, t) -> object t == obj) (assocs (areaModel area))
findOverworldStartPosition :: Area -> Position
findOverworldStartPosition overworld = fromJust . findObject Home $ overworld
findDungeonStartPosition :: Area -> Position
findDungeonStartPosition dungeon = fromJust . findObject (Gate $ Overworld) $ dungeon
overworldSize = 42
dungeonSize = 28
weight :: Terrain -> Weight
weight terr = Map.findWithDefault 10 terr $ Map.fromList [(Grass, 10),
(Sand, 20),
(Forest, 100),
(Mountain, 150),
(Water, 180),
(WDungeon, 10)]
walkable :: Area -> Position -> Bool
walkable area pos = terrain ((areaModel area) ! pos) /= NWDungeon
nextStepGen :: Area -> Position -> [(Position, Weight)]
nextStepGen area pos@(a,b) = let area' = areaModel area
w = weight . terrain $ area' ! pos
in map (\x -> (x, w)) $ nub [
if a > 0 && walkable area (a - 1, b) then (a - 1, b) else (a, b) , -- walk to the left
if a < (fst . snd . bounds $ (areaModel area)) && walkable area (a + 1, b) then (a + 1, b) else (a, b) , -- walk to the right
if b > 0 && walkable area (a, b - 1) then (a, b - 1) else (a, b) , -- walk down
if b < (snd . snd . bounds $ (areaModel area)) && walkable area (a, b + 1) then (a , b + 1) else (a, b)] -- walk up
reachedGoal :: Object -> Area -> Position -> Bool
reachedGoal obj area pos = object ((areaModel area) ! pos) == obj
reachedSword = reachedGoal MasterSword
reachedPendant = reachedGoal Pendant
reachedGate = reachedGoal . Gate . Dungeon
heuristic :: Area -> Position -> Weight
heuristic area pos = weight . terrain $ ((areaModel area) ! pos)
-- map position from (y,x), zero-index to (x,y), one-idex
rearrangePosition :: Position -> Position
rearrangePosition (a,b) = (b + 1,a + 1)
main :: IO ()
main = do
contentOverworld <- readFile "../maps/overworld.map"
contentDungeon1 <- readFile "../maps/dungeon1.map"
contentDungeon2 <- readFile "../maps/dungeon2.map"
contentDungeon3 <- readFile "../maps/dungeon3.map"
let overworldMap = parseMap Overworld overworldSize contentOverworld
dungeon1Map = parseMap (Dungeon 1) dungeonSize contentDungeon1
dungeon2Map = parseMap (Dungeon 2) dungeonSize contentDungeon2
dungeon3Map = parseMap (Dungeon 3) dungeonSize contentDungeon3
overworldSP = findOverworldStartPosition overworldMap
firstDungeonSP = findDungeonStartPosition dungeon1Map
secondDungeonSP = findDungeonStartPosition dungeon2Map
thirdDungeonSP = findDungeonStartPosition dungeon3Map
totalCostAndPath = do
(costFD, pathToFirstDungeon) <- astarSearch overworldSP (reachedGate 1 overworldMap) (nextStepGen overworldMap) $ heuristic overworldMap
(costFP, pathToFirstPendant) <- astarSearch firstDungeonSP (reachedPendant dungeon1Map) (nextStepGen dungeon1Map) $ heuristic dungeon1Map
(costSD, pathToSecondDungeon) <- astarSearch (last pathToFirstDungeon) (reachedGate 2 overworldMap) (nextStepGen overworldMap) $ heuristic overworldMap
(costSP, pathToSecondPendant) <- astarSearch secondDungeonSP (reachedPendant dungeon2Map) (nextStepGen dungeon2Map) $ heuristic dungeon2Map
(costTD, pathToThirdDungeon) <- astarSearch (last pathToSecondDungeon) (reachedGate 3 overworldMap) (nextStepGen overworldMap) $ heuristic overworldMap
(costTP, pathToThirdPendant) <- astarSearch thirdDungeonSP (reachedPendant dungeon3Map) (nextStepGen dungeon3Map) $ heuristic dungeon3Map
(costMS, pathToMasterSword) <- astarSearch (last pathToThirdDungeon) (reachedSword overworldMap) (nextStepGen overworldMap) $ heuristic overworldMap
let totalCost' = [costFD, 2 * costFP, costSD, 2 * costSP, costTD, 2 * costTP, costMS]
totalPath' = [Path Overworld pathToFirstDungeon,
Path (Dungeon 1) $ pathToFirstPendant ++ (tail . reverse $ pathToFirstPendant),
Path Overworld pathToSecondDungeon,
Path (Dungeon 2) $ pathToSecondPendant ++ (tail . reverse $ pathToSecondPendant),
Path Overworld pathToThirdDungeon,
Path (Dungeon 3) $ pathToThirdPendant ++ (tail .reverse $ pathToThirdPendant),
Path Overworld pathToMasterSword]
return (totalCost', map (\(Path _ xs) -> (map rearrangePosition xs)) totalPath')
boot [overworldMap, dungeon1Map, dungeon2Map, dungeon3Map]-- TODO: Implement link tracer
let (totalCost', totalPath') = fromJust totalCostAndPath
putStrLn $ "Custo para chegar a primeira dungeon: " ++ (show $ totalCost' !! 0)
putChar '\n'
putStrLn $ "Caminho a primeira dungeon:" ++ (show $ totalPath' !! 0)
putChar '\n'
putStrLn $ "Custo para chegar ao primeiro pingente: " ++ (show $ totalCost' !! 1)
putChar '\n'
putStrLn $ "Caminho ao primeiro pingente e volta:" ++ (show $ totalPath' !! 1)
putChar '\n'
putStrLn $ "Custo para chegar a segunda dungeon: " ++ (show $ totalCost' !! 2)
putChar '\n'
putStrLn $ "Caminho a segunda dungeon:" ++ (show $ totalPath' !! 2)
putChar '\n'
putStrLn $ "Custo para chegar ao segundo pingente e volta: " ++ (show $ totalCost' !! 3)
putChar '\n'
putStrLn $ "Caminho ao segundo pingente:" ++ (show $ totalPath' !! 3)
putChar '\n'
putStrLn $ "Custo para chegar a terceira dungeon: " ++ (show $ totalCost' !! 4)
putChar '\n'
putStrLn $ "Caminho a terceira dungeon:" ++ (show $ totalPath' !! 4)
putChar '\n'
putStrLn $ "Custo para chegar ao terceiro pingente e volta: " ++ (show $ totalCost' !! 5)
putChar '\n'
putStrLn $ "Caminho ao terceiro pingente:" ++ (show $ totalPath' !! 5)
putChar '\n'
putStrLn $ "Custo para chegar a MasterSword: " ++ (show $ totalCost' !! 6)
putChar '\n'
putStrLn $ "Caminho a MasterSword :" ++ (show $ totalPath' !! 6)
putChar '\n'
putStrLn $ "Custo total: " ++ (show . sum $ totalCost')
putChar '\n'
|
trxeste/wrk
|
haskell/TrabalhoIA/src/Main_old.hs
|
bsd-3-clause
| 6,582 | 1 | 20 | 1,612 | 1,965 | 1,015 | 950 | 107 | 5 |
module TransparentCache where
import Control.Concurrent
import Control.Concurrent.MSampleVar
import Control.Monad
import qualified Data.Set as Set
import qualified Data.Map as Map
import Data.ByteString.Lazy (ByteString)
import Frenetic.NetCore
import Frenetic.NetworkFrames (arpReply)
import System.Log.Logger
import System.IO
-- TODO:
-- MAC rewriting
-- simplify!
-- Heartbeat --
-- For now, ping request packets count as the heartbeat.
isIP = DlTyp 0x800
isArp = DlTyp 0x806
heartbeatPred = isIP <&&> NwProto 1 <&&> NwTos 0
heartbeatDelay = 7 * 1000 * 1000 -- microseconds
-- Monitors for heartbeat packets from a given set of IP addresses and
-- periodically emits a set of ports that are still alive (i.e. are connected
-- to a TC that has sent a heartbeat in the most recent time interval).
monitorHeartbeats :: Set.Set IPAddress -> IO (MSampleVar (Set.Set Port), Policy)
monitorHeartbeats targetIPs = do
svar <- newEmptySV
(pktChan, act) <- getPkts
let pol = heartbeatPred ==> act
-- In a loop, delay for heartbeatDelay milliseconds, then read all the
-- heartbeat messages in the channel. Any host that sent a message is
-- still alive.
let loop ports = do
-- Unreachable for testing ...
isEmpty <- isEmptyChan pktChan
case isEmpty of
False -> do
((Loc switch port), heartbeatPkt) <- readChan pktChan
infoM "heartbeat" $ "packet in: " ++ show heartbeatPkt
case pktNwSrc heartbeatPkt of
Nothing -> loop ports
Just ip
| Set.member ip targetIPs -> loop $ Set.insert port ports
| otherwise -> loop ports
True -> do
infoM "heartbeat" $ "writing live ports: " ++ show ports
writeSV svar ports
threadDelay heartbeatDelay
loop Set.empty
let threadStart = do
threadDelay heartbeatDelay
loop Set.empty
forkIO threadStart
return (svar, pol)
-- Load Balancer --
-- TODO: currently drops the first packet of each new flow.
-- Generate a stream of policies forwarding IP flows out
-- ports drawn from the set of live ports pulled from the
-- livePortsSV channel.
balance :: MSampleVar (Set.Set Port) -> IO (Chan Policy)
balance livePortsSV = do
(ipChan, ipAct) <- getPkts
polChan <- newChan
let loop :: Set.Set Port -> [Port] -> Map.Map IPAddress Port -> IO ()
-- If there are no live ports, wait until some show up.
loop livePorts _ ip2port | Set.null livePorts = do
-- TODO: deploy a temporary policy forwarding everything?
infoM "balance" "no live ports."
livePorts' <- readSV livePortsSV
loop livePorts' (Set.toList livePorts') ip2port
-- If the portList is empty, refresh it.
loop livePorts [] ip2port | not $ Set.null livePorts = do
let newPorts = Set.toList livePorts
infoM "balance" $ "Reset live ports: " ++ show newPorts
loop livePorts (Set.toList livePorts) ip2port
-- Otherwise, proceed normally.
loop livePorts portList@(nextPort:portTail) ip2port
| not $ Set.null livePorts = do
infoM "balance" $ "next port: " ++ show nextPort
infoM "balance" $ "port tail: " ++ show portTail
-- Before taking any action, check whether the live TC's changed.
svIsEmpty <- isEmptySV livePortsSV
if not svIsEmpty then do
livePorts' <- readSV livePortsSV
-- Forget any dead ports and any IP addresses loaded onto
-- dead ports.
let portList' = filter (\p -> Set.member p livePorts') portList
let ip2port' = Map.filter (\p -> Set.member p livePorts') ip2port
infoM "balance" $ "livePorts': " ++ show livePorts'
infoM "balance" $ "portList': " ++ show portList'
loop livePorts' portList' ip2port'
else return ()
-- Otherwise, wait for a new flow.
((Loc switch port), pkt) <- readChan ipChan
case pktNwSrc pkt of
Nothing -> loop livePorts portList ip2port
Just ip ->
if Map.member ip ip2port then loop livePorts portList ip2port
else do
infoM "balance" $ "sending " ++ show ip ++ " to " ++ show nextPort
let ip2port' = Map.insert ip nextPort ip2port
writeChan polChan $ genPol ip2port' ipAct
loop livePorts portTail ip2port'
-- Wait for the initial set of live ports.
livePorts <- readSV livePortsSV
forkIO $ loop livePorts (Set.toList livePorts) Map.empty
writeChan polChan $ isIP ==> ipAct
return polChan
where
genPol :: Map.Map IPAddress Port -> [Action] -> Policy
genPol ip2port ipAct = genLoadRoutes ip2port <+> (genQ ip2port) ==> ipAct
genLoadRoutes ip2port = Map.foldrWithKey f PoBottom ip2port <%> isIP
f ip port pol = NwSrc (IPAddressPrefix ip 32) ==> forward [port] <+> pol
genQ ip2port = Not $ Map.foldrWithKey g None ip2port
g ip _ pred = NwSrc (IPAddressPrefix ip 32) <||> pred
-- Restrict policies in the channel to only match source IPs
-- in the given set of IP addresses. Useful to ensure we only
-- load-balance flows coming from the outside world.
restrict :: Set.Set IPAddress -> Chan Policy -> IO (Chan Policy)
restrict ips polChanIn = do
polChanOut <- newChan
let loop _ = do
pol <- readChan polChanIn
writeChan polChanOut $ pol <%> pred
loop ()
forkIO $ loop ()
return polChanOut
where
pred = Set.fold f None ips
f ip p = p <||> NwSrc (IPAddressPrefix ip 32)
transparentCache = do
let sourceIPs = Set.fromList [ipAddress 10 0 0 1, ipAddress 10 0 0 2]
let targetIPs = Set.fromList [ipAddress 10 0 0 3, ipAddress 10 0 0 4]
(livePortsSV, heartbeatPol) <- monitorHeartbeats targetIPs
loadChan <- balance livePortsSV
restChan <- restrict sourceIPs loadChan
allChan <- newChan
let loop _ = do
pol <- readChan restChan
writeChan allChan $ pol
<+> heartbeatPol
<+> isArp ==> allPorts unmodified
loop ()
forkIO $ loop ()
return allChan
startDebugLoop :: FilePath -> IO (Chan String)
startDebugLoop fp = do
handle <- openFile fp WriteMode
logChan <- newChan
forkIO $ forever $ do
str <- readChan logChan
hPutStrLn handle str
hFlush handle
return logChan
main addr = do
allChan <- transparentCache
logChan <- startDebugLoop "transparentCacheDebugLog.log"
debugDynController addr logChan allChan
|
frenetic-lang/netcore-1.0
|
examples/TransparentCache.hs
|
bsd-3-clause
| 6,576 | 0 | 24 | 1,799 | 1,732 | 812 | 920 | -1 | -1 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Numeral.CA.Rules (rules) where
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HashMap
import Data.Maybe
import Data.String
import Data.Text (Text)
import qualified Data.Text as Text
import Prelude
import Duckling.Dimensions.Types
import Duckling.Numeral.Helpers
import Duckling.Numeral.Types (NumeralData(..))
import qualified Duckling.Numeral.Types as TNumeral
import Duckling.Regex.Types
import Duckling.Types
zeroToFifteenMap :: HashMap Text Integer
zeroToFifteenMap =
HashMap.fromList
[ ("zero", 0)
, ("u", 1)
, ("un", 1)
, ("una", 1)
, ("dos", 2)
, ("dues", 2)
, ("tres", 3)
, ("quatre", 4)
, ("cinc", 5)
, ("sis", 6)
, ("set", 7)
, ("vuit", 8)
, ("nou", 9)
, ("deu", 10)
, ("onze", 11)
, ("dotze", 12)
, ("tretze", 13)
, ("catorze", 14)
, ("quinze", 15)
]
ruleZeroToFifteen :: Rule
ruleZeroToFifteen = Rule
{ name = "number (0..15)"
, pattern =
[ regex
"(zero|u(na|n)?|d(o|ue)s|tres|quatre|cinc|sis|set|vuit|nou|deu|onze|dotze|tretze|catorze|quinze)"
]
, prod = \case
(Token RegexMatch (GroupMatch (match:_)):_) ->
HashMap.lookup (Text.toLower match) zeroToFifteenMap >>= integer
_ -> Nothing
}
ruleNumeralsPrefixWithNegativeOrMinus :: Rule
ruleNumeralsPrefixWithNegativeOrMinus = Rule
{ name = "numbers prefix with -, negative or minus"
, pattern = [regex "-|menys", Predicate isPositive]
, prod = \case
(_ : Token Numeral NumeralData { TNumeral.value = v } : _) ->
double $ negate v
_ -> Nothing
}
tensMap :: HashMap Text Integer
tensMap =
HashMap.fromList
[ ("vint", 20)
, ("trenta", 30)
, ("quaranta", 40)
, ("cinquanta", 50)
, ("seixanta", 60)
, ("setanta", 70)
, ("vuitanta", 80)
, ("noranta", 90)
]
ruleTens :: Rule
ruleTens = Rule
{ name = "number (20..90)"
, pattern =
[ regex
"(vint|(tre|quara|cinqua|seixa|seta|vuita|nora)nta)"
]
, prod = \case
(Token RegexMatch (GroupMatch (match:_)) : _) ->
HashMap.lookup (Text.toLower match) tensMap >>= integer
_ -> Nothing
}
sixteenToTwentyNineMap :: HashMap Text Integer
sixteenToTwentyNineMap =
HashMap.fromList
[ ("setze", 16)
, ("disset", 17)
, ("dèsset", 17)
, ("devuit", 18)
, ("divuit", 18)
, ("dihuit", 18)
, ("dinou", 19)
, ("dènou", 19)
, ("denou", 19)
, ("vint-i-u", 21)
, ("vint-i-una", 21)
, ("vint-i-dos", 22)
, ("vint-i-tres", 23)
, ("vint-i-quatre", 24)
, ("vint-i-cinc", 25)
, ("vint-i-sis", 26)
, ("vint-i-set", 27)
, ("vint-i-vuit", 28)
, ("vint-i-nou", 29)
]
ruleLowerTensWithOnes :: Rule
ruleLowerTensWithOnes = Rule
{ name = "number (16..19 21..29)"
, pattern =
[ regex
"(setze|d(i|e|è)sset|d(e|i)(v|h)uit|d(i|e|è)nou|vint-i-u(na)?|vint-i-dos|vint-i-tres|vint-i-quatre|vint-i-cinc|vint-i-sis|vint-i-set|vint-i-vuit|vint-i-nou)"
]
, prod = \case
(Token RegexMatch (GroupMatch (match:_)):_) ->
HashMap.lookup (Text.toLower match) sixteenToTwentyNineMap >>= integer
_ -> Nothing
}
ruleHigherTensWithOnes :: Rule
ruleHigherTensWithOnes = Rule
{ name = "number (31..39 41..49 51..59 61..69 71..79 81..89 91..99)"
, pattern =
[oneOf [30, 40, 50, 60, 70, 80, 90], regex "-", numberBetween 1 9]
, prod = \case
(Token Numeral NumeralData{TNumeral.value = v1}:
_:
Token Numeral NumeralData{TNumeral.value = v2}:
_) -> double $ v1 + v2
_ -> Nothing
}
ruleNumeralsSuffixesKMG :: Rule
ruleNumeralsSuffixesKMG = Rule
{ name = "numbers suffixes (K, M, G)"
, pattern = [dimension Numeral, regex "([kmg])(?=[\\W\\$€]|$)"]
, prod = \case
(Token Numeral NumeralData{TNumeral.value = v}:
Token RegexMatch (GroupMatch (match:_)):
_) ->
case Text.toLower match of
"k" -> double $ v * 1e3
"m" -> double $ v * 1e6
"g" -> double $ v * 1e9
_ -> Nothing
_ -> Nothing
}
oneHundredToThousandMap :: HashMap Text Integer
oneHundredToThousandMap =
HashMap.fromList
[ ("cent", 100)
, ("cents", 100)
, ("dos-cents", 200)
, ("tres-cents", 300)
, ("quatre-cents", 400)
, ("cinc-cents", 500)
, ("sis-cents", 600)
, ("set-cents", 700)
, ("vuit-cents", 800)
, ("nou-cents", 900)
, ("mil", 1000)
]
ruleTwenties :: Rule
ruleTwenties = Rule
{ name = "number (21..29)"
, pattern =
[oneOf [20], regex "(-i-| i )", numberBetween 1 10]
, prod = \case
(Token Numeral NumeralData{TNumeral.value = v1}:
_:
Token Numeral NumeralData{TNumeral.value = v2}:
_) -> double $ v1 + v2
_ -> Nothing
}
ruleHundreds :: Rule
ruleHundreds = Rule
{ name = "number 100..1000 "
, pattern =
[ regex
"(cent(s)?|dos-cents|tres-cents|quatre-cents|cinc-cents|sis-cents|set-cents|vuit-cents|nou-cents|mil)"
]
, prod = \case
(Token RegexMatch (GroupMatch (match:_)):_) ->
HashMap.lookup (Text.toLower match) oneHundredToThousandMap >>= integer
_ -> Nothing
}
-- Afegeixo regex "-" perque les centenes s'escriuen dos-cent, tres-cent
ruleNumerals :: Rule
ruleNumerals = Rule
{ name = "numbers 200..999"
, pattern =
[ numberBetween 2 10
, regex "-"
, numberWith TNumeral.value (== 100)
, numberBetween 0 100
]
, prod = \case
(Token Numeral NumeralData{TNumeral.value = v1}:
_:
Token Numeral NumeralData{TNumeral.value = v2}:
_) -> double $ 100 * v1 + v2
_ -> Nothing
}
ruleNumeralDotNumeral :: Rule
ruleNumeralDotNumeral = Rule
{ name = "number dot number"
, pattern = [dimension Numeral, regex "coma", Predicate $ not . hasGrain]
, prod = \case
(Token Numeral NumeralData{TNumeral.value = v1}:
_:
Token Numeral NumeralData{TNumeral.value = v2}:
_) -> double $ v1 + decimalsToDouble v2
_ -> Nothing
}
ruleBelowTenWithTwoDigits :: Rule
ruleBelowTenWithTwoDigits = Rule
{ name = "integer (0-9) with two digits"
, pattern =
[ regex "zero|0"
, numberBetween 1 10
]
, prod = \case
(_:Token Numeral NumeralData{TNumeral.value = v}:_) -> double v
_ -> Nothing
}
ruleDecimalWithThousandsSeparator :: Rule
ruleDecimalWithThousandsSeparator = Rule
{ name = "decimal with thousands separator ."
, pattern = [regex "(\\d+(\\.\\d\\d\\d)+,\\d+)"]
, prod = \case
(Token RegexMatch (GroupMatch (match:_)):_) ->
let fmt = Text.replace "," "." . Text.replace "." Text.empty $ match
in parseDouble fmt >>= double
_ -> Nothing
}
ruleDecimalNumeral :: Rule
ruleDecimalNumeral = Rule
{ name = "decimal number ,"
, pattern = [regex "(\\d*,\\d+)"]
, prod = \case
(Token RegexMatch (GroupMatch (match:_)):_) ->
parseDecimal False match
_ -> Nothing
}
ruleIntegerWithThousandsSeparator :: Rule
ruleIntegerWithThousandsSeparator = Rule
{ name = "integer with thousands separator ."
, pattern = [regex "(\\d{1,3}(\\.\\d\\d\\d){1,5})"]
, prod = \case
(Token RegexMatch (GroupMatch (match:_)):_) ->
parseDouble (Text.replace "." Text.empty match) >>= double
_ -> Nothing
}
rules :: [Rule]
rules =
[ ruleBelowTenWithTwoDigits
, ruleZeroToFifteen
, ruleTens
, ruleTwenties
, ruleLowerTensWithOnes
, ruleHigherTensWithOnes
, ruleHundreds
, ruleNumeralDotNumeral
, ruleNumerals
, ruleNumeralsPrefixWithNegativeOrMinus
, ruleNumeralsSuffixesKMG
, ruleDecimalNumeral
, ruleDecimalWithThousandsSeparator
, ruleIntegerWithThousandsSeparator
]
|
facebookincubator/duckling
|
Duckling/Numeral/CA/Rules.hs
|
bsd-3-clause
| 8,005 | 0 | 17 | 1,941 | 2,299 | 1,329 | 970 | 244 | 5 |
{-# LANGUAGE TypeFamilies, DataKinds, OverloadedStrings, FlexibleContexts #-}
-- | Allow to select a 'SQLFragment' as tuple with a type signature
-- corresponding to SQLFragment type.
--
-- @
-- let itemCode = "code.items" :: SQLFragment '[String] '[]
-- let itemPrice = "price.items" :: SQLFragment '[Double] '[]
--
-- main = do
-- connection <- ...
-- rows <- selectTuples connection (itemCode !&! itemPrice)
-- -- rows :: [(String, Double)]
-- mapM_ print rows
-- @
module Database.SQLFragment.MySQL.Simple.Tuple where
-- standard
import Data.Int(Int64)
import Data.Monoid
import Data.String(IsString(..))
import System.Environment (lookupEnv)
import Control.Monad(when)
-- third-party
import qualified Database.MySQL.Simple as SQL
import qualified Database.MySQL.Simple.QueryResults as SQL
import qualified Database.MySQL.Simple.QueryParams as SQL
import Database.SQLFragment
import Database.SQLFragment.MySQL.Simple.Internal
import Database.SQLFragment.TypeFamilies
-- local
type family Tuple (e :: [*]) :: *
-- | Execute an SQLFragment as a SELECT and return the result
-- as a list of tuples.
selectTuples :: (SQL.QueryResults (Tuple e), Show (Tuple e))
=>
SQL.Connection
-> SQLFragment e '[]
-> IO [Tuple e]
selectTuples conn query = select conn query
selectTuplesWith :: (SQL.QueryResults (Tuple e), Show (Tuple e), SQL.QueryParams (Tuple p), Show (Tuple p))
=>
SQL.Connection
-> SQLFragment e p
-> Tuple p
-> IO [Tuple e]
selectTuplesWith conn query params = selectWith conn query params
insertTuples :: (SQL.QueryParams (Tuple e), Show (Tuple e))
=> SQL.Connection
-> SQLFragment e '[]
-> [Tuple e]
-> IO Int64
insertTuples conn query values = insertMulti conn query values
-- * Instance
type instance Tuple '[a] = (SQL.Only (GetValue a))
type instance Tuple '[a, b] = ((GetValue a), (GetValue b))
type instance Tuple '[a, b, c] = ((GetValue a), (GetValue b), (GetValue c))
type instance Tuple '[a, b, c, d] = ((GetValue a), (GetValue b), (GetValue c), (GetValue d))
type instance Tuple '[a, b, c, d, e] = ((GetValue a), (GetValue b), (GetValue c), (GetValue d), (GetValue e))
type instance Tuple '[a, b, c, d, e, f] = ((GetValue a), (GetValue b), (GetValue c), (GetValue d), (GetValue e), (GetValue f))
type instance Tuple '[a, b, c, d, e, f, g] = ((GetValue a), (GetValue b), (GetValue c), (GetValue d), (GetValue e), (GetValue f), (GetValue g))
type instance Tuple '[a, b, c, d, e, f, g, h] = ((GetValue a), (GetValue b), (GetValue c), (GetValue d), (GetValue e), (GetValue f), (GetValue g), (GetValue h))
type instance Tuple '[a, b, c, d, e, f, g, h, i] = ((GetValue a), (GetValue b), (GetValue c), (GetValue d), (GetValue e), (GetValue f), (GetValue g), (GetValue h), (GetValue i))
type instance Tuple '[a, b, c, d, e, f, g, h, i, j] = ((GetValue a), (GetValue b), (GetValue c), (GetValue d), (GetValue e), (GetValue f), (GetValue g), (GetValue h), (GetValue i), (GetValue j))
type instance Tuple '[a, b, c, d, e, f, g, h, i, j, k] = ((GetValue a), (GetValue b), (GetValue c), (GetValue d), (GetValue e), (GetValue f), (GetValue g), (GetValue h), (GetValue i), (GetValue j), (GetValue k))
type instance Tuple '[a, b, c, d, e, f, g, h, i, j, k, l] = ((GetValue a), (GetValue b), (GetValue c), (GetValue d), (GetValue e), (GetValue f), (GetValue g), (GetValue h), (GetValue i), (GetValue j), (GetValue k), (GetValue l))
type instance Tuple '[a, b, c, d, e, f, g, h, i, j, k, l, m] = ((GetValue a), (GetValue b), (GetValue c), (GetValue d), (GetValue e), (GetValue f), (GetValue g), (GetValue h), (GetValue i), (GetValue j), (GetValue k), (GetValue l), (GetValue m))
type instance Tuple '[a, b, c, d, e, f, g, h, i, j, k, l, m, n] = ((GetValue a), (GetValue b), (GetValue c), (GetValue d), (GetValue e), (GetValue f), (GetValue g), (GetValue h), (GetValue i), (GetValue j), (GetValue k), (GetValue l), (GetValue m), (GetValue n))
instance (Semigroup a) => Semigroup (SQL.Only a) where
a <> b = SQL.Only (SQL.fromOnly a <> SQL.fromOnly b)
instance (Monoid a) => Monoid (SQL.Only a) where
mempty = SQL.Only mempty
|
maxigit/sql-fragment-mysql-simple
|
src/Database/SQLFragment/MySQL/Simple/Tuple.hs
|
bsd-3-clause
| 4,223 | 0 | 11 | 835 | 1,942 | 1,120 | 822 | 49 | 1 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Mir.Compositional.Clobber
where
import Control.Lens ((^.), (^?), ix)
import Control.Monad.Except
import qualified Data.Map as Map
import qualified Data.Parameterized.Context as Ctx
import Data.Parameterized.TraversableFC
import qualified Data.Vector as V
import GHC.Stack (HasCallStack)
import qualified What4.Expr.Builder as W4
import qualified What4.Interface as W4
import qualified What4.Partial as W4
import What4.ProgramLoc
import Lang.Crucible.Backend
import Lang.Crucible.Simulator
import Lang.Crucible.Types
import Mir.Generator (CollectionState, collection, staticMap, StaticVar(..))
import Mir.Intrinsics hiding (MethodSpec, MethodSpecBuilder)
import qualified Mir.Mir as M
import Mir.TransTy (pattern CTyUnsafeCell)
import Mir.Compositional.Convert
-- Helper functions for generating clobbering PointsTos
-- | Replace each primitive value within `rv` with a fresh symbolic variable.
clobberSymbolic :: forall sym p t st fs tp rtp args ret.
(IsSymInterface sym, sym ~ W4.ExprBuilder t st fs, HasCallStack) =>
sym -> ProgramLoc -> String -> TypeShape tp -> RegValue sym tp ->
OverrideSim (p sym) sym MIR rtp args ret (RegValue sym tp)
clobberSymbolic sym loc nameStr shp rv = go shp rv
where
go :: forall tp. TypeShape tp -> RegValue sym tp ->
OverrideSim (p sym) sym MIR rtp args ret (RegValue sym tp)
go (UnitShape _) () = return ()
go shp@(PrimShape _ _btpr) _rv = freshSymbolic sym loc nameStr shp
go (ArrayShape _ _ shp) mirVec = case mirVec of
MirVector_Vector v -> MirVector_Vector <$> mapM (go shp) v
MirVector_PartialVector pv ->
MirVector_PartialVector <$> mapM (mapM (go shp)) pv
MirVector_Array _ -> error $ "clobberSymbolic: MirVector_Array is unsupported"
go (TupleShape _ _ flds) rvs =
Ctx.zipWithM goField flds rvs
go (StructShape _ _ flds) (AnyValue tpr rvs)
| Just Refl <- testEquality tpr shpTpr = AnyValue tpr <$> Ctx.zipWithM goField flds rvs
| otherwise = error $ "clobberSymbolic: type error: expected " ++ show shpTpr ++
", but got Any wrapping " ++ show tpr
where shpTpr = StructRepr $ fmapFC fieldShapeType flds
go (TransparentShape _ shp) rv = go shp rv
go shp _rv = error $ "clobberSymbolic: " ++ show (shapeType shp) ++ " NYI"
goField :: forall tp. FieldShape tp -> RegValue' sym tp ->
OverrideSim (p sym) sym MIR rtp args ret (RegValue' sym tp)
goField (ReqField shp) (RV rv) = RV <$> go shp rv
goField (OptField shp) (RV rv) = do
rv' <- liftIO $ readMaybeType sym "field" (shapeType shp) rv
rv'' <- go shp rv'
return $ RV $ W4.justPartExpr sym rv''
-- | Like `clobberSymbolic`, but for values in "immutable" memory. Values
-- inside an `UnsafeCell<T>` wrapper can still be modified even with only
-- immutable (`&`) access. So this function modifies only the portions of `rv`
-- that lie within an `UnsafeCell` and leaves the rest unchanged.
clobberImmutSymbolic :: forall sym p t st fs tp rtp args ret.
(IsSymInterface sym, sym ~ W4.ExprBuilder t st fs, HasCallStack) =>
sym -> ProgramLoc -> String -> TypeShape tp -> RegValue sym tp ->
OverrideSim (p sym) sym MIR rtp args ret (RegValue sym tp)
clobberImmutSymbolic sym loc nameStr shp rv = go shp rv
where
go :: forall tp. TypeShape tp -> RegValue sym tp ->
OverrideSim (p sym) sym MIR rtp args ret (RegValue sym tp)
go (UnitShape _) () = return ()
-- If we reached a leaf value without entering an `UnsafeCell`, then
-- there's nothing to change.
go (PrimShape _ _) rv = return rv
go (ArrayShape _ _ shp) mirVec = case mirVec of
MirVector_Vector v -> MirVector_Vector <$> mapM (go shp) v
MirVector_PartialVector pv ->
MirVector_PartialVector <$> mapM (mapM (go shp)) pv
MirVector_Array _ -> error $ "clobberSymbolic: MirVector_Array is unsupported"
go shp@(StructShape (CTyUnsafeCell _) _ _) rv =
clobberSymbolic sym loc nameStr shp rv
go shp@(TransparentShape (CTyUnsafeCell _) _) rv =
clobberSymbolic sym loc nameStr shp rv
go (TupleShape _ _ flds) rvs =
Ctx.zipWithM goField flds rvs
go (StructShape _ _ flds) (AnyValue tpr rvs)
| Just Refl <- testEquality tpr shpTpr = AnyValue tpr <$> Ctx.zipWithM goField flds rvs
| otherwise = error $ "clobberSymbolic: type error: expected " ++ show shpTpr ++
", but got Any wrapping " ++ show tpr
where shpTpr = StructRepr $ fmapFC fieldShapeType flds
go (TransparentShape _ shp) rv = go shp rv
-- Since this ref is in immutable memory, whatever behavior we're
-- approximating with this clobber can't possibly modify it.
go (RefShape _ _ _tpr) rv = return rv
goField :: forall tp. FieldShape tp -> RegValue' sym tp ->
OverrideSim (p sym) sym MIR rtp args ret (RegValue' sym tp)
goField (ReqField shp) (RV rv) = RV <$> go shp rv
goField (OptField shp) (RV rv) = do
rv' <- liftIO $ readMaybeType sym "field" (shapeType shp) rv
rv'' <- go shp rv'
return $ RV $ W4.justPartExpr sym rv''
-- | Construct a fresh symbolic `RegValue` of type `tp`.
freshSymbolic :: forall sym p t st fs tp rtp args ret.
(IsSymInterface sym, sym ~ W4.ExprBuilder t st fs, HasCallStack) =>
sym -> ProgramLoc -> String -> TypeShape tp ->
OverrideSim (p sym) sym MIR rtp args ret (RegValue sym tp)
freshSymbolic sym loc nameStr shp = go shp
where
go :: forall tp. TypeShape tp ->
OverrideSim (p sym) sym MIR rtp args ret (RegValue sym tp)
go (UnitShape _) = return ()
go (PrimShape _ btpr) = do
let nameSymbol = W4.safeSymbol nameStr
expr <- liftIO $ W4.freshConstant sym nameSymbol btpr
let ev = CreateVariableEvent loc nameStr btpr expr
ovrWithBackend $ \bak ->
liftIO $ addAssumptions bak (singleEvent ev)
return expr
go (ArrayShape (M.TyArray _ len) _ shp) =
MirVector_Vector <$> V.replicateM len (go shp)
go shp = error $ "freshSymbolic: " ++ show (shapeType shp) ++ " NYI"
-- Note on clobbering refs inside `static`s: The current behavior is to leave
-- refs inside immutable memory unchanged, and to error on encountering a ref
-- inside mutable memory. We don't explicitly traverse refs inside
-- `clobberGlobals`; however, since immutable statics always contain a constant
-- value (and can't be mutated after the program starts), refs inside them can
-- only ever point to other statics. So if immutable static `A` contains a
-- reference to a non-`Freeze` (i.e. `UnsafeCell`-containing) allocation `x`,
-- it's okay that we don't traverse the ref from `A` to `x`, because `x` is
-- guaranteed to be another static, and will get clobbered that way.
--
-- If we ever add a `RefShape` case to the non-`Immut` `clobberSymbolic`, that
-- case will need to traverse through refs and clobber their contents. We
-- can't rely on the target of the ref being another static, since the program
-- might have stored the result of e.g. `Box::leak` (of type `&'static mut T`)
-- into the mutable static. And overwriting the ref itself with a symbolic or
-- invalid ref value is not enough, since the function we're approximating
-- might write through the old ref before replacing it with a new one.
clobberGlobals :: forall sym p t st fs rtp args ret.
(IsSymInterface sym, sym ~ W4.ExprBuilder t st fs, HasCallStack) =>
sym -> ProgramLoc -> String -> CollectionState ->
OverrideSim (p sym) sym MIR rtp args ret ()
clobberGlobals sym loc nameStr cs = do
forM_ (Map.toList $ cs ^. staticMap) $ \(defId, StaticVar gv) -> do
let static = case cs ^? collection . M.statics . ix defId of
Just x -> x
Nothing -> error $ "couldn't find static def for " ++ show defId
let tpr = globalType gv
let shp = tyToShapeEq (cs ^. collection) (static ^. M.sTy) tpr
let clobber = case static ^. M.sMutable of
False -> clobberImmutSymbolic sym loc nameStr
True -> clobberSymbolic sym loc nameStr
rv <- readGlobal gv
rv' <- clobber shp rv
writeGlobal gv rv'
clobberGlobalsOverride :: forall sym p t st fs rtp args ret.
(IsSymInterface sym, sym ~ W4.ExprBuilder t st fs, HasCallStack) =>
CollectionState ->
OverrideSim (p sym) sym MIR rtp args ret ()
clobberGlobalsOverride cs = do
sym <- getSymInterface
loc <- liftIO $ W4.getCurrentProgramLoc sym
clobberGlobals sym loc "clobber_globals" cs
|
GaloisInc/saw-script
|
crux-mir-comp/src/Mir/Compositional/Clobber.hs
|
bsd-3-clause
| 8,664 | 0 | 18 | 1,989 | 2,428 | 1,239 | 1,189 | -1 | -1 |
module Semant ( ExpTy(..), semant ) where
import AbSyn
import Control.Monad
import Control.Monad.Trans.Class
import Control.Monad.Trans.Error
import Control.Monad.Trans.Reader
import Control.Monad.Trans.State
import Data.Functor.Identity
import Env
import Symbol
import qualified Translate
import qualified Types
--------------------------------------------------------------------------------
data Envs = Envs {
vEnv :: VEnv,
tEnv :: TEnv
} deriving ( Show )
initialEnvs :: Envs
initialEnvs = Envs baseVEnv baseTEnv
--------------------------------------------------------------------------------
type Trans = StateT [Types.Unique] (ReaderT Envs (ErrorT String Identity))
evalT :: Trans a -> Either String a
evalT = runIdentity . runErrorT . flip runReaderT initialEnvs . flip evalStateT Types.uniqueSupply
throwT :: Pos -> String -> Trans a
throwT pos = lift . lift . throwError . shows pos . showString ": "
lookupT :: Pos -> (Envs -> Table a) -> Symbol -> Trans a
lookupT pos f sym = do
env <- lift (asks f)
case look sym env of
Nothing -> throwT pos ("unknown identifier '" ++ show sym ++ "'")
Just x -> return x
nextUnique :: Trans Types.Unique
nextUnique = do
(unique:rest) <- get
put rest
return unique
--------------------------------------------------------------------------------
data ExpTy = ExpTy {
translatedExp :: Translate.Exp,
typeOf :: Types.Ty
} deriving ( Show )
returnTy :: Types.Ty -> Trans ExpTy
returnTy = return . ExpTy Translate.Exp
--------------------------------------------------------------------------------
-- TODO Use this more often.
actualTy :: Types.Ty -> Types.Ty
actualTy ty = case ty of
Types.Name _ (Just realTy) -> actualTy realTy
_ -> ty
getVarTy :: Pos -> EnvEntry -> Trans Types.Ty
getVarTy pos entry = case entry of
FunEntry _ _ -> throwT pos "variable required"
VarEntry ty -> return $ actualTy ty
getFunTy :: Pos -> EnvEntry -> Trans ([Types.Ty], Types.Ty)
getFunTy pos entry = case entry of
FunEntry formals result -> return (formals, result)
VarEntry _ -> throwT pos "function required"
getArrayBaseTy :: Pos -> Types.Ty -> Trans Types.Ty
getArrayBaseTy pos t = case t of
Types.Array baseTy _ -> return baseTy
_ -> throwT pos "array type required"
getRecordFields :: Pos -> Types.Ty -> Trans [(Symbol, Types.Ty)]
getRecordFields pos t = case t of
Types.Record symTys _ -> return symTys
_ -> throwT pos "record type required"
-- Used for lvalues and rvalues, at least for now.
transVar :: Var -> Trans ExpTy
transVar var = case var of
SimpleVar varId pos -> do
entry <- lookupT pos vEnv varId
ty <- getVarTy pos entry
returnTy ty
FieldVar v field pos -> do
etVar <- transVar v
symTys <- getRecordFields pos (typeOf etVar)
case lookup field symTys of
Nothing -> throwT pos ("'" ++ show field ++ "' is not a field of the record type")
Just t -> returnTy t
SubscriptVar v idx pos -> do
etV <- transVar v
etIdx <- transExp idx
baseTy <- getArrayBaseTy pos (typeOf etV)
checkArithmeticTy pos (typeOf etIdx)
returnTy baseTy
checkCompatibleTys :: Pos -> Types.Ty -> Types.Ty -> Trans ()
checkCompatibleTys pos ty1 ty2 =
unless (ty1 `Types.isCompatibleWith` ty2) $
throwT pos "incompatible types"
transCall :: Pos -> Symbol -> [Exp] -> Trans ExpTy
transCall pos func args = do
entry <- lookupT pos vEnv func
(formals, result) <- getFunTy pos entry
unless (length args == length formals) $
throwT pos ("expected " ++ show (length formals) ++ " number of arguments")
etArgs <- mapM transExp args
zipWithM_ (checkCompatibleTys pos) formals (map typeOf etArgs)
returnTy result
checkField :: (Symbol, Types.Ty) -> (Symbol, Exp, Pos) -> Trans ()
checkField (s1, ty) (s2, expr, pos) = do
unless (s1 == s2) $
throwT pos ("expected field " ++ name s1)
etExpr <- transExp expr
checkCompatibleTys pos ty (typeOf etExpr)
transRecordExp :: Pos -> [(Symbol, Exp, Pos)] -> Symbol -> Trans ExpTy
transRecordExp pos fields typeId = do
ty <- lookupT pos tEnv typeId
symTys <- getRecordFields pos ty
unless (length symTys == length fields) $
throwT pos ("expected " ++ show (length symTys) ++ " number of fields")
zipWithM_ checkField symTys fields
returnTy ty
transSeq :: [(Exp,Pos)] -> Trans ExpTy
transSeq exprs
| null exprs = returnTy Types.Unit
| otherwise = fmap last $ mapM (transExp . fst) exprs
transAssign :: Pos -> Var -> Exp -> Trans ExpTy
transAssign pos var expr = do
etVar <- transVar var
etExpr <- transExp expr
checkCompatibleTys pos (typeOf etVar) (typeOf etExpr)
returnTy Types.Unit
transIf :: Pos -> Exp -> Exp -> Maybe Exp -> Trans ExpTy
transIf pos test then_ else_ = do
etTest <- transExp test
etThen <- transExp then_
etElse <- maybe (returnTy Types.Unit) transExp else_
checkArithmeticTy pos (typeOf etTest)
checkCompatibleTys pos (typeOf etThen) (typeOf etElse)
returnTy $ typeOf etThen
checkUnitTy :: Pos -> Types.Ty -> Trans ()
checkUnitTy pos ty = case ty of
Types.Unit -> return ()
_ -> throwT pos "no return value expected"
transWhile :: Pos -> Exp -> Exp -> Trans ExpTy
transWhile pos test body = do
etTest <- transExp test
etBody <- transExp body
checkArithmeticTy pos (typeOf etTest)
checkUnitTy pos (typeOf etBody)
returnTy Types.Unit
transFor :: Pos -> Symbol -> Exp -> Exp -> Exp -> Trans ExpTy
transFor pos _var lo hi body = do
etLo <- transExp lo
etHi <- transExp hi
etBody <- transExp body
checkArithmeticTy pos (typeOf etLo)
checkArithmeticTy pos (typeOf etHi)
checkUnitTy pos (typeOf etBody)
returnTy Types.Unit
-- TODO actually handle environments
transLet :: Pos -> [Dec] -> Exp -> Trans ExpTy
transLet _pos decs body = do
mapM_ transDec decs
transExp body
transArray :: Pos -> Symbol -> Exp -> Exp -> Trans ExpTy
transArray pos typeId size initVal = do
ty <- lookupT pos tEnv typeId
etSize <- transExp size
etInitVal <- transExp initVal
baseTy <- getArrayBaseTy pos ty
checkArithmeticTy pos (typeOf etSize)
checkCompatibleTys pos baseTy (typeOf etInitVal)
returnTy ty
transExp :: Exp -> Trans ExpTy
transExp e = case e of
VarExp var -> transVar var
NilExp -> returnTy Types.Nil
IntExp _ -> returnTy Types.Int
StringExp _ _ -> returnTy Types.String
CallExp func args pos -> transCall pos func args
OpExp left oper right pos -> transOp pos left oper right
RecordExp fields typeId pos -> transRecordExp pos fields typeId
SeqExp exprs -> transSeq exprs
AssignExp var expr pos -> transAssign pos var expr
IfExp test then_ else_ pos -> transIf pos test then_ else_
WhileExp test body pos -> transWhile pos test body
ForExp var lo hi body pos -> transFor pos var lo hi body
BreakExp _ -> returnTy Types.Unit -- TODO Check for loop
LetExp decs body pos -> transLet pos decs body
ArrayExp typeId size initVal pos -> transArray pos typeId size initVal
transOp :: Pos -> Exp -> Oper -> Exp -> Trans ExpTy
transOp pos left oper right = do
etLeft <- transExp left
etRight <- transExp right
checkForOper oper pos (typeOf etLeft)
checkCompatibleTys pos (typeOf etLeft) (typeOf etRight)
returnTy Types.Int
checkForOper :: Oper -> Pos -> Types.Ty -> Trans ()
checkForOper oper = case oper of
PlusOp -> checkArithmeticTy
MinusOp -> checkArithmeticTy
TimesOp -> checkArithmeticTy
DivideOp -> checkArithmeticTy
EqOp -> checkEqualityTy
NeqOp -> checkEqualityTy
LtOp -> checkComparableTy
LeOp -> checkComparableTy
GtOp -> checkComparableTy
GeOp -> checkComparableTy
checkArithmeticTy :: Pos -> Types.Ty -> Trans ()
checkArithmeticTy pos ty =
unless (Types.isArithmeticTy ty) $
throwT pos "arithmetic type (integer) required"
checkEqualityTy :: Pos -> Types.Ty -> Trans ()
checkEqualityTy pos ty =
unless (Types.isEqualityTy ty) $
throwT pos "equality type (record/integer/string/array) required"
checkComparableTy :: Pos -> Types.Ty -> Trans ()
checkComparableTy pos ty =
unless (Types.isComparableTy ty) $
throwT pos "comparable type (integer/string) required"
transFunDec :: FunDec -> Trans ()
transFunDec (FunDec funId params result body pos) = undefined
transVarDec :: Pos -> Symbol -> Maybe (Symbol, Pos) -> Exp -> Trans ()
transVarDec pos varId mbTy initVal = undefined
transTyDec :: TyDec -> Trans ()
transTyDec (TyDec typeId ty pos) = undefined
-- TODO recursive types
transDec :: Dec -> Trans ()
transDec dec = case dec of
FunctionDec funDecs -> mapM_ transFunDec funDecs
VarDec varId mbTy initVal pos -> transVarDec pos varId mbTy initVal
TypeDec tyDecs -> mapM_ transTyDec tyDecs
transField :: Field -> Trans (Symbol, Types.Ty)
transField (Field fieldName typeId pos) = do
fieldTy <- lookupT pos tEnv typeId
return (fieldName, fieldTy)
transTy :: Ty -> Trans Types.Ty
transTy ty = case ty of
NameTy typeId pos -> lookupT pos tEnv typeId
RecordTy fields -> do
fs <- mapM transField fields
unique <- nextUnique
return $ Types.Record fs unique
ArrayTy typeId pos -> do
baseTy <- lookupT pos tEnv typeId
unique <- nextUnique
return $ Types.Array baseTy unique
semant :: Exp -> Either String ExpTy
semant = evalT . transExp
|
svenpanne/tiger
|
chapter05/src/Semant.hs
|
bsd-3-clause
| 9,168 | 0 | 17 | 1,788 | 3,267 | 1,563 | 1,704 | 232 | 15 |
{-# OPTIONS -fglasgow-exts #-}
{-# LANGUAGE IncoherentInstances #-}
{-# LANGUAGE UndecidableInstances #-}
module Graphics.Ubigraph.Fgl (
addGraph, pathVertexColor,
) where
import Data.Graph.Inductive
import Data.Graph.Inductive.Graph
import qualified Graphics.Ubigraph as H
mkEdgeId :: Edge -> Int
mkEdgeId (src,dst) = src * 10000 + dst
newE :: Edge -> H.Hubigraph Int
newE e = H.newEdgeWithID (mkEdgeId e) e
newV :: LNode' a => LNode a -> H.Hubigraph ()
newV ln = do
H.newVertexWithID $ fst ln
H.vertexLabel (fst ln) $ print' ln
return ()
pathEdges :: Path -> [Edge]
pathEdges (s:d:xs) = (s,d):pathEdges xs
pathEdges (s:[]) = []
pathEdges [] = []
addGraph :: LNode' a => Graph gr => gr a b -> H.Hubigraph ()
addGraph g = do
mapM_ newV (labNodes g)
mapM_ newE (edges g)
pathVertexColor :: Path -> H.Color -> H.Hubigraph ()
pathVertexColor p c = mapM_ (\n -> H.vertexColor n c) p
pathEdgeColor :: Path -> H.Color -> H.Hubigraph ()
pathEdgeColor p c = undefined
pathWidth :: Path -> Float -> H.Hubigraph ()
pathWidth p width = mapM_ (\n -> H.edgeWidth (mkEdgeId n) width) $ pathEdges p
class LNode' a where
print' :: LNode a -> String
instance LNode' String where
print' (n,l) = l
instance LNode' Int where
print' (n,l) = show l
instance LNode' Double where
print' (n,l) = show l
instance LNode' a where
print' (n,l) = ""
|
smly/hubigraph
|
Graphics/Ubigraph/Fgl.hs
|
bsd-3-clause
| 1,372 | 0 | 11 | 274 | 587 | 300 | 287 | -1 | -1 |
{-# LANGUAGE QuasiQuotes #-}
import LiquidHaskell
[lq| (>>=) :: m a -> (a -> m b) -> m b |]
|
spinda/liquidhaskell
|
tests/gsoc15/unknown/pos/PlugHoles.hs
|
bsd-3-clause
| 96 | 0 | 4 | 24 | 12 | 8 | 4 | 3 | 0 |
module Init.Guide (init, chapters) where
import Control.Monad (when)
import qualified Data.Maybe as Maybe
import Prelude hiding (init)
import System.Exit (exitFailure)
import System.FilePath ((</>), (<.>))
import qualified Init.FileTree as FT
import Init.Helpers (makeWithStyle, write, isOutdated)
-- CHAPTERS
chapters :: [String]
chapters =
[ "core-language"
, "model-the-problem"
, "reactivity"
, "interop"
]
-- INITIALIZE
init :: IO ()
init =
do write "Setting up guide ."
mapM_ initChapter chapters
mapM_ generateHtml chapters
putStrLn " done\n"
initChapter :: String -> IO ()
initChapter name =
let
input =
"src" </> "guide" </> "chapters" </> name <.> "md"
output =
FT.file ["guide","elm"] name "elm"
in
do outdated <- isOutdated input output
when outdated $ do
markdown <- readFile input
let mdLines = lines markdown
case Maybe.mapMaybe toTitle mdLines of
[] ->
do putStrLn $ " no title found for '" ++ name ++ "'!\n"
exitFailure
[title] ->
do let content = unlines (filter notTitle mdLines)
writeFile output (toElm title content)
_ ->
do putStrLn $ " fould multiple titles for '" ++ name ++ "'!\n"
exitFailure
generateHtml :: String -> IO Bool
generateHtml name =
do write "."
makeWithStyle
(FT.file ["guide", "elm"] name "elm")
(FT.file ["guide", "html"] name "html")
-- CONVERSIONS
toTitle :: String -> Maybe String
toTitle line =
case line of
'#' : ' ' : title ->
Just title
_ ->
Nothing
notTitle :: String -> Bool
notTitle line =
Maybe.isNothing (toTitle line)
toElm :: String -> String -> String
toElm title markdown =
unlines
[ "import Html exposing (..)"
, "import Html.Attributes exposing (..)"
, "import Blog"
, "import Center"
, ""
, "port title : String"
, "port title ="
, " " ++ show title
, ""
, "main ="
, " Blog.docs " ++ show title ++ " [ Center.markdown \"600px\" info ]"
, ""
, "info = \"\"\"\n" ++ markdown ++ "\n\"\"\""
]
|
FranklinChen/elm-lang.org
|
src/backend/Init/Guide.hs
|
bsd-3-clause
| 2,203 | 0 | 22 | 659 | 621 | 324 | 297 | 73 | 3 |
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Data.Semigroup.Instances () where
import Data.Semigroup
import Data.VectorSpace hiding (Sum)
import Data.AffineSpace
import Control.Applicative
import Music.Pitch.Literal
import Music.Dynamics.Literal
-- TODO move these to semigroups and music-pitch-literal
deriving instance Real a => Real (Sum a)
deriving instance Fractional a => Fractional (Sum a)
deriving instance AdditiveGroup a => AdditiveGroup (Sum a)
instance VectorSpace a => VectorSpace (Sum a) where
type Scalar (Sum a) = Scalar a
s *^ Sum v = Sum (s *^ v)
instance AffineSpace a => AffineSpace (Sum a) where
type Diff (Sum a) = Sum (Diff a)
Sum p .-. Sum q = Sum (p .-. q)
Sum p .+^ Sum v = Sum (p .+^ v)
deriving instance Real a => Real (Product a)
deriving instance Fractional a => Fractional (Product a)
deriving instance AdditiveGroup a => AdditiveGroup (Product a)
instance VectorSpace a => VectorSpace (Product a) where
type Scalar (Product a) = Scalar a
x *^ Product y = Product (x *^ y)
instance AffineSpace a => AffineSpace (Product a) where
type Diff (Product a) = Product (Diff a)
Product p .-. Product q = Product (p .-. q)
Product p .+^ Product v = Product (p .+^ v)
deriving instance IsDynamics a => IsDynamics (Sum a)
deriving instance IsDynamics a => IsDynamics (Product a)
deriving instance IsPitch a => IsPitch (Sum a)
deriving instance IsPitch a => IsPitch (Product a)
deriving instance Functor Product
instance Applicative Product where
pure = Product
Product f <*> Product x = Product (f x)
deriving instance Functor Sum
instance Applicative Sum where
pure = Sum
Sum f <*> Sum x = Sum (f x)
{-
deriving instance Floating a => Floating (Product a)
instance Num a => Num (Product a) where
fromInteger = pure . fromInteger
abs = fmap abs
signum = fmap signum
(+) = liftA2 (+)
(-) = liftA2 (-)
(*) = liftA2 (*)
instance Fractional a => Fractional (Product a) where
fromRational = pure . fromRational
(/) = liftA2 (/)
instance Real a => Real (Product a) where
toRational (Product x) = toRational x
-}
|
FranklinChen/music-score
|
src/Data/Semigroup/Instances.hs
|
bsd-3-clause
| 2,205 | 0 | 8 | 432 | 682 | 333 | 349 | 43 | 0 |
--------------------------------------------------------------------------------
{-# LANGUAGE OverloadedStrings, TupleSections #-}
--http://julien.jhome.fr/posts/2013-05-14-adding-toc-to-posts.html
module TableOfContents where
import Data.Monoid
import qualified Data.Set as S
import Hakyll
import Text.Pandoc.Options
import Control.Monad
import Data.List
compileTOCVersion = version "toc" $
compile $ pandocCompilerWith defaultHakyllReaderOptions
defaultHakyllWriterOptions {
writerTableOfContents = True
, writerTemplate = Just "$if(toc)$ $toc$ $endif$"
-- , writerStandalone = True
}
blankTOCCtx :: Context String
blankTOCCtx = constField "toc" ""
tocCtx :: Context String
tocCtx = field "toc" $ \item ->
loadBody ((itemIdentifier item) { identifierVersion = Just "toc"})
|
holdenlee/philosophocle
|
src/TableOfContents.hs
|
mit
| 1,038 | 0 | 11 | 343 | 144 | 82 | 62 | 18 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.SES.GetIdentityVerificationAttributes
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Given a list of identities (email addresses and\/or domains), returns
-- the verification status and (for domain identities) the verification
-- token for each identity.
--
-- This action is throttled at one request per second and can only get
-- verification attributes for up to 100 identities at a time.
--
-- /See:/ <http://docs.aws.amazon.com/ses/latest/APIReference/API_GetIdentityVerificationAttributes.html AWS API Reference> for GetIdentityVerificationAttributes.
module Network.AWS.SES.GetIdentityVerificationAttributes
(
-- * Creating a Request
getIdentityVerificationAttributes
, GetIdentityVerificationAttributes
-- * Request Lenses
, givaIdentities
-- * Destructuring the Response
, getIdentityVerificationAttributesResponse
, GetIdentityVerificationAttributesResponse
-- * Response Lenses
, givarsResponseStatus
, givarsVerificationAttributes
) where
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
import Network.AWS.SES.Types
import Network.AWS.SES.Types.Product
-- | Represents a request instructing the service to provide the verification
-- attributes for a list of identities.
--
-- /See:/ 'getIdentityVerificationAttributes' smart constructor.
newtype GetIdentityVerificationAttributes = GetIdentityVerificationAttributes'
{ _givaIdentities :: [Text]
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'GetIdentityVerificationAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'givaIdentities'
getIdentityVerificationAttributes
:: GetIdentityVerificationAttributes
getIdentityVerificationAttributes =
GetIdentityVerificationAttributes'
{ _givaIdentities = mempty
}
-- | A list of identities.
givaIdentities :: Lens' GetIdentityVerificationAttributes [Text]
givaIdentities = lens _givaIdentities (\ s a -> s{_givaIdentities = a}) . _Coerce;
instance AWSRequest GetIdentityVerificationAttributes
where
type Rs GetIdentityVerificationAttributes =
GetIdentityVerificationAttributesResponse
request = postQuery sES
response
= receiveXMLWrapper
"GetIdentityVerificationAttributesResult"
(\ s h x ->
GetIdentityVerificationAttributesResponse' <$>
(pure (fromEnum s)) <*>
(x .@? "VerificationAttributes" .!@ mempty >>=
parseXMLMap "entry" "key" "value"))
instance ToHeaders GetIdentityVerificationAttributes
where
toHeaders = const mempty
instance ToPath GetIdentityVerificationAttributes
where
toPath = const "/"
instance ToQuery GetIdentityVerificationAttributes
where
toQuery GetIdentityVerificationAttributes'{..}
= mconcat
["Action" =:
("GetIdentityVerificationAttributes" :: ByteString),
"Version" =: ("2010-12-01" :: ByteString),
"Identities" =: toQueryList "member" _givaIdentities]
-- | Represents the verification attributes for a list of identities.
--
-- /See:/ 'getIdentityVerificationAttributesResponse' smart constructor.
data GetIdentityVerificationAttributesResponse = GetIdentityVerificationAttributesResponse'
{ _givarsResponseStatus :: !Int
, _givarsVerificationAttributes :: !(Map Text IdentityVerificationAttributes)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'GetIdentityVerificationAttributesResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'givarsResponseStatus'
--
-- * 'givarsVerificationAttributes'
getIdentityVerificationAttributesResponse
:: Int -- ^ 'givarsResponseStatus'
-> GetIdentityVerificationAttributesResponse
getIdentityVerificationAttributesResponse pResponseStatus_ =
GetIdentityVerificationAttributesResponse'
{ _givarsResponseStatus = pResponseStatus_
, _givarsVerificationAttributes = mempty
}
-- | The response status code.
givarsResponseStatus :: Lens' GetIdentityVerificationAttributesResponse Int
givarsResponseStatus = lens _givarsResponseStatus (\ s a -> s{_givarsResponseStatus = a});
-- | A map of Identities to IdentityVerificationAttributes objects.
givarsVerificationAttributes :: Lens' GetIdentityVerificationAttributesResponse (HashMap Text IdentityVerificationAttributes)
givarsVerificationAttributes = lens _givarsVerificationAttributes (\ s a -> s{_givarsVerificationAttributes = a}) . _Map;
|
fmapfmapfmap/amazonka
|
amazonka-ses/gen/Network/AWS/SES/GetIdentityVerificationAttributes.hs
|
mpl-2.0
| 5,402 | 0 | 14 | 1,019 | 586 | 353 | 233 | 74 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.StorageGateway.ListGateways
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | This operation lists gateways owned by an AWS account in a region specified
-- in the request. The returned list is ordered by gateway Amazon Resource Name
-- (ARN).
--
-- By default, the operation returns a maximum of 100 gateways. This operation
-- supports pagination that allows you to optionally reduce the number of
-- gateways returned in a response.
--
-- If you have more gateways than are returned in a response-that is, the
-- response returns only a truncated list of your gateways-the response contains
-- a marker that you can specify in your next request to fetch the next page of
-- gateways.
--
-- <http://docs.aws.amazon.com/storagegateway/latest/APIReference/API_ListGateways.html>
module Network.AWS.StorageGateway.ListGateways
(
-- * Request
ListGateways
-- ** Request constructor
, listGateways
-- ** Request lenses
, lgLimit
, lgMarker
-- * Response
, ListGatewaysResponse
-- ** Response constructor
, listGatewaysResponse
-- ** Response lenses
, lgrGateways
, lgrMarker
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.StorageGateway.Types
import qualified GHC.Exts
data ListGateways = ListGateways
{ _lgLimit :: Maybe Nat
, _lgMarker :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'ListGateways' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'lgLimit' @::@ 'Maybe' 'Natural'
--
-- * 'lgMarker' @::@ 'Maybe' 'Text'
--
listGateways :: ListGateways
listGateways = ListGateways
{ _lgMarker = Nothing
, _lgLimit = Nothing
}
-- | Specifies that the list of gateways returned be limited to the specified
-- number of items.
lgLimit :: Lens' ListGateways (Maybe Natural)
lgLimit = lens _lgLimit (\s a -> s { _lgLimit = a }) . mapping _Nat
-- | An opaque string that indicates the position at which to begin the returned
-- list of gateways.
lgMarker :: Lens' ListGateways (Maybe Text)
lgMarker = lens _lgMarker (\s a -> s { _lgMarker = a })
data ListGatewaysResponse = ListGatewaysResponse
{ _lgrGateways :: List "Gateways" GatewayInfo
, _lgrMarker :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'ListGatewaysResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'lgrGateways' @::@ ['GatewayInfo']
--
-- * 'lgrMarker' @::@ 'Maybe' 'Text'
--
listGatewaysResponse :: ListGatewaysResponse
listGatewaysResponse = ListGatewaysResponse
{ _lgrGateways = mempty
, _lgrMarker = Nothing
}
lgrGateways :: Lens' ListGatewaysResponse [GatewayInfo]
lgrGateways = lens _lgrGateways (\s a -> s { _lgrGateways = a }) . _List
lgrMarker :: Lens' ListGatewaysResponse (Maybe Text)
lgrMarker = lens _lgrMarker (\s a -> s { _lgrMarker = a })
instance ToPath ListGateways where
toPath = const "/"
instance ToQuery ListGateways where
toQuery = const mempty
instance ToHeaders ListGateways
instance ToJSON ListGateways where
toJSON ListGateways{..} = object
[ "Marker" .= _lgMarker
, "Limit" .= _lgLimit
]
instance AWSRequest ListGateways where
type Sv ListGateways = StorageGateway
type Rs ListGateways = ListGatewaysResponse
request = post "ListGateways"
response = jsonResponse
instance FromJSON ListGatewaysResponse where
parseJSON = withObject "ListGatewaysResponse" $ \o -> ListGatewaysResponse
<$> o .:? "Gateways" .!= mempty
<*> o .:? "Marker"
instance AWSPager ListGateways where
page rq rs
| stop (rs ^. lgrMarker) = Nothing
| otherwise = (\x -> rq & lgMarker ?~ x)
<$> (rs ^. lgrMarker)
|
romanb/amazonka
|
amazonka-storagegateway/gen/Network/AWS/StorageGateway/ListGateways.hs
|
mpl-2.0
| 4,730 | 0 | 12 | 1,045 | 686 | 406 | 280 | 72 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ViewPatterns #-}
-- | Build the project.
module Stack.Build
(build
,withLoadPackage
,mkBaseConfigOpts
,queryBuildInfo)
where
import Control.Monad
import Control.Monad.Catch (MonadCatch, MonadMask)
import Control.Monad.IO.Class
import Control.Monad.Logger
import Control.Monad.Reader (MonadReader, asks)
import Control.Monad.Trans.Resource
import Data.Aeson (Value (Object, Array), (.=), object)
import Data.Function
import qualified Data.HashMap.Strict as HM
import Data.IORef.RunOnce (runOnce)
import Data.List ((\\))
import Data.List.Extra (groupSort)
import Data.List.NonEmpty (NonEmpty(..))
import qualified Data.List.NonEmpty as NE
import qualified Data.Map as Map
import Data.Map.Strict (Map)
import Data.Monoid
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding (decodeUtf8)
import qualified Data.Text.IO as TIO
import Data.Text.Read (decimal)
import qualified Data.Vector as V
import qualified Data.Yaml as Yaml
import Network.HTTP.Client.Conduit (HasHttpManager)
import Path
import Prelude hiding (FilePath, writeFile)
import Stack.Build.ConstructPlan
import Stack.Build.Execute
import Stack.Build.Haddock
import Stack.Build.Installed
import Stack.Build.Source
import Stack.Build.Target
import Stack.Fetch as Fetch
import Stack.GhcPkg
import Stack.Package
import Stack.Types
import Stack.Types.Internal
import System.FileLock (FileLock, unlockFile)
#ifdef WINDOWS
import System.Win32.Console (setConsoleCP, setConsoleOutputCP, getConsoleCP, getConsoleOutputCP)
import qualified Control.Monad.Catch as Catch
#endif
type M env m = (MonadIO m,MonadReader env m,HasHttpManager env,HasBuildConfig env,MonadLogger m,MonadBaseControl IO m,MonadCatch m,MonadMask m,HasLogLevel env,HasEnvConfig env,HasTerminal env)
-- | Build.
--
-- If a buildLock is passed there is an important contract here. That lock must
-- protect the snapshot, and it must be safe to unlock it if there are no further
-- modifications to the snapshot to be performed by this build.
build :: M env m
=> (Set (Path Abs File) -> IO ()) -- ^ callback after discovering all local files
-> Maybe FileLock
-> BuildOpts
-> m ()
build setLocalFiles mbuildLk bopts = fixCodePage' $ do
menv <- getMinimalEnvOverride
(_, mbp, locals, extraToBuild, sourceMap) <- loadSourceMap NeedTargets bopts
-- Set local files, necessary for file watching
stackYaml <- asks $ bcStackYaml . getBuildConfig
liftIO $ setLocalFiles
$ Set.insert stackYaml
$ Set.unions
$ map lpFiles locals
(installedMap, globalDumpPkgs, snapshotDumpPkgs, localDumpPkgs) <-
getInstalled menv
GetInstalledOpts
{ getInstalledProfiling = profiling
, getInstalledHaddock = shouldHaddockDeps bopts }
sourceMap
baseConfigOpts <- mkBaseConfigOpts bopts
plan <- withLoadPackage menv $ \loadPackage ->
constructPlan mbp baseConfigOpts locals extraToBuild localDumpPkgs loadPackage sourceMap installedMap
-- If our work to do is all local, let someone else have a turn with the snapshot.
-- They won't damage what's already in there.
case (mbuildLk, allLocal plan) of
-- NOTE: This policy is too conservative. In the future we should be able to
-- schedule unlocking as an Action that happens after all non-local actions are
-- complete.
(Just lk,True) -> do $logDebug "All installs are local; releasing snapshot lock early."
liftIO $ unlockFile lk
_ -> return ()
warnIfExecutablesWithSameNameCouldBeOverwritten locals plan
when (boptsPreFetch bopts) $
preFetch plan
if boptsDryrun bopts
then printPlan plan
else executePlan menv bopts baseConfigOpts locals
globalDumpPkgs
snapshotDumpPkgs
localDumpPkgs
installedMap
plan
where
profiling = boptsLibProfile bopts || boptsExeProfile bopts
-- | If all the tasks are local, they don't mutate anything outside of our local directory.
allLocal :: Plan -> Bool
allLocal =
all (== Local) .
map taskLocation .
Map.elems .
planTasks
-- | See https://github.com/commercialhaskell/stack/issues/1198.
warnIfExecutablesWithSameNameCouldBeOverwritten
:: MonadLogger m => [LocalPackage] -> Plan -> m ()
warnIfExecutablesWithSameNameCouldBeOverwritten locals plan =
forM_ (Map.toList warnings) $ \(exe,(toBuild,otherLocals)) -> do
let exe_s
| length toBuild > 1 = "several executables with the same name:"
| otherwise = "executable"
exesText pkgs =
T.intercalate
", "
["'" <> packageNameText p <> ":" <> exe <> "'" | p <- pkgs]
($logWarn . T.unlines . concat)
[ [ "Building " <> exe_s <> " " <> exesText toBuild <> "." ]
, [ "Only one of them will be available via 'stack exec' or locally installed."
| length toBuild > 1
]
, [ "Other executables with the same name might be overwritten: " <>
exesText otherLocals <> "."
| not (null otherLocals)
]
]
where
-- Cases of several local packages having executables with the same name.
-- The Map entries have the following form:
--
-- executable name: ( package names for executables that are being built
-- , package names for other local packages that have an
-- executable with the same name
-- )
warnings :: Map Text ([PackageName],[PackageName])
warnings =
Map.mapMaybe
(\(pkgsToBuild,localPkgs) ->
case (pkgsToBuild,NE.toList localPkgs \\ NE.toList pkgsToBuild) of
(_ :| [],[]) ->
-- We want to build the executable of single local package
-- and there are no other local packages with an executable of
-- the same name. Nothing to warn about, ignore.
Nothing
(_,otherLocals) ->
-- We could be here for two reasons (or their combination):
-- 1) We are building two or more executables with the same
-- name that will end up overwriting each other.
-- 2) In addition to the executable(s) that we want to build
-- there are other local packages with an executable of the
-- same name that might get overwritten.
-- Both cases warrant a warning.
Just (NE.toList pkgsToBuild,otherLocals))
(Map.intersectionWith (,) exesToBuild localExes)
exesToBuild :: Map Text (NonEmpty PackageName)
exesToBuild =
collect
[ (exe,pkgName)
| (pkgName,task) <- Map.toList (planTasks plan)
, isLocal task
, exe <- (Set.toList . exeComponents . lpComponents . taskLP) task
]
where
isLocal Task{taskType = (TTLocal _)} = True
isLocal _ = False
taskLP Task{taskType = (TTLocal lp)} = lp
taskLP _ = error "warnIfExecutablesWithSameNameCouldBeOverwritten/taskLP: task isn't local"
localExes :: Map Text (NonEmpty PackageName)
localExes =
collect
[ (exe,packageName pkg)
| pkg <- map lpPackage locals
, exe <- Set.toList (packageExes pkg)
]
collect :: Ord k => [(k,v)] -> Map k (NonEmpty v)
collect = Map.map NE.fromList . Map.fromDistinctAscList . groupSort
-- | Get the @BaseConfigOpts@ necessary for constructing configure options
mkBaseConfigOpts :: (MonadIO m, MonadReader env m, HasEnvConfig env, MonadThrow m)
=> BuildOpts -> m BaseConfigOpts
mkBaseConfigOpts bopts = do
snapDBPath <- packageDatabaseDeps
localDBPath <- packageDatabaseLocal
snapInstallRoot <- installationRootDeps
localInstallRoot <- installationRootLocal
packageExtraDBs <- packageDatabaseExtra
return BaseConfigOpts
{ bcoSnapDB = snapDBPath
, bcoLocalDB = localDBPath
, bcoSnapInstallRoot = snapInstallRoot
, bcoLocalInstallRoot = localInstallRoot
, bcoBuildOpts = bopts
, bcoExtraDBs = packageExtraDBs
}
-- | Provide a function for loading package information from the package index
withLoadPackage :: ( MonadIO m
, HasHttpManager env
, MonadReader env m
, MonadBaseControl IO m
, MonadCatch m
, MonadLogger m
, HasEnvConfig env)
=> EnvOverride
-> ((PackageName -> Version -> Map FlagName Bool -> IO Package) -> m a)
-> m a
withLoadPackage menv inner = do
econfig <- asks getEnvConfig
withCabalLoader' <- runOnce $ withCabalLoader menv $ \cabalLoader ->
inner $ \name version flags -> do
bs <- cabalLoader $ PackageIdentifier name version -- TODO automatically update index the first time this fails
-- Intentionally ignore warnings, as it's not really
-- appropriate to print a bunch of warnings out while
-- resolving the package index.
(_warnings,pkg) <- readPackageBS (depPackageConfig econfig flags) bs
return pkg
withCabalLoader'
where
-- | Package config to be used for dependencies
depPackageConfig :: EnvConfig -> Map FlagName Bool -> PackageConfig
depPackageConfig econfig flags = PackageConfig
{ packageConfigEnableTests = False
, packageConfigEnableBenchmarks = False
, packageConfigFlags = flags
, packageConfigCompilerVersion = envConfigCompilerVersion econfig
, packageConfigPlatform = configPlatform (getConfig econfig)
}
-- | Set the code page for this process as necessary. Only applies to Windows.
-- See: https://github.com/commercialhaskell/stack/issues/738
fixCodePage :: (MonadIO m, MonadMask m, MonadLogger m) => m a -> m a
#ifdef WINDOWS
fixCodePage inner = do
origCPI <- liftIO getConsoleCP
origCPO <- liftIO getConsoleOutputCP
let setInput = origCPI /= expected
setOutput = origCPO /= expected
fixInput
| setInput = Catch.bracket_
(liftIO $ do
setConsoleCP expected)
(liftIO $ setConsoleCP origCPI)
| otherwise = id
fixOutput
| setInput = Catch.bracket_
(liftIO $ do
setConsoleOutputCP expected)
(liftIO $ setConsoleOutputCP origCPO)
| otherwise = id
case (setInput, setOutput) of
(False, False) -> return ()
(True, True) -> warn ""
(True, False) -> warn " input"
(False, True) -> warn " output"
fixInput $ fixOutput inner
where
expected = 65001 -- UTF-8
warn typ = $logInfo $ T.concat
[ "Setting"
, typ
, " codepage to UTF-8 (65001) to ensure correct output from GHC"
]
#else
fixCodePage = id
#endif
fixCodePage' :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env)
=> m a
-> m a
fixCodePage' inner = do
mcp <- asks $ configModifyCodePage . getConfig
if mcp
then fixCodePage inner
else inner
-- | Query information about the build and print the result to stdout in YAML format.
queryBuildInfo :: M env m
=> [Text] -- ^ selectors
-> m ()
queryBuildInfo selectors0 =
rawBuildInfo
>>= select id selectors0
>>= liftIO . TIO.putStrLn . decodeUtf8 . Yaml.encode
where
select _ [] value = return value
select front (sel:sels) value =
case value of
Object o ->
case HM.lookup sel o of
Nothing -> err "Selector not found"
Just value' -> cont value'
Array v ->
case decimal sel of
Right (i, "")
| i >= 0 && i < V.length v -> cont $ v V.! i
| otherwise -> err "Index out of range"
_ -> err "Encountered array and needed numeric selector"
_ -> err $ "Cannot apply selector to " ++ show value
where
cont = select (front . (sel:)) sels
err msg = error $ msg ++ ": " ++ show (front [sel])
-- | Get the raw build information object
rawBuildInfo :: M env m => m Value
rawBuildInfo = do
(_, _mbp, locals, _extraToBuild, _sourceMap) <- loadSourceMap NeedTargets defaultBuildOpts
return $ object
[ "locals" .= Object (HM.fromList $ map localToPair locals)
]
where
localToPair lp =
(T.pack $ packageNameString $ packageName p, value)
where
p = lpPackage lp
value = object
[ "version" .= packageVersion p
, "path" .= toFilePath (lpDir lp)
]
|
rubik/stack
|
src/Stack/Build.hs
|
bsd-3-clause
| 13,959 | 0 | 18 | 4,466 | 2,883 | 1,540 | 1,343 | 232 | 6 |
{-|
Module : Data.STM.Bag.Internal.ListBag
Description : STM-based Concurrent Bag data structure implementation
Copyright : (c) Alex Semin, 2015
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : portable
Implementation of the 'Data.STM.Bag.Class' using coarse-grained list.
It is efficient only if there are not many threads.
-}
module Data.STM.Bag.Internal.ListBag(
ListBag
) where
import Control.Concurrent.STM
import Data.STM.Bag.Class
data ListBag v = B (TVar [v]) -- stack behavior
bNew :: STM (ListBag v)
bNew = B `fmap` newTVar []
bAdd :: ListBag v -> v -> STM ()
bAdd (B b') v = readTVar b' >>= return . (v:) >>= writeTVar b'
bTake :: ListBag v -> STM v
bTake (B b') = do
b <- readTVar b'
case b of
[] -> retry
(v:vs) -> writeTVar b' vs >> return v
bIsEmpty :: ListBag v -> STM Bool
bIsEmpty (B b') = do
b <- readTVar b'
case b of
[] -> return True
_ -> return False
instance Bag ListBag where
new = bNew
add = bAdd
take = bTake
isEmpty = bIsEmpty
|
Alllex/stm-data-collection
|
src/Data/STM/Bag/Internal/ListBag.hs
|
bsd-3-clause
| 1,089 | 0 | 11 | 267 | 310 | 160 | 150 | 26 | 2 |
{-# LANGUAGE Haskell98 #-}
{-# LINE 1 "Data/Text/Internal/Fusion/Types.hs" #-}
{-# LANGUAGE BangPatterns, ExistentialQuantification #-}
-- |
-- Module : Data.Text.Internal.Fusion.Types
-- Copyright : (c) Tom Harper 2008-2009,
-- (c) Bryan O'Sullivan 2009,
-- (c) Duncan Coutts 2009,
-- (c) Jasper Van der Jeugt 2011
--
-- License : BSD-style
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : GHC
--
-- /Warning/: this is an internal module, and does not have a stable
-- API or name. Functions in this module may not check or enforce
-- preconditions expected by public modules. Use at your own risk!
--
-- Core stream fusion functionality for text.
module Data.Text.Internal.Fusion.Types
(
CC(..)
, PairS(..)
, Scan(..)
, RS(..)
, Step(..)
, Stream(..)
, empty
) where
import Data.Text.Internal.Fusion.Size
import Data.Word (Word8)
-- | Specialised tuple for case conversion.
data CC s = CC !s {-# UNPACK #-} !Char {-# UNPACK #-} !Char
-- | Restreaming state.
data RS s
= RS0 !s
| RS1 !s {-# UNPACK #-} !Word8
| RS2 !s {-# UNPACK #-} !Word8 {-# UNPACK #-} !Word8
| RS3 !s {-# UNPACK #-} !Word8 {-# UNPACK #-} !Word8 {-# UNPACK #-} !Word8
-- | Strict pair.
data PairS a b = !a :*: !b
-- deriving (Eq, Ord, Show)
infixl 2 :*:
-- | An intermediate result in a scan.
data Scan s = Scan1 {-# UNPACK #-} !Char !s
| Scan2 {-# UNPACK #-} !Char !s
-- | Intermediate result in a processing pipeline.
data Step s a = Done
| Skip !s
| Yield !a !s
{-
instance (Show a) => Show (Step s a)
where show Done = "Done"
show (Skip _) = "Skip"
show (Yield x _) = "Yield " ++ show x
-}
instance (Eq a) => Eq (Stream a) where
(==) = eq
instance (Ord a) => Ord (Stream a) where
compare = cmp
-- The length hint in a Stream has two roles. If its value is zero,
-- we trust it, and treat the stream as empty. Otherwise, we treat it
-- as a hint: it should usually be accurate, so we use it when
-- unstreaming to decide what size array to allocate. However, the
-- unstreaming functions must be able to cope with the hint being too
-- small or too large.
--
-- The size hint tries to track the UTF-16 code points in a stream,
-- but often counts the number of characters instead. It can easily
-- undercount if, for instance, a transformed stream contains astral
-- plane characters (those above 0x10000).
data Stream a =
forall s. Stream
(s -> Step s a) -- stepper function
!s -- current state
!Size -- size hint
-- | /O(n)/ Determines if two streams are equal.
eq :: (Eq a) => Stream a -> Stream a -> Bool
eq (Stream next1 s1 _) (Stream next2 s2 _) = loop (next1 s1) (next2 s2)
where
loop Done Done = True
loop (Skip s1') (Skip s2') = loop (next1 s1') (next2 s2')
loop (Skip s1') x2 = loop (next1 s1') x2
loop x1 (Skip s2') = loop x1 (next2 s2')
loop Done _ = False
loop _ Done = False
loop (Yield x1 s1') (Yield x2 s2') = x1 == x2 &&
loop (next1 s1') (next2 s2')
{-# INLINE [0] eq #-}
cmp :: (Ord a) => Stream a -> Stream a -> Ordering
cmp (Stream next1 s1 _) (Stream next2 s2 _) = loop (next1 s1) (next2 s2)
where
loop Done Done = EQ
loop (Skip s1') (Skip s2') = loop (next1 s1') (next2 s2')
loop (Skip s1') x2 = loop (next1 s1') x2
loop x1 (Skip s2') = loop x1 (next2 s2')
loop Done _ = LT
loop _ Done = GT
loop (Yield x1 s1') (Yield x2 s2') =
case compare x1 x2 of
EQ -> loop (next1 s1') (next2 s2')
other -> other
{-# INLINE [0] cmp #-}
-- | The empty stream.
empty :: Stream a
empty = Stream next () 0
where next _ = Done
{-# INLINE [0] empty #-}
|
phischu/fragnix
|
tests/packages/scotty/Data.Text.Internal.Fusion.Types.hs
|
bsd-3-clause
| 4,169 | 0 | 12 | 1,387 | 898 | 489 | 409 | 92 | 8 |
{- scheduled activities
-
- Copyright 2013-2014 Joey Hess <[email protected]>
-
- License: BSD-2-clause
-}
module Utility.Scheduled (
Schedule(..),
Recurrance(..),
ScheduledTime(..),
NextTime(..),
WeekDay,
MonthDay,
YearDay,
nextTime,
calcNextTime,
startTime,
fromSchedule,
fromScheduledTime,
toScheduledTime,
fromRecurrance,
toRecurrance,
toSchedule,
parseSchedule,
prop_schedule_roundtrips,
prop_past_sane,
) where
import Utility.Data
import Utility.QuickCheck
import Utility.PartialPrelude
import Utility.Misc
import Control.Applicative
import Data.List
import Data.Time.Clock
import Data.Time.LocalTime
import Data.Time.Calendar
import Data.Time.Calendar.WeekDate
import Data.Time.Calendar.OrdinalDate
import Data.Tuple.Utils
import Data.Char
{- Some sort of scheduled event. -}
data Schedule = Schedule Recurrance ScheduledTime
deriving (Eq, Read, Show, Ord)
data Recurrance
= Daily
| Weekly (Maybe WeekDay)
| Monthly (Maybe MonthDay)
| Yearly (Maybe YearDay)
| Divisible Int Recurrance
-- ^ Days, Weeks, or Months of the year evenly divisible by a number.
-- (Divisible Year is years evenly divisible by a number.)
deriving (Eq, Read, Show, Ord)
type WeekDay = Int
type MonthDay = Int
type YearDay = Int
data ScheduledTime
= AnyTime
| SpecificTime Hour Minute
deriving (Eq, Read, Show, Ord)
type Hour = Int
type Minute = Int
-- | Next time a Schedule should take effect. The NextTimeWindow is used
-- when a Schedule is allowed to start at some point within the window.
data NextTime
= NextTimeExactly LocalTime
| NextTimeWindow LocalTime LocalTime
deriving (Eq, Read, Show)
startTime :: NextTime -> LocalTime
startTime (NextTimeExactly t) = t
startTime (NextTimeWindow t _) = t
nextTime :: Schedule -> Maybe LocalTime -> IO (Maybe NextTime)
nextTime schedule lasttime = do
now <- getCurrentTime
tz <- getTimeZone now
return $ calcNextTime schedule lasttime $ utcToLocalTime tz now
-- | Calculate the next time that fits a Schedule, based on the
-- last time it occurred, and the current time.
calcNextTime :: Schedule -> Maybe LocalTime -> LocalTime -> Maybe NextTime
calcNextTime schedule@(Schedule recurrance scheduledtime) lasttime currenttime
| scheduledtime == AnyTime = do
next <- findfromtoday True
return $ case next of
NextTimeWindow _ _ -> next
NextTimeExactly t -> window (localDay t) (localDay t)
| otherwise = NextTimeExactly . startTime <$> findfromtoday False
where
findfromtoday anytime = findfrom recurrance afterday today
where
today = localDay currenttime
afterday = sameaslastrun || toolatetoday
toolatetoday = not anytime && localTimeOfDay currenttime >= nexttime
sameaslastrun = lastrun == Just today
lastrun = localDay <$> lasttime
nexttime = case scheduledtime of
AnyTime -> TimeOfDay 0 0 0
SpecificTime h m -> TimeOfDay h m 0
exactly d = NextTimeExactly $ LocalTime d nexttime
window startd endd = NextTimeWindow
(LocalTime startd nexttime)
(LocalTime endd (TimeOfDay 23 59 0))
findfrom r afterday candidate
| ynum candidate > (ynum (localDay currenttime)) + 100 =
-- avoid possible infinite recusion
error $ "bug: calcNextTime did not find a time within 100 years to run " ++
show (schedule, lasttime, currenttime)
| otherwise = findfromChecked r afterday candidate
findfromChecked r afterday candidate = case r of
Daily
| afterday -> Just $ exactly $ addDays 1 candidate
| otherwise -> Just $ exactly candidate
Weekly Nothing
| afterday -> skip 1
| otherwise -> case (wday <$> lastrun, wday candidate) of
(Nothing, _) -> Just $ window candidate (addDays 6 candidate)
(Just old, curr)
| old == curr -> Just $ window candidate (addDays 6 candidate)
| otherwise -> skip 1
Monthly Nothing
| afterday -> skip 1
| maybe True (candidate `oneMonthPast`) lastrun ->
Just $ window candidate (endOfMonth candidate)
| otherwise -> skip 1
Yearly Nothing
| afterday -> skip 1
| maybe True (candidate `oneYearPast`) lastrun ->
Just $ window candidate (endOfYear candidate)
| otherwise -> skip 1
Weekly (Just w)
| w < 0 || w > maxwday -> Nothing
| w == wday candidate -> if afterday
then Just $ exactly $ addDays 7 candidate
else Just $ exactly candidate
| otherwise -> Just $ exactly $
addDays (fromIntegral $ (w - wday candidate) `mod` 7) candidate
Monthly (Just m)
| m < 0 || m > maxmday -> Nothing
-- TODO can be done more efficiently than recursing
| m == mday candidate -> if afterday
then skip 1
else Just $ exactly candidate
| otherwise -> skip 1
Yearly (Just y)
| y < 0 || y > maxyday -> Nothing
| y == yday candidate -> if afterday
then skip 365
else Just $ exactly candidate
| otherwise -> skip 1
Divisible n r'@Daily -> handlediv n r' yday (Just maxyday)
Divisible n r'@(Weekly _) -> handlediv n r' wnum (Just maxwnum)
Divisible n r'@(Monthly _) -> handlediv n r' mnum (Just maxmnum)
Divisible n r'@(Yearly _) -> handlediv n r' ynum Nothing
Divisible _ r'@(Divisible _ _) -> findfrom r' afterday candidate
where
skip n = findfrom r False (addDays n candidate)
handlediv n r' getval mmax
| n > 0 && maybe True (n <=) mmax =
findfromwhere r' (divisible n . getval) afterday candidate
| otherwise = Nothing
findfromwhere r p afterday candidate
| maybe True (p . getday) next = next
| otherwise = maybe Nothing (findfromwhere r p True . getday) next
where
next = findfrom r afterday candidate
getday = localDay . startTime
divisible n v = v `rem` n == 0
-- Check if the new Day occurs one month or more past the old Day.
oneMonthPast :: Day -> Day -> Bool
new `oneMonthPast` old = fromGregorian y (m+1) d <= new
where
(y,m,d) = toGregorian old
-- Check if the new Day occurs one year or more past the old Day.
oneYearPast :: Day -> Day -> Bool
new `oneYearPast` old = fromGregorian (y+1) m d <= new
where
(y,m,d) = toGregorian old
endOfMonth :: Day -> Day
endOfMonth day =
let (y,m,_d) = toGregorian day
in fromGregorian y m (gregorianMonthLength y m)
endOfYear :: Day -> Day
endOfYear day =
let (y,_m,_d) = toGregorian day
in endOfMonth (fromGregorian y maxmnum 1)
-- extracting various quantities from a Day
wday :: Day -> Int
wday = thd3 . toWeekDate
wnum :: Day -> Int
wnum = snd3 . toWeekDate
mday :: Day -> Int
mday = thd3 . toGregorian
mnum :: Day -> Int
mnum = snd3 . toGregorian
yday :: Day -> Int
yday = snd . toOrdinalDate
ynum :: Day -> Int
ynum = fromIntegral . fst . toOrdinalDate
-- Calendar max values.
maxyday :: Int
maxyday = 366 -- with leap days
maxwnum :: Int
maxwnum = 53 -- some years have more than 52
maxmday :: Int
maxmday = 31
maxmnum :: Int
maxmnum = 12
maxwday :: Int
maxwday = 7
fromRecurrance :: Recurrance -> String
fromRecurrance (Divisible n r) =
fromRecurrance' (++ "s divisible by " ++ show n) r
fromRecurrance r = fromRecurrance' ("every " ++) r
fromRecurrance' :: (String -> String) -> Recurrance -> String
fromRecurrance' a Daily = a "day"
fromRecurrance' a (Weekly n) = onday n (a "week")
fromRecurrance' a (Monthly n) = onday n (a "month")
fromRecurrance' a (Yearly n) = onday n (a "year")
fromRecurrance' a (Divisible _n r) = fromRecurrance' a r -- not used
onday :: Maybe Int -> String -> String
onday (Just n) s = "on day " ++ show n ++ " of " ++ s
onday Nothing s = s
toRecurrance :: String -> Maybe Recurrance
toRecurrance s = case words s of
("every":"day":[]) -> Just Daily
("on":"day":sd:"of":"every":something:[]) -> withday sd something
("every":something:[]) -> noday something
("days":"divisible":"by":sn:[]) ->
Divisible <$> getdivisor sn <*> pure Daily
("on":"day":sd:"of":something:"divisible":"by":sn:[]) ->
Divisible
<$> getdivisor sn
<*> withday sd something
("every":something:"divisible":"by":sn:[]) ->
Divisible
<$> getdivisor sn
<*> noday something
(something:"divisible":"by":sn:[]) ->
Divisible
<$> getdivisor sn
<*> noday something
_ -> Nothing
where
constructor "week" = Just Weekly
constructor "month" = Just Monthly
constructor "year" = Just Yearly
constructor u
| "s" `isSuffixOf` u = constructor $ reverse $ drop 1 $ reverse u
| otherwise = Nothing
withday sd u = do
c <- constructor u
d <- readish sd
Just $ c (Just d)
noday u = do
c <- constructor u
Just $ c Nothing
getdivisor sn = do
n <- readish sn
if n > 0
then Just n
else Nothing
fromScheduledTime :: ScheduledTime -> String
fromScheduledTime AnyTime = "any time"
fromScheduledTime (SpecificTime h m) =
show h' ++ (if m > 0 then ":" ++ pad 2 (show m) else "") ++ " " ++ ampm
where
pad n s = take (n - length s) (repeat '0') ++ s
(h', ampm)
| h == 0 = (12, "AM")
| h < 12 = (h, "AM")
| h == 12 = (h, "PM")
| otherwise = (h - 12, "PM")
toScheduledTime :: String -> Maybe ScheduledTime
toScheduledTime "any time" = Just AnyTime
toScheduledTime v = case words v of
(s:ampm:[])
| map toUpper ampm == "AM" ->
go s h0
| map toUpper ampm == "PM" ->
go s (\h -> (h0 h) + 12)
| otherwise -> Nothing
(s:[]) -> go s id
_ -> Nothing
where
h0 h
| h == 12 = 0
| otherwise = h
go :: String -> (Int -> Int) -> Maybe ScheduledTime
go s adjust =
let (h, m) = separate (== ':') s
in SpecificTime
<$> (adjust <$> readish h)
<*> if null m then Just 0 else readish m
fromSchedule :: Schedule -> String
fromSchedule (Schedule recurrance scheduledtime) = unwords
[ fromRecurrance recurrance
, "at"
, fromScheduledTime scheduledtime
]
toSchedule :: String -> Maybe Schedule
toSchedule = eitherToMaybe . parseSchedule
parseSchedule :: String -> Either String Schedule
parseSchedule s = do
r <- maybe (Left $ "bad recurrance: " ++ recurrance) Right
(toRecurrance recurrance)
t <- maybe (Left $ "bad time of day: " ++ scheduledtime) Right
(toScheduledTime scheduledtime)
Right $ Schedule r t
where
(rws, tws) = separate (== "at") (words s)
recurrance = unwords rws
scheduledtime = unwords tws
instance Arbitrary Schedule where
arbitrary = Schedule <$> arbitrary <*> arbitrary
instance Arbitrary ScheduledTime where
arbitrary = oneof
[ pure AnyTime
, SpecificTime
<$> choose (0, 23)
<*> choose (1, 59)
]
instance Arbitrary Recurrance where
arbitrary = oneof
[ pure Daily
, Weekly <$> arbday
, Monthly <$> arbday
, Yearly <$> arbday
, Divisible
<$> positive arbitrary
<*> oneof -- no nested Divisibles
[ pure Daily
, Weekly <$> arbday
, Monthly <$> arbday
, Yearly <$> arbday
]
]
where
arbday = oneof
[ Just <$> nonNegative arbitrary
, pure Nothing
]
prop_schedule_roundtrips :: Schedule -> Bool
prop_schedule_roundtrips s = toSchedule (fromSchedule s) == Just s
prop_past_sane :: Bool
prop_past_sane = and
[ all (checksout oneMonthPast) (mplus1 ++ yplus1)
, all (not . (checksout oneMonthPast)) (map swap (mplus1 ++ yplus1))
, all (checksout oneYearPast) yplus1
, all (not . (checksout oneYearPast)) (map swap yplus1)
]
where
mplus1 = -- new date old date, 1+ months before it
[ (fromGregorian 2014 01 15, fromGregorian 2013 12 15)
, (fromGregorian 2014 01 15, fromGregorian 2013 02 15)
, (fromGregorian 2014 02 15, fromGregorian 2013 01 15)
, (fromGregorian 2014 03 01, fromGregorian 2013 01 15)
, (fromGregorian 2014 03 01, fromGregorian 2013 12 15)
, (fromGregorian 2015 01 01, fromGregorian 2010 01 01)
]
yplus1 = -- new date old date, 1+ years before it
[ (fromGregorian 2014 01 15, fromGregorian 2012 01 16)
, (fromGregorian 2014 01 15, fromGregorian 2013 01 14)
, (fromGregorian 2022 12 31, fromGregorian 2000 01 01)
]
checksout cmp (new, old) = new `cmp` old
swap (a,b) = (b,a)
|
avengerpenguin/propellor
|
src/Utility/Scheduled.hs
|
bsd-2-clause
| 11,685 | 142 | 18 | 2,451 | 4,379 | 2,218 | 2,161 | 324 | 18 |
module A (caf, c_two) where
import Debug.Trace (trace)
data C = C Int Int
caf :: C
caf = C 3 (trace "value forced" 4)
c_two :: C -> Int
c_two (C _ b) = b
|
sdiehl/ghc
|
testsuite/tests/ghci/T16392/A.hs
|
bsd-3-clause
| 158 | 0 | 7 | 40 | 81 | 45 | 36 | 7 | 1 |
{-# LANGUAGE TypeFamilies #-}
module T8227
(
absoluteToParam
) where
import T8227a
type family Scalar a :: *
type instance Scalar (a -> v) = a -> Scalar v
arcLengthToParam :: Scalar (V p) -> p -> Scalar (V p) -> Scalar (V p)
arcLengthToParam = undefined
absoluteToParam :: Scalar (V a) -> a -> Scalar (V a)
absoluteToParam eps seg = arcLengthToParam eps eps
{-
Scalar (V a) ~ Scalar (V p0)
Scalar (V a) ~ p0
Scalar (V a) ~ Scalar (V p0) -> Scalar (V p0)
Scalar (V a) ~ t0
Scalar (V p0) ~ t0
Scalar (V a) ~ p0
Scalar (V a) ~ t0 -> t0
Scalar (V a) ~ t0
Scalar (V t0) ~ t0
Scalar (V a) ~ t0 -> t0
-}
|
frantisekfarka/ghc-dsi
|
testsuite/tests/indexed-types/should_fail/T8227.hs
|
bsd-3-clause
| 619 | 0 | 10 | 151 | 142 | 75 | 67 | 11 | 1 |
{-# LANGUAGE StandaloneDeriving, GADTs, DeriveDataTypeable #-}
module DataCacheTest (tests) where
import Haxl.Core.DataCache as DataCache
import Haxl.Core
import Control.Exception
import Data.Hashable
import Data.Traversable
import Data.Typeable
import Prelude hiding (mapM)
import Test.HUnit
data TestReq a where
Req :: Int -> TestReq a -- polymorphic result
deriving Typeable
deriving instance Eq (TestReq a)
deriving instance Show (TestReq a)
instance Hashable (TestReq a) where
hashWithSalt salt (Req i) = hashWithSalt salt i
dcSoundnessTest :: Test
dcSoundnessTest = TestLabel "DataCache soundness" $ TestCase $ do
m1 <- newResult 1
m2 <- newResult "hello"
let cache =
DataCache.insert (Req 1 :: TestReq Int) m1 $
DataCache.insert (Req 2 :: TestReq String) m2 $
DataCache.empty
-- "Req 1" has a result of type Int, so if we try to look it up
-- with a result of type String, we should get Nothing, not a crash.
r <- mapM takeResult $ DataCache.lookup (Req 1) cache
assertBool "dcSoundness1" $
case r :: Maybe (Either SomeException String) of
Nothing -> True
_something_else -> False
r <- mapM takeResult $ DataCache.lookup (Req 1) cache
assertBool "dcSoundness2" $
case r :: Maybe (Either SomeException Int) of
Just (Right 1) -> True
_something_else -> False
r <- mapM takeResult $ DataCache.lookup (Req 2) cache
assertBool "dcSoundness3" $
case r :: Maybe (Either SomeException String) of
Just (Right "hello") -> True
_something_else -> False
r <- mapM takeResult $ DataCache.lookup (Req 2) cache
assertBool "dcSoundness4" $
case r :: Maybe (Either SomeException Int) of
Nothing -> True
_something_else -> False
dcStrictnessTest :: Test
dcStrictnessTest = TestLabel "DataCache strictness" $ TestCase $ do
env <- initEnv stateEmpty ()
r <- Control.Exception.try $ runHaxl env $
cachedComputation (Req (error "BOOM")) $ return "OK"
assertBool "dcStrictnessTest" $
case r of
Left (ErrorCall "BOOM") -> True
_other -> False
-- tests :: Assertion
tests = TestList [dcSoundnessTest, dcStrictnessTest]
|
kantp/Haxl
|
tests/DataCacheTest.hs
|
bsd-3-clause
| 2,164 | 1 | 15 | 464 | 656 | 322 | 334 | 55 | 5 |
{-# LANGUAGE ExistentialQuantification, NamedFieldPuns #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Client.ParseUtils
-- Maintainer : [email protected]
-- Portability : portable
--
-- Parsing utilities.
-----------------------------------------------------------------------------
module Distribution.Client.ParseUtils (
-- * Fields and field utilities
FieldDescr(..),
liftField,
liftFields,
filterFields,
mapFieldNames,
commandOptionToField,
commandOptionsToFields,
-- * Sections and utilities
SectionDescr(..),
liftSection,
-- * Parsing and printing flat config
parseFields,
ppFields,
ppSection,
-- * Parsing and printing config with sections and subsections
parseFieldsAndSections,
ppFieldsAndSections,
-- ** Top level of config files
parseConfig,
showConfig,
)
where
import Distribution.ParseUtils
( FieldDescr(..), ParseResult(..), warning, LineNo, lineNo
, Field(..), liftField, readFieldsFlat )
import Distribution.Simple.Command
( OptionField, viewAsFieldDescr )
import Control.Monad ( foldM )
import Text.PrettyPrint ( (<>), (<+>), ($+$) )
import qualified Data.Map as Map
import qualified Text.PrettyPrint as Disp
( Doc, text, colon, vcat, empty, isEmpty, nest )
-------------------------
-- FieldDescr utilities
--
liftFields :: (b -> a)
-> (a -> b -> b)
-> [FieldDescr a]
-> [FieldDescr b]
liftFields get set = map (liftField get set)
-- | Given a collection of field descriptions, keep only a given list of them,
-- identified by name.
--
filterFields :: [String] -> [FieldDescr a] -> [FieldDescr a]
filterFields includeFields = filter ((`elem` includeFields) . fieldName)
-- | Apply a name mangling function to the field names of all the field
-- descriptions. The typical use case is to apply some prefix.
--
mapFieldNames :: (String -> String) -> [FieldDescr a] -> [FieldDescr a]
mapFieldNames mangleName =
map (\descr -> descr { fieldName = mangleName (fieldName descr) })
-- | Reuse a command line 'OptionField' as a config file 'FieldDescr'.
--
commandOptionToField :: OptionField a -> FieldDescr a
commandOptionToField = viewAsFieldDescr
-- | Reuse a bunch of command line 'OptionField's as config file 'FieldDescr's.
--
commandOptionsToFields :: [OptionField a] -> [FieldDescr a]
commandOptionsToFields = map viewAsFieldDescr
------------------------------------------
-- SectionDescr definition and utilities
--
-- | The description of a section in a config file. It can contain both
-- fields and optionally further subsections. See also 'FieldDescr'.
--
data SectionDescr a = forall b. SectionDescr {
sectionName :: String,
sectionFields :: [FieldDescr b],
sectionSubsections :: [SectionDescr b],
sectionGet :: a -> [(String, b)],
sectionSet :: LineNo -> String -> b -> a -> ParseResult a,
sectionEmpty :: b
}
-- | To help construction of config file descriptions in a modular way it is
-- useful to define fields and sections on local types and then hoist them
-- into the parent types when combining them in bigger descriptions.
--
-- This is essentially a lens operation for 'SectionDescr' to help embedding
-- one inside another.
--
liftSection :: (b -> a)
-> (a -> b -> b)
-> SectionDescr a
-> SectionDescr b
liftSection get' set' (SectionDescr name fields sections get set empty) =
let sectionGet' = get . get'
sectionSet' lineno param x y = do
x' <- set lineno param x (get' y)
return (set' x' y)
in SectionDescr name fields sections sectionGet' sectionSet' empty
-------------------------------------
-- Parsing and printing flat config
--
-- | Parse a bunch of semi-parsed 'Field's according to a set of field
-- descriptions. It accumulates the result on top of a given initial value.
--
-- This only covers the case of flat configuration without subsections. See
-- also 'parseFieldsAndSections'.
--
parseFields :: [FieldDescr a] -> a -> [Field] -> ParseResult a
parseFields fieldDescrs =
foldM setField
where
fieldMap = Map.fromList [ (fieldName f, f) | f <- fieldDescrs ]
setField accum (F line name value) =
case Map.lookup name fieldMap of
Just (FieldDescr _ _ set) -> set line value accum
Nothing -> do
warning $ "Unrecognized field " ++ name ++ " on line " ++ show line
return accum
setField accum f = do
warning $ "Unrecognized stanza on line " ++ show (lineNo f)
return accum
-- | This is a customised version of the functions from Distribution.ParseUtils
-- that also optionally print default values for empty fields as comments.
--
ppFields :: [FieldDescr a] -> (Maybe a) -> a -> Disp.Doc
ppFields fields def cur =
Disp.vcat [ ppField name (fmap getter def) (getter cur)
| FieldDescr name getter _ <- fields]
ppField :: String -> (Maybe Disp.Doc) -> Disp.Doc -> Disp.Doc
ppField name mdef cur
| Disp.isEmpty cur = maybe Disp.empty
(\def -> Disp.text "--" <+> Disp.text name
<> Disp.colon <+> def) mdef
| otherwise = Disp.text name <> Disp.colon <+> cur
-- | Pretty print a section.
--
-- Since 'ppFields' does not cover subsections you can use this to add them.
-- Or alternatively use a 'SectionDescr' and use 'ppFieldsAndSections'.
--
ppSection :: String -> String -> [FieldDescr a] -> (Maybe a) -> a -> Disp.Doc
ppSection name arg fields def cur
| Disp.isEmpty fieldsDoc = Disp.empty
| otherwise = Disp.text name <+> argDoc
$+$ (Disp.nest 2 fieldsDoc)
where
fieldsDoc = ppFields fields def cur
argDoc | arg == "" = Disp.empty
| otherwise = Disp.text arg
-----------------------------------------
-- Parsing and printing non-flat config
--
-- | Much like 'parseFields' but it also allows subsections. The permitted
-- subsections are given by a list of 'SectionDescr's.
--
parseFieldsAndSections :: [FieldDescr a] -> [SectionDescr a] -> a
-> [Field] -> ParseResult a
parseFieldsAndSections fieldDescrs sectionDescrs =
foldM setField
where
fieldMap = Map.fromList [ (fieldName f, f) | f <- fieldDescrs ]
sectionMap = Map.fromList [ (sectionName s, s) | s <- sectionDescrs ]
setField a (F line name value) =
case Map.lookup name fieldMap of
Just (FieldDescr _ _ set) -> set line value a
Nothing -> do
warning $ "Unrecognized field '" ++ name
++ "' on line " ++ show line
return a
setField a (Section line name param fields) =
case Map.lookup name sectionMap of
Just (SectionDescr _ fieldDescrs' sectionDescrs' _ set sectionEmpty) -> do
b <- parseFieldsAndSections fieldDescrs' sectionDescrs' sectionEmpty fields
set line param b a
Nothing -> do
warning $ "Unrecognized section '" ++ name
++ "' on line " ++ show line
return a
setField accum (block@IfBlock {}) = do
warning $ "Unrecognized stanza on line " ++ show (lineNo block)
return accum
-- | Much like 'ppFields' but also pretty prints any subsections. Subsection
-- are only shown if they are non-empty.
--
-- Note that unlike 'ppFields', at present it does not support printing
-- default values. If needed, adding such support would be quite reasonable.
--
ppFieldsAndSections :: [FieldDescr a] -> [SectionDescr a] -> a -> Disp.Doc
ppFieldsAndSections fieldDescrs sectionDescrs val =
ppFields fieldDescrs Nothing val
$+$
Disp.vcat
[ Disp.text "" $+$ sectionDoc
| SectionDescr {
sectionName, sectionGet,
sectionFields, sectionSubsections
} <- sectionDescrs
, (param, x) <- sectionGet val
, let sectionDoc = ppSectionAndSubsections
sectionName param
sectionFields sectionSubsections x
, not (Disp.isEmpty sectionDoc)
]
-- | Unlike 'ppSection' which has to be called directly, this gets used via
-- 'ppFieldsAndSections' and so does not need to be exported.
--
ppSectionAndSubsections :: String -> String
-> [FieldDescr a] -> [SectionDescr a] -> a -> Disp.Doc
ppSectionAndSubsections name arg fields sections cur
| Disp.isEmpty fieldsDoc = Disp.empty
| otherwise = Disp.text name <+> argDoc
$+$ (Disp.nest 2 fieldsDoc)
where
fieldsDoc = showConfig fields sections cur
argDoc | arg == "" = Disp.empty
| otherwise = Disp.text arg
-----------------------------------------------
-- Top level config file parsing and printing
--
-- | Parse a string in the config file syntax into a value, based on a
-- description of the configuration file in terms of its fields and sections.
--
-- It accumulates the result on top of a given initial (typically empty) value.
--
parseConfig :: [FieldDescr a] -> [SectionDescr a] -> a
-> String -> ParseResult a
parseConfig fieldDescrs sectionDescrs empty str =
parseFieldsAndSections fieldDescrs sectionDescrs empty
=<< readFieldsFlat str
-- | Render a value in the config file syntax, based on a description of the
-- configuration file in terms of its fields and sections.
--
showConfig :: [FieldDescr a] -> [SectionDescr a] -> a -> Disp.Doc
showConfig = ppFieldsAndSections
|
tolysz/prepare-ghcjs
|
spec-lts8/cabal/cabal-install/Distribution/Client/ParseUtils.hs
|
bsd-3-clause
| 9,627 | 0 | 15 | 2,361 | 2,067 | 1,101 | 966 | 146 | 5 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
module T12634 where
twacePowDec :: t m' r -> t m r
twacePowDec = undefined
data Bench a
bench :: (a -> b) -> a -> Bench params
bench f = undefined
bench_twacePow :: forall t m m' r . _ => t m' r -> Bench '(t,m,m',r)
bench_twacePow = bench (twacePowDec :: t m' r -> t m r)
|
olsner/ghc
|
testsuite/tests/partial-sigs/should_fail/T12634.hs
|
bsd-3-clause
| 351 | 0 | 10 | 83 | 137 | 75 | 62 | -1 | -1 |
-- Copyright © 2021 Mark Raynsford <[email protected]> https://www.io7m.com
--
-- Permission to use, copy, modify, and/or distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
module Matrix4f (
T (..),
mult,
mult_v,
row,
row_column
) where
import qualified Vector4f as V4
data T = T {
column_0 :: V4.T,
column_1 :: V4.T,
column_2 :: V4.T,
column_3 :: V4.T
} deriving (Eq, Ord, Show)
v4_get :: V4.T -> Integer -> Float
v4_get v 0 = V4.x v
v4_get v 1 = V4.y v
v4_get v 2 = V4.z v
v4_get v 3 = V4.w v
v4_get _ _ = undefined
row_column :: T -> (Integer, Integer) -> Float
row_column m (r, c) =
case c of
0 -> v4_get (column_0 m) r
1 -> v4_get (column_1 m) r
2 -> v4_get (column_2 m) r
3 -> v4_get (column_3 m) r
_ -> undefined
row :: T -> Integer -> V4.T
row m r =
V4.V4
(row_column m (r, 0))
(row_column m (r, 1))
(row_column m (r, 2))
(row_column m (r, 3))
mult_v :: T -> V4.T -> V4.T
mult_v m v =
V4.V4
(V4.dot4 (row m 0) v)
(V4.dot4 (row m 1) v)
(V4.dot4 (row m 2) v)
(V4.dot4 (row m 3) v)
mult :: T -> T -> T
mult m0 m1 =
let
m0r0 = row m0 0
m0r1 = row m0 1
m0r2 = row m0 2
m0r3 = row m0 3
m1c0 = column_0 m1
m1c1 = column_1 m1
m1c2 = column_2 m1
m1c3 = column_3 m1
r0c0 = V4.dot4 m0r0 m1c0
r0c1 = V4.dot4 m0r1 m1c0
r0c2 = V4.dot4 m0r2 m1c0
r0c3 = V4.dot4 m0r3 m1c0
r1c0 = V4.dot4 m0r0 m1c1
r1c1 = V4.dot4 m0r1 m1c1
r1c2 = V4.dot4 m0r2 m1c1
r1c3 = V4.dot4 m0r3 m1c1
r2c0 = V4.dot4 m0r0 m1c2
r2c1 = V4.dot4 m0r1 m1c2
r2c2 = V4.dot4 m0r2 m1c2
r2c3 = V4.dot4 m0r3 m1c2
r3c0 = V4.dot4 m0r0 m1c3
r3c1 = V4.dot4 m0r1 m1c3
r3c2 = V4.dot4 m0r2 m1c3
r3c3 = V4.dot4 m0r3 m1c3
in
T {
column_0 = V4.V4 r0c0 r1c0 r2c0 r3c0,
column_1 = V4.V4 r0c1 r1c1 r2c1 r3c1,
column_2 = V4.V4 r0c2 r1c2 r2c2 r3c2,
column_3 = V4.V4 r0c3 r1c3 r2c3 r3c3
}
|
io7m/jcamera
|
com.io7m.jcamera.documentation/src/main/resources/com/io7m/jcamera/documentation/haskell/Matrix4f.hs
|
isc
| 2,578 | 0 | 10 | 689 | 863 | 454 | 409 | 73 | 5 |
class YesNo a where
yesno :: a -> Bool
instance YesNo Int where
yesno 0 = False
yesno _ = True
instance YesNo [a] where
yesno [] = False
yesno _ = True
instance YesNo Bool where
yesno = id
instance YesNo (Maybe a) where
yesno (Just _) = True
yesno Nothing = False
instance YesNo TrafficLight where
yesno Red = False
yesno _ = True
yesnoIf :: (YesNo y) => y -> a -> a -> a
yesnoIf yesnoVal yesResult noResult =
if yesno yesnoVal
then yesResult
else noResult
|
v0lkan/learning-haskell
|
yesno.hs
|
mit
| 524 | 0 | 8 | 157 | 194 | 99 | 95 | 21 | 2 |
-- Generated by protobuf-simple. DO NOT EDIT!
module Types.Enum where
import Prelude ()
import qualified Data.ProtoBufInt as PB
data Enum = Zero | One | Two | Three | Four | Five | Six | Seven | Eight | Nine
deriving (PB.Show, PB.Eq, PB.Ord)
instance PB.Default Enum where
defaultVal = Zero
instance PB.Mergeable Enum where
instance PB.WireEnum Enum where
intToEnum 0 = Zero
intToEnum 1 = One
intToEnum 2 = Two
intToEnum 3 = Three
intToEnum 4 = Four
intToEnum 5 = Five
intToEnum 6 = Six
intToEnum 7 = Seven
intToEnum 8 = Eight
intToEnum 9 = Nine
intToEnum _ = PB.defaultVal
enumToInt Zero = 0
enumToInt One = 1
enumToInt Two = 2
enumToInt Three = 3
enumToInt Four = 4
enumToInt Five = 5
enumToInt Six = 6
enumToInt Seven = 7
enumToInt Eight = 8
enumToInt Nine = 9
|
sru-systems/protobuf-simple
|
test/Types/Enum.hs
|
mit
| 818 | 0 | 7 | 197 | 281 | 151 | 130 | 30 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Castor.Std.Logic (exports) where
import Control.Applicative
import Control.Monad.Error
import qualified Data.Map as M
import Data.Maybe
import Castor.Externs
import Castor.Interpreter
import Castor.Types
ifthenelse :: Value
ifthenelse = mkBif [Sym "p", Sym "t", Sym "f", Sym "x"] $ \envref cenvref -> do
p <- extract (Sym "p") envref
t <- extract (Sym "t") envref
f <- extract (Sym "f") envref
x <- extract (Sym "x") envref
Primitive (Boolean pv) <- apply p x cenvref
if pv then apply t x cenvref else apply f x cenvref
trycatch :: Value
trycatch = mkBif [Sym "t", Sym "c", Sym "x"] $ \envref cenvref -> do
t <- extract (Sym "t") envref
c <- extract (Sym "c") envref
x <- extract (Sym "x") envref
catchError (apply t x cenvref) $ \x -> apply c x cenvref
throw :: Value
throw = mkBif [Sym "e"] $ \envref _ -> do
e <- extract (Sym "e") envref
throwError e
exports :: Exports
exports = Exports $ M.fromList [ (Sym "if-then-else", ifthenelse)
, (Sym "try-catch", trycatch)
, (Sym "throw", throw)
, (Sym "t", Primitive (Boolean True))
, (Sym "f", Primitive (Boolean False))]
|
rfw/castor
|
Std/Logic.hs
|
mit
| 1,293 | 0 | 12 | 369 | 499 | 253 | 246 | 33 | 2 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeSynonymInstances #-}
-- | This module holds the base monads used throughout the library.
module Docker.Base ( Docker
, Auth(..)
, DockerError(..)
, Logs
, runDocker
, execDocker
, execDocker'
, getConnection
, getAuth
, login
, logout
, log
, clientError
, serverError
, parseError
) where
import Control.Applicative
import Control.Monad.Error
import Control.Monad.RWS.Strict
import qualified Data.ByteString.Char8 as BS
import qualified Network.Http.Client as H
import Prelude hiding (log)
-- | This data type represents authentication credentials for a certain Docker
-- server.
data Auth = Auth { username :: BS.ByteString
, password :: BS.ByteString
, email :: BS.ByteString
, server :: BS.ByteString
} deriving (Eq, Show)
-- | The 'Logs' are just a list of 'BS.ByteString's.
type Logs = [BS.ByteString]
-- | A 'DockerError' can stem from one of the following:
data DockerError
-- | 'ClientError' is thrown when there is a malformed request.
= ClientError BS.ByteString
-- | 'ServerError' is thrown when the server cannot complete the requset.
| ServerError BS.ByteString
-- | 'ParseError' is thrown when the server cannot complete the requset.
| ParseError BS.ByteString
-- | 'BaseError' is never actually thrown in the library, but is used as for
-- making this datatype an instance of 'Error'.
| BaseError BS.ByteString
deriving (Eq, Show)
-- | The 'Docker' type is a transformer stack of 'RWST' and 'ErrorT'. The reader
-- value is a 'H.Connection', the state value is a 'Maybe Auth', the writter value
-- is a list of 'BS.ByteString's, and the error that maybe be thrown is a
-- 'DockerError'. These two monads wrap 'IO' so that HTTP requests and file IO
-- may be performed.
newtype Docker a =
Docker (ErrorT DockerError (RWST H.Connection Logs (Maybe Auth) IO) a)
deriving (Functor, Applicative, Monad, MonadIO)
-- Make 'Docker' instances of the required type classes.
instance Error DockerError where
strMsg = BaseError . BS.pack
instance MonadError DockerError Docker where
throwError = Docker . throwError
catchError comp handler =
Docker $ (runDocker comp) `catchError` (runDocker . handler)
instance MonadReader H.Connection Docker where
ask = Docker ask
local f = Docker . local f . runDocker
instance MonadWriter Logs Docker where
tell = Docker . tell
listen = Docker . listen . runDocker
pass = Docker . pass . runDocker
instance MonadState (Maybe Auth) Docker where
get = Docker get
put = Docker . put
-- | Transform the 'Docker' computation into the actual 'Monad' stack it holds.
runDocker :: Docker a ->
ErrorT DockerError (RWST H.Connection Logs (Maybe Auth) IO) a
runDocker (Docker comp) = comp
-- | Given a 'H.Hostname', 'H.Port', and 'Docker' computation, returns a tuple.
-- The first value in the tuple is either the 'DockerError' that was thrown or
-- the result of the 'Docker' computation; the second value is the 'Logs'
-- recorded during the computation.
execDocker :: H.Hostname -> H.Port -> Docker a ->
IO (Either DockerError a, Logs)
execDocker host port docker = do
conn <- H.openConnection host port
result <- execDocker' conn docker
H.closeConnection conn
return result
-- | Much like 'execDocker', except that it provides no 'H.Connection'
-- management.
execDocker' :: H.Connection -> Docker a -> IO (Either DockerError a, Logs)
execDocker' conn docker = do
(x, _, logs) <- runRWST (runErrorT $ runDocker docker) conn Nothing
return (x, logs)
-- | Retreive the 'H.Connection' with which this computation was initiated.
getConnection :: Docker H.Connection
getConnection = ask
-- | Get the current 'Auth' credentials (if any).
getAuth :: Docker (Maybe Auth)
getAuth = get
-- | Set the current 'Auth' credentials.
login :: Auth -> Docker ()
login = put . Just
-- | Remove the current 'Auth' credentials.
logout :: Docker ()
logout = put Nothing
-- | Log a 'BS.ByteString'.
log :: BS.ByteString -> Docker ()
log = tell . return
-- | Convenience method to raise a 'ClientError'.
clientError :: BS.ByteString -> Docker a
clientError = throwError . ClientError
-- | Convenience method to raise a 'ServerError'.
serverError :: BS.ByteString -> Docker a
serverError = throwError . ServerError
-- | Convenience method to raise a 'ParseError'.
parseError :: BS.ByteString -> Docker a
parseError = throwError . ParseError
|
nahiluhmot/docker-hs
|
src/Docker/Base.hs
|
mit
| 4,915 | 0 | 11 | 1,222 | 892 | 498 | 394 | 86 | 1 |
module Bot
( bot
)
where
import Vindinium
import System.Random (getStdRandom, randomR)
import Data.Maybe (fromJust)
import Control.Monad (liftM)
import Control.Monad.IO.Class (liftIO)
bot :: Bot
bot = randomBot
myBot :: Bot
myBot = error "it's up to you :)"
randomBot :: Bot
randomBot _ = liftM fromJust $ liftIO $ pickRandom [Stay, North, South, East, West]
inBoard :: Board -> Pos -> Bool
inBoard b (Pos x y) =
let s = boardSize b
in x >= 0 && x < s && y >= 0 && y < s
tileAt :: Board -> Pos -> Maybe Tile
tileAt b p@(Pos x y) =
if inBoard b p
then Just $ boardTiles b !! idx
else Nothing
where
idx = y * boardSize b + x
pickRandom :: [a] -> IO (Maybe a)
pickRandom [] = return Nothing
pickRandom xs = do
idx <- getStdRandom (randomR (0, length xs - 1))
return . Just $ xs !! idx
|
Herzult/vindinium-starter-haskell
|
src/Bot.hs
|
mit
| 852 | 0 | 13 | 227 | 360 | 190 | 170 | 28 | 2 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.AllAudioCapabilities
(js_getSourceId, getSourceId, js_getVolume, getVolume,
AllAudioCapabilities, castToAllAudioCapabilities,
gTypeAllAudioCapabilities)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSRef(..), JSString, castRef)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSRef(..), FromJSRef(..))
import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.Enums
foreign import javascript unsafe "$1[\"sourceId\"]" js_getSourceId
:: JSRef AllAudioCapabilities -> IO (JSRef [result])
-- | <https://developer.mozilla.org/en-US/docs/Web/API/AllAudioCapabilities.sourceId Mozilla AllAudioCapabilities.sourceId documentation>
getSourceId ::
(MonadIO m, FromJSString result) =>
AllAudioCapabilities -> m [result]
getSourceId self
= liftIO
((js_getSourceId (unAllAudioCapabilities self)) >>=
fromJSRefUnchecked)
foreign import javascript unsafe "$1[\"volume\"]" js_getVolume ::
JSRef AllAudioCapabilities -> IO (JSRef CapabilityRange)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/AllAudioCapabilities.volume Mozilla AllAudioCapabilities.volume documentation>
getVolume ::
(MonadIO m) => AllAudioCapabilities -> m (Maybe CapabilityRange)
getVolume self
= liftIO
((js_getVolume (unAllAudioCapabilities self)) >>= fromJSRef)
|
plow-technologies/ghcjs-dom
|
src/GHCJS/DOM/JSFFI/Generated/AllAudioCapabilities.hs
|
mit
| 1,983 | 12 | 11 | 276 | 477 | 291 | 186 | 35 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
module Hpack.Syntax.Dependencies (
Dependencies(..)
, DependencyInfo(..)
, parseDependency
) where
import Imports
import qualified Control.Monad.Fail as Fail
import qualified Data.Text as T
import qualified Distribution.Package as D
import qualified Distribution.Types.LibraryName as D
import Distribution.Pretty (prettyShow)
import Data.Map.Lazy (Map)
import qualified Data.Map.Lazy as Map
import GHC.Exts
#if MIN_VERSION_Cabal(3,4,0)
import qualified Distribution.Compat.NonEmptySet as DependencySet
#else
import qualified Data.Set as DependencySet
#endif
import Data.Aeson.Config.FromValue
import Data.Aeson.Config.Types
import Hpack.Syntax.DependencyVersion
import Hpack.Syntax.ParseDependencies
newtype Dependencies = Dependencies {
unDependencies :: Map String DependencyInfo
} deriving (Eq, Show, Semigroup, Monoid)
instance IsList Dependencies where
type Item Dependencies = (String, DependencyInfo)
fromList = Dependencies . Map.fromList
toList = Map.toList . unDependencies
instance FromValue Dependencies where
fromValue = fmap (Dependencies . Map.fromList) . parseDependencies parse
where
parse :: Parse String DependencyInfo
parse = Parse {
parseString = \ input -> do
(name, version) <- parseDependency "dependency" input
return (name, DependencyInfo [] version)
, parseListItem = objectDependencyInfo
, parseDictItem = dependencyInfo
, parseName = T.unpack
}
data DependencyInfo = DependencyInfo {
dependencyInfoMixins :: [String]
, dependencyInfoVersion :: DependencyVersion
} deriving (Eq, Ord, Show)
addMixins :: Object -> DependencyVersion -> Parser DependencyInfo
addMixins o version = do
mixinsMay <- o .:? "mixin"
return $ DependencyInfo (fromMaybeList mixinsMay) version
objectDependencyInfo :: Object -> Parser DependencyInfo
objectDependencyInfo o = objectDependency o >>= addMixins o
dependencyInfo :: Value -> Parser DependencyInfo
dependencyInfo = withDependencyVersion (DependencyInfo []) addMixins
parseDependency :: Fail.MonadFail m => String -> Text -> m (String, DependencyVersion)
parseDependency subject = fmap fromCabal . cabalParse subject . T.unpack
where
fromCabal :: D.Dependency -> (String, DependencyVersion)
fromCabal d = (toName (D.depPkgName d) (DependencySet.toList $ D.depLibraries d), DependencyVersion Nothing . versionConstraintFromCabal $ D.depVerRange d)
toName :: D.PackageName -> [D.LibraryName] -> String
toName package components = prettyShow package <> case components of
[D.LMainLibName] -> ""
[D.LSubLibName lib] -> ":" <> prettyShow lib
xs -> ":{" <> (intercalate "," $ map prettyShow [name | D.LSubLibName name <- xs]) <> "}"
|
sol/hpack
|
src/Hpack/Syntax/Dependencies.hs
|
mit
| 2,933 | 0 | 20 | 545 | 744 | 414 | 330 | 60 | 3 |
{-# LANGUAGE DeriveDataTypeable, CPP #-}
-- | A lightweight implementation of a subset of Hspec's API.
module Test.Hspec (
-- * Types
SpecM
, Spec
-- * Defining a spec
, describe
, context
, it
-- ** Setting expectations
, Expectation
, expect
, shouldBe
, shouldReturn
-- * Running a spec
, hspec
#ifdef TEST
-- * Internal stuff
, evaluateExpectation
, Result (..)
#endif
) where
#if !(MIN_VERSION_base(4,8,0))
import Control.Applicative
import Data.Monoid
#endif
import Control.Monad
import Data.List (intercalate)
import Data.Typeable
import qualified Control.Exception as E
import System.Exit
-- a writer monad
data SpecM a = SpecM a [SpecTree]
add :: SpecTree -> SpecM ()
add s = SpecM () [s]
instance Functor SpecM where
fmap = undefined
instance Applicative SpecM where
pure a = SpecM a []
(<*>) = ap
instance Monad SpecM where
return = pure
SpecM a xs >>= f = case f a of
SpecM b ys -> SpecM b (xs ++ ys)
data SpecTree = SpecGroup String Spec
| SpecExample String (IO Result)
data Result = Success | Failure String
deriving (Eq, Show)
type Spec = SpecM ()
describe :: String -> Spec -> Spec
describe label = add . SpecGroup label
context :: String -> Spec -> Spec
context = describe
it :: String -> Expectation -> Spec
it label = add . SpecExample label . evaluateExpectation
-- | Summary of a test run.
data Summary = Summary Int Int
instance Monoid Summary where
mempty = Summary 0 0
#if !MIN_VERSION_base(4,11,0)
(Summary x1 x2) `mappend` (Summary y1 y2) = Summary (x1 + y1) (x2 + y2)
#else
instance Semigroup Summary where
(Summary x1 x2) <> (Summary y1 y2) = Summary (x1 + y1) (x2 + y2)
#endif
runSpec :: Spec -> IO Summary
runSpec = runForrest []
where
runForrest :: [String] -> Spec -> IO Summary
runForrest labels (SpecM () xs) = mconcat <$> mapM (runTree labels) xs
runTree :: [String] -> SpecTree -> IO Summary
runTree labels spec = case spec of
SpecExample label x -> do
putStr $ "/" ++ (intercalate "/" . reverse) (label:labels) ++ "/ "
r <- x
case r of
Success -> do
putStrLn "OK"
return (Summary 1 0)
Failure err -> do
putStrLn "FAILED"
putStrLn err
return (Summary 1 1)
SpecGroup label xs -> do
runForrest (label:labels) xs
hspec :: Spec -> IO ()
hspec spec = do
Summary total failures <- runSpec spec
putStrLn (show total ++ " example(s), " ++ show failures ++ " failure(s)")
when (failures /= 0) exitFailure
type Expectation = IO ()
infix 1 `shouldBe`, `shouldReturn`
shouldBe :: (Show a, Eq a) => a -> a -> Expectation
actual `shouldBe` expected =
expect ("expected: " ++ show expected ++ "\n but got: " ++ show actual) (actual == expected)
shouldReturn :: (Show a, Eq a) => IO a -> a -> Expectation
action `shouldReturn` expected = action >>= (`shouldBe` expected)
expect :: String -> Bool -> Expectation
expect label f
| f = return ()
| otherwise = E.throwIO (ExpectationFailure label)
data ExpectationFailure = ExpectationFailure String
deriving (Show, Eq, Typeable)
instance E.Exception ExpectationFailure
evaluateExpectation :: Expectation -> IO Result
evaluateExpectation action = (action >> return Success)
`E.catches` [
-- Re-throw AsyncException, otherwise execution will not terminate on SIGINT
-- (ctrl-c). All AsyncExceptions are re-thrown (not just UserInterrupt)
-- because all of them indicate severe conditions and should not occur during
-- normal operation.
E.Handler $ \e -> E.throw (e :: E.AsyncException)
, E.Handler $ \(ExpectationFailure err) -> return (Failure err)
, E.Handler $ \e -> (return . Failure) ("*** Exception: " ++ show (e :: E.SomeException))
]
|
hspec/nanospec
|
src/Test/Hspec.hs
|
mit
| 3,825 | 0 | 19 | 914 | 1,184 | 622 | 562 | 90 | 3 |
{-
Copyright (c) 2008-2015 the Urho3D project.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-}
{-
Skeletal animation example.
This sample demonstrates:
- Populating a 3D scene with skeletally animated AnimatedModel components;
- Moving the animated models and advancing their animation using a custom component
- Enabling a cascaded shadow map on a directional light, which allows high-quality shadows
over a large area (typically used in outdoor scenes for shadows cast by sunlight)
- Displaying renderer debug geometry
-}
module Main where
import Control.Lens hiding (Context, element)
import Control.Monad
import Data.IORef
import Foreign
import Graphics.Urho3D
import Sample
import Mover
main :: IO ()
main = withObject () $ \cntx -> do
newSample cntx "SkeletalAnimation" joysticPatch (customStart cntx) >>= runSample
-- | Setup after engine initialization and before running the main loop.
customStart :: Ptr Context -> SampleRef -> IO ()
customStart cntx sr = do
s <- readIORef sr
let app = s ^. sampleApplication
-- Register an object factory for our custom Mover component so that we can create them to scene nodes
moverType <- registerMover cntx
-- Create the scene content
(scene, cameraNode) <- createScene app moverType
-- Create the UI content
createInstructions app
-- Setup the viewport for displaying the scene
setupViewport app scene cameraNode
-- Hook up to the frame update events
subscribeToEvents app cameraNode
-- Save scene to prevent garbage collecting
writeIORef sr $ sampleScene .~ scene $ s
-- | Construct the scene content.
createScene :: SharedPtr Application -> MoverType -> IO (SharedPtr Scene, Ptr Node)
createScene app moverType = do
(cache :: Ptr ResourceCache) <- fromJustTrace "ResourceCache" <$> getSubsystem app
(scene :: SharedPtr Scene) <- newSharedObject =<< getContext app
{-
Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
Also create a DebugRenderer component so that we can draw debug geometry
-}
(_ :: Ptr Octree) <- fromJustTrace "Octree" <$> nodeCreateComponent scene Nothing Nothing
(_ :: Ptr DebugRenderer) <- fromJustTrace "DebugRenderer" <$> nodeCreateComponent scene Nothing Nothing
-- Create scene node & StaticModel component for showing a static plane
planeNode <- nodeCreateChild scene "Plane" CMReplicated 0
nodeSetScale planeNode (Vector3 100 1 100)
(planeObject :: Ptr StaticModel) <- fromJustTrace "Plane StaticModel" <$> nodeCreateComponent planeNode Nothing Nothing
(planeModel :: Ptr Model) <- fromJustTrace "Plane.mdl" <$> cacheGetResource cache "Models/Plane.mdl" True
staticModelSetModel planeObject planeModel
(planeMaterial :: Ptr Material) <- fromJustTrace "StoneTiled.xml" <$> cacheGetResource cache "Materials/StoneTiled.xml" True
staticModelSetMaterial planeObject planeMaterial
-- Create a Zone component for ambient lighting & fog control
zoneNode <- nodeCreateChild scene "Zone" CMReplicated 0
(zone :: Ptr Zone) <- fromJustTrace "Zone" <$> nodeCreateComponent zoneNode Nothing Nothing
-- Set same volume as the Octree, set a close bluish fog and some ambient light
zoneSetBoundingBox zone $ BoundingBox (-1000) 1000
zoneSetAmbientColor zone $ rgb 0.15 0.15 0.15
zoneSetFogColor zone $ rgb 0.5 0.5 0.7
zoneSetFogStart zone 100
zoneSetFogEnd zone 300
{-
Create a directional light to the world so that we can see something. The light scene node's orientation controls the
light direction; we will use the SetDirection() function which calculates the orientation from a forward direction vector.
The light will use default settings (white light, no shadows)
-}
lightNode <- nodeCreateChild scene "DirectionalLight" CMReplicated 0
nodeSetDirection lightNode (Vector3 0.6 (-1.0) 0.8)
(light :: Ptr Light) <- fromJustTrace "Light" <$> nodeCreateComponent lightNode Nothing Nothing
lightSetLightType light LT'Directional
drawableSetCastShadows light True
lightSetShadowBias light $ BiasParameters 0.00025 0.5
-- Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
lightSetShadowCascade light $ CascadeParameters 10 50 200 0 0.8 1.0
-- Create animated models
let numModels = 100
modelMoveSpeed = 2.0
modelRotateSpeed = 100.0
bounds = BoundingBox (Vector3 (-47) 0 (-47)) (Vector3 47 0 47)
_ <- replicateM numModels $ do
modelNode <- nodeCreateChild scene "Jill" CMReplicated 0
[r1, r2] <- replicateM 2 (randomUp 90)
nodeSetPosition modelNode $ Vector3 (r1 - 45) 0 (r2 - 45)
r3 <- randomUp 360
nodeSetRotation modelNode $ quaternionFromEuler 0 r3 0
(modelObject :: Ptr AnimatedModel) <- fromJustTrace "Jill model" <$> nodeCreateComponent modelNode Nothing Nothing
(modelModel :: Ptr Model) <- fromJustTrace "Kachujin.mdl" <$> cacheGetResource cache "Models/Kachujin/Kachujin.mdl" True
animatedModelSetModel modelObject modelModel True
(modelMaterial :: Ptr Material) <- fromJustTrace "Jack.xml" <$> cacheGetResource cache "Models/Kachujin/Materials/Kachujin.xml" True
staticModelSetMaterial modelObject modelMaterial
drawableSetCastShadows modelObject True
-- Create an AnimationState for a walk animation. Its time position will need to be manually updated to advance the
-- animation, The alternative would be to use an AnimationController component which updates the animation automatically,
-- but we need to update the model's position manually in any case
(walkAnimation :: Ptr Animation) <- fromJustTrace "Kachujin_Walk.ani" <$> cacheGetResource cache "Models/Kachujin/Kachujin_Walk.ani" True
(astate :: Ptr AnimationState) <- animatedModelAddAnimationState modelObject walkAnimation
-- The state would fail to create (return null) if the animation was not found
unless (isNull astate) $ do
-- Enable full blending weight and looping
animationStateSetWeight astate 1
animationStateSetLooped astate True
animationStateSetTime astate =<< randomUp =<< animationGetLength walkAnimation
-- Create our custom Mover component that will move & animate the model during each frame's update
(mover :: Ptr Mover) <- fromJustTrace "Mover" <$> nodeCreateCustomComponent modelNode moverType Nothing Nothing
setMoverParameters mover modelMoveSpeed modelRotateSpeed bounds
return ()
-- Create the camera. Let the starting position be at the world origin. As the fog limits maximum visible distance, we can
-- bring the far clip plane closer for more effective culling of distant objects
cameraNode <- nodeCreateChild scene "Camera" CMReplicated 0
(cam :: Ptr Camera) <- fromJustTrace "Camera component" <$> nodeCreateComponent cameraNode Nothing Nothing
cameraSetFarClip cam 300
-- Set an initial position for the camera scene node above the plane
nodeSetPosition cameraNode (Vector3 0 5 0)
return (scene, cameraNode)
-- | Construct an instruction text to the UI.
createInstructions :: SharedPtr Application -> IO ()
createInstructions app = do
(cache :: Ptr ResourceCache) <- fromJustTrace "ResourceCache" <$> getSubsystem app
(ui :: Ptr UI) <- fromJustTrace "UI" <$> getSubsystem app
roote <- uiRoot ui
-- Construct new Text object, set string to display and font to use
(instructionText :: Ptr Text) <- createChildSimple roote
textSetText instructionText "Use WASD keys and mouse/touch to move\nSpace to toggle debug geometry"
(font :: Ptr Font) <- fromJustTrace "Anonymous Pro.ttf" <$> cacheGetResource cache "Fonts/Anonymous Pro.ttf" True
textSetFont instructionText font 15
-- Position the text relative to the screen center
uiElementSetAlignment instructionText AlignmentHorizontalCenter AlignmentVerticalCenter
rootHeight <- uiElementGetHeight roote
uiElementSetPosition instructionText $ IntVector2 0 (rootHeight `div` 4)
-- | Set up a viewport for displaying the scene.
setupViewport :: SharedPtr Application -> SharedPtr Scene -> Ptr Node -> IO ()
setupViewport app scene cameraNode = do
(renderer :: Ptr Renderer) <- fromJustTrace "Renderer" <$> getSubsystem app
{-
Set up a viewport to the Renderer subsystem so that the 3D scene can be seen. We need to define the scene and the camera
at minimum. Additionally we could configure the viewport screen size and the rendering path (eg. forward / deferred) to
use, but now we just use full screen and default render path configured in the engine command line options
-}
cntx <- getContext app
(cam :: Ptr Camera) <- fromJustTrace "Camera" <$> nodeGetComponent cameraNode False
(viewport :: SharedPtr Viewport) <- newSharedObject (cntx, pointer scene, cam)
rendererSetViewport renderer 0 viewport
data CameraData = CameraData {
camYaw :: Float
, camPitch :: Float
, camDebugGeometry :: Bool
}
-- | Read input and moves the camera.
moveCamera :: SharedPtr Application -> Ptr Node -> Float -> CameraData -> IO CameraData
moveCamera app cameraNode t camData = do
(ui :: Ptr UI) <- fromJustTrace "UI" <$> getSubsystem app
-- Do not move if the UI has a focused element (the console)
mFocusElem <- uiFocusElement ui
whenNothing mFocusElem camData $ do
(input :: Ptr Input) <- fromJustTrace "Input" <$> getSubsystem app
-- Movement speed as world units per second
let moveSpeed = 20
-- Mouse sensitivity as degrees per pixel
let mouseSensitivity = 0.1
-- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
mouseMove <- inputGetMouseMove input
let yaw = camYaw camData + mouseSensitivity * fromIntegral (mouseMove ^. x)
let pitch = clamp (-90) 90 $ camPitch camData + mouseSensitivity * fromIntegral (mouseMove ^. y)
-- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
nodeSetRotation cameraNode $ quaternionFromEuler pitch yaw 0
-- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
-- Use the Translate() function (default local space) to move relative to the node's orientation.
whenM (inputGetKeyDown input KeyW) $
nodeTranslate cameraNode (vec3Forward `mul` (moveSpeed * t)) TSLocal
whenM (inputGetKeyDown input KeyS) $
nodeTranslate cameraNode (vec3Back `mul` (moveSpeed * t)) TSLocal
whenM (inputGetKeyDown input KeyA) $
nodeTranslate cameraNode (vec3Left `mul` (moveSpeed * t)) TSLocal
whenM (inputGetKeyDown input KeyD) $
nodeTranslate cameraNode (vec3Right `mul` (moveSpeed * t)) TSLocal
-- Toggle debug geometry with space
spacePressed <- inputGetKeyPress input KeySpace
return camData {
camYaw = yaw
, camPitch = pitch
, camDebugGeometry = (if spacePressed then not else id) $ camDebugGeometry camData
}
where
mul (Vector3 a b c) v = Vector3 (a*v) (b*v) (c*v)
-- | Subscribe to application-wide logic update events.
subscribeToEvents :: SharedPtr Application -> Ptr Node -> IO ()
subscribeToEvents app cameraNode = do
camDataRef <- newIORef $ CameraData 0 0 False
subscribeToEvent app $ handleUpdate app cameraNode camDataRef
subscribeToEvent app $ handlePostRenderUpdate app camDataRef
-- | Handle the logic update event.
handleUpdate :: SharedPtr Application -> Ptr Node -> IORef CameraData -> EventUpdate -> IO ()
handleUpdate app cameraNode camDataRef e = do
-- Take the frame time step, which is stored as a float
let t = e ^. timeStep
camData <- readIORef camDataRef
-- Move the camera, scale movement with time step
writeIORef camDataRef =<< moveCamera app cameraNode t camData
handlePostRenderUpdate :: SharedPtr Application -> IORef CameraData -> EventPostRenderUpdate -> IO ()
handlePostRenderUpdate app camDataRef _ = do
camData <- readIORef camDataRef
(renderer :: Ptr Renderer) <- fromJustTrace "Input" <$> getSubsystem app
-- If draw debug mode is enabled, draw viewport debug geometry, which will show eg. drawable bounding boxes and skeleton
-- bones. Note that debug geometry has to be separately requested each frame. Disable depth test so that we can see the
-- bones properly
when (camDebugGeometry camData) $
rendererDrawDebugGeometry renderer False
|
Teaspot-Studio/Urho3D-Haskell
|
app/sample06/Main.hs
|
mit
| 13,282 | 0 | 18 | 2,432 | 2,494 | 1,177 | 1,317 | -1 | -1 |
{-# LANGUAGE FlexibleContexts #-}
module Network.Visualizations
( networkHistogram
, weightList
, biasList
) where
import Network.Layer
import Network.Network
import Network.Network.FeedForwardNetwork
import Network.Neuron
import Numeric.LinearAlgebra
import Data.Foldable (foldMap)
import GHC.Float
import Graphics.Histogram
import Network.Trainer
weightList :: FeedForwardNetwork -> [Double]
weightList n = concat $ map (toList . flatten . weightMatrix) (layers n)
biasList :: FeedForwardNetwork -> [Double]
biasList n = concat $ map (toList . biasVector) (layers n)
networkHistogram :: FilePath -> (FeedForwardNetwork -> [Double]) -> FeedForwardNetwork -> IO ()
networkHistogram filename listFunction n = do
let hist = histogram binSturges (listFunction n)
plot filename hist
return ()
|
mckeankylej/hwRecog
|
Network/Visualizations.hs
|
mit
| 912 | 0 | 12 | 220 | 237 | 127 | 110 | 23 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import qualified Data.ByteString as B
import Ketchup.Auth
import Ketchup.Httpd
import Ketchup.Routing
import Ketchup.Utils
import Ketchup.Chunked
import Ketchup.Static
handle hnd req =
sendReply hnd 200 [("Content-Type", ["text/html"])] response
where
response = B.concat ["<center>You requested <b>", url, "</b></center>"]
url = uri req
greet hnd req params =
sendReply hnd 200 [("Content-Type", ["text/html"])] response
where
response = B.concat ["<h1>Hi ", name, "!</h1>"]
name = fallback (params "user") "Anonymous"
chunked hnd req = do
chunkHeaders hnd 200 [("Content-Type",["text/plain"])]
chunk hnd "PUTIFERIO"
chunk hnd "AAAAAAAAAHHH"
endchunk hnd
post hnd req = do
print $ parseBody $ body req
sendReply hnd 200 [("Content-Type", ["text/html"])] "OK!"
router = route [ (match "/greet/:user" , greet )
, (prefix "/chunk/" , useHandler $ chunked )
, (match "/post" , useHandler $ post )
, (prefix "/Ketchup/" , useHandler $ static "." )
, (match "/auth" , useHandler $ basicAuth [("a","b")] "test" handle )
, (match "/" , useHandler $ handle )
]
main = do listenHTTP "*" 8080 router
|
Hamcha/ketchup
|
example.hs
|
mit
| 1,468 | 0 | 11 | 492 | 409 | 221 | 188 | 32 | 1 |
import Graphics.Rendering.OpenGL as GL
import Graphics.UI.GLFW as GLFW
import Graphics.Rendering.OpenGL (($=))
import Data.IORef
import Control.Monad
import System.Environment (getArgs, getProgName)
data Action = Action (IO Action)
main = do
-- invoke either active or passive drawing loop depending on command line argument
args <- getArgs
prog <- getProgName
case args of
["active"] -> putStrLn "Running in active mode" >> main' active
["passive"] -> putStrLn "Running in passive mode" >> main' passive
_ -> putStrLn $ "USAGE: " ++ prog ++ " [active|passive]"
main' run = do
GLFW.initialize
-- open window
GLFW.openWindow (GL.Size 400 400) [GLFW.DisplayAlphaBits 8] GLFW.Window
GLFW.windowTitle $= "GLFW Demo"
GL.shadeModel $= GL.Smooth
-- enable antialiasing
GL.lineSmooth $= GL.Enabled
GL.blend $= GL.Enabled
GL.blendFunc $= (GL.SrcAlpha, GL.OneMinusSrcAlpha)
GL.lineWidth $= 1.5
-- set the color to clear background
GL.clearColor $= Color4 0 0 0 0
-- set 2D orthogonal view inside windowSizeCallback because
-- any change to the Window size should result in different
-- OpenGL Viewport.
GLFW.windowSizeCallback $= \ size@(GL.Size w h) ->
do
GL.viewport $= (GL.Position 0 0, size)
GL.matrixMode $= GL.Projection
GL.loadIdentity
GL.ortho2D 0 (realToFrac w) (realToFrac h) 0
-- keep all line strokes as a list of points in an IORef
lines <- newIORef []
-- run the main loop
run lines
-- finish up
GLFW.closeWindow
GLFW.terminate
-- we start with waitForPress action
active lines = loop waitForPress
where
loop action = do
-- draw the entire screen
render lines
-- swap buffer
GLFW.swapBuffers
-- check whether ESC is pressed for termination
p <- GLFW.getKey GLFW.ESC
unless (p == GLFW.Press) $
do
-- perform action
Action action' <- action
-- sleep for 1ms to yield CPU to other applications
GLFW.sleep 0.001
-- only continue when the window is not closed
windowOpen <- getParam Opened
unless (not windowOpen) $
loop action' -- loop with next action
waitForPress = do
b <- GLFW.getMouseButton GLFW.ButtonLeft
case b of
GLFW.Release -> return (Action waitForPress)
GLFW.Press -> do
-- when left mouse button is pressed, add the point
-- to lines and switch to waitForRelease action.
(GL.Position x y) <- GL.get GLFW.mousePos
modifyIORef lines (((x,y):) . ((x,y):))
return (Action waitForRelease)
waitForRelease = do
-- keep track of mouse movement while waiting for button
-- release
(GL.Position x y) <- GL.get GLFW.mousePos
-- update the line with new ending position
modifyIORef lines (((x,y):) . tail)
b <- GLFW.getMouseButton GLFW.ButtonLeft
case b of
-- when button is released, switch back back to
-- waitForPress action
GLFW.Release -> return (Action waitForPress)
GLFW.Press -> return (Action waitForRelease)
passive lines = do
-- disable auto polling in swapBuffers
GLFW.disableSpecial GLFW.AutoPollEvent
-- keep track of whether ESC has been pressed
quit <- newIORef False
-- keep track of whether screen needs to be redrawn
dirty <- newIORef True
-- mark screen dirty in refresh callback which is often called
-- when screen or part of screen comes into visibility.
GLFW.windowRefreshCallback $= writeIORef dirty True
-- use key callback to track whether ESC is pressed
GLFW.keyCallback $= \k s ->
when (fromEnum k == fromEnum GLFW.ESC && s == GLFW.Press) $
writeIORef quit True
-- Terminate the program if the window is closed
GLFW.windowCloseCallback $= (writeIORef quit True >> return True)
-- by default start with waitForPress
waitForPress dirty
loop dirty quit
where
loop dirty quit = do
GLFW.waitEvents
-- redraw screen if dirty
d <- readIORef dirty
when d $
render lines >> GLFW.swapBuffers
writeIORef dirty False
-- check if we need to quit the loop
q <- readIORef quit
unless q $
loop dirty quit
waitForPress dirty =
do
--GLFW.mousePosCallback $= \_ -> return ()
GLFW.mousePosCallback $= \s ->
when (True) $
do
-- when left mouse button is pressed, add the point
-- to lines and switch to waitForRelease action.
(GL.Position x y) <- GL.get GLFW.mousePos
modifyIORef lines (((x,y):) . ((x,y):))
waitForRelease dirty
GLFW.mouseButtonCallback $= \b s ->
when (b == GLFW.ButtonLeft && s == GLFW.Press) $
do
-- when left mouse button is pressed, add the point
-- to lines and switch to waitForRelease action.
(GL.Position x y) <- GL.get GLFW.mousePos
modifyIORef lines (((x,y):) . ((x,y):))
waitForRelease dirty
waitForRelease dirty =
do
GLFW.mousePosCallback $= \(Position x y) ->
do
-- update the line with new ending position
modifyIORef lines (((x,y):) . tail)
-- mark screen dirty
writeIORef dirty True
GLFW.mouseButtonCallback $= \b s ->
-- when left mouse button is released, switch back to
-- waitForPress action.
when (b == GLFW.ButtonLeft && s == GLFW.Release) $
waitForPress dirty
render lines = do
l <- readIORef lines
GL.clear [GL.ColorBuffer]
GL.color $ color3 1 0 0
GL.renderPrimitive GL.Lines $ mapM_
(\ (x, y) -> GL.vertex (vertex3 (fromIntegral x) (fromIntegral y) 0)) l
vertex3 :: GLfloat -> GLfloat -> GLfloat -> GL.Vertex3 GLfloat
vertex3 = GL.Vertex3
color3 :: GLfloat -> GLfloat -> GLfloat -> GL.Color3 GLfloat
color3 = GL.Color3
|
dragonly/HasCraft
|
test_mouse.hs
|
gpl-2.0
| 6,114 | 4 | 17 | 1,832 | 1,493 | 741 | 752 | 114 | 3 |
{-# LANGUAGE OverloadedStrings #-}
{-| Implementation of the Ganeti confd server functionality.
-}
{-
Copyright (C) 2013 Google Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
-}
module Ganeti.Monitoring.Server
( main
, checkMain
, prepMain
) where
import Control.Applicative
import Control.Monad
import Control.Monad.IO.Class
import Data.ByteString.Char8 hiding (map, filter, find)
import Data.List
import qualified Data.Map as Map
import Snap.Core
import Snap.Http.Server
import qualified Text.JSON as J
import Control.Concurrent
import qualified Ganeti.BasicTypes as BT
import Ganeti.Daemon
import qualified Ganeti.DataCollectors.CPUload as CPUload
import qualified Ganeti.DataCollectors.Diskstats as Diskstats
import qualified Ganeti.DataCollectors.Drbd as Drbd
import qualified Ganeti.DataCollectors.InstStatus as InstStatus
import qualified Ganeti.DataCollectors.Lv as Lv
import Ganeti.DataCollectors.Types
import qualified Ganeti.Constants as C
import Ganeti.Runtime
-- * Types and constants definitions
-- | Type alias for checkMain results.
type CheckResult = ()
-- | Type alias for prepMain results.
type PrepResult = Config Snap ()
-- | Version of the latest supported http API.
latestAPIVersion :: Int
latestAPIVersion = C.mondLatestApiVersion
-- | A report of a data collector might be stateful or stateless.
data Report = StatelessR (IO DCReport)
| StatefulR (Maybe CollectorData -> IO DCReport)
-- | Type describing a data collector basic information
data DataCollector = DataCollector
{ dName :: String -- ^ Name of the data collector
, dCategory :: Maybe DCCategory -- ^ Category (storage, instance, ecc)
-- of the collector
, dKind :: DCKind -- ^ Kind (performance or status reporting) of
-- the data collector
, dReport :: Report -- ^ Report produced by the collector
, dUpdate :: Maybe (Maybe CollectorData -> IO CollectorData)
-- ^ Update operation for stateful collectors.
}
-- | The list of available builtin data collectors.
collectors :: [DataCollector]
collectors =
[ DataCollector Diskstats.dcName Diskstats.dcCategory Diskstats.dcKind
(StatelessR Diskstats.dcReport) Nothing
, DataCollector Drbd.dcName Drbd.dcCategory Drbd.dcKind
(StatelessR Drbd.dcReport) Nothing
, DataCollector InstStatus.dcName InstStatus.dcCategory InstStatus.dcKind
(StatelessR InstStatus.dcReport) Nothing
, DataCollector Lv.dcName Lv.dcCategory Lv.dcKind
(StatelessR Lv.dcReport) Nothing
, DataCollector CPUload.dcName CPUload.dcCategory CPUload.dcKind
(StatefulR CPUload.dcReport) (Just CPUload.dcUpdate)
]
-- * Configuration handling
-- | The default configuration for the HTTP server.
defaultHttpConf :: FilePath -> FilePath -> Config Snap ()
defaultHttpConf accessLog errorLog =
setAccessLog (ConfigFileLog accessLog) .
setCompression False .
setErrorLog (ConfigFileLog errorLog) $
setVerbose False
emptyConfig
-- * Helper functions
-- | Check function for the monitoring agent.
checkMain :: CheckFn CheckResult
checkMain _ = return $ Right ()
-- | Prepare function for monitoring agent.
prepMain :: PrepFn CheckResult PrepResult
prepMain opts _ = do
accessLog <- daemonsExtraLogFile GanetiMond AccessLog
errorLog <- daemonsExtraLogFile GanetiMond ErrorLog
return .
setPort
(maybe C.defaultMondPort fromIntegral (optPort opts)) .
maybe id (setBind . pack) (optBindAddress opts)
$ defaultHttpConf accessLog errorLog
-- * Query answers
-- | Reply to the supported API version numbers query.
versionQ :: Snap ()
versionQ = writeBS . pack $ J.encode [latestAPIVersion]
-- | Version 1 of the monitoring HTTP API.
version1Api :: MVar CollectorMap -> Snap ()
version1Api mvar =
let returnNull = writeBS . pack $ J.encode J.JSNull :: Snap ()
in ifTop returnNull <|>
route
[ ("list", listHandler)
, ("report", reportHandler mvar)
]
-- | Get the JSON representation of a data collector to be used in the collector
-- list.
dcListItem :: DataCollector -> J.JSValue
dcListItem dc =
J.JSArray
[ J.showJSON $ dName dc
, maybe J.JSNull J.showJSON $ dCategory dc
, J.showJSON $ dKind dc
]
-- | Handler for returning lists.
listHandler :: Snap ()
listHandler =
dir "collectors" . writeBS . pack . J.encode $ map dcListItem collectors
-- | Handler for returning data collector reports.
reportHandler :: MVar CollectorMap -> Snap ()
reportHandler mvar =
route
[ ("all", allReports mvar)
, (":category/:collector", oneReport mvar)
] <|>
errorReport
-- | Return the report of all the available collectors.
allReports :: MVar CollectorMap -> Snap ()
allReports mvar = do
reports <- mapM (liftIO . getReport mvar) collectors
writeBS . pack . J.encode $ reports
-- | Takes the CollectorMap and a DataCollector and returns the report for this
-- collector.
getReport :: MVar CollectorMap -> DataCollector -> IO DCReport
getReport mvar collector =
case dReport collector of
StatelessR r -> r
StatefulR r -> do
colData <- getColData (dName collector) mvar
r colData
-- | Returns the data for the corresponding collector.
getColData :: String -> MVar CollectorMap -> IO (Maybe CollectorData)
getColData name mvar = do
m <- readMVar mvar
return $ Map.lookup name m
-- | Returns a category given its name.
-- If "collector" is given as the name, the collector has no category, and
-- Nothing will be returned.
catFromName :: String -> BT.Result (Maybe DCCategory)
catFromName "instance" = BT.Ok $ Just DCInstance
catFromName "storage" = BT.Ok $ Just DCStorage
catFromName "daemon" = BT.Ok $ Just DCDaemon
catFromName "hypervisor" = BT.Ok $ Just DCHypervisor
catFromName "default" = BT.Ok Nothing
catFromName _ = BT.Bad "No such category"
errorReport :: Snap ()
errorReport = do
modifyResponse $ setResponseStatus 404 "Not found"
writeBS "Unable to produce a report for the requested resource"
error404 :: Snap ()
error404 = do
modifyResponse $ setResponseStatus 404 "Not found"
writeBS "Resource not found"
-- | Return the report of one collector.
oneReport :: MVar CollectorMap -> Snap ()
oneReport mvar = do
categoryName <- fmap (maybe mzero unpack) $ getParam "category"
collectorName <- fmap (maybe mzero unpack) $ getParam "collector"
category <-
case catFromName categoryName of
BT.Ok cat -> return cat
BT.Bad msg -> fail msg
collector <-
case
find (\col -> collectorName == dName col) $
filter (\c -> category == dCategory c) collectors of
Just col -> return col
Nothing -> fail "Unable to find the requested collector"
dcr <- liftIO $ getReport mvar collector
writeBS . pack . J.encode $ dcr
-- | The function implementing the HTTP API of the monitoring agent.
monitoringApi :: MVar CollectorMap -> Snap ()
monitoringApi mvar =
ifTop versionQ <|>
dir "1" (version1Api mvar) <|>
error404
-- | The function collecting data for each data collector providing a dcUpdate
-- function.
collect :: CollectorMap -> DataCollector -> IO CollectorMap
collect m collector =
case dUpdate collector of
Nothing -> return m
Just update -> do
let name = dName collector
existing = Map.lookup name m
new_data <- update existing
return $ Map.insert name new_data m
-- | Invokes collect for each data collector.
collection :: CollectorMap -> IO CollectorMap
collection m = foldM collect m collectors
-- | The thread responsible for the periodical collection of data for each data
-- data collector.
collectord :: MVar CollectorMap -> IO ()
collectord mvar = do
m <- takeMVar mvar
m' <- collection m
putMVar mvar m'
threadDelay $ 10^(6 :: Int) * C.mondTimeInterval
collectord mvar
-- | Main function.
main :: MainFn CheckResult PrepResult
main _ _ httpConf = do
mvar <- newMVar Map.empty
_ <- forkIO $ collectord mvar
httpServe httpConf . method GET $ monitoringApi mvar
|
badp/ganeti
|
src/Ganeti/Monitoring/Server.hs
|
gpl-2.0
| 8,714 | 0 | 14 | 1,772 | 1,909 | 974 | 935 | 166 | 3 |
module Handler.Wishlist where
import Text.Julius (juliusFile, rawJS)
import Import
import Types (Priority (..))
import Util.Widgets (getSortValue, sortWidget, sortListByOption)
-- | A 'Book' 'Entity' & 'WishlistItem' 'Entity' packed into a Tuple.
type WishlistItemAndBook = (Entity Book, Entity WishlistItem)
-- | Show the WishlistItems & a form to add Books.
getWishlistR :: Text -> Handler Html
getWishlistR name = do
(wishlistId, wishlist, booksAndItems, otherLists) <- getStandardWishlistData name
(addBookWidget, addBookEnctype) <- generateFormPost wishlistItemForm
defaultLayout $ do
setTitle $ toHtml $ wishlistName wishlist `mappend` " Wishlist"
toWidget $(juliusFile "templates/wishlist/wishlistGet.julius")
$(widgetFile "wishlist/wishlist")
-- | Process the addition of new Books to the Wishlist.
postWishlistR :: Text -> Handler Html
postWishlistR name = do
(wishlistId, wishlist, booksAndItems, otherLists) <- getStandardWishlistData name
((result, addBookWidget), addBookEnctype) <- runFormPost wishlistItemForm
case result of
FormSuccess formInstance -> do
bookid <- fromMaybe (error "create failed") <$>
createBookFromIsbn (fst formInstance)
mLibraryItem <- runDB $ getBy $ UniqueLibraryBook bookid
when (isJust mLibraryItem) $ do
setMessage "That book is already in your Library"
redirect $ WishlistR name
mItem <- runDB $ getBy $ WishlistBook wishlistId bookid
case mItem of
Just _ -> setMessage "That Book is already in your Wishlist"
Nothing -> runDB (insert $ WishlistItem bookid wishlistId
$ snd formInstance)
>> setMessage "Added Book to your Wishlist"
redirect $ WishlistR name
_ -> defaultLayout $ do
setTitle $ toHtml $ wishlistName wishlist `mappend` " Wishlist"
$(widgetFile "wishlist/wishlist")
-- | Retrieve variables used in both GET & POST requests
getStandardWishlistData :: Text
-> Handler (Key Wishlist, Wishlist,
[WishlistItemAndBook], [Entity Wishlist])
getStandardWishlistData name = do
sortVal <- getSortValue "priority"
Entity listId list <- runDB . getBy404 $ UniqueWishlistName name
booksAndItems <- sortWishlist sortVal <$> getBooksInWishlist listId
otherLists <- runDB $ selectList [WishlistName !=. name] []
return (listId, list, booksAndItems, otherLists)
where sortWishlist = sortListByOption wishlistSortingOptions
-- | Render a dropdown button group for modifying a 'WishlistItemPriority'.
priorityDropdownWidget :: WishlistItemId -> Priority -> Text -> Widget
priorityDropdownWidget itemId priority btnColorClass =
let otherPriorities = filter (/= priority)
[Highest, High, Medium, Low, Lowest]
in $(widgetFile "wishlist/priorityDropdown")
-- | Display a Dropdown Button to Select a Wishlist Sorting Option.
wishlistSortWidget :: Widget
wishlistSortWidget = sortWidget wishlistSortingOptions
-- | Return the GET Value, Name & Sorting Function for Library Sort Types.
wishlistSortingOptions :: [(Text, Text,
WishlistItemAndBook -> WishlistItemAndBook ->
Ordering)]
wishlistSortingOptions =
[ ("priority", "Priority", flipComparing $ wishlistItemPriority . getItem)
, ("name", "Name (A-Z)", comparing $ bookTitle . getBook)
, ("name-reverse", "Name (Z-A)", flipComparing $ bookTitle . getBook)
]
where getBook (Entity _ b, _) = b
getItem (_, Entity _ i) = i
|
prikhi/MyBookList
|
Handler/Wishlist.hs
|
gpl-3.0
| 3,869 | 0 | 20 | 1,079 | 827 | 424 | 403 | -1 | -1 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
module Sepa.BillingConcept
( -- BillingConcept
mkBillingConcept,
BillingConcept, BillingConceptId,
shortName,
longName,
basePrice,
vatRatio,
finalPrice,
validBillingConcept,
priceToText,
setBasePrice
) where
import ClassyPrelude
import Control.Lens ((^.), (&), (.~))
import qualified Control.Lens as L (Conjoined, Contravariant)
import qualified Control.Lens.Getter as L (to)
import qualified Database.Persist.Quasi as DB (upperCaseSettings)
import qualified Database.Persist.TH as DB (mkPersist, mpsGenerateLenses,
mpsPrefixFields, persistFileWith,
share)
import Sepa.MongoSettings
-- WARNING: the use of lenses (setters) can violate the invariants of the Abstract Data
-- Types in this module.
DB.share [DB.mkPersist mongoSettings { DB.mpsGenerateLenses = True
, DB.mpsPrefixFields = False }]
$(DB.persistFileWith DB.upperCaseSettings "Sepa/BillingConcept.persistent")
-- Billing concepts
mkBillingConcept :: Text -> Text -> Maybe Int -> Maybe Int -> BillingConcept
mkBillingConcept short long price vat =
assert (validBillingConcept short long price vat)
-- We set defaults for basePrice and vatRatio, if not given
$ BillingConcept short long (fromMaybe 0 price) (fromMaybe 21 vat)
validBillingConcept :: Text -> Text -> Maybe Int -> Maybe Int -> Bool
validBillingConcept short long price vat =
not (null short) && length short <= maxLengthShortName
&& length long <= maxLengthLongName
&& fromMaybe 0 price >= 0
&& fromMaybe 0 vat >= 0
where maxLengthShortName = 10 -- To be able to concat many of them in a line
maxLengthLongName = 70 -- GUI constraint
-- | Getter for basePrice * vatRatio.
finalPrice :: (Functor f, L.Contravariant f, L.Conjoined p) =>
p Int (f Int) -> p BillingConcept (f BillingConcept)
finalPrice = L.to _finalPrice
_finalPrice :: BillingConcept -> Int
_finalPrice concept = concept ^. basePrice + vat
where vat = round $ toRational (concept ^. basePrice * concept ^. vatRatio) / 100
-- | Helper function to convert any non-negative Int representing an amount * 100 (all
-- across this module money amounts are stored in this way to avoid fractional digits) to
-- text with two fractional digits.
priceToText :: Int -> Text
priceToText amount = assert (amount >= 0) $ pack amountWithFractional
where amountReversed = (reverse . show) amount
amountWithFractional = case amountReversed of
x : [] -> "0.0" ++ [x]
x : y : [] -> "0." ++ (y : [x])
x : y : z : [] -> z : '.' : y : [x]
x : y : l -> reverse l ++ ('.' : y : [x])
_ -> error "priceToText: show has returned empty list for a number"
setBasePrice :: Int -> BillingConcept -> BillingConcept
setBasePrice price bc = bc & basePrice .~ price
|
gmarpons/sepa-debits
|
Sepa/BillingConcept.hs
|
gpl-3.0
| 3,271 | 0 | 15 | 920 | 744 | 408 | 336 | 58 | 5 |
module Sites.Batoto
( batoto
) where
import Network.HTTP.Types.URI (decodePathSegments)
import Data.List (isInfixOf)
import Text.XML.HXT.Core
import qualified Data.Text as T
import qualified Data.ByteString.Lazy.UTF8 as UL
import qualified Data.ByteString.UTF8 as US
import qualified Network.HTTP.Conduit as CH
import Data.Time.Clock
import Data.Time.Calendar
import Control.Monad
import Control.Monad.IO.Class
import Pipes (Pipe)
-- Local imports
import Types
import Sites.Util
import Interpreter
-- Tagsoup
import Text.XML.HXT.TagSoup
-- Safehead
import Safe
--
-- Batoto
--
batoto = Comic
{ comicName = "Batoto"
, seedPage = error "Please specify a Batoto comic."
, seedCache = Always
, pageParse = batotoPageParse
, cookies = [batotoCookie]
}
batotoPageParse :: Pipe ReplyType FetchType IO ()
batotoPageParse = runWebFetchT $ do
debug "Parsing index page"
html <- fetchSeedpage
let doc = readString [withParseHTML yes, withWarnings no, withTagSoup] $ UL.toString html
story <- liftIO (runX $ doc //> storyName)
volChpPageP <- liftIO (runX $ doc //> volChpPage)
-- Do we have any comic we want to store to disk?
debug "Story"
mapM_ (liftIO . print) story
debug "Vol Chp Pages"
mapM_ (liftIO . print) volChpPageP
-- Parse the Vol/Chp
let next = map (\(a, b) -> (a, volChpParse "batoto" (headMay story) b)) volChpPageP
debug "Parse First Page"
forM_ next (\(url, ct) -> do
debug url
html' <- fetchWebpage [(url, Always)]
let doc' = readString [withParseHTML yes, withWarnings no, withTagSoup] $ UL.toString html'
img <- liftIO (runX $ doc' //> comic)
otherPagesP <- liftIO (runX $ doc' >>> otherPages)
-- Do we have any comic we want to store to disk?
debug "img url"
mapM_ (liftIO . print) img
debug "Next pages"
mapM_ (liftIO . print) otherPagesP
debug "Fetch image"
forM_ img (\url' -> fetchImage url' (comicTagFileName ct url'))
debug "Fetch next pages"
forM_ otherPagesP (\url' -> do
debug url
html'' <- fetchWebpage [(url', Always)]
let doc'' = readString [withParseHTML yes, withWarnings no, withTagSoup] $ UL.toString html''
img' <- liftIO (runX $ doc'' //> comic)
-- Do we have any comic we want to store to disk?
debug "img url"
mapM_ (liftIO . print) img'
forM_ img' (\url'' -> fetchImage url'' (comicTagFileName ct url''))
)
)
where
storyName = hasName "h1" >>> hasAttrValue "class" ((==) "ipsType_pagetitle") /> getText >>> arr textStrip
volChpPage =
hasName "table"
>>> hasAttrValue "class" (isInfixOf "chapters_list")
//> hasName "tr"
>>> hasAttrValue "class" (isInfixOf "lang_English")
//> (hasName "a" `containing` (getChildren >>> hasName "img"))
>>> (
(getAttrValue "href")
&&&
(getChildren >>> getText >>> arr textStrip)
)
textStrip :: String -> String
textStrip = T.unpack . T.strip . T.pack
otherPages =
(getChildren
//> hasName "select"
>>> hasAttrValue "id" ((==) "page_select"))
-- Drop the rest
>. head
>>> getChildren
>>> hasName "option"
>>> ifA (hasAttr "selected") none (getAttrValue "value")
comic = hasName "img" >>> hasAttrValue "id" ((==) "comic_page") >>> getAttrValue "src"
comicTagFileName ct url = ct{ctFileName = Just $ last $ decodePathSegments $ US.fromString url}
--
-- Custom cookie jar for Batoto to only display english
--
-- TODO: Create a way for us to have per site rules for (auth/cookies/etc)
past :: UTCTime
past = UTCTime (ModifiedJulianDay 56000) (secondsToDiffTime 0) -- 2012-03-14
future :: UTCTime
future = UTCTime (ModifiedJulianDay 60000) (secondsToDiffTime 0) -- 2023-02-25
batotoCookie :: CH.Cookie
batotoCookie = CH.Cookie
{ CH.cookie_name = US.fromString "lang_option"
, CH.cookie_value = US.fromString "English"
, CH.cookie_domain = US.fromString ".batoto.net"
, CH.cookie_path = US.fromString "/"
, CH.cookie_expiry_time = future
, CH.cookie_creation_time = past
, CH.cookie_last_access_time = past
, CH.cookie_persistent = True
, CH.cookie_host_only = False
, CH.cookie_secure_only = False
, CH.cookie_http_only = False
}
|
pharaun/hComicFetcher
|
src/Sites/Batoto.hs
|
gpl-3.0
| 4,487 | 0 | 24 | 1,163 | 1,239 | 654 | 585 | -1 | -1 |
module LinkedList
( LinkedList
, datum
, fromList
, isNil
, new
, next
, nil
, reverseLinkedList
, toList
) where
data LinkedList a = Nil | Cons a (LinkedList a)
datum :: LinkedList a -> a
datum (Cons a _) = a
datum Nil = undefined
fromList :: [a] -> LinkedList a
fromList (x : xs) = Cons x $ fromList xs
fromList [] = Nil
isNil :: LinkedList a -> Bool
isNil Nil = True
isNil _ = False
new :: a -> LinkedList a -> LinkedList a
new a xs = Cons a xs
next :: LinkedList a -> LinkedList a
next (Cons _ rest) = rest
next Nil = Nil
nil :: LinkedList a
nil = Nil
reverseLinkedList :: LinkedList a -> LinkedList a
reverseLinkedList xs = revAcc xs Nil where
revAcc :: LinkedList a -> LinkedList a -> LinkedList a
revAcc (Cons a rest) acc = revAcc rest $ Cons a acc
revAcc Nil acc = acc
toList :: LinkedList a -> [a]
toList (Cons a rest) = a : (toList rest)
toList Nil = []
|
daewon/til
|
exercism/haskell/simple-linked-list/src/LinkedList.hs
|
mpl-2.0
| 919 | 0 | 9 | 237 | 397 | 202 | 195 | 35 | 2 |
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RankNTypes, ExistentialQuantification #-}
module FoldingThroughAFixedPoint where
import Control.Applicative
-- Consider the two following types
newtype Least f
= Least (forall r . (f r -> r) -> r)
--
data Greatest f
= forall s . Greatest (s -> f s) s
--
-- They each have a special non-recursive relationship with 'f' when
-- it is a 'Functor'
unwrap :: Functor f => Greatest f -> f (Greatest f)
unwrap (Greatest u s) = Greatest u <$> u s
wrap :: Functor f => f (Least f) -> Least f
wrap f = Least (\k -> k (fold k <$> f))
-- They each are closely tied to the notions of folding and unfolding
-- as well
fold :: (f r -> r) -> (Least f -> r)
fold k (Least g) = g k
unfold :: (s -> f s) -> (s -> Greatest f)
unfold = Greatest
-- It is the case that any "strictly positive"
-- type in Haskell is representable using Least.
-- We first need the data type's "signature functor".
-- For instance, here is one for []
data ListF a x = Nil | Cons a x deriving Functor
-- Then we can map into and out of lists
listLeast :: [a] -> Least (ListF a)
listLeast l = Least $ \k -> k $ case l of
[] -> Nil
a : as -> Cons a (fold k (listLeast as))
--
leastList :: Least (ListF a) -> [a]
leastList = fold $ \case
Nil -> []
Cons a as -> a : as
--
-- It is also the case that these types are representable using
-- Greatest.
listGreatest :: [a] -> Greatest (ListF a)
listGreatest = unfold $ \case
[] -> Nil
a : as -> Cons a as
--
greatestList :: Greatest (ListF a) -> [a]
greatestList (Greatest u s) = case u s of
Nil -> []
Cons a s' -> a : greatestList (unfold u s')
--
-- Given all of these types are isomorphic, we ought to be able to go
-- directly from least to greatest fixed points and visa versa. Can
-- you write the functions which witness this last isomorphism
-- generally for any functor?
greatestLeast :: Functor f => Greatest f -> Least f
greatestLeast = intermediate2L . g2Intermediate
leastGreatest :: Functor f => Least f -> Greatest f
leastGreatest = intermediate2G . l2Intermediate
newtype Intermediate f = Intermediate {
unIntermediate :: f (Intermediate f)
}
--
g2Intermediate :: Functor f => Greatest f -> Intermediate f
g2Intermediate (Greatest f a) = ana f a
where ana f = Intermediate . (ana f <$>) . f
--
intermediate2L :: Functor f => Intermediate f -> Least f
intermediate2L x = Least $ \f -> cata f x
where cata f = f . (cata f <$>) . unIntermediate
--
l2Intermediate :: Least f -> Intermediate f
l2Intermediate (Least k) = k Intermediate
intermediate2G :: Intermediate f -> Greatest f
intermediate2G = Greatest unIntermediate
|
ice1000/OI-codes
|
codewars/1-100/folding-through-a-fixed-point.hs
|
agpl-3.0
| 2,677 | 0 | 15 | 580 | 858 | 448 | 410 | 50 | 2 |
--------------------------------------------------------------------------------
-- $Id: SwishTest.hs,v 1.10 2004/01/06 13:53:10 graham Exp $
--
-- Copyright (c) 2003, G. KLYNE. All rights reserved.
-- See end of this file for licence information.
--------------------------------------------------------------------------------
-- |
-- Module : SwishTest
-- Copyright : (c) 2003, Graham Klyne
-- License : GPL V2
--
-- Maintainer : Graham Klyne
-- Stability : provisional
-- Portability : H98
--
-- SwishTest: Test cases for Swish program.
--
--------------------------------------------------------------------------------
-- WNH RIP OUT module Swish.HaskellRDF.SwishTest where
import System.Exit
import System.Time
import Test.HUnit
( Test(..), Assertable(..),
assertEqual, runTestTT, runTestText, putTextToHandle )
import Swish.HaskellRDF.SwishMain
------------------------------------------------------------
-- Interactive test cases
------------------------------------------------------------
testSwish :: String -> IO Bool
testSwish cmdline =
do { exitcode <- runSwish cmdline
-- ; putStr $ "Exit status: "++(show exitcode)
; return $ exitcode == ExitSuccess
}
swishTestCase :: String -> Test
swishTestCase cmdline = TestCase ( assert $ testSwish cmdline )
test1 = runSwish "-?"
test2 = runSwish "-!not=validcommand"
test3 = swishTestCase "-i=Data/N3TestGenReport.n3"
test4 = swishTestCase "-i=Data/sbp-data.n3"
test5 = swishTestCase "-i=Data/Simple.n3 "
test6 = swishTestCase "-i=Data/Simple.n3 -o=Data/Simple.tmp"
test7 = swishTestCase "-i=Data/Simple.n3 -c=Data/Simple.n3"
test8 = swishTestCase "-i=Data/Simple.n3 -c=Data/Simple.tmp"
test9 = swishTestCase "-i=Data/Simple.tmp -c=Data/Simple.tmp"
test10a = swishTestCase "-i=Data/Simple3.n3"
test10b = swishTestCase "-i=Data/Simple3.n3 -o"
test10 = swishTestCase "-i=Data/Simple3.n3 -o=Data/Simple3.tmp"
test11 = swishTestCase "-i=Data/Simple3.n3 -c=Data/Simple3.n3"
test12 = swishTestCase "-i=Data/Simple3.n3 -c=Data/Simple3.tmp"
test13 = swishTestCase "-i=Data/Simple3.tmp -c=Data/Simple3.tmp"
test20a = swishTestCase "-i=Data/N3TestGenReport.n3"
test20b = swishTestCase "-i=Data/N3TestGenReport.n3 -o"
test20 = swishTestCase "-i=Data/N3TestGenReport.n3 -o=Data/N3TestGenReport.tmp"
test21 = swishTestCase "-i=Data/N3TestGenReport.n3 -c=Data/N3TestGenReport.n3"
test22 = swishTestCase "-i=Data/N3TestGenReport.n3 -c=Data/N3TestGenReport.tmp"
test23 = swishTestCase "-i=Data/N3TestGenReport.tmp -c=Data/N3TestGenReport.tmp"
test30 = swishTestCase "-i=Data/Merge1.n3 -m=Data/Merge2.n3 -c=Data/Merge3.n3"
test31 = swishTestCase "-s=Swishtest.ss"
tests1a = swishTestCase "-i=Data/Simple2.n3 -o=Data/Simple2.tmp"
tests1b = swishTestCase "-i=Data/Simple2.n3 -c=Data/Simple2.tmp"
allTests = TestList
[ test3
, test4
, test5
, test6
, test7
, test8
, test9
, test10
, test11
, test12
, test13
, tests1a
, tests1b
, test20
, test21
, test22
, test23
, test30
, test31
]
runTest t =
do { st <- getClockTime
; putStr $ "Test started: "++show st++"\n"
; runTestTT t
; ft <- getClockTime
; putStr $ "Test finished: "++show ft++"\n"
; let et = diffClockTimes ft st
; return et
; putStr $ "Test duration: "++show et++"\n"
}
testAll = runTest allTests
tt = runTest
t20a = runTest test20a
t20b = runTest test20b
main = testAll
--------------------------------------------------------------------------------
--
-- Copyright (c) 2003, G. KLYNE. All rights reserved.
--
-- This file is part of Swish.
--
-- Swish is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- Swish is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with Swish; if not, write to:
-- The Free Software Foundation, Inc.,
-- 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--
--------------------------------------------------------------------------------
-- $Source: /file/cvsdev/HaskellRDF/SwishTest.hs,v $
-- $Author: graham $
-- $Revision: 1.10 $
-- $Log: SwishTest.hs,v $
-- Revision 1.10 2004/01/06 13:53:10 graham
-- Created consolidated test harness (SwishTestAll.hs)
--
-- Revision 1.9 2003/09/24 18:50:53 graham
-- Revised module format to be Haddock compatible.
--
-- Revision 1.8 2003/06/03 19:24:13 graham
-- Updated all source modules to cite GNU Public Licence
--
-- Revision 1.7 2003/05/29 11:53:31 graham
-- Juggle Swish code: SwishMain.hs is main program logic, with
-- Swish.hs and SwishTest.hs being alternative "Main" modules for
-- the real program and test harness respectively.
--
-- Revision 1.6 2003/05/29 10:49:08 graham
-- Added and tested merge option (-m) for Swish program
--
-- Revision 1.5 2003/05/29 01:50:56 graham
-- More performance tuning, courtesy of GHC profiler.
-- All modules showing reasonable performance now.
--
-- Revision 1.4 2003/05/29 00:57:37 graham
-- Resolved swish performance problem, which turned out to an inefficient
-- method used by the parser to add arcs to a graph.
--
-- Revision 1.3 2003/05/28 19:57:50 graham
-- Adjusting code to compile with GHC
--
-- Revision 1.2 2003/05/28 17:39:30 graham
-- Trying to track down N3 formatter performance problem.
--
-- Revision 1.1 2003/05/23 00:03:55 graham
-- Added HUnit test module for swish program.
-- Greatly enhanced N3Formatter tests
--
|
amccausl/Swish
|
Swish/HaskellRDF/SwishTest.hs
|
lgpl-2.1
| 6,093 | 0 | 10 | 1,207 | 618 | 366 | 252 | 71 | 1 |
module Main ( main )
where
------------------------------------------------------------------------------
import Test.Framework ( defaultMain )
------------------------------------------------------------------------------
import Control.Concurrent.Barrier.Test ( tests )
------------------------------------------------------------------------------
main :: IO ()
main = defaultMain tests
|
aartamonau/haskell-barrier
|
tests/test.hs
|
lgpl-3.0
| 403 | 0 | 6 | 40 | 52 | 32 | 20 | 5 | 1 |
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Fadno.MusicXml.MusicXml30 where
import GHC.Generics
import Data.Data
import Data.Decimal
import Data.String
import Fadno.Xml.EmitXml
import qualified Fadno.Xml.XParse as P
import qualified Control.Applicative as P
import Control.Applicative ((<|>))
import qualified Control.Arrow as A
-- | @xs:ID@ /(simple)/
newtype ID = ID { iD :: NCName }
deriving (Eq,Typeable,Generic,Ord,IsString)
instance Show ID where show (ID a) = show a
instance Read ID where readsPrec i = map (A.first ID) . readsPrec i
instance EmitXml ID where
emitXml = emitXml . iD
parseID :: String -> P.XParse ID
parseID = return . fromString
-- | @xs:IDREF@ /(simple)/
newtype IDREF = IDREF { iDREF :: NCName }
deriving (Eq,Typeable,Generic,Ord,IsString)
instance Show IDREF where show (IDREF a) = show a
instance Read IDREF where readsPrec i = map (A.first IDREF) . readsPrec i
instance EmitXml IDREF where
emitXml = emitXml . iDREF
parseIDREF :: String -> P.XParse IDREF
parseIDREF = return . fromString
-- | @xs:NCName@ /(simple)/
newtype NCName = NCName { nCName :: Name }
deriving (Eq,Typeable,Generic,Ord,IsString)
instance Show NCName where show (NCName a) = show a
instance Read NCName where readsPrec i = map (A.first NCName) . readsPrec i
instance EmitXml NCName where
emitXml = emitXml . nCName
parseNCName :: String -> P.XParse NCName
parseNCName = return . fromString
-- | @xs:NMTOKEN@ /(simple)/
newtype NMTOKEN = NMTOKEN { nMTOKEN :: Token }
deriving (Eq,Typeable,Generic,Ord,IsString)
instance Show NMTOKEN where show (NMTOKEN a) = show a
instance Read NMTOKEN where readsPrec i = map (A.first NMTOKEN) . readsPrec i
instance EmitXml NMTOKEN where
emitXml = emitXml . nMTOKEN
parseNMTOKEN :: String -> P.XParse NMTOKEN
parseNMTOKEN = return . fromString
-- | @xs:Name@ /(simple)/
newtype Name = Name { name :: Token }
deriving (Eq,Typeable,Generic,Ord,IsString)
instance Show Name where show (Name a) = show a
instance Read Name where readsPrec i = map (A.first Name) . readsPrec i
instance EmitXml Name where
emitXml = emitXml . name
parseName :: String -> P.XParse Name
parseName = return . fromString
-- | @above-below@ /(simple)/
--
-- The above-below type is used to indicate whether one element appears above or below another element.
data AboveBelow =
AboveBelowAbove -- ^ /above/
| AboveBelowBelow -- ^ /below/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml AboveBelow where
emitXml AboveBelowAbove = XLit "above"
emitXml AboveBelowBelow = XLit "below"
parseAboveBelow :: String -> P.XParse AboveBelow
parseAboveBelow s
| s == "above" = return $ AboveBelowAbove
| s == "below" = return $ AboveBelowBelow
| otherwise = P.xfail $ "AboveBelow: " ++ s
-- | @accidental-value@ /(simple)/
--
-- The accidental-value type represents notated accidentals supported by MusicXML. In the MusicXML 2.0 DTD this was a string with values that could be included. The XSD strengthens the data typing to an enumerated list. The quarter- and three-quarters- accidentals are Tartini-style quarter-tone accidentals. The -down and -up accidentals are quarter-tone accidentals that include arrows pointing down or up. The slash- accidentals are used in Turkish classical music. The numbered sharp and flat accidentals are superscripted versions of the accidental signs, used in Turkish folk music. The sori and koron accidentals are microtonal sharp and flat accidentals used in Iranian and Persian music.
data AccidentalValue =
AccidentalValueSharp -- ^ /sharp/
| AccidentalValueNatural -- ^ /natural/
| AccidentalValueFlat -- ^ /flat/
| AccidentalValueDoubleSharp -- ^ /double-sharp/
| AccidentalValueSharpSharp -- ^ /sharp-sharp/
| AccidentalValueFlatFlat -- ^ /flat-flat/
| AccidentalValueNaturalSharp -- ^ /natural-sharp/
| AccidentalValueNaturalFlat -- ^ /natural-flat/
| AccidentalValueQuarterFlat -- ^ /quarter-flat/
| AccidentalValueQuarterSharp -- ^ /quarter-sharp/
| AccidentalValueThreeQuartersFlat -- ^ /three-quarters-flat/
| AccidentalValueThreeQuartersSharp -- ^ /three-quarters-sharp/
| AccidentalValueSharpDown -- ^ /sharp-down/
| AccidentalValueSharpUp -- ^ /sharp-up/
| AccidentalValueNaturalDown -- ^ /natural-down/
| AccidentalValueNaturalUp -- ^ /natural-up/
| AccidentalValueFlatDown -- ^ /flat-down/
| AccidentalValueFlatUp -- ^ /flat-up/
| AccidentalValueTripleSharp -- ^ /triple-sharp/
| AccidentalValueTripleFlat -- ^ /triple-flat/
| AccidentalValueSlashQuarterSharp -- ^ /slash-quarter-sharp/
| AccidentalValueSlashSharp -- ^ /slash-sharp/
| AccidentalValueSlashFlat -- ^ /slash-flat/
| AccidentalValueDoubleSlashFlat -- ^ /double-slash-flat/
| AccidentalValueSharp1 -- ^ /sharp-1/
| AccidentalValueSharp2 -- ^ /sharp-2/
| AccidentalValueSharp3 -- ^ /sharp-3/
| AccidentalValueSharp5 -- ^ /sharp-5/
| AccidentalValueFlat1 -- ^ /flat-1/
| AccidentalValueFlat2 -- ^ /flat-2/
| AccidentalValueFlat3 -- ^ /flat-3/
| AccidentalValueFlat4 -- ^ /flat-4/
| AccidentalValueSori -- ^ /sori/
| AccidentalValueKoron -- ^ /koron/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml AccidentalValue where
emitXml AccidentalValueSharp = XLit "sharp"
emitXml AccidentalValueNatural = XLit "natural"
emitXml AccidentalValueFlat = XLit "flat"
emitXml AccidentalValueDoubleSharp = XLit "double-sharp"
emitXml AccidentalValueSharpSharp = XLit "sharp-sharp"
emitXml AccidentalValueFlatFlat = XLit "flat-flat"
emitXml AccidentalValueNaturalSharp = XLit "natural-sharp"
emitXml AccidentalValueNaturalFlat = XLit "natural-flat"
emitXml AccidentalValueQuarterFlat = XLit "quarter-flat"
emitXml AccidentalValueQuarterSharp = XLit "quarter-sharp"
emitXml AccidentalValueThreeQuartersFlat = XLit "three-quarters-flat"
emitXml AccidentalValueThreeQuartersSharp = XLit "three-quarters-sharp"
emitXml AccidentalValueSharpDown = XLit "sharp-down"
emitXml AccidentalValueSharpUp = XLit "sharp-up"
emitXml AccidentalValueNaturalDown = XLit "natural-down"
emitXml AccidentalValueNaturalUp = XLit "natural-up"
emitXml AccidentalValueFlatDown = XLit "flat-down"
emitXml AccidentalValueFlatUp = XLit "flat-up"
emitXml AccidentalValueTripleSharp = XLit "triple-sharp"
emitXml AccidentalValueTripleFlat = XLit "triple-flat"
emitXml AccidentalValueSlashQuarterSharp = XLit "slash-quarter-sharp"
emitXml AccidentalValueSlashSharp = XLit "slash-sharp"
emitXml AccidentalValueSlashFlat = XLit "slash-flat"
emitXml AccidentalValueDoubleSlashFlat = XLit "double-slash-flat"
emitXml AccidentalValueSharp1 = XLit "sharp-1"
emitXml AccidentalValueSharp2 = XLit "sharp-2"
emitXml AccidentalValueSharp3 = XLit "sharp-3"
emitXml AccidentalValueSharp5 = XLit "sharp-5"
emitXml AccidentalValueFlat1 = XLit "flat-1"
emitXml AccidentalValueFlat2 = XLit "flat-2"
emitXml AccidentalValueFlat3 = XLit "flat-3"
emitXml AccidentalValueFlat4 = XLit "flat-4"
emitXml AccidentalValueSori = XLit "sori"
emitXml AccidentalValueKoron = XLit "koron"
parseAccidentalValue :: String -> P.XParse AccidentalValue
parseAccidentalValue s
| s == "sharp" = return $ AccidentalValueSharp
| s == "natural" = return $ AccidentalValueNatural
| s == "flat" = return $ AccidentalValueFlat
| s == "double-sharp" = return $ AccidentalValueDoubleSharp
| s == "sharp-sharp" = return $ AccidentalValueSharpSharp
| s == "flat-flat" = return $ AccidentalValueFlatFlat
| s == "natural-sharp" = return $ AccidentalValueNaturalSharp
| s == "natural-flat" = return $ AccidentalValueNaturalFlat
| s == "quarter-flat" = return $ AccidentalValueQuarterFlat
| s == "quarter-sharp" = return $ AccidentalValueQuarterSharp
| s == "three-quarters-flat" = return $ AccidentalValueThreeQuartersFlat
| s == "three-quarters-sharp" = return $ AccidentalValueThreeQuartersSharp
| s == "sharp-down" = return $ AccidentalValueSharpDown
| s == "sharp-up" = return $ AccidentalValueSharpUp
| s == "natural-down" = return $ AccidentalValueNaturalDown
| s == "natural-up" = return $ AccidentalValueNaturalUp
| s == "flat-down" = return $ AccidentalValueFlatDown
| s == "flat-up" = return $ AccidentalValueFlatUp
| s == "triple-sharp" = return $ AccidentalValueTripleSharp
| s == "triple-flat" = return $ AccidentalValueTripleFlat
| s == "slash-quarter-sharp" = return $ AccidentalValueSlashQuarterSharp
| s == "slash-sharp" = return $ AccidentalValueSlashSharp
| s == "slash-flat" = return $ AccidentalValueSlashFlat
| s == "double-slash-flat" = return $ AccidentalValueDoubleSlashFlat
| s == "sharp-1" = return $ AccidentalValueSharp1
| s == "sharp-2" = return $ AccidentalValueSharp2
| s == "sharp-3" = return $ AccidentalValueSharp3
| s == "sharp-5" = return $ AccidentalValueSharp5
| s == "flat-1" = return $ AccidentalValueFlat1
| s == "flat-2" = return $ AccidentalValueFlat2
| s == "flat-3" = return $ AccidentalValueFlat3
| s == "flat-4" = return $ AccidentalValueFlat4
| s == "sori" = return $ AccidentalValueSori
| s == "koron" = return $ AccidentalValueKoron
| otherwise = P.xfail $ "AccidentalValue: " ++ s
-- | @accordion-middle@ /(simple)/
--
-- The accordion-middle type may have values of 1, 2, or 3, corresponding to having 1 to 3 dots in the middle section of the accordion registration symbol.
newtype AccordionMiddle = AccordionMiddle { accordionMiddle :: PositiveInteger }
deriving (Eq,Typeable,Generic,Ord,Bounded,Enum,Num,Real,Integral)
instance Show AccordionMiddle where show (AccordionMiddle a) = show a
instance Read AccordionMiddle where readsPrec i = map (A.first AccordionMiddle) . readsPrec i
instance EmitXml AccordionMiddle where
emitXml = emitXml . accordionMiddle
parseAccordionMiddle :: String -> P.XParse AccordionMiddle
parseAccordionMiddle = P.xread "AccordionMiddle"
-- | @xlink:actuate@ /(simple)/
data Actuate =
ActuateOnRequest -- ^ /onRequest/
| ActuateOnLoad -- ^ /onLoad/
| ActuateOther -- ^ /other/
| ActuateNone -- ^ /none/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml Actuate where
emitXml ActuateOnRequest = XLit "onRequest"
emitXml ActuateOnLoad = XLit "onLoad"
emitXml ActuateOther = XLit "other"
emitXml ActuateNone = XLit "none"
parseActuate :: String -> P.XParse Actuate
parseActuate s
| s == "onRequest" = return $ ActuateOnRequest
| s == "onLoad" = return $ ActuateOnLoad
| s == "other" = return $ ActuateOther
| s == "none" = return $ ActuateNone
| otherwise = P.xfail $ "Actuate: " ++ s
-- | @arrow-direction@ /(simple)/
--
-- The arrow-direction type represents the direction in which an arrow points, using Unicode arrow terminology.
data ArrowDirection =
ArrowDirectionLeft -- ^ /left/
| ArrowDirectionUp -- ^ /up/
| ArrowDirectionRight -- ^ /right/
| ArrowDirectionDown -- ^ /down/
| ArrowDirectionNorthwest -- ^ /northwest/
| ArrowDirectionNortheast -- ^ /northeast/
| ArrowDirectionSoutheast -- ^ /southeast/
| ArrowDirectionSouthwest -- ^ /southwest/
| ArrowDirectionLeftRight -- ^ /left right/
| ArrowDirectionUpDown -- ^ /up down/
| ArrowDirectionNorthwestSoutheast -- ^ /northwest southeast/
| ArrowDirectionNortheastSouthwest -- ^ /northeast southwest/
| ArrowDirectionOther -- ^ /other/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml ArrowDirection where
emitXml ArrowDirectionLeft = XLit "left"
emitXml ArrowDirectionUp = XLit "up"
emitXml ArrowDirectionRight = XLit "right"
emitXml ArrowDirectionDown = XLit "down"
emitXml ArrowDirectionNorthwest = XLit "northwest"
emitXml ArrowDirectionNortheast = XLit "northeast"
emitXml ArrowDirectionSoutheast = XLit "southeast"
emitXml ArrowDirectionSouthwest = XLit "southwest"
emitXml ArrowDirectionLeftRight = XLit "left right"
emitXml ArrowDirectionUpDown = XLit "up down"
emitXml ArrowDirectionNorthwestSoutheast = XLit "northwest southeast"
emitXml ArrowDirectionNortheastSouthwest = XLit "northeast southwest"
emitXml ArrowDirectionOther = XLit "other"
parseArrowDirection :: String -> P.XParse ArrowDirection
parseArrowDirection s
| s == "left" = return $ ArrowDirectionLeft
| s == "up" = return $ ArrowDirectionUp
| s == "right" = return $ ArrowDirectionRight
| s == "down" = return $ ArrowDirectionDown
| s == "northwest" = return $ ArrowDirectionNorthwest
| s == "northeast" = return $ ArrowDirectionNortheast
| s == "southeast" = return $ ArrowDirectionSoutheast
| s == "southwest" = return $ ArrowDirectionSouthwest
| s == "left right" = return $ ArrowDirectionLeftRight
| s == "up down" = return $ ArrowDirectionUpDown
| s == "northwest southeast" = return $ ArrowDirectionNorthwestSoutheast
| s == "northeast southwest" = return $ ArrowDirectionNortheastSouthwest
| s == "other" = return $ ArrowDirectionOther
| otherwise = P.xfail $ "ArrowDirection: " ++ s
-- | @arrow-style@ /(simple)/
--
-- The arrow-style type represents the style of an arrow, using Unicode arrow terminology. Filled and hollow arrows indicate polygonal single arrows. Paired arrows are duplicate single arrows in the same direction. Combined arrows apply to double direction arrows like left right, indicating that an arrow in one direction should be combined with an arrow in the other direction.
data ArrowStyle =
ArrowStyleSingle -- ^ /single/
| ArrowStyleDouble -- ^ /double/
| ArrowStyleFilled -- ^ /filled/
| ArrowStyleHollow -- ^ /hollow/
| ArrowStylePaired -- ^ /paired/
| ArrowStyleCombined -- ^ /combined/
| ArrowStyleOther -- ^ /other/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml ArrowStyle where
emitXml ArrowStyleSingle = XLit "single"
emitXml ArrowStyleDouble = XLit "double"
emitXml ArrowStyleFilled = XLit "filled"
emitXml ArrowStyleHollow = XLit "hollow"
emitXml ArrowStylePaired = XLit "paired"
emitXml ArrowStyleCombined = XLit "combined"
emitXml ArrowStyleOther = XLit "other"
parseArrowStyle :: String -> P.XParse ArrowStyle
parseArrowStyle s
| s == "single" = return $ ArrowStyleSingle
| s == "double" = return $ ArrowStyleDouble
| s == "filled" = return $ ArrowStyleFilled
| s == "hollow" = return $ ArrowStyleHollow
| s == "paired" = return $ ArrowStylePaired
| s == "combined" = return $ ArrowStyleCombined
| s == "other" = return $ ArrowStyleOther
| otherwise = P.xfail $ "ArrowStyle: " ++ s
-- | @backward-forward@ /(simple)/
--
-- The backward-forward type is used to specify repeat directions. The start of the repeat has a forward direction while the end of the repeat has a backward direction.
data BackwardForward =
BackwardForwardBackward -- ^ /backward/
| BackwardForwardForward -- ^ /forward/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml BackwardForward where
emitXml BackwardForwardBackward = XLit "backward"
emitXml BackwardForwardForward = XLit "forward"
parseBackwardForward :: String -> P.XParse BackwardForward
parseBackwardForward s
| s == "backward" = return $ BackwardForwardBackward
| s == "forward" = return $ BackwardForwardForward
| otherwise = P.xfail $ "BackwardForward: " ++ s
-- | @bar-style@ /(simple)/
--
-- The bar-style type represents barline style information. Choices are regular, dotted, dashed, heavy, light-light, light-heavy, heavy-light, heavy-heavy, tick (a short stroke through the top line), short (a partial barline between the 2nd and 4th lines), and none.
data BarStyle =
BarStyleRegular -- ^ /regular/
| BarStyleDotted -- ^ /dotted/
| BarStyleDashed -- ^ /dashed/
| BarStyleHeavy -- ^ /heavy/
| BarStyleLightLight -- ^ /light-light/
| BarStyleLightHeavy -- ^ /light-heavy/
| BarStyleHeavyLight -- ^ /heavy-light/
| BarStyleHeavyHeavy -- ^ /heavy-heavy/
| BarStyleTick -- ^ /tick/
| BarStyleShort -- ^ /short/
| BarStyleNone -- ^ /none/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml BarStyle where
emitXml BarStyleRegular = XLit "regular"
emitXml BarStyleDotted = XLit "dotted"
emitXml BarStyleDashed = XLit "dashed"
emitXml BarStyleHeavy = XLit "heavy"
emitXml BarStyleLightLight = XLit "light-light"
emitXml BarStyleLightHeavy = XLit "light-heavy"
emitXml BarStyleHeavyLight = XLit "heavy-light"
emitXml BarStyleHeavyHeavy = XLit "heavy-heavy"
emitXml BarStyleTick = XLit "tick"
emitXml BarStyleShort = XLit "short"
emitXml BarStyleNone = XLit "none"
parseBarStyle :: String -> P.XParse BarStyle
parseBarStyle s
| s == "regular" = return $ BarStyleRegular
| s == "dotted" = return $ BarStyleDotted
| s == "dashed" = return $ BarStyleDashed
| s == "heavy" = return $ BarStyleHeavy
| s == "light-light" = return $ BarStyleLightLight
| s == "light-heavy" = return $ BarStyleLightHeavy
| s == "heavy-light" = return $ BarStyleHeavyLight
| s == "heavy-heavy" = return $ BarStyleHeavyHeavy
| s == "tick" = return $ BarStyleTick
| s == "short" = return $ BarStyleShort
| s == "none" = return $ BarStyleNone
| otherwise = P.xfail $ "BarStyle: " ++ s
-- | @beam-level@ /(simple)/
--
-- The MusicXML format supports six levels of beaming, up to 1024th notes. Unlike the number-level type, the beam-level type identifies concurrent beams in a beam group. It does not distinguish overlapping beams such as grace notes within regular notes, or beams used in different voices.
newtype BeamLevel = BeamLevel { beamLevel :: PositiveInteger }
deriving (Eq,Typeable,Generic,Ord,Bounded,Enum,Num,Real,Integral)
instance Show BeamLevel where show (BeamLevel a) = show a
instance Read BeamLevel where readsPrec i = map (A.first BeamLevel) . readsPrec i
instance EmitXml BeamLevel where
emitXml = emitXml . beamLevel
parseBeamLevel :: String -> P.XParse BeamLevel
parseBeamLevel = P.xread "BeamLevel"
-- | @beam-value@ /(simple)/
--
-- The beam-value type represents the type of beam associated with each of 8 beam levels (up to 1024th notes) available for each note.
data BeamValue =
BeamValueBegin -- ^ /begin/
| BeamValueContinue -- ^ /continue/
| BeamValueEnd -- ^ /end/
| BeamValueForwardHook -- ^ /forward hook/
| BeamValueBackwardHook -- ^ /backward hook/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml BeamValue where
emitXml BeamValueBegin = XLit "begin"
emitXml BeamValueContinue = XLit "continue"
emitXml BeamValueEnd = XLit "end"
emitXml BeamValueForwardHook = XLit "forward hook"
emitXml BeamValueBackwardHook = XLit "backward hook"
parseBeamValue :: String -> P.XParse BeamValue
parseBeamValue s
| s == "begin" = return $ BeamValueBegin
| s == "continue" = return $ BeamValueContinue
| s == "end" = return $ BeamValueEnd
| s == "forward hook" = return $ BeamValueForwardHook
| s == "backward hook" = return $ BeamValueBackwardHook
| otherwise = P.xfail $ "BeamValue: " ++ s
-- | @beater-value@ /(simple)/
--
-- The beater-value type represents pictograms for beaters, mallets, and sticks that do not have different materials represented in the pictogram. The finger and hammer values are in addition to Stone's list.
data BeaterValue =
BeaterValueBow -- ^ /bow/
| BeaterValueChimeHammer -- ^ /chime hammer/
| BeaterValueCoin -- ^ /coin/
| BeaterValueFinger -- ^ /finger/
| BeaterValueFingernail -- ^ /fingernail/
| BeaterValueFist -- ^ /fist/
| BeaterValueGuiroScraper -- ^ /guiro scraper/
| BeaterValueHammer -- ^ /hammer/
| BeaterValueHand -- ^ /hand/
| BeaterValueJazzStick -- ^ /jazz stick/
| BeaterValueKnittingNeedle -- ^ /knitting needle/
| BeaterValueMetalHammer -- ^ /metal hammer/
| BeaterValueSnareStick -- ^ /snare stick/
| BeaterValueSpoonMallet -- ^ /spoon mallet/
| BeaterValueTriangleBeater -- ^ /triangle beater/
| BeaterValueTriangleBeaterPlain -- ^ /triangle beater plain/
| BeaterValueWireBrush -- ^ /wire brush/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml BeaterValue where
emitXml BeaterValueBow = XLit "bow"
emitXml BeaterValueChimeHammer = XLit "chime hammer"
emitXml BeaterValueCoin = XLit "coin"
emitXml BeaterValueFinger = XLit "finger"
emitXml BeaterValueFingernail = XLit "fingernail"
emitXml BeaterValueFist = XLit "fist"
emitXml BeaterValueGuiroScraper = XLit "guiro scraper"
emitXml BeaterValueHammer = XLit "hammer"
emitXml BeaterValueHand = XLit "hand"
emitXml BeaterValueJazzStick = XLit "jazz stick"
emitXml BeaterValueKnittingNeedle = XLit "knitting needle"
emitXml BeaterValueMetalHammer = XLit "metal hammer"
emitXml BeaterValueSnareStick = XLit "snare stick"
emitXml BeaterValueSpoonMallet = XLit "spoon mallet"
emitXml BeaterValueTriangleBeater = XLit "triangle beater"
emitXml BeaterValueTriangleBeaterPlain = XLit "triangle beater plain"
emitXml BeaterValueWireBrush = XLit "wire brush"
parseBeaterValue :: String -> P.XParse BeaterValue
parseBeaterValue s
| s == "bow" = return $ BeaterValueBow
| s == "chime hammer" = return $ BeaterValueChimeHammer
| s == "coin" = return $ BeaterValueCoin
| s == "finger" = return $ BeaterValueFinger
| s == "fingernail" = return $ BeaterValueFingernail
| s == "fist" = return $ BeaterValueFist
| s == "guiro scraper" = return $ BeaterValueGuiroScraper
| s == "hammer" = return $ BeaterValueHammer
| s == "hand" = return $ BeaterValueHand
| s == "jazz stick" = return $ BeaterValueJazzStick
| s == "knitting needle" = return $ BeaterValueKnittingNeedle
| s == "metal hammer" = return $ BeaterValueMetalHammer
| s == "snare stick" = return $ BeaterValueSnareStick
| s == "spoon mallet" = return $ BeaterValueSpoonMallet
| s == "triangle beater" = return $ BeaterValueTriangleBeater
| s == "triangle beater plain" = return $ BeaterValueTriangleBeaterPlain
| s == "wire brush" = return $ BeaterValueWireBrush
| otherwise = P.xfail $ "BeaterValue: " ++ s
-- | @breath-mark-value@ /(simple)/
--
-- The breath-mark-value type represents the symbol used for a breath mark.
data BreathMarkValue =
BreathMarkValue -- ^ //
| BreathMarkValueComma -- ^ /comma/
| BreathMarkValueTick -- ^ /tick/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml BreathMarkValue where
emitXml BreathMarkValue = XLit ""
emitXml BreathMarkValueComma = XLit "comma"
emitXml BreathMarkValueTick = XLit "tick"
parseBreathMarkValue :: String -> P.XParse BreathMarkValue
parseBreathMarkValue s
| s == "" = return $ BreathMarkValue
| s == "comma" = return $ BreathMarkValueComma
| s == "tick" = return $ BreathMarkValueTick
| otherwise = P.xfail $ "BreathMarkValue: " ++ s
-- | @cancel-location@ /(simple)/
--
-- The cancel-location type is used to indicate where a key signature cancellation appears relative to a new key signature: to the left, to the right, or before the barline and to the left. It is left by default. For mid-measure key elements, a cancel-location of before-barline should be treated like a cancel-location of left.
data CancelLocation =
CancelLocationLeft -- ^ /left/
| CancelLocationRight -- ^ /right/
| CancelLocationBeforeBarline -- ^ /before-barline/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml CancelLocation where
emitXml CancelLocationLeft = XLit "left"
emitXml CancelLocationRight = XLit "right"
emitXml CancelLocationBeforeBarline = XLit "before-barline"
parseCancelLocation :: String -> P.XParse CancelLocation
parseCancelLocation s
| s == "left" = return $ CancelLocationLeft
| s == "right" = return $ CancelLocationRight
| s == "before-barline" = return $ CancelLocationBeforeBarline
| otherwise = P.xfail $ "CancelLocation: " ++ s
-- | @circular-arrow@ /(simple)/
--
-- The circular-arrow type represents the direction in which a circular arrow points, using Unicode arrow terminology.
data CircularArrow =
CircularArrowClockwise -- ^ /clockwise/
| CircularArrowAnticlockwise -- ^ /anticlockwise/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml CircularArrow where
emitXml CircularArrowClockwise = XLit "clockwise"
emitXml CircularArrowAnticlockwise = XLit "anticlockwise"
parseCircularArrow :: String -> P.XParse CircularArrow
parseCircularArrow s
| s == "clockwise" = return $ CircularArrowClockwise
| s == "anticlockwise" = return $ CircularArrowAnticlockwise
| otherwise = P.xfail $ "CircularArrow: " ++ s
-- | @clef-sign@ /(simple)/
--
-- The clef-sign element represents the different clef symbols. The jianpu sign indicates that the music that follows should be in jianpu numbered notation, just as the TAB sign indicates that the music that follows should be in tablature notation. Unlike TAB, a jianpu sign does not correspond to a visual clef notation.
data ClefSign =
ClefSignG -- ^ /G/
| ClefSignF -- ^ /F/
| ClefSignC -- ^ /C/
| ClefSignPercussion -- ^ /percussion/
| ClefSignTAB -- ^ /TAB/
| ClefSignJianpu -- ^ /jianpu/
| ClefSignNone -- ^ /none/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml ClefSign where
emitXml ClefSignG = XLit "G"
emitXml ClefSignF = XLit "F"
emitXml ClefSignC = XLit "C"
emitXml ClefSignPercussion = XLit "percussion"
emitXml ClefSignTAB = XLit "TAB"
emitXml ClefSignJianpu = XLit "jianpu"
emitXml ClefSignNone = XLit "none"
parseClefSign :: String -> P.XParse ClefSign
parseClefSign s
| s == "G" = return $ ClefSignG
| s == "F" = return $ ClefSignF
| s == "C" = return $ ClefSignC
| s == "percussion" = return $ ClefSignPercussion
| s == "TAB" = return $ ClefSignTAB
| s == "jianpu" = return $ ClefSignJianpu
| s == "none" = return $ ClefSignNone
| otherwise = P.xfail $ "ClefSign: " ++ s
-- | @color@ /(simple)/
--
-- The color type indicates the color of an element. Color may be represented as hexadecimal RGB triples, as in HTML, or as hexadecimal ARGB tuples, with the A indicating alpha of transparency. An alpha value of 00 is totally transparent; FF is totally opaque. If RGB is used, the A value is assumed to be FF.
--
-- For instance, the RGB value "#800080" represents purple. An ARGB value of "#40800080" would be a transparent purple.
--
-- As in SVG 1.1, colors are defined in terms of the sRGB color space (IEC 61966).
newtype Color = Color { color :: Token }
deriving (Eq,Typeable,Generic,Ord,IsString)
instance Show Color where show (Color a) = show a
instance Read Color where readsPrec i = map (A.first Color) . readsPrec i
instance EmitXml Color where
emitXml = emitXml . color
parseColor :: String -> P.XParse Color
parseColor = return . fromString
-- | @comma-separated-text@ /(simple)/
--
-- The comma-separated-text type is used to specify a comma-separated list of text elements, as is used by the font-family attribute.
newtype CommaSeparatedText = CommaSeparatedText { commaSeparatedText :: Token }
deriving (Eq,Typeable,Generic,Ord,IsString)
instance Show CommaSeparatedText where show (CommaSeparatedText a) = show a
instance Read CommaSeparatedText where readsPrec i = map (A.first CommaSeparatedText) . readsPrec i
instance EmitXml CommaSeparatedText where
emitXml = emitXml . commaSeparatedText
parseCommaSeparatedText :: String -> P.XParse CommaSeparatedText
parseCommaSeparatedText = return . fromString
-- | @css-font-size@ /(simple)/
--
-- The css-font-size type includes the CSS font sizes used as an alternative to a numeric point size.
data CssFontSize =
CssFontSizeXxSmall -- ^ /xx-small/
| CssFontSizeXSmall -- ^ /x-small/
| CssFontSizeSmall -- ^ /small/
| CssFontSizeMedium -- ^ /medium/
| CssFontSizeLarge -- ^ /large/
| CssFontSizeXLarge -- ^ /x-large/
| CssFontSizeXxLarge -- ^ /xx-large/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml CssFontSize where
emitXml CssFontSizeXxSmall = XLit "xx-small"
emitXml CssFontSizeXSmall = XLit "x-small"
emitXml CssFontSizeSmall = XLit "small"
emitXml CssFontSizeMedium = XLit "medium"
emitXml CssFontSizeLarge = XLit "large"
emitXml CssFontSizeXLarge = XLit "x-large"
emitXml CssFontSizeXxLarge = XLit "xx-large"
parseCssFontSize :: String -> P.XParse CssFontSize
parseCssFontSize s
| s == "xx-small" = return $ CssFontSizeXxSmall
| s == "x-small" = return $ CssFontSizeXSmall
| s == "small" = return $ CssFontSizeSmall
| s == "medium" = return $ CssFontSizeMedium
| s == "large" = return $ CssFontSizeLarge
| s == "x-large" = return $ CssFontSizeXLarge
| s == "xx-large" = return $ CssFontSizeXxLarge
| otherwise = P.xfail $ "CssFontSize: " ++ s
-- | @degree-symbol-value@ /(simple)/
--
-- The degree-symbol-value type indicates indicates that a symbol should be used in specifying the degree.
data DegreeSymbolValue =
DegreeSymbolValueMajor -- ^ /major/
| DegreeSymbolValueMinor -- ^ /minor/
| DegreeSymbolValueAugmented -- ^ /augmented/
| DegreeSymbolValueDiminished -- ^ /diminished/
| DegreeSymbolValueHalfDiminished -- ^ /half-diminished/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml DegreeSymbolValue where
emitXml DegreeSymbolValueMajor = XLit "major"
emitXml DegreeSymbolValueMinor = XLit "minor"
emitXml DegreeSymbolValueAugmented = XLit "augmented"
emitXml DegreeSymbolValueDiminished = XLit "diminished"
emitXml DegreeSymbolValueHalfDiminished = XLit "half-diminished"
parseDegreeSymbolValue :: String -> P.XParse DegreeSymbolValue
parseDegreeSymbolValue s
| s == "major" = return $ DegreeSymbolValueMajor
| s == "minor" = return $ DegreeSymbolValueMinor
| s == "augmented" = return $ DegreeSymbolValueAugmented
| s == "diminished" = return $ DegreeSymbolValueDiminished
| s == "half-diminished" = return $ DegreeSymbolValueHalfDiminished
| otherwise = P.xfail $ "DegreeSymbolValue: " ++ s
-- | @degree-type-value@ /(simple)/
--
-- The degree-type-value type indicates whether the current degree element is an addition, alteration, or subtraction to the kind of the current chord in the harmony element.
data DegreeTypeValue =
DegreeTypeValueAdd -- ^ /add/
| DegreeTypeValueAlter -- ^ /alter/
| DegreeTypeValueSubtract -- ^ /subtract/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml DegreeTypeValue where
emitXml DegreeTypeValueAdd = XLit "add"
emitXml DegreeTypeValueAlter = XLit "alter"
emitXml DegreeTypeValueSubtract = XLit "subtract"
parseDegreeTypeValue :: String -> P.XParse DegreeTypeValue
parseDegreeTypeValue s
| s == "add" = return $ DegreeTypeValueAdd
| s == "alter" = return $ DegreeTypeValueAlter
| s == "subtract" = return $ DegreeTypeValueSubtract
| otherwise = P.xfail $ "DegreeTypeValue: " ++ s
-- | @distance-type@ /(simple)/
--
-- The distance-type defines what type of distance is being defined in a distance element. Values include beam and hyphen. This is left as a string so that other application-specific types can be defined, but it is made a separate type so that it can be redefined more strictly.
newtype DistanceType = DistanceType { distanceType :: Token }
deriving (Eq,Typeable,Generic,Ord,IsString)
instance Show DistanceType where show (DistanceType a) = show a
instance Read DistanceType where readsPrec i = map (A.first DistanceType) . readsPrec i
instance EmitXml DistanceType where
emitXml = emitXml . distanceType
parseDistanceType :: String -> P.XParse DistanceType
parseDistanceType = return . fromString
-- | @divisions@ /(simple)/
--
-- The divisions type is used to express values in terms of the musical divisions defined by the divisions element. It is preferred that these be integer values both for MIDI interoperability and to avoid roundoff errors.
newtype Divisions = Divisions { divisions :: Decimal }
deriving (Eq,Typeable,Generic,Ord,Num,Real,Fractional,RealFrac)
instance Show Divisions where show (Divisions a) = show a
instance Read Divisions where readsPrec i = map (A.first Divisions) . readsPrec i
instance EmitXml Divisions where
emitXml = emitXml . divisions
parseDivisions :: String -> P.XParse Divisions
parseDivisions = P.xread "Divisions"
-- | @effect@ /(simple)/
--
-- The effect type represents pictograms for sound effect percussion instruments. The cannon value is in addition to Stone's list.
data Effect =
EffectAnvil -- ^ /anvil/
| EffectAutoHorn -- ^ /auto horn/
| EffectBirdWhistle -- ^ /bird whistle/
| EffectCannon -- ^ /cannon/
| EffectDuckCall -- ^ /duck call/
| EffectGunShot -- ^ /gun shot/
| EffectKlaxonHorn -- ^ /klaxon horn/
| EffectLionsRoar -- ^ /lions roar/
| EffectPoliceWhistle -- ^ /police whistle/
| EffectSiren -- ^ /siren/
| EffectSlideWhistle -- ^ /slide whistle/
| EffectThunderSheet -- ^ /thunder sheet/
| EffectWindMachine -- ^ /wind machine/
| EffectWindWhistle -- ^ /wind whistle/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml Effect where
emitXml EffectAnvil = XLit "anvil"
emitXml EffectAutoHorn = XLit "auto horn"
emitXml EffectBirdWhistle = XLit "bird whistle"
emitXml EffectCannon = XLit "cannon"
emitXml EffectDuckCall = XLit "duck call"
emitXml EffectGunShot = XLit "gun shot"
emitXml EffectKlaxonHorn = XLit "klaxon horn"
emitXml EffectLionsRoar = XLit "lions roar"
emitXml EffectPoliceWhistle = XLit "police whistle"
emitXml EffectSiren = XLit "siren"
emitXml EffectSlideWhistle = XLit "slide whistle"
emitXml EffectThunderSheet = XLit "thunder sheet"
emitXml EffectWindMachine = XLit "wind machine"
emitXml EffectWindWhistle = XLit "wind whistle"
parseEffect :: String -> P.XParse Effect
parseEffect s
| s == "anvil" = return $ EffectAnvil
| s == "auto horn" = return $ EffectAutoHorn
| s == "bird whistle" = return $ EffectBirdWhistle
| s == "cannon" = return $ EffectCannon
| s == "duck call" = return $ EffectDuckCall
| s == "gun shot" = return $ EffectGunShot
| s == "klaxon horn" = return $ EffectKlaxonHorn
| s == "lions roar" = return $ EffectLionsRoar
| s == "police whistle" = return $ EffectPoliceWhistle
| s == "siren" = return $ EffectSiren
| s == "slide whistle" = return $ EffectSlideWhistle
| s == "thunder sheet" = return $ EffectThunderSheet
| s == "wind machine" = return $ EffectWindMachine
| s == "wind whistle" = return $ EffectWindWhistle
| otherwise = P.xfail $ "Effect: " ++ s
-- | @enclosure-shape@ /(simple)/
--
-- The enclosure-shape type describes the shape and presence / absence of an enclosure around text or symbols. A bracket enclosure is similar to a rectangle with the bottom line missing, as is common in jazz notation.
data EnclosureShape =
EnclosureShapeRectangle -- ^ /rectangle/
| EnclosureShapeSquare -- ^ /square/
| EnclosureShapeOval -- ^ /oval/
| EnclosureShapeCircle -- ^ /circle/
| EnclosureShapeBracket -- ^ /bracket/
| EnclosureShapeTriangle -- ^ /triangle/
| EnclosureShapeDiamond -- ^ /diamond/
| EnclosureShapeNone -- ^ /none/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml EnclosureShape where
emitXml EnclosureShapeRectangle = XLit "rectangle"
emitXml EnclosureShapeSquare = XLit "square"
emitXml EnclosureShapeOval = XLit "oval"
emitXml EnclosureShapeCircle = XLit "circle"
emitXml EnclosureShapeBracket = XLit "bracket"
emitXml EnclosureShapeTriangle = XLit "triangle"
emitXml EnclosureShapeDiamond = XLit "diamond"
emitXml EnclosureShapeNone = XLit "none"
parseEnclosureShape :: String -> P.XParse EnclosureShape
parseEnclosureShape s
| s == "rectangle" = return $ EnclosureShapeRectangle
| s == "square" = return $ EnclosureShapeSquare
| s == "oval" = return $ EnclosureShapeOval
| s == "circle" = return $ EnclosureShapeCircle
| s == "bracket" = return $ EnclosureShapeBracket
| s == "triangle" = return $ EnclosureShapeTriangle
| s == "diamond" = return $ EnclosureShapeDiamond
| s == "none" = return $ EnclosureShapeNone
| otherwise = P.xfail $ "EnclosureShape: " ++ s
-- | @ending-number@ /(simple)/
--
-- The ending-number type is used to specify either a comma-separated list of positive integers without leading zeros, or a string of zero or more spaces. It is used for the number attribute of the ending element. The zero or more spaces version is used when software knows that an ending is present, but cannot determine the type of the ending.
newtype EndingNumber = EndingNumber { endingNumber :: Token }
deriving (Eq,Typeable,Generic,Ord,IsString)
instance Show EndingNumber where show (EndingNumber a) = show a
instance Read EndingNumber where readsPrec i = map (A.first EndingNumber) . readsPrec i
instance EmitXml EndingNumber where
emitXml = emitXml . endingNumber
parseEndingNumber :: String -> P.XParse EndingNumber
parseEndingNumber = return . fromString
-- | @fan@ /(simple)/
--
-- The fan type represents the type of beam fanning present on a note, used to represent accelerandos and ritardandos.
data Fan =
FanAccel -- ^ /accel/
| FanRit -- ^ /rit/
| FanNone -- ^ /none/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml Fan where
emitXml FanAccel = XLit "accel"
emitXml FanRit = XLit "rit"
emitXml FanNone = XLit "none"
parseFan :: String -> P.XParse Fan
parseFan s
| s == "accel" = return $ FanAccel
| s == "rit" = return $ FanRit
| s == "none" = return $ FanNone
| otherwise = P.xfail $ "Fan: " ++ s
-- | @fermata-shape@ /(simple)/
--
-- The fermata-shape type represents the shape of the fermata sign. The empty value is equivalent to the normal value.
data FermataShape =
FermataShapeNormal -- ^ /normal/
| FermataShapeAngled -- ^ /angled/
| FermataShapeSquare -- ^ /square/
| FermataShape -- ^ //
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml FermataShape where
emitXml FermataShapeNormal = XLit "normal"
emitXml FermataShapeAngled = XLit "angled"
emitXml FermataShapeSquare = XLit "square"
emitXml FermataShape = XLit ""
parseFermataShape :: String -> P.XParse FermataShape
parseFermataShape s
| s == "normal" = return $ FermataShapeNormal
| s == "angled" = return $ FermataShapeAngled
| s == "square" = return $ FermataShapeSquare
| s == "" = return $ FermataShape
| otherwise = P.xfail $ "FermataShape: " ++ s
-- | @fifths@ /(simple)/
--
-- The fifths type represents the number of flats or sharps in a traditional key signature. Negative numbers are used for flats and positive numbers for sharps, reflecting the key's placement within the circle of fifths (hence the type name).
newtype Fifths = Fifths { fifths :: Int }
deriving (Eq,Typeable,Generic,Ord,Bounded,Enum,Num,Real,Integral)
instance Show Fifths where show (Fifths a) = show a
instance Read Fifths where readsPrec i = map (A.first Fifths) . readsPrec i
instance EmitXml Fifths where
emitXml = emitXml . fifths
parseFifths :: String -> P.XParse Fifths
parseFifths = P.xread "Fifths"
-- | @font-size@ /(simple)/
--
-- The font-size can be one of the CSS font sizes or a numeric point size.
data FontSize =
FontSizeDecimal {
fontSize1 :: Decimal
}
| FontSizeCssFontSize {
fontSize2 :: CssFontSize
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml FontSize where
emitXml (FontSizeDecimal a) = emitXml a
emitXml (FontSizeCssFontSize a) = emitXml a
parseFontSize :: String -> P.XParse FontSize
parseFontSize s =
FontSizeDecimal
<$> (P.xread "Decimal") s
<|> FontSizeCssFontSize
<$> parseCssFontSize s
-- | @font-style@ /(simple)/
--
-- The font-style type represents a simplified version of the CSS font-style property.
data FontStyle =
FontStyleNormal -- ^ /normal/
| FontStyleItalic -- ^ /italic/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml FontStyle where
emitXml FontStyleNormal = XLit "normal"
emitXml FontStyleItalic = XLit "italic"
parseFontStyle :: String -> P.XParse FontStyle
parseFontStyle s
| s == "normal" = return $ FontStyleNormal
| s == "italic" = return $ FontStyleItalic
| otherwise = P.xfail $ "FontStyle: " ++ s
-- | @font-weight@ /(simple)/
--
-- The font-weight type represents a simplified version of the CSS font-weight property.
data FontWeight =
FontWeightNormal -- ^ /normal/
| FontWeightBold -- ^ /bold/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml FontWeight where
emitXml FontWeightNormal = XLit "normal"
emitXml FontWeightBold = XLit "bold"
parseFontWeight :: String -> P.XParse FontWeight
parseFontWeight s
| s == "normal" = return $ FontWeightNormal
| s == "bold" = return $ FontWeightBold
| otherwise = P.xfail $ "FontWeight: " ++ s
-- | @glass@ /(simple)/
--
-- The glass type represents pictograms for glass percussion instruments.
data Glass =
GlassWindChimes -- ^ /wind chimes/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml Glass where
emitXml GlassWindChimes = XLit "wind chimes"
parseGlass :: String -> P.XParse Glass
parseGlass s
| s == "wind chimes" = return $ GlassWindChimes
| otherwise = P.xfail $ "Glass: " ++ s
-- | @group-barline-value@ /(simple)/
--
-- The group-barline-value type indicates if the group should have common barlines.
data GroupBarlineValue =
GroupBarlineValueYes -- ^ /yes/
| GroupBarlineValueNo -- ^ /no/
| GroupBarlineValueMensurstrich -- ^ /Mensurstrich/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml GroupBarlineValue where
emitXml GroupBarlineValueYes = XLit "yes"
emitXml GroupBarlineValueNo = XLit "no"
emitXml GroupBarlineValueMensurstrich = XLit "Mensurstrich"
parseGroupBarlineValue :: String -> P.XParse GroupBarlineValue
parseGroupBarlineValue s
| s == "yes" = return $ GroupBarlineValueYes
| s == "no" = return $ GroupBarlineValueNo
| s == "Mensurstrich" = return $ GroupBarlineValueMensurstrich
| otherwise = P.xfail $ "GroupBarlineValue: " ++ s
-- | @group-symbol-value@ /(simple)/
--
-- The group-symbol-value type indicates how the symbol for a group is indicated in the score. The default value is none.
data GroupSymbolValue =
GroupSymbolValueNone -- ^ /none/
| GroupSymbolValueBrace -- ^ /brace/
| GroupSymbolValueLine -- ^ /line/
| GroupSymbolValueBracket -- ^ /bracket/
| GroupSymbolValueSquare -- ^ /square/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml GroupSymbolValue where
emitXml GroupSymbolValueNone = XLit "none"
emitXml GroupSymbolValueBrace = XLit "brace"
emitXml GroupSymbolValueLine = XLit "line"
emitXml GroupSymbolValueBracket = XLit "bracket"
emitXml GroupSymbolValueSquare = XLit "square"
parseGroupSymbolValue :: String -> P.XParse GroupSymbolValue
parseGroupSymbolValue s
| s == "none" = return $ GroupSymbolValueNone
| s == "brace" = return $ GroupSymbolValueBrace
| s == "line" = return $ GroupSymbolValueLine
| s == "bracket" = return $ GroupSymbolValueBracket
| s == "square" = return $ GroupSymbolValueSquare
| otherwise = P.xfail $ "GroupSymbolValue: " ++ s
-- | @handbell-value@ /(simple)/
--
-- The handbell-value type represents the type of handbell technique being notated.
data HandbellValue =
HandbellValueDamp -- ^ /damp/
| HandbellValueEcho -- ^ /echo/
| HandbellValueGyro -- ^ /gyro/
| HandbellValueHandMartellato -- ^ /hand martellato/
| HandbellValueMalletLift -- ^ /mallet lift/
| HandbellValueMalletTable -- ^ /mallet table/
| HandbellValueMartellato -- ^ /martellato/
| HandbellValueMartellatoLift -- ^ /martellato lift/
| HandbellValueMutedMartellato -- ^ /muted martellato/
| HandbellValuePluckLift -- ^ /pluck lift/
| HandbellValueSwing -- ^ /swing/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml HandbellValue where
emitXml HandbellValueDamp = XLit "damp"
emitXml HandbellValueEcho = XLit "echo"
emitXml HandbellValueGyro = XLit "gyro"
emitXml HandbellValueHandMartellato = XLit "hand martellato"
emitXml HandbellValueMalletLift = XLit "mallet lift"
emitXml HandbellValueMalletTable = XLit "mallet table"
emitXml HandbellValueMartellato = XLit "martellato"
emitXml HandbellValueMartellatoLift = XLit "martellato lift"
emitXml HandbellValueMutedMartellato = XLit "muted martellato"
emitXml HandbellValuePluckLift = XLit "pluck lift"
emitXml HandbellValueSwing = XLit "swing"
parseHandbellValue :: String -> P.XParse HandbellValue
parseHandbellValue s
| s == "damp" = return $ HandbellValueDamp
| s == "echo" = return $ HandbellValueEcho
| s == "gyro" = return $ HandbellValueGyro
| s == "hand martellato" = return $ HandbellValueHandMartellato
| s == "mallet lift" = return $ HandbellValueMalletLift
| s == "mallet table" = return $ HandbellValueMalletTable
| s == "martellato" = return $ HandbellValueMartellato
| s == "martellato lift" = return $ HandbellValueMartellatoLift
| s == "muted martellato" = return $ HandbellValueMutedMartellato
| s == "pluck lift" = return $ HandbellValuePluckLift
| s == "swing" = return $ HandbellValueSwing
| otherwise = P.xfail $ "HandbellValue: " ++ s
-- | @harmony-type@ /(simple)/
--
-- The harmony-type type differentiates different types of harmonies when alternate harmonies are possible. Explicit harmonies have all note present in the music; implied have some notes missing but implied; alternate represents alternate analyses.
data HarmonyType =
HarmonyTypeExplicit -- ^ /explicit/
| HarmonyTypeImplied -- ^ /implied/
| HarmonyTypeAlternate -- ^ /alternate/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml HarmonyType where
emitXml HarmonyTypeExplicit = XLit "explicit"
emitXml HarmonyTypeImplied = XLit "implied"
emitXml HarmonyTypeAlternate = XLit "alternate"
parseHarmonyType :: String -> P.XParse HarmonyType
parseHarmonyType s
| s == "explicit" = return $ HarmonyTypeExplicit
| s == "implied" = return $ HarmonyTypeImplied
| s == "alternate" = return $ HarmonyTypeAlternate
| otherwise = P.xfail $ "HarmonyType: " ++ s
-- | @hole-closed-location@ /(simple)/
--
-- The hole-closed-location type indicates which portion of the hole is filled in when the corresponding hole-closed-value is half.
data HoleClosedLocation =
HoleClosedLocationRight -- ^ /right/
| HoleClosedLocationBottom -- ^ /bottom/
| HoleClosedLocationLeft -- ^ /left/
| HoleClosedLocationTop -- ^ /top/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml HoleClosedLocation where
emitXml HoleClosedLocationRight = XLit "right"
emitXml HoleClosedLocationBottom = XLit "bottom"
emitXml HoleClosedLocationLeft = XLit "left"
emitXml HoleClosedLocationTop = XLit "top"
parseHoleClosedLocation :: String -> P.XParse HoleClosedLocation
parseHoleClosedLocation s
| s == "right" = return $ HoleClosedLocationRight
| s == "bottom" = return $ HoleClosedLocationBottom
| s == "left" = return $ HoleClosedLocationLeft
| s == "top" = return $ HoleClosedLocationTop
| otherwise = P.xfail $ "HoleClosedLocation: " ++ s
-- | @hole-closed-value@ /(simple)/
--
-- The hole-closed-value type represents whether the hole is closed, open, or half-open.
data HoleClosedValue =
HoleClosedValueYes -- ^ /yes/
| HoleClosedValueNo -- ^ /no/
| HoleClosedValueHalf -- ^ /half/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml HoleClosedValue where
emitXml HoleClosedValueYes = XLit "yes"
emitXml HoleClosedValueNo = XLit "no"
emitXml HoleClosedValueHalf = XLit "half"
parseHoleClosedValue :: String -> P.XParse HoleClosedValue
parseHoleClosedValue s
| s == "yes" = return $ HoleClosedValueYes
| s == "no" = return $ HoleClosedValueNo
| s == "half" = return $ HoleClosedValueHalf
| otherwise = P.xfail $ "HoleClosedValue: " ++ s
-- | @kind-value@ /(simple)/
--
-- A kind-value indicates the type of chord. Degree elements can then add, subtract, or alter from these starting points. Values include:
--
-- @
--
-- Triads:
-- major (major third, perfect fifth)
-- minor (minor third, perfect fifth)
-- augmented (major third, augmented fifth)
-- diminished (minor third, diminished fifth)
-- Sevenths:
-- dominant (major triad, minor seventh)
-- major-seventh (major triad, major seventh)
-- minor-seventh (minor triad, minor seventh)
-- diminished-seventh (diminished triad, diminished seventh)
-- augmented-seventh (augmented triad, minor seventh)
-- half-diminished (diminished triad, minor seventh)
-- major-minor (minor triad, major seventh)
-- Sixths:
-- major-sixth (major triad, added sixth)
-- minor-sixth (minor triad, added sixth)
-- Ninths:
-- dominant-ninth (dominant-seventh, major ninth)
-- major-ninth (major-seventh, major ninth)
-- minor-ninth (minor-seventh, major ninth)
-- 11ths (usually as the basis for alteration):
-- dominant-11th (dominant-ninth, perfect 11th)
-- major-11th (major-ninth, perfect 11th)
-- minor-11th (minor-ninth, perfect 11th)
-- 13ths (usually as the basis for alteration):
-- dominant-13th (dominant-11th, major 13th)
-- major-13th (major-11th, major 13th)
-- minor-13th (minor-11th, major 13th)
-- Suspended:
-- suspended-second (major second, perfect fifth)
-- suspended-fourth (perfect fourth, perfect fifth)
-- Functional sixths:
-- Neapolitan
-- Italian
-- French
-- German
-- Other:
-- pedal (pedal-point bass)
-- power (perfect fifth)
-- Tristan
--
-- The "other" kind is used when the harmony is entirely composed of add elements. The "none" kind is used to explicitly encode absence of chords or functional harmony.
-- @
data KindValue =
KindValueMajor -- ^ /major/
| KindValueMinor -- ^ /minor/
| KindValueAugmented -- ^ /augmented/
| KindValueDiminished -- ^ /diminished/
| KindValueDominant -- ^ /dominant/
| KindValueMajorSeventh -- ^ /major-seventh/
| KindValueMinorSeventh -- ^ /minor-seventh/
| KindValueDiminishedSeventh -- ^ /diminished-seventh/
| KindValueAugmentedSeventh -- ^ /augmented-seventh/
| KindValueHalfDiminished -- ^ /half-diminished/
| KindValueMajorMinor -- ^ /major-minor/
| KindValueMajorSixth -- ^ /major-sixth/
| KindValueMinorSixth -- ^ /minor-sixth/
| KindValueDominantNinth -- ^ /dominant-ninth/
| KindValueMajorNinth -- ^ /major-ninth/
| KindValueMinorNinth -- ^ /minor-ninth/
| KindValueDominant11th -- ^ /dominant-11th/
| KindValueMajor11th -- ^ /major-11th/
| KindValueMinor11th -- ^ /minor-11th/
| KindValueDominant13th -- ^ /dominant-13th/
| KindValueMajor13th -- ^ /major-13th/
| KindValueMinor13th -- ^ /minor-13th/
| KindValueSuspendedSecond -- ^ /suspended-second/
| KindValueSuspendedFourth -- ^ /suspended-fourth/
| KindValueNeapolitan -- ^ /Neapolitan/
| KindValueItalian -- ^ /Italian/
| KindValueFrench -- ^ /French/
| KindValueGerman -- ^ /German/
| KindValuePedal -- ^ /pedal/
| KindValuePower -- ^ /power/
| KindValueTristan -- ^ /Tristan/
| KindValueOther -- ^ /other/
| KindValueNone -- ^ /none/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml KindValue where
emitXml KindValueMajor = XLit "major"
emitXml KindValueMinor = XLit "minor"
emitXml KindValueAugmented = XLit "augmented"
emitXml KindValueDiminished = XLit "diminished"
emitXml KindValueDominant = XLit "dominant"
emitXml KindValueMajorSeventh = XLit "major-seventh"
emitXml KindValueMinorSeventh = XLit "minor-seventh"
emitXml KindValueDiminishedSeventh = XLit "diminished-seventh"
emitXml KindValueAugmentedSeventh = XLit "augmented-seventh"
emitXml KindValueHalfDiminished = XLit "half-diminished"
emitXml KindValueMajorMinor = XLit "major-minor"
emitXml KindValueMajorSixth = XLit "major-sixth"
emitXml KindValueMinorSixth = XLit "minor-sixth"
emitXml KindValueDominantNinth = XLit "dominant-ninth"
emitXml KindValueMajorNinth = XLit "major-ninth"
emitXml KindValueMinorNinth = XLit "minor-ninth"
emitXml KindValueDominant11th = XLit "dominant-11th"
emitXml KindValueMajor11th = XLit "major-11th"
emitXml KindValueMinor11th = XLit "minor-11th"
emitXml KindValueDominant13th = XLit "dominant-13th"
emitXml KindValueMajor13th = XLit "major-13th"
emitXml KindValueMinor13th = XLit "minor-13th"
emitXml KindValueSuspendedSecond = XLit "suspended-second"
emitXml KindValueSuspendedFourth = XLit "suspended-fourth"
emitXml KindValueNeapolitan = XLit "Neapolitan"
emitXml KindValueItalian = XLit "Italian"
emitXml KindValueFrench = XLit "French"
emitXml KindValueGerman = XLit "German"
emitXml KindValuePedal = XLit "pedal"
emitXml KindValuePower = XLit "power"
emitXml KindValueTristan = XLit "Tristan"
emitXml KindValueOther = XLit "other"
emitXml KindValueNone = XLit "none"
parseKindValue :: String -> P.XParse KindValue
parseKindValue s
| s == "major" = return $ KindValueMajor
| s == "minor" = return $ KindValueMinor
| s == "augmented" = return $ KindValueAugmented
| s == "diminished" = return $ KindValueDiminished
| s == "dominant" = return $ KindValueDominant
| s == "major-seventh" = return $ KindValueMajorSeventh
| s == "minor-seventh" = return $ KindValueMinorSeventh
| s == "diminished-seventh" = return $ KindValueDiminishedSeventh
| s == "augmented-seventh" = return $ KindValueAugmentedSeventh
| s == "half-diminished" = return $ KindValueHalfDiminished
| s == "major-minor" = return $ KindValueMajorMinor
| s == "major-sixth" = return $ KindValueMajorSixth
| s == "minor-sixth" = return $ KindValueMinorSixth
| s == "dominant-ninth" = return $ KindValueDominantNinth
| s == "major-ninth" = return $ KindValueMajorNinth
| s == "minor-ninth" = return $ KindValueMinorNinth
| s == "dominant-11th" = return $ KindValueDominant11th
| s == "major-11th" = return $ KindValueMajor11th
| s == "minor-11th" = return $ KindValueMinor11th
| s == "dominant-13th" = return $ KindValueDominant13th
| s == "major-13th" = return $ KindValueMajor13th
| s == "minor-13th" = return $ KindValueMinor13th
| s == "suspended-second" = return $ KindValueSuspendedSecond
| s == "suspended-fourth" = return $ KindValueSuspendedFourth
| s == "Neapolitan" = return $ KindValueNeapolitan
| s == "Italian" = return $ KindValueItalian
| s == "French" = return $ KindValueFrench
| s == "German" = return $ KindValueGerman
| s == "pedal" = return $ KindValuePedal
| s == "power" = return $ KindValuePower
| s == "Tristan" = return $ KindValueTristan
| s == "other" = return $ KindValueOther
| s == "none" = return $ KindValueNone
| otherwise = P.xfail $ "KindValue: " ++ s
-- | @xml:lang@ /(simple)/
data Lang =
LangLanguage {
lang1 :: Language
}
| LangLang {
lang2 :: SumLang
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Lang where
emitXml (LangLanguage a) = emitXml a
emitXml (LangLang a) = emitXml a
parseLang :: String -> P.XParse Lang
parseLang s =
LangLanguage
<$> parseLanguage s
<|> LangLang
<$> parseSumLang s
-- | @xs:language@ /(simple)/
newtype Language = Language { language :: Token }
deriving (Eq,Typeable,Generic,Ord,IsString)
instance Show Language where show (Language a) = show a
instance Read Language where readsPrec i = map (A.first Language) . readsPrec i
instance EmitXml Language where
emitXml = emitXml . language
parseLanguage :: String -> P.XParse Language
parseLanguage = return . fromString
-- | @left-center-right@ /(simple)/
--
-- The left-center-right type is used to define horizontal alignment and text justification.
data LeftCenterRight =
LeftCenterRightLeft -- ^ /left/
| LeftCenterRightCenter -- ^ /center/
| LeftCenterRightRight -- ^ /right/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml LeftCenterRight where
emitXml LeftCenterRightLeft = XLit "left"
emitXml LeftCenterRightCenter = XLit "center"
emitXml LeftCenterRightRight = XLit "right"
parseLeftCenterRight :: String -> P.XParse LeftCenterRight
parseLeftCenterRight s
| s == "left" = return $ LeftCenterRightLeft
| s == "center" = return $ LeftCenterRightCenter
| s == "right" = return $ LeftCenterRightRight
| otherwise = P.xfail $ "LeftCenterRight: " ++ s
-- | @left-right@ /(simple)/
--
-- The left-right type is used to indicate whether one element appears to the left or the right of another element.
data LeftRight =
LeftRightLeft -- ^ /left/
| LeftRightRight -- ^ /right/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml LeftRight where
emitXml LeftRightLeft = XLit "left"
emitXml LeftRightRight = XLit "right"
parseLeftRight :: String -> P.XParse LeftRight
parseLeftRight s
| s == "left" = return $ LeftRightLeft
| s == "right" = return $ LeftRightRight
| otherwise = P.xfail $ "LeftRight: " ++ s
-- | @line-end@ /(simple)/
--
-- The line-end type specifies if there is a jog up or down (or both), an arrow, or nothing at the start or end of a bracket.
data LineEnd =
LineEndUp -- ^ /up/
| LineEndDown -- ^ /down/
| LineEndBoth -- ^ /both/
| LineEndArrow -- ^ /arrow/
| LineEndNone -- ^ /none/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml LineEnd where
emitXml LineEndUp = XLit "up"
emitXml LineEndDown = XLit "down"
emitXml LineEndBoth = XLit "both"
emitXml LineEndArrow = XLit "arrow"
emitXml LineEndNone = XLit "none"
parseLineEnd :: String -> P.XParse LineEnd
parseLineEnd s
| s == "up" = return $ LineEndUp
| s == "down" = return $ LineEndDown
| s == "both" = return $ LineEndBoth
| s == "arrow" = return $ LineEndArrow
| s == "none" = return $ LineEndNone
| otherwise = P.xfail $ "LineEnd: " ++ s
-- | @line-shape@ /(simple)/
--
-- The line-shape type distinguishes between straight and curved lines.
data LineShape =
LineShapeStraight -- ^ /straight/
| LineShapeCurved -- ^ /curved/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml LineShape where
emitXml LineShapeStraight = XLit "straight"
emitXml LineShapeCurved = XLit "curved"
parseLineShape :: String -> P.XParse LineShape
parseLineShape s
| s == "straight" = return $ LineShapeStraight
| s == "curved" = return $ LineShapeCurved
| otherwise = P.xfail $ "LineShape: " ++ s
-- | @line-type@ /(simple)/
--
-- The line-type type distinguishes between solid, dashed, dotted, and wavy lines.
data LineType =
LineTypeSolid -- ^ /solid/
| LineTypeDashed -- ^ /dashed/
| LineTypeDotted -- ^ /dotted/
| LineTypeWavy -- ^ /wavy/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml LineType where
emitXml LineTypeSolid = XLit "solid"
emitXml LineTypeDashed = XLit "dashed"
emitXml LineTypeDotted = XLit "dotted"
emitXml LineTypeWavy = XLit "wavy"
parseLineType :: String -> P.XParse LineType
parseLineType s
| s == "solid" = return $ LineTypeSolid
| s == "dashed" = return $ LineTypeDashed
| s == "dotted" = return $ LineTypeDotted
| s == "wavy" = return $ LineTypeWavy
| otherwise = P.xfail $ "LineType: " ++ s
-- | @line-width-type@ /(simple)/
--
-- The line-width-type defines what type of line is being defined in a line-width element. Values include beam, bracket, dashes, enclosure, ending, extend, heavy barline, leger, light barline, octave shift, pedal, slur middle, slur tip, staff, stem, tie middle, tie tip, tuplet bracket, and wedge. This is left as a string so that other application-specific types can be defined, but it is made a separate type so that it can be redefined more strictly.
newtype LineWidthType = LineWidthType { lineWidthType :: Token }
deriving (Eq,Typeable,Generic,Ord,IsString)
instance Show LineWidthType where show (LineWidthType a) = show a
instance Read LineWidthType where readsPrec i = map (A.first LineWidthType) . readsPrec i
instance EmitXml LineWidthType where
emitXml = emitXml . lineWidthType
parseLineWidthType :: String -> P.XParse LineWidthType
parseLineWidthType = return . fromString
-- | @margin-type@ /(simple)/
--
-- The margin-type type specifies whether margins apply to even page, odd pages, or both.
data MarginType =
MarginTypeOdd -- ^ /odd/
| MarginTypeEven -- ^ /even/
| MarginTypeBoth -- ^ /both/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml MarginType where
emitXml MarginTypeOdd = XLit "odd"
emitXml MarginTypeEven = XLit "even"
emitXml MarginTypeBoth = XLit "both"
parseMarginType :: String -> P.XParse MarginType
parseMarginType s
| s == "odd" = return $ MarginTypeOdd
| s == "even" = return $ MarginTypeEven
| s == "both" = return $ MarginTypeBoth
| otherwise = P.xfail $ "MarginType: " ++ s
-- | @measure-numbering-value@ /(simple)/
--
-- The measure-numbering-value type describes how measure numbers are displayed on this part: no numbers, numbers every measure, or numbers every system.
data MeasureNumberingValue =
MeasureNumberingValueNone -- ^ /none/
| MeasureNumberingValueMeasure -- ^ /measure/
| MeasureNumberingValueSystem -- ^ /system/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml MeasureNumberingValue where
emitXml MeasureNumberingValueNone = XLit "none"
emitXml MeasureNumberingValueMeasure = XLit "measure"
emitXml MeasureNumberingValueSystem = XLit "system"
parseMeasureNumberingValue :: String -> P.XParse MeasureNumberingValue
parseMeasureNumberingValue s
| s == "none" = return $ MeasureNumberingValueNone
| s == "measure" = return $ MeasureNumberingValueMeasure
| s == "system" = return $ MeasureNumberingValueSystem
| otherwise = P.xfail $ "MeasureNumberingValue: " ++ s
-- | @membrane@ /(simple)/
--
-- The membrane type represents pictograms for membrane percussion instruments. The goblet drum value is in addition to Stone's list.
data Membrane =
MembraneBassDrum -- ^ /bass drum/
| MembraneBassDrumOnSide -- ^ /bass drum on side/
| MembraneBongos -- ^ /bongos/
| MembraneCongaDrum -- ^ /conga drum/
| MembraneGobletDrum -- ^ /goblet drum/
| MembraneMilitaryDrum -- ^ /military drum/
| MembraneSnareDrum -- ^ /snare drum/
| MembraneSnareDrumSnaresOff -- ^ /snare drum snares off/
| MembraneTambourine -- ^ /tambourine/
| MembraneTenorDrum -- ^ /tenor drum/
| MembraneTimbales -- ^ /timbales/
| MembraneTomtom -- ^ /tomtom/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml Membrane where
emitXml MembraneBassDrum = XLit "bass drum"
emitXml MembraneBassDrumOnSide = XLit "bass drum on side"
emitXml MembraneBongos = XLit "bongos"
emitXml MembraneCongaDrum = XLit "conga drum"
emitXml MembraneGobletDrum = XLit "goblet drum"
emitXml MembraneMilitaryDrum = XLit "military drum"
emitXml MembraneSnareDrum = XLit "snare drum"
emitXml MembraneSnareDrumSnaresOff = XLit "snare drum snares off"
emitXml MembraneTambourine = XLit "tambourine"
emitXml MembraneTenorDrum = XLit "tenor drum"
emitXml MembraneTimbales = XLit "timbales"
emitXml MembraneTomtom = XLit "tomtom"
parseMembrane :: String -> P.XParse Membrane
parseMembrane s
| s == "bass drum" = return $ MembraneBassDrum
| s == "bass drum on side" = return $ MembraneBassDrumOnSide
| s == "bongos" = return $ MembraneBongos
| s == "conga drum" = return $ MembraneCongaDrum
| s == "goblet drum" = return $ MembraneGobletDrum
| s == "military drum" = return $ MembraneMilitaryDrum
| s == "snare drum" = return $ MembraneSnareDrum
| s == "snare drum snares off" = return $ MembraneSnareDrumSnaresOff
| s == "tambourine" = return $ MembraneTambourine
| s == "tenor drum" = return $ MembraneTenorDrum
| s == "timbales" = return $ MembraneTimbales
| s == "tomtom" = return $ MembraneTomtom
| otherwise = P.xfail $ "Membrane: " ++ s
-- | @metal@ /(simple)/
--
-- The metal type represents pictograms for metal percussion instruments. The hi-hat value refers to a pictogram like Stone's high-hat cymbals but without the long vertical line at the bottom.
data Metal =
MetalAlmglocken -- ^ /almglocken/
| MetalBell -- ^ /bell/
| MetalBellPlate -- ^ /bell plate/
| MetalBrakeDrum -- ^ /brake drum/
| MetalChineseCymbal -- ^ /Chinese cymbal/
| MetalCowbell -- ^ /cowbell/
| MetalCrashCymbals -- ^ /crash cymbals/
| MetalCrotale -- ^ /crotale/
| MetalCymbalTongs -- ^ /cymbal tongs/
| MetalDomedGong -- ^ /domed gong/
| MetalFingerCymbals -- ^ /finger cymbals/
| MetalFlexatone -- ^ /flexatone/
| MetalGong -- ^ /gong/
| MetalHiHat -- ^ /hi-hat/
| MetalHighHatCymbals -- ^ /high-hat cymbals/
| MetalHandbell -- ^ /handbell/
| MetalSistrum -- ^ /sistrum/
| MetalSizzleCymbal -- ^ /sizzle cymbal/
| MetalSleighBells -- ^ /sleigh bells/
| MetalSuspendedCymbal -- ^ /suspended cymbal/
| MetalTamTam -- ^ /tam tam/
| MetalTriangle -- ^ /triangle/
| MetalVietnameseHat -- ^ /Vietnamese hat/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml Metal where
emitXml MetalAlmglocken = XLit "almglocken"
emitXml MetalBell = XLit "bell"
emitXml MetalBellPlate = XLit "bell plate"
emitXml MetalBrakeDrum = XLit "brake drum"
emitXml MetalChineseCymbal = XLit "Chinese cymbal"
emitXml MetalCowbell = XLit "cowbell"
emitXml MetalCrashCymbals = XLit "crash cymbals"
emitXml MetalCrotale = XLit "crotale"
emitXml MetalCymbalTongs = XLit "cymbal tongs"
emitXml MetalDomedGong = XLit "domed gong"
emitXml MetalFingerCymbals = XLit "finger cymbals"
emitXml MetalFlexatone = XLit "flexatone"
emitXml MetalGong = XLit "gong"
emitXml MetalHiHat = XLit "hi-hat"
emitXml MetalHighHatCymbals = XLit "high-hat cymbals"
emitXml MetalHandbell = XLit "handbell"
emitXml MetalSistrum = XLit "sistrum"
emitXml MetalSizzleCymbal = XLit "sizzle cymbal"
emitXml MetalSleighBells = XLit "sleigh bells"
emitXml MetalSuspendedCymbal = XLit "suspended cymbal"
emitXml MetalTamTam = XLit "tam tam"
emitXml MetalTriangle = XLit "triangle"
emitXml MetalVietnameseHat = XLit "Vietnamese hat"
parseMetal :: String -> P.XParse Metal
parseMetal s
| s == "almglocken" = return $ MetalAlmglocken
| s == "bell" = return $ MetalBell
| s == "bell plate" = return $ MetalBellPlate
| s == "brake drum" = return $ MetalBrakeDrum
| s == "Chinese cymbal" = return $ MetalChineseCymbal
| s == "cowbell" = return $ MetalCowbell
| s == "crash cymbals" = return $ MetalCrashCymbals
| s == "crotale" = return $ MetalCrotale
| s == "cymbal tongs" = return $ MetalCymbalTongs
| s == "domed gong" = return $ MetalDomedGong
| s == "finger cymbals" = return $ MetalFingerCymbals
| s == "flexatone" = return $ MetalFlexatone
| s == "gong" = return $ MetalGong
| s == "hi-hat" = return $ MetalHiHat
| s == "high-hat cymbals" = return $ MetalHighHatCymbals
| s == "handbell" = return $ MetalHandbell
| s == "sistrum" = return $ MetalSistrum
| s == "sizzle cymbal" = return $ MetalSizzleCymbal
| s == "sleigh bells" = return $ MetalSleighBells
| s == "suspended cymbal" = return $ MetalSuspendedCymbal
| s == "tam tam" = return $ MetalTamTam
| s == "triangle" = return $ MetalTriangle
| s == "Vietnamese hat" = return $ MetalVietnameseHat
| otherwise = P.xfail $ "Metal: " ++ s
-- | @midi-128@ /(simple)/
--
-- The midi-16 type is used to express MIDI 1.0 values that range from 1 to 128.
newtype Midi128 = Midi128 { midi128 :: PositiveInteger }
deriving (Eq,Typeable,Generic,Ord,Bounded,Enum,Num,Real,Integral)
instance Show Midi128 where show (Midi128 a) = show a
instance Read Midi128 where readsPrec i = map (A.first Midi128) . readsPrec i
instance EmitXml Midi128 where
emitXml = emitXml . midi128
parseMidi128 :: String -> P.XParse Midi128
parseMidi128 = P.xread "Midi128"
-- | @midi-16@ /(simple)/
--
-- The midi-16 type is used to express MIDI 1.0 values that range from 1 to 16.
newtype Midi16 = Midi16 { midi16 :: PositiveInteger }
deriving (Eq,Typeable,Generic,Ord,Bounded,Enum,Num,Real,Integral)
instance Show Midi16 where show (Midi16 a) = show a
instance Read Midi16 where readsPrec i = map (A.first Midi16) . readsPrec i
instance EmitXml Midi16 where
emitXml = emitXml . midi16
parseMidi16 :: String -> P.XParse Midi16
parseMidi16 = P.xread "Midi16"
-- | @midi-16384@ /(simple)/
--
-- The midi-16 type is used to express MIDI 1.0 values that range from 1 to 16,384.
newtype Midi16384 = Midi16384 { midi16384 :: PositiveInteger }
deriving (Eq,Typeable,Generic,Ord,Bounded,Enum,Num,Real,Integral)
instance Show Midi16384 where show (Midi16384 a) = show a
instance Read Midi16384 where readsPrec i = map (A.first Midi16384) . readsPrec i
instance EmitXml Midi16384 where
emitXml = emitXml . midi16384
parseMidi16384 :: String -> P.XParse Midi16384
parseMidi16384 = P.xread "Midi16384"
-- | @millimeters@ /(simple)/
--
-- The millimeters type is a number representing millimeters. This is used in the scaling element to provide a default scaling from tenths to physical units.
newtype Millimeters = Millimeters { millimeters :: Decimal }
deriving (Eq,Typeable,Generic,Ord,Num,Real,Fractional,RealFrac)
instance Show Millimeters where show (Millimeters a) = show a
instance Read Millimeters where readsPrec i = map (A.first Millimeters) . readsPrec i
instance EmitXml Millimeters where
emitXml = emitXml . millimeters
parseMillimeters :: String -> P.XParse Millimeters
parseMillimeters = P.xread "Millimeters"
-- | @mode@ /(simple)/
--
-- The mode type is used to specify major/minor and other mode distinctions. Valid mode values include major, minor, dorian, phrygian, lydian, mixolydian, aeolian, ionian, locrian, and none.
newtype Mode = Mode { mode :: String }
deriving (Eq,Typeable,Generic,Ord,IsString)
instance Show Mode where show (Mode a) = show a
instance Read Mode where readsPrec i = map (A.first Mode) . readsPrec i
instance EmitXml Mode where
emitXml = emitXml . mode
parseMode :: String -> P.XParse Mode
parseMode = return . fromString
-- | @mute@ /(simple)/
--
-- The mute type represents muting for different instruments, including brass, winds, and strings. The on and off values are used for undifferentiated mutes. The remaining values represent specific mutes.
data Mute =
MuteOn -- ^ /on/
| MuteOff -- ^ /off/
| MuteStraight -- ^ /straight/
| MuteCup -- ^ /cup/
| MuteHarmonNoStem -- ^ /harmon-no-stem/
| MuteHarmonStem -- ^ /harmon-stem/
| MuteBucket -- ^ /bucket/
| MutePlunger -- ^ /plunger/
| MuteHat -- ^ /hat/
| MuteSolotone -- ^ /solotone/
| MutePractice -- ^ /practice/
| MuteStopMute -- ^ /stop-mute/
| MuteStopHand -- ^ /stop-hand/
| MuteEcho -- ^ /echo/
| MutePalm -- ^ /palm/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml Mute where
emitXml MuteOn = XLit "on"
emitXml MuteOff = XLit "off"
emitXml MuteStraight = XLit "straight"
emitXml MuteCup = XLit "cup"
emitXml MuteHarmonNoStem = XLit "harmon-no-stem"
emitXml MuteHarmonStem = XLit "harmon-stem"
emitXml MuteBucket = XLit "bucket"
emitXml MutePlunger = XLit "plunger"
emitXml MuteHat = XLit "hat"
emitXml MuteSolotone = XLit "solotone"
emitXml MutePractice = XLit "practice"
emitXml MuteStopMute = XLit "stop-mute"
emitXml MuteStopHand = XLit "stop-hand"
emitXml MuteEcho = XLit "echo"
emitXml MutePalm = XLit "palm"
parseMute :: String -> P.XParse Mute
parseMute s
| s == "on" = return $ MuteOn
| s == "off" = return $ MuteOff
| s == "straight" = return $ MuteStraight
| s == "cup" = return $ MuteCup
| s == "harmon-no-stem" = return $ MuteHarmonNoStem
| s == "harmon-stem" = return $ MuteHarmonStem
| s == "bucket" = return $ MuteBucket
| s == "plunger" = return $ MutePlunger
| s == "hat" = return $ MuteHat
| s == "solotone" = return $ MuteSolotone
| s == "practice" = return $ MutePractice
| s == "stop-mute" = return $ MuteStopMute
| s == "stop-hand" = return $ MuteStopHand
| s == "echo" = return $ MuteEcho
| s == "palm" = return $ MutePalm
| otherwise = P.xfail $ "Mute: " ++ s
-- | @non-negative-decimal@ /(simple)/
--
-- The non-negative-decimal type specifies a non-negative decimal value.
newtype NonNegativeDecimal = NonNegativeDecimal { nonNegativeDecimal :: Decimal }
deriving (Eq,Typeable,Generic,Ord,Num,Real,Fractional,RealFrac)
instance Show NonNegativeDecimal where show (NonNegativeDecimal a) = show a
instance Read NonNegativeDecimal where readsPrec i = map (A.first NonNegativeDecimal) . readsPrec i
instance EmitXml NonNegativeDecimal where
emitXml = emitXml . nonNegativeDecimal
parseNonNegativeDecimal :: String -> P.XParse NonNegativeDecimal
parseNonNegativeDecimal = P.xread "NonNegativeDecimal"
-- | @xs:nonNegativeInteger@ /(simple)/
newtype NonNegativeInteger = NonNegativeInteger { nonNegativeInteger :: Int }
deriving (Eq,Typeable,Generic,Ord,Bounded,Enum,Num,Real,Integral)
instance Show NonNegativeInteger where show (NonNegativeInteger a) = show a
instance Read NonNegativeInteger where readsPrec i = map (A.first NonNegativeInteger) . readsPrec i
instance EmitXml NonNegativeInteger where
emitXml = emitXml . nonNegativeInteger
parseNonNegativeInteger :: String -> P.XParse NonNegativeInteger
parseNonNegativeInteger = P.xread "NonNegativeInteger"
-- | @xs:normalizedString@ /(simple)/
newtype NormalizedString = NormalizedString { normalizedString :: String }
deriving (Eq,Typeable,Generic,Ord,IsString)
instance Show NormalizedString where show (NormalizedString a) = show a
instance Read NormalizedString where readsPrec i = map (A.first NormalizedString) . readsPrec i
instance EmitXml NormalizedString where
emitXml = emitXml . normalizedString
parseNormalizedString :: String -> P.XParse NormalizedString
parseNormalizedString = return . fromString
-- | @note-size-type@ /(simple)/
--
-- The note-size-type type indicates the type of note being defined by a note-size element. The grace type is used for notes of cue size that that include a grace element. The cue type is used for all other notes with cue size, whether defined explicitly or implicitly via a cue element. The large type is used for notes of large size.
data NoteSizeType =
NoteSizeTypeCue -- ^ /cue/
| NoteSizeTypeGrace -- ^ /grace/
| NoteSizeTypeLarge -- ^ /large/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml NoteSizeType where
emitXml NoteSizeTypeCue = XLit "cue"
emitXml NoteSizeTypeGrace = XLit "grace"
emitXml NoteSizeTypeLarge = XLit "large"
parseNoteSizeType :: String -> P.XParse NoteSizeType
parseNoteSizeType s
| s == "cue" = return $ NoteSizeTypeCue
| s == "grace" = return $ NoteSizeTypeGrace
| s == "large" = return $ NoteSizeTypeLarge
| otherwise = P.xfail $ "NoteSizeType: " ++ s
-- | @note-type-value@ /(simple)/
--
-- The note-type type is used for the MusicXML type element and represents the graphic note type, from 1024th (shortest) to maxima (longest).
data NoteTypeValue =
NoteTypeValue1024th -- ^ /1024th/
| NoteTypeValue512th -- ^ /512th/
| NoteTypeValue256th -- ^ /256th/
| NoteTypeValue128th -- ^ /128th/
| NoteTypeValue64th -- ^ /64th/
| NoteTypeValue32nd -- ^ /32nd/
| NoteTypeValue16th -- ^ /16th/
| NoteTypeValueEighth -- ^ /eighth/
| NoteTypeValueQuarter -- ^ /quarter/
| NoteTypeValueHalf -- ^ /half/
| NoteTypeValueWhole -- ^ /whole/
| NoteTypeValueBreve -- ^ /breve/
| NoteTypeValueLong -- ^ /long/
| NoteTypeValueMaxima -- ^ /maxima/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml NoteTypeValue where
emitXml NoteTypeValue1024th = XLit "1024th"
emitXml NoteTypeValue512th = XLit "512th"
emitXml NoteTypeValue256th = XLit "256th"
emitXml NoteTypeValue128th = XLit "128th"
emitXml NoteTypeValue64th = XLit "64th"
emitXml NoteTypeValue32nd = XLit "32nd"
emitXml NoteTypeValue16th = XLit "16th"
emitXml NoteTypeValueEighth = XLit "eighth"
emitXml NoteTypeValueQuarter = XLit "quarter"
emitXml NoteTypeValueHalf = XLit "half"
emitXml NoteTypeValueWhole = XLit "whole"
emitXml NoteTypeValueBreve = XLit "breve"
emitXml NoteTypeValueLong = XLit "long"
emitXml NoteTypeValueMaxima = XLit "maxima"
parseNoteTypeValue :: String -> P.XParse NoteTypeValue
parseNoteTypeValue s
| s == "1024th" = return $ NoteTypeValue1024th
| s == "512th" = return $ NoteTypeValue512th
| s == "256th" = return $ NoteTypeValue256th
| s == "128th" = return $ NoteTypeValue128th
| s == "64th" = return $ NoteTypeValue64th
| s == "32nd" = return $ NoteTypeValue32nd
| s == "16th" = return $ NoteTypeValue16th
| s == "eighth" = return $ NoteTypeValueEighth
| s == "quarter" = return $ NoteTypeValueQuarter
| s == "half" = return $ NoteTypeValueHalf
| s == "whole" = return $ NoteTypeValueWhole
| s == "breve" = return $ NoteTypeValueBreve
| s == "long" = return $ NoteTypeValueLong
| s == "maxima" = return $ NoteTypeValueMaxima
| otherwise = P.xfail $ "NoteTypeValue: " ++ s
-- | @notehead-value@ /(simple)/
--
--
-- The notehead type indicates shapes other than the open and closed ovals associated with note durations. The values do, re, mi, fa, fa up, so, la, and ti correspond to Aikin's 7-shape system. The fa up shape is typically used with upstems; the fa shape is typically used with downstems or no stems.
--
-- The arrow shapes differ from triangle and inverted triangle by being centered on the stem. Slashed and back slashed notes include both the normal notehead and a slash. The triangle shape has the tip of the triangle pointing up; the inverted triangle shape has the tip of the triangle pointing down. The left triangle shape is a right triangle with the hypotenuse facing up and to the left.
data NoteheadValue =
NoteheadValueSlash -- ^ /slash/
| NoteheadValueTriangle -- ^ /triangle/
| NoteheadValueDiamond -- ^ /diamond/
| NoteheadValueSquare -- ^ /square/
| NoteheadValueCross -- ^ /cross/
| NoteheadValueX -- ^ /x/
| NoteheadValueCircleX -- ^ /circle-x/
| NoteheadValueInvertedTriangle -- ^ /inverted triangle/
| NoteheadValueArrowDown -- ^ /arrow down/
| NoteheadValueArrowUp -- ^ /arrow up/
| NoteheadValueSlashed -- ^ /slashed/
| NoteheadValueBackSlashed -- ^ /back slashed/
| NoteheadValueNormal -- ^ /normal/
| NoteheadValueCluster -- ^ /cluster/
| NoteheadValueCircleDot -- ^ /circle dot/
| NoteheadValueLeftTriangle -- ^ /left triangle/
| NoteheadValueRectangle -- ^ /rectangle/
| NoteheadValueNone -- ^ /none/
| NoteheadValueDo -- ^ /do/
| NoteheadValueRe -- ^ /re/
| NoteheadValueMi -- ^ /mi/
| NoteheadValueFa -- ^ /fa/
| NoteheadValueFaUp -- ^ /fa up/
| NoteheadValueSo -- ^ /so/
| NoteheadValueLa -- ^ /la/
| NoteheadValueTi -- ^ /ti/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml NoteheadValue where
emitXml NoteheadValueSlash = XLit "slash"
emitXml NoteheadValueTriangle = XLit "triangle"
emitXml NoteheadValueDiamond = XLit "diamond"
emitXml NoteheadValueSquare = XLit "square"
emitXml NoteheadValueCross = XLit "cross"
emitXml NoteheadValueX = XLit "x"
emitXml NoteheadValueCircleX = XLit "circle-x"
emitXml NoteheadValueInvertedTriangle = XLit "inverted triangle"
emitXml NoteheadValueArrowDown = XLit "arrow down"
emitXml NoteheadValueArrowUp = XLit "arrow up"
emitXml NoteheadValueSlashed = XLit "slashed"
emitXml NoteheadValueBackSlashed = XLit "back slashed"
emitXml NoteheadValueNormal = XLit "normal"
emitXml NoteheadValueCluster = XLit "cluster"
emitXml NoteheadValueCircleDot = XLit "circle dot"
emitXml NoteheadValueLeftTriangle = XLit "left triangle"
emitXml NoteheadValueRectangle = XLit "rectangle"
emitXml NoteheadValueNone = XLit "none"
emitXml NoteheadValueDo = XLit "do"
emitXml NoteheadValueRe = XLit "re"
emitXml NoteheadValueMi = XLit "mi"
emitXml NoteheadValueFa = XLit "fa"
emitXml NoteheadValueFaUp = XLit "fa up"
emitXml NoteheadValueSo = XLit "so"
emitXml NoteheadValueLa = XLit "la"
emitXml NoteheadValueTi = XLit "ti"
parseNoteheadValue :: String -> P.XParse NoteheadValue
parseNoteheadValue s
| s == "slash" = return $ NoteheadValueSlash
| s == "triangle" = return $ NoteheadValueTriangle
| s == "diamond" = return $ NoteheadValueDiamond
| s == "square" = return $ NoteheadValueSquare
| s == "cross" = return $ NoteheadValueCross
| s == "x" = return $ NoteheadValueX
| s == "circle-x" = return $ NoteheadValueCircleX
| s == "inverted triangle" = return $ NoteheadValueInvertedTriangle
| s == "arrow down" = return $ NoteheadValueArrowDown
| s == "arrow up" = return $ NoteheadValueArrowUp
| s == "slashed" = return $ NoteheadValueSlashed
| s == "back slashed" = return $ NoteheadValueBackSlashed
| s == "normal" = return $ NoteheadValueNormal
| s == "cluster" = return $ NoteheadValueCluster
| s == "circle dot" = return $ NoteheadValueCircleDot
| s == "left triangle" = return $ NoteheadValueLeftTriangle
| s == "rectangle" = return $ NoteheadValueRectangle
| s == "none" = return $ NoteheadValueNone
| s == "do" = return $ NoteheadValueDo
| s == "re" = return $ NoteheadValueRe
| s == "mi" = return $ NoteheadValueMi
| s == "fa" = return $ NoteheadValueFa
| s == "fa up" = return $ NoteheadValueFaUp
| s == "so" = return $ NoteheadValueSo
| s == "la" = return $ NoteheadValueLa
| s == "ti" = return $ NoteheadValueTi
| otherwise = P.xfail $ "NoteheadValue: " ++ s
-- | @number-level@ /(simple)/
--
-- Slurs, tuplets, and many other features can be concurrent and overlapping within a single musical part. The number-level type distinguishes up to six concurrent objects of the same type. A reading program should be prepared to handle cases where the number-levels stop in an arbitrary order. Different numbers are needed when the features overlap in MusicXML document order. When a number-level value is implied, the value is 1 by default.
newtype NumberLevel = NumberLevel { numberLevel :: PositiveInteger }
deriving (Eq,Typeable,Generic,Ord,Bounded,Enum,Num,Real,Integral)
instance Show NumberLevel where show (NumberLevel a) = show a
instance Read NumberLevel where readsPrec i = map (A.first NumberLevel) . readsPrec i
instance EmitXml NumberLevel where
emitXml = emitXml . numberLevel
parseNumberLevel :: String -> P.XParse NumberLevel
parseNumberLevel = P.xread "NumberLevel"
-- | @number-of-lines@ /(simple)/
--
-- The number-of-lines type is used to specify the number of lines in text decoration attributes.
newtype NumberOfLines = NumberOfLines { numberOfLines :: NonNegativeInteger }
deriving (Eq,Typeable,Generic,Ord,Bounded,Enum,Num,Real,Integral)
instance Show NumberOfLines where show (NumberOfLines a) = show a
instance Read NumberOfLines where readsPrec i = map (A.first NumberOfLines) . readsPrec i
instance EmitXml NumberOfLines where
emitXml = emitXml . numberOfLines
parseNumberOfLines :: String -> P.XParse NumberOfLines
parseNumberOfLines = P.xread "NumberOfLines"
-- | @number-or-normal@ /(simple)/
--
-- The number-or-normal values can be either a decimal number or the string "normal". This is used by the line-height and letter-spacing attributes.
data NumberOrNormal =
NumberOrNormalDecimal {
numberOrNormal1 :: Decimal
}
| NumberOrNormalNumberOrNormal {
numberOrNormal2 :: SumNumberOrNormal
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml NumberOrNormal where
emitXml (NumberOrNormalDecimal a) = emitXml a
emitXml (NumberOrNormalNumberOrNormal a) = emitXml a
parseNumberOrNormal :: String -> P.XParse NumberOrNormal
parseNumberOrNormal s =
NumberOrNormalDecimal
<$> (P.xread "Decimal") s
<|> NumberOrNormalNumberOrNormal
<$> parseSumNumberOrNormal s
-- | @octave@ /(simple)/
--
-- Octaves are represented by the numbers 0 to 9, where 4 indicates the octave started by middle C.
newtype Octave = Octave { octave :: Int }
deriving (Eq,Typeable,Generic,Ord,Bounded,Enum,Num,Real,Integral)
instance Show Octave where show (Octave a) = show a
instance Read Octave where readsPrec i = map (A.first Octave) . readsPrec i
instance EmitXml Octave where
emitXml = emitXml . octave
parseOctave :: String -> P.XParse Octave
parseOctave = P.xread "Octave"
-- | @on-off@ /(simple)/
--
-- The on-off type is used for notation elements such as string mutes.
data OnOff =
OnOffOn -- ^ /on/
| OnOffOff -- ^ /off/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml OnOff where
emitXml OnOffOn = XLit "on"
emitXml OnOffOff = XLit "off"
parseOnOff :: String -> P.XParse OnOff
parseOnOff s
| s == "on" = return $ OnOffOn
| s == "off" = return $ OnOffOff
| otherwise = P.xfail $ "OnOff: " ++ s
-- | @over-under@ /(simple)/
--
-- The over-under type is used to indicate whether the tips of curved lines such as slurs and ties are overhand (tips down) or underhand (tips up).
data OverUnder =
OverUnderOver -- ^ /over/
| OverUnderUnder -- ^ /under/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml OverUnder where
emitXml OverUnderOver = XLit "over"
emitXml OverUnderUnder = XLit "under"
parseOverUnder :: String -> P.XParse OverUnder
parseOverUnder s
| s == "over" = return $ OverUnderOver
| s == "under" = return $ OverUnderUnder
| otherwise = P.xfail $ "OverUnder: " ++ s
-- | @percent@ /(simple)/
--
-- The percent type specifies a percentage from 0 to 100.
newtype Percent = Percent { percent :: Decimal }
deriving (Eq,Typeable,Generic,Ord,Num,Real,Fractional,RealFrac)
instance Show Percent where show (Percent a) = show a
instance Read Percent where readsPrec i = map (A.first Percent) . readsPrec i
instance EmitXml Percent where
emitXml = emitXml . percent
parsePercent :: String -> P.XParse Percent
parsePercent = P.xread "Percent"
-- | @pitched@ /(simple)/
--
-- The pitched type represents pictograms for pitched percussion instruments. The chimes and tubular chimes values distinguish the single-line and double-line versions of the pictogram. The mallet value is in addition to Stone's list.
data Pitched =
PitchedChimes -- ^ /chimes/
| PitchedGlockenspiel -- ^ /glockenspiel/
| PitchedMallet -- ^ /mallet/
| PitchedMarimba -- ^ /marimba/
| PitchedTubularChimes -- ^ /tubular chimes/
| PitchedVibraphone -- ^ /vibraphone/
| PitchedXylophone -- ^ /xylophone/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml Pitched where
emitXml PitchedChimes = XLit "chimes"
emitXml PitchedGlockenspiel = XLit "glockenspiel"
emitXml PitchedMallet = XLit "mallet"
emitXml PitchedMarimba = XLit "marimba"
emitXml PitchedTubularChimes = XLit "tubular chimes"
emitXml PitchedVibraphone = XLit "vibraphone"
emitXml PitchedXylophone = XLit "xylophone"
parsePitched :: String -> P.XParse Pitched
parsePitched s
| s == "chimes" = return $ PitchedChimes
| s == "glockenspiel" = return $ PitchedGlockenspiel
| s == "mallet" = return $ PitchedMallet
| s == "marimba" = return $ PitchedMarimba
| s == "tubular chimes" = return $ PitchedTubularChimes
| s == "vibraphone" = return $ PitchedVibraphone
| s == "xylophone" = return $ PitchedXylophone
| otherwise = P.xfail $ "Pitched: " ++ s
-- | @positive-divisions@ /(simple)/
--
-- The positive-divisions type restricts divisions values to positive numbers.
newtype PositiveDivisions = PositiveDivisions { positiveDivisions :: Divisions }
deriving (Eq,Typeable,Generic,Ord,Num,Real,Fractional,RealFrac)
instance Show PositiveDivisions where show (PositiveDivisions a) = show a
instance Read PositiveDivisions where readsPrec i = map (A.first PositiveDivisions) . readsPrec i
instance EmitXml PositiveDivisions where
emitXml = emitXml . positiveDivisions
parsePositiveDivisions :: String -> P.XParse PositiveDivisions
parsePositiveDivisions = P.xread "PositiveDivisions"
-- | @positive-integer-or-empty@ /(simple)/
--
-- The positive-integer-or-empty values can be either a positive integer or an empty string.
data PositiveIntegerOrEmpty =
PositiveIntegerOrEmptyPositiveInteger {
positiveIntegerOrEmpty1 :: PositiveInteger
}
| PositiveIntegerOrEmptyPositiveIntegerOrEmpty {
positiveIntegerOrEmpty2 :: SumPositiveIntegerOrEmpty
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml PositiveIntegerOrEmpty where
emitXml (PositiveIntegerOrEmptyPositiveInteger a) = emitXml a
emitXml (PositiveIntegerOrEmptyPositiveIntegerOrEmpty a) = emitXml a
parsePositiveIntegerOrEmpty :: String -> P.XParse PositiveIntegerOrEmpty
parsePositiveIntegerOrEmpty s =
PositiveIntegerOrEmptyPositiveInteger
<$> parsePositiveInteger s
<|> PositiveIntegerOrEmptyPositiveIntegerOrEmpty
<$> parseSumPositiveIntegerOrEmpty s
-- | @xs:positiveInteger@ /(simple)/
newtype PositiveInteger = PositiveInteger { positiveInteger :: NonNegativeInteger }
deriving (Eq,Typeable,Generic,Ord,Bounded,Enum,Num,Real,Integral)
instance Show PositiveInteger where show (PositiveInteger a) = show a
instance Read PositiveInteger where readsPrec i = map (A.first PositiveInteger) . readsPrec i
instance EmitXml PositiveInteger where
emitXml = emitXml . positiveInteger
parsePositiveInteger :: String -> P.XParse PositiveInteger
parsePositiveInteger = P.xread "PositiveInteger"
-- | @principal-voice-symbol@ /(simple)/
--
-- The principal-voice-symbol type represents the type of symbol used to indicate the start of a principal or secondary voice. The "plain" value represents a plain square bracket. The value of "none" is used for analysis markup when the principal-voice element does not have a corresponding appearance in the score.
data PrincipalVoiceSymbol =
PrincipalVoiceSymbolHauptstimme -- ^ /Hauptstimme/
| PrincipalVoiceSymbolNebenstimme -- ^ /Nebenstimme/
| PrincipalVoiceSymbolPlain -- ^ /plain/
| PrincipalVoiceSymbolNone -- ^ /none/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml PrincipalVoiceSymbol where
emitXml PrincipalVoiceSymbolHauptstimme = XLit "Hauptstimme"
emitXml PrincipalVoiceSymbolNebenstimme = XLit "Nebenstimme"
emitXml PrincipalVoiceSymbolPlain = XLit "plain"
emitXml PrincipalVoiceSymbolNone = XLit "none"
parsePrincipalVoiceSymbol :: String -> P.XParse PrincipalVoiceSymbol
parsePrincipalVoiceSymbol s
| s == "Hauptstimme" = return $ PrincipalVoiceSymbolHauptstimme
| s == "Nebenstimme" = return $ PrincipalVoiceSymbolNebenstimme
| s == "plain" = return $ PrincipalVoiceSymbolPlain
| s == "none" = return $ PrincipalVoiceSymbolNone
| otherwise = P.xfail $ "PrincipalVoiceSymbol: " ++ s
-- | @right-left-middle@ /(simple)/
--
-- The right-left-middle type is used to specify barline location.
data RightLeftMiddle =
RightLeftMiddleRight -- ^ /right/
| RightLeftMiddleLeft -- ^ /left/
| RightLeftMiddleMiddle -- ^ /middle/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml RightLeftMiddle where
emitXml RightLeftMiddleRight = XLit "right"
emitXml RightLeftMiddleLeft = XLit "left"
emitXml RightLeftMiddleMiddle = XLit "middle"
parseRightLeftMiddle :: String -> P.XParse RightLeftMiddle
parseRightLeftMiddle s
| s == "right" = return $ RightLeftMiddleRight
| s == "left" = return $ RightLeftMiddleLeft
| s == "middle" = return $ RightLeftMiddleMiddle
| otherwise = P.xfail $ "RightLeftMiddle: " ++ s
-- | @rotation-degrees@ /(simple)/
--
-- The rotation-degrees type specifies rotation, pan, and elevation values in degrees. Values range from -180 to 180.
newtype RotationDegrees = RotationDegrees { rotationDegrees :: Decimal }
deriving (Eq,Typeable,Generic,Ord,Num,Real,Fractional,RealFrac)
instance Show RotationDegrees where show (RotationDegrees a) = show a
instance Read RotationDegrees where readsPrec i = map (A.first RotationDegrees) . readsPrec i
instance EmitXml RotationDegrees where
emitXml = emitXml . rotationDegrees
parseRotationDegrees :: String -> P.XParse RotationDegrees
parseRotationDegrees = P.xread "RotationDegrees"
-- | @semi-pitched@ /(simple)/
--
-- The semi-pitched type represents categories of indefinite pitch for percussion instruments.
data SemiPitched =
SemiPitchedHigh -- ^ /high/
| SemiPitchedMediumHigh -- ^ /medium-high/
| SemiPitchedMedium -- ^ /medium/
| SemiPitchedMediumLow -- ^ /medium-low/
| SemiPitchedLow -- ^ /low/
| SemiPitchedVeryLow -- ^ /very-low/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml SemiPitched where
emitXml SemiPitchedHigh = XLit "high"
emitXml SemiPitchedMediumHigh = XLit "medium-high"
emitXml SemiPitchedMedium = XLit "medium"
emitXml SemiPitchedMediumLow = XLit "medium-low"
emitXml SemiPitchedLow = XLit "low"
emitXml SemiPitchedVeryLow = XLit "very-low"
parseSemiPitched :: String -> P.XParse SemiPitched
parseSemiPitched s
| s == "high" = return $ SemiPitchedHigh
| s == "medium-high" = return $ SemiPitchedMediumHigh
| s == "medium" = return $ SemiPitchedMedium
| s == "medium-low" = return $ SemiPitchedMediumLow
| s == "low" = return $ SemiPitchedLow
| s == "very-low" = return $ SemiPitchedVeryLow
| otherwise = P.xfail $ "SemiPitched: " ++ s
-- | @semitones@ /(simple)/
--
-- The semitones type is a number representing semitones, used for chromatic alteration. A value of -1 corresponds to a flat and a value of 1 to a sharp. Decimal values like 0.5 (quarter tone sharp) are used for microtones.
newtype Semitones = Semitones { semitones :: Decimal }
deriving (Eq,Typeable,Generic,Ord,Num,Real,Fractional,RealFrac)
instance Show Semitones where show (Semitones a) = show a
instance Read Semitones where readsPrec i = map (A.first Semitones) . readsPrec i
instance EmitXml Semitones where
emitXml = emitXml . semitones
parseSemitones :: String -> P.XParse Semitones
parseSemitones = P.xread "Semitones"
-- | @xlink:show@ /(simple)/
data SmpShow =
ShowNew -- ^ /new/
| ShowReplace -- ^ /replace/
| ShowEmbed -- ^ /embed/
| ShowOther -- ^ /other/
| ShowNone -- ^ /none/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml SmpShow where
emitXml ShowNew = XLit "new"
emitXml ShowReplace = XLit "replace"
emitXml ShowEmbed = XLit "embed"
emitXml ShowOther = XLit "other"
emitXml ShowNone = XLit "none"
parseSmpShow :: String -> P.XParse SmpShow
parseSmpShow s
| s == "new" = return $ ShowNew
| s == "replace" = return $ ShowReplace
| s == "embed" = return $ ShowEmbed
| s == "other" = return $ ShowOther
| s == "none" = return $ ShowNone
| otherwise = P.xfail $ "SmpShow: " ++ s
-- | @show-frets@ /(simple)/
--
-- The show-frets type indicates whether to show tablature frets as numbers (0, 1, 2) or letters (a, b, c). The default choice is numbers.
data ShowFrets =
ShowFretsNumbers -- ^ /numbers/
| ShowFretsLetters -- ^ /letters/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml ShowFrets where
emitXml ShowFretsNumbers = XLit "numbers"
emitXml ShowFretsLetters = XLit "letters"
parseShowFrets :: String -> P.XParse ShowFrets
parseShowFrets s
| s == "numbers" = return $ ShowFretsNumbers
| s == "letters" = return $ ShowFretsLetters
| otherwise = P.xfail $ "ShowFrets: " ++ s
-- | @show-tuplet@ /(simple)/
--
-- The show-tuplet type indicates whether to show a part of a tuplet relating to the tuplet-actual element, both the tuplet-actual and tuplet-normal elements, or neither.
data ShowTuplet =
ShowTupletActual -- ^ /actual/
| ShowTupletBoth -- ^ /both/
| ShowTupletNone -- ^ /none/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml ShowTuplet where
emitXml ShowTupletActual = XLit "actual"
emitXml ShowTupletBoth = XLit "both"
emitXml ShowTupletNone = XLit "none"
parseShowTuplet :: String -> P.XParse ShowTuplet
parseShowTuplet s
| s == "actual" = return $ ShowTupletActual
| s == "both" = return $ ShowTupletBoth
| s == "none" = return $ ShowTupletNone
| otherwise = P.xfail $ "ShowTuplet: " ++ s
-- | @xml:space@ /(simple)/
data Space =
SpaceDefault -- ^ /default/
| SpacePreserve -- ^ /preserve/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml Space where
emitXml SpaceDefault = XLit "default"
emitXml SpacePreserve = XLit "preserve"
parseSpace :: String -> P.XParse Space
parseSpace s
| s == "default" = return $ SpaceDefault
| s == "preserve" = return $ SpacePreserve
| otherwise = P.xfail $ "Space: " ++ s
-- | @staff-line@ /(simple)/
--
-- The staff-line type indicates the line on a given staff. Staff lines are numbered from bottom to top, with 1 being the bottom line on a staff. Staff line values can be used to specify positions outside the staff, such as a C clef positioned in the middle of a grand staff.
newtype StaffLine = StaffLine { staffLine :: Int }
deriving (Eq,Typeable,Generic,Ord,Bounded,Enum,Num,Real,Integral)
instance Show StaffLine where show (StaffLine a) = show a
instance Read StaffLine where readsPrec i = map (A.first StaffLine) . readsPrec i
instance EmitXml StaffLine where
emitXml = emitXml . staffLine
parseStaffLine :: String -> P.XParse StaffLine
parseStaffLine = P.xread "StaffLine"
-- | @staff-number@ /(simple)/
--
-- The staff-number type indicates staff numbers within a multi-staff part. Staves are numbered from top to bottom, with 1 being the top staff on a part.
newtype StaffNumber = StaffNumber { staffNumber :: PositiveInteger }
deriving (Eq,Typeable,Generic,Ord,Bounded,Enum,Num,Real,Integral)
instance Show StaffNumber where show (StaffNumber a) = show a
instance Read StaffNumber where readsPrec i = map (A.first StaffNumber) . readsPrec i
instance EmitXml StaffNumber where
emitXml = emitXml . staffNumber
parseStaffNumber :: String -> P.XParse StaffNumber
parseStaffNumber = P.xread "StaffNumber"
-- | @staff-type@ /(simple)/
--
-- The staff-type value can be ossia, cue, editorial, regular, or alternate. An alternate staff indicates one that shares the same musical data as the prior staff, but displayed differently (e.g., treble and bass clef, standard notation and tab).
data StaffType =
StaffTypeOssia -- ^ /ossia/
| StaffTypeCue -- ^ /cue/
| StaffTypeEditorial -- ^ /editorial/
| StaffTypeRegular -- ^ /regular/
| StaffTypeAlternate -- ^ /alternate/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml StaffType where
emitXml StaffTypeOssia = XLit "ossia"
emitXml StaffTypeCue = XLit "cue"
emitXml StaffTypeEditorial = XLit "editorial"
emitXml StaffTypeRegular = XLit "regular"
emitXml StaffTypeAlternate = XLit "alternate"
parseStaffType :: String -> P.XParse StaffType
parseStaffType s
| s == "ossia" = return $ StaffTypeOssia
| s == "cue" = return $ StaffTypeCue
| s == "editorial" = return $ StaffTypeEditorial
| s == "regular" = return $ StaffTypeRegular
| s == "alternate" = return $ StaffTypeAlternate
| otherwise = P.xfail $ "StaffType: " ++ s
-- | @start-note@ /(simple)/
--
-- The start-note type describes the starting note of trills and mordents for playback, relative to the current note.
data StartNote =
StartNoteUpper -- ^ /upper/
| StartNoteMain -- ^ /main/
| StartNoteBelow -- ^ /below/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml StartNote where
emitXml StartNoteUpper = XLit "upper"
emitXml StartNoteMain = XLit "main"
emitXml StartNoteBelow = XLit "below"
parseStartNote :: String -> P.XParse StartNote
parseStartNote s
| s == "upper" = return $ StartNoteUpper
| s == "main" = return $ StartNoteMain
| s == "below" = return $ StartNoteBelow
| otherwise = P.xfail $ "StartNote: " ++ s
-- | @start-stop@ /(simple)/
--
-- The start-stop type is used for an attribute of musical elements that can either start or stop, such as tuplets.
--
-- The values of start and stop refer to how an element appears in musical score order, not in MusicXML document order. An element with a stop attribute may precede the corresponding element with a start attribute within a MusicXML document. This is particularly common in multi-staff music. For example, the stopping point for a tuplet may appear in staff 1 before the starting point for the tuplet appears in staff 2 later in the document.
data StartStop =
StartStopStart -- ^ /start/
| StartStopStop -- ^ /stop/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml StartStop where
emitXml StartStopStart = XLit "start"
emitXml StartStopStop = XLit "stop"
parseStartStop :: String -> P.XParse StartStop
parseStartStop s
| s == "start" = return $ StartStopStart
| s == "stop" = return $ StartStopStop
| otherwise = P.xfail $ "StartStop: " ++ s
-- | @start-stop-change-continue@ /(simple)/
--
-- The start-stop-change-continue type is used to distinguish types of pedal directions.
data StartStopChangeContinue =
StartStopChangeContinueStart -- ^ /start/
| StartStopChangeContinueStop -- ^ /stop/
| StartStopChangeContinueChange -- ^ /change/
| StartStopChangeContinueContinue -- ^ /continue/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml StartStopChangeContinue where
emitXml StartStopChangeContinueStart = XLit "start"
emitXml StartStopChangeContinueStop = XLit "stop"
emitXml StartStopChangeContinueChange = XLit "change"
emitXml StartStopChangeContinueContinue = XLit "continue"
parseStartStopChangeContinue :: String -> P.XParse StartStopChangeContinue
parseStartStopChangeContinue s
| s == "start" = return $ StartStopChangeContinueStart
| s == "stop" = return $ StartStopChangeContinueStop
| s == "change" = return $ StartStopChangeContinueChange
| s == "continue" = return $ StartStopChangeContinueContinue
| otherwise = P.xfail $ "StartStopChangeContinue: " ++ s
-- | @start-stop-continue@ /(simple)/
--
-- The start-stop-continue type is used for an attribute of musical elements that can either start or stop, but also need to refer to an intermediate point in the symbol, as for complex slurs or for formatting of symbols across system breaks.
--
-- The values of start, stop, and continue refer to how an element appears in musical score order, not in MusicXML document order. An element with a stop attribute may precede the corresponding element with a start attribute within a MusicXML document. This is particularly common in multi-staff music. For example, the stopping point for a slur may appear in staff 1 before the starting point for the slur appears in staff 2 later in the document.
data StartStopContinue =
StartStopContinueStart -- ^ /start/
| StartStopContinueStop -- ^ /stop/
| StartStopContinueContinue -- ^ /continue/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml StartStopContinue where
emitXml StartStopContinueStart = XLit "start"
emitXml StartStopContinueStop = XLit "stop"
emitXml StartStopContinueContinue = XLit "continue"
parseStartStopContinue :: String -> P.XParse StartStopContinue
parseStartStopContinue s
| s == "start" = return $ StartStopContinueStart
| s == "stop" = return $ StartStopContinueStop
| s == "continue" = return $ StartStopContinueContinue
| otherwise = P.xfail $ "StartStopContinue: " ++ s
-- | @start-stop-discontinue@ /(simple)/
--
-- The start-stop-discontinue type is used to specify ending types. Typically, the start type is associated with the left barline of the first measure in an ending. The stop and discontinue types are associated with the right barline of the last measure in an ending. Stop is used when the ending mark concludes with a downward jog, as is typical for first endings. Discontinue is used when there is no downward jog, as is typical for second endings that do not conclude a piece.
data StartStopDiscontinue =
StartStopDiscontinueStart -- ^ /start/
| StartStopDiscontinueStop -- ^ /stop/
| StartStopDiscontinueDiscontinue -- ^ /discontinue/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml StartStopDiscontinue where
emitXml StartStopDiscontinueStart = XLit "start"
emitXml StartStopDiscontinueStop = XLit "stop"
emitXml StartStopDiscontinueDiscontinue = XLit "discontinue"
parseStartStopDiscontinue :: String -> P.XParse StartStopDiscontinue
parseStartStopDiscontinue s
| s == "start" = return $ StartStopDiscontinueStart
| s == "stop" = return $ StartStopDiscontinueStop
| s == "discontinue" = return $ StartStopDiscontinueDiscontinue
| otherwise = P.xfail $ "StartStopDiscontinue: " ++ s
-- | @start-stop-single@ /(simple)/
--
-- The start-stop-single type is used for an attribute of musical elements that can be used for either multi-note or single-note musical elements, as for tremolos.
data StartStopSingle =
StartStopSingleStart -- ^ /start/
| StartStopSingleStop -- ^ /stop/
| StartStopSingleSingle -- ^ /single/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml StartStopSingle where
emitXml StartStopSingleStart = XLit "start"
emitXml StartStopSingleStop = XLit "stop"
emitXml StartStopSingleSingle = XLit "single"
parseStartStopSingle :: String -> P.XParse StartStopSingle
parseStartStopSingle s
| s == "start" = return $ StartStopSingleStart
| s == "stop" = return $ StartStopSingleStop
| s == "single" = return $ StartStopSingleSingle
| otherwise = P.xfail $ "StartStopSingle: " ++ s
-- | @stem-value@ /(simple)/
--
-- The stem type represents the notated stem direction.
data StemValue =
StemValueDown -- ^ /down/
| StemValueUp -- ^ /up/
| StemValueDouble -- ^ /double/
| StemValueNone -- ^ /none/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml StemValue where
emitXml StemValueDown = XLit "down"
emitXml StemValueUp = XLit "up"
emitXml StemValueDouble = XLit "double"
emitXml StemValueNone = XLit "none"
parseStemValue :: String -> P.XParse StemValue
parseStemValue s
| s == "down" = return $ StemValueDown
| s == "up" = return $ StemValueUp
| s == "double" = return $ StemValueDouble
| s == "none" = return $ StemValueNone
| otherwise = P.xfail $ "StemValue: " ++ s
-- | @step@ /(simple)/
--
-- The step type represents a step of the diatonic scale, represented using the English letters A through G.
data Step =
StepA -- ^ /A/
| StepB -- ^ /B/
| StepC -- ^ /C/
| StepD -- ^ /D/
| StepE -- ^ /E/
| StepF -- ^ /F/
| StepG -- ^ /G/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml Step where
emitXml StepA = XLit "A"
emitXml StepB = XLit "B"
emitXml StepC = XLit "C"
emitXml StepD = XLit "D"
emitXml StepE = XLit "E"
emitXml StepF = XLit "F"
emitXml StepG = XLit "G"
parseStep :: String -> P.XParse Step
parseStep s
| s == "A" = return $ StepA
| s == "B" = return $ StepB
| s == "C" = return $ StepC
| s == "D" = return $ StepD
| s == "E" = return $ StepE
| s == "F" = return $ StepF
| s == "G" = return $ StepG
| otherwise = P.xfail $ "Step: " ++ s
-- | @stick-location@ /(simple)/
--
-- The stick-location type represents pictograms for the location of sticks, beaters, or mallets on cymbals, gongs, drums, and other instruments.
data StickLocation =
StickLocationCenter -- ^ /center/
| StickLocationRim -- ^ /rim/
| StickLocationCymbalBell -- ^ /cymbal bell/
| StickLocationCymbalEdge -- ^ /cymbal edge/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml StickLocation where
emitXml StickLocationCenter = XLit "center"
emitXml StickLocationRim = XLit "rim"
emitXml StickLocationCymbalBell = XLit "cymbal bell"
emitXml StickLocationCymbalEdge = XLit "cymbal edge"
parseStickLocation :: String -> P.XParse StickLocation
parseStickLocation s
| s == "center" = return $ StickLocationCenter
| s == "rim" = return $ StickLocationRim
| s == "cymbal bell" = return $ StickLocationCymbalBell
| s == "cymbal edge" = return $ StickLocationCymbalEdge
| otherwise = P.xfail $ "StickLocation: " ++ s
-- | @stick-material@ /(simple)/
--
-- The stick-material type represents the material being displayed in a stick pictogram.
data StickMaterial =
StickMaterialSoft -- ^ /soft/
| StickMaterialMedium -- ^ /medium/
| StickMaterialHard -- ^ /hard/
| StickMaterialShaded -- ^ /shaded/
| StickMaterialX -- ^ /x/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml StickMaterial where
emitXml StickMaterialSoft = XLit "soft"
emitXml StickMaterialMedium = XLit "medium"
emitXml StickMaterialHard = XLit "hard"
emitXml StickMaterialShaded = XLit "shaded"
emitXml StickMaterialX = XLit "x"
parseStickMaterial :: String -> P.XParse StickMaterial
parseStickMaterial s
| s == "soft" = return $ StickMaterialSoft
| s == "medium" = return $ StickMaterialMedium
| s == "hard" = return $ StickMaterialHard
| s == "shaded" = return $ StickMaterialShaded
| s == "x" = return $ StickMaterialX
| otherwise = P.xfail $ "StickMaterial: " ++ s
-- | @stick-type@ /(simple)/
--
-- The stick-type type represents the shape of pictograms where the material
-- in the stick, mallet, or beater is represented in the pictogram.
data StickType =
StickTypeBassDrum -- ^ /bass drum/
| StickTypeDoubleBassDrum -- ^ /double bass drum/
| StickTypeTimpani -- ^ /timpani/
| StickTypeXylophone -- ^ /xylophone/
| StickTypeYarn -- ^ /yarn/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml StickType where
emitXml StickTypeBassDrum = XLit "bass drum"
emitXml StickTypeDoubleBassDrum = XLit "double bass drum"
emitXml StickTypeTimpani = XLit "timpani"
emitXml StickTypeXylophone = XLit "xylophone"
emitXml StickTypeYarn = XLit "yarn"
parseStickType :: String -> P.XParse StickType
parseStickType s
| s == "bass drum" = return $ StickTypeBassDrum
| s == "double bass drum" = return $ StickTypeDoubleBassDrum
| s == "timpani" = return $ StickTypeTimpani
| s == "xylophone" = return $ StickTypeXylophone
| s == "yarn" = return $ StickTypeYarn
| otherwise = P.xfail $ "StickType: " ++ s
-- | @string-number@ /(simple)/
--
-- The string-number type indicates a string number. Strings are numbered from high to low, with 1 being the highest pitched string.
newtype StringNumber = StringNumber { stringNumber :: PositiveInteger }
deriving (Eq,Typeable,Generic,Ord,Bounded,Enum,Num,Real,Integral)
instance Show StringNumber where show (StringNumber a) = show a
instance Read StringNumber where readsPrec i = map (A.first StringNumber) . readsPrec i
instance EmitXml StringNumber where
emitXml = emitXml . stringNumber
parseStringNumber :: String -> P.XParse StringNumber
parseStringNumber = P.xread "StringNumber"
-- | @syllabic@ /(simple)/
--
-- Lyric hyphenation is indicated by the syllabic type. The single, begin, end, and middle values represent single-syllable words, word-beginning syllables, word-ending syllables, and mid-word syllables, respectively.
data Syllabic =
SyllabicSingle -- ^ /single/
| SyllabicBegin -- ^ /begin/
| SyllabicEnd -- ^ /end/
| SyllabicMiddle -- ^ /middle/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml Syllabic where
emitXml SyllabicSingle = XLit "single"
emitXml SyllabicBegin = XLit "begin"
emitXml SyllabicEnd = XLit "end"
emitXml SyllabicMiddle = XLit "middle"
parseSyllabic :: String -> P.XParse Syllabic
parseSyllabic s
| s == "single" = return $ SyllabicSingle
| s == "begin" = return $ SyllabicBegin
| s == "end" = return $ SyllabicEnd
| s == "middle" = return $ SyllabicMiddle
| otherwise = P.xfail $ "Syllabic: " ++ s
-- | @symbol-size@ /(simple)/
--
-- The symbol-size type is used to indicate full vs. cue-sized vs. oversized symbols. The large value for oversized symbols was added in version 1.1.
data SymbolSize =
SymbolSizeFull -- ^ /full/
| SymbolSizeCue -- ^ /cue/
| SymbolSizeLarge -- ^ /large/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml SymbolSize where
emitXml SymbolSizeFull = XLit "full"
emitXml SymbolSizeCue = XLit "cue"
emitXml SymbolSizeLarge = XLit "large"
parseSymbolSize :: String -> P.XParse SymbolSize
parseSymbolSize s
| s == "full" = return $ SymbolSizeFull
| s == "cue" = return $ SymbolSizeCue
| s == "large" = return $ SymbolSizeLarge
| otherwise = P.xfail $ "SymbolSize: " ++ s
-- | @tenths@ /(simple)/
--
-- The tenths type is a number representing tenths of interline staff space (positive or negative). Both integer and decimal values are allowed, such as 5 for a half space and 2.5 for a quarter space. Interline space is measured from the middle of a staff line.
--
-- Distances in a MusicXML file are measured in tenths of staff space. Tenths are then scaled to millimeters within the scaling element, used in the defaults element at the start of a score. Individual staves can apply a scaling factor to adjust staff size. When a MusicXML element or attribute refers to tenths, it means the global tenths defined by the scaling element, not the local tenths as adjusted by the staff-size element.
newtype Tenths = Tenths { tenths :: Decimal }
deriving (Eq,Typeable,Generic,Ord,Num,Real,Fractional,RealFrac)
instance Show Tenths where show (Tenths a) = show a
instance Read Tenths where readsPrec i = map (A.first Tenths) . readsPrec i
instance EmitXml Tenths where
emitXml = emitXml . tenths
parseTenths :: String -> P.XParse Tenths
parseTenths = P.xread "Tenths"
-- | @text-direction@ /(simple)/
--
-- The text-direction type is used to adjust and override the Unicode bidirectional text algorithm, similar to the W3C Internationalization Tag Set recommendation. Values are ltr (left-to-right embed), rtl (right-to-left embed), lro (left-to-right bidi-override), and rlo (right-to-left bidi-override). The default value is ltr. This type is typically used by applications that store text in left-to-right visual order rather than logical order. Such applications can use the lro value to better communicate with other applications that more fully support bidirectional text.
data TextDirection =
TextDirectionLtr -- ^ /ltr/
| TextDirectionRtl -- ^ /rtl/
| TextDirectionLro -- ^ /lro/
| TextDirectionRlo -- ^ /rlo/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml TextDirection where
emitXml TextDirectionLtr = XLit "ltr"
emitXml TextDirectionRtl = XLit "rtl"
emitXml TextDirectionLro = XLit "lro"
emitXml TextDirectionRlo = XLit "rlo"
parseTextDirection :: String -> P.XParse TextDirection
parseTextDirection s
| s == "ltr" = return $ TextDirectionLtr
| s == "rtl" = return $ TextDirectionRtl
| s == "lro" = return $ TextDirectionLro
| s == "rlo" = return $ TextDirectionRlo
| otherwise = P.xfail $ "TextDirection: " ++ s
-- | @time-only@ /(simple)/
--
-- The time-only type is used to indicate that a particular playback-related element only applies particular times through a repeated section. The value is a comma-separated list of positive integers arranged in ascending order, indicating which times through the repeated section that the element applies.
newtype TimeOnly = TimeOnly { timeOnly :: Token }
deriving (Eq,Typeable,Generic,Ord,IsString)
instance Show TimeOnly where show (TimeOnly a) = show a
instance Read TimeOnly where readsPrec i = map (A.first TimeOnly) . readsPrec i
instance EmitXml TimeOnly where
emitXml = emitXml . timeOnly
parseTimeOnly :: String -> P.XParse TimeOnly
parseTimeOnly = return . fromString
-- | @time-relation@ /(simple)/
--
-- The time-relation type indicates the symbol used to represent the interchangeable aspect of dual time signatures.
data TimeRelation =
TimeRelationParentheses -- ^ /parentheses/
| TimeRelationBracket -- ^ /bracket/
| TimeRelationEquals -- ^ /equals/
| TimeRelationSlash -- ^ /slash/
| TimeRelationSpace -- ^ /space/
| TimeRelationHyphen -- ^ /hyphen/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml TimeRelation where
emitXml TimeRelationParentheses = XLit "parentheses"
emitXml TimeRelationBracket = XLit "bracket"
emitXml TimeRelationEquals = XLit "equals"
emitXml TimeRelationSlash = XLit "slash"
emitXml TimeRelationSpace = XLit "space"
emitXml TimeRelationHyphen = XLit "hyphen"
parseTimeRelation :: String -> P.XParse TimeRelation
parseTimeRelation s
| s == "parentheses" = return $ TimeRelationParentheses
| s == "bracket" = return $ TimeRelationBracket
| s == "equals" = return $ TimeRelationEquals
| s == "slash" = return $ TimeRelationSlash
| s == "space" = return $ TimeRelationSpace
| s == "hyphen" = return $ TimeRelationHyphen
| otherwise = P.xfail $ "TimeRelation: " ++ s
-- | @time-separator@ /(simple)/
--
-- The time-separator type indicates how to display the arrangement between the beats and beat-type values in a time signature. The default value is none. The horizontal, diagonal, and vertical values represent horizontal, diagonal lower-left to upper-right, and vertical lines respectively. For these values, the beats and beat-type values are arranged on either side of the separator line. The none value represents no separator with the beats and beat-type arranged vertically. The adjacent value represents no separator with the beats and beat-type arranged horizontally.
data TimeSeparator =
TimeSeparatorNone -- ^ /none/
| TimeSeparatorHorizontal -- ^ /horizontal/
| TimeSeparatorDiagonal -- ^ /diagonal/
| TimeSeparatorVertical -- ^ /vertical/
| TimeSeparatorAdjacent -- ^ /adjacent/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml TimeSeparator where
emitXml TimeSeparatorNone = XLit "none"
emitXml TimeSeparatorHorizontal = XLit "horizontal"
emitXml TimeSeparatorDiagonal = XLit "diagonal"
emitXml TimeSeparatorVertical = XLit "vertical"
emitXml TimeSeparatorAdjacent = XLit "adjacent"
parseTimeSeparator :: String -> P.XParse TimeSeparator
parseTimeSeparator s
| s == "none" = return $ TimeSeparatorNone
| s == "horizontal" = return $ TimeSeparatorHorizontal
| s == "diagonal" = return $ TimeSeparatorDiagonal
| s == "vertical" = return $ TimeSeparatorVertical
| s == "adjacent" = return $ TimeSeparatorAdjacent
| otherwise = P.xfail $ "TimeSeparator: " ++ s
-- | @time-symbol@ /(simple)/
--
-- The time-symbol type indicates how to display a time signature. The normal value is the usual fractional display, and is the implied symbol type if none is specified. Other options are the common and cut time symbols, as well as a single number with an implied denominator. The note symbol indicates that the beat-type should be represented with the corresponding downstem note rather than a number. The dotted-note symbol indicates that the beat-type should be represented with a dotted downstem note that corresponds to three times the beat-type value, and a numerator that is one third the beats value.
data TimeSymbol =
TimeSymbolCommon -- ^ /common/
| TimeSymbolCut -- ^ /cut/
| TimeSymbolSingleNumber -- ^ /single-number/
| TimeSymbolNote -- ^ /note/
| TimeSymbolDottedNote -- ^ /dotted-note/
| TimeSymbolNormal -- ^ /normal/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml TimeSymbol where
emitXml TimeSymbolCommon = XLit "common"
emitXml TimeSymbolCut = XLit "cut"
emitXml TimeSymbolSingleNumber = XLit "single-number"
emitXml TimeSymbolNote = XLit "note"
emitXml TimeSymbolDottedNote = XLit "dotted-note"
emitXml TimeSymbolNormal = XLit "normal"
parseTimeSymbol :: String -> P.XParse TimeSymbol
parseTimeSymbol s
| s == "common" = return $ TimeSymbolCommon
| s == "cut" = return $ TimeSymbolCut
| s == "single-number" = return $ TimeSymbolSingleNumber
| s == "note" = return $ TimeSymbolNote
| s == "dotted-note" = return $ TimeSymbolDottedNote
| s == "normal" = return $ TimeSymbolNormal
| otherwise = P.xfail $ "TimeSymbol: " ++ s
-- | @tip-direction@ /(simple)/
--
-- The tip-direction type represents the direction in which the tip of a stick or beater points, using Unicode arrow terminology.
data TipDirection =
TipDirectionUp -- ^ /up/
| TipDirectionDown -- ^ /down/
| TipDirectionLeft -- ^ /left/
| TipDirectionRight -- ^ /right/
| TipDirectionNorthwest -- ^ /northwest/
| TipDirectionNortheast -- ^ /northeast/
| TipDirectionSoutheast -- ^ /southeast/
| TipDirectionSouthwest -- ^ /southwest/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml TipDirection where
emitXml TipDirectionUp = XLit "up"
emitXml TipDirectionDown = XLit "down"
emitXml TipDirectionLeft = XLit "left"
emitXml TipDirectionRight = XLit "right"
emitXml TipDirectionNorthwest = XLit "northwest"
emitXml TipDirectionNortheast = XLit "northeast"
emitXml TipDirectionSoutheast = XLit "southeast"
emitXml TipDirectionSouthwest = XLit "southwest"
parseTipDirection :: String -> P.XParse TipDirection
parseTipDirection s
| s == "up" = return $ TipDirectionUp
| s == "down" = return $ TipDirectionDown
| s == "left" = return $ TipDirectionLeft
| s == "right" = return $ TipDirectionRight
| s == "northwest" = return $ TipDirectionNorthwest
| s == "northeast" = return $ TipDirectionNortheast
| s == "southeast" = return $ TipDirectionSoutheast
| s == "southwest" = return $ TipDirectionSouthwest
| otherwise = P.xfail $ "TipDirection: " ++ s
-- | @xs:token@ /(simple)/
newtype Token = Token { token :: NormalizedString }
deriving (Eq,Typeable,Generic,Ord,IsString)
instance Show Token where show (Token a) = show a
instance Read Token where readsPrec i = map (A.first Token) . readsPrec i
instance EmitXml Token where
emitXml = emitXml . token
parseToken :: String -> P.XParse Token
parseToken = return . fromString
-- | @top-bottom@ /(simple)/
--
-- The top-bottom type is used to indicate the top or bottom part of a vertical shape like non-arpeggiate.
data TopBottom =
TopBottomTop -- ^ /top/
| TopBottomBottom -- ^ /bottom/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml TopBottom where
emitXml TopBottomTop = XLit "top"
emitXml TopBottomBottom = XLit "bottom"
parseTopBottom :: String -> P.XParse TopBottom
parseTopBottom s
| s == "top" = return $ TopBottomTop
| s == "bottom" = return $ TopBottomBottom
| otherwise = P.xfail $ "TopBottom: " ++ s
-- | @tremolo-marks@ /(simple)/
--
-- The number of tremolo marks is represented by a number from 0 to 8: the same as beam-level with 0 added.
newtype TremoloMarks = TremoloMarks { tremoloMarks :: Int }
deriving (Eq,Typeable,Generic,Ord,Bounded,Enum,Num,Real,Integral)
instance Show TremoloMarks where show (TremoloMarks a) = show a
instance Read TremoloMarks where readsPrec i = map (A.first TremoloMarks) . readsPrec i
instance EmitXml TremoloMarks where
emitXml = emitXml . tremoloMarks
parseTremoloMarks :: String -> P.XParse TremoloMarks
parseTremoloMarks = P.xread "TremoloMarks"
-- | @trill-beats@ /(simple)/
--
-- The trill-beats type specifies the beats used in a trill-sound or bend-sound attribute group. It is a decimal value with a minimum value of 2.
newtype TrillBeats = TrillBeats { trillBeats :: Decimal }
deriving (Eq,Typeable,Generic,Ord,Num,Real,Fractional,RealFrac)
instance Show TrillBeats where show (TrillBeats a) = show a
instance Read TrillBeats where readsPrec i = map (A.first TrillBeats) . readsPrec i
instance EmitXml TrillBeats where
emitXml = emitXml . trillBeats
parseTrillBeats :: String -> P.XParse TrillBeats
parseTrillBeats = P.xread "TrillBeats"
-- | @trill-step@ /(simple)/
--
-- The trill-step type describes the alternating note of trills and mordents for playback, relative to the current note.
data TrillStep =
TrillStepWhole -- ^ /whole/
| TrillStepHalf -- ^ /half/
| TrillStepUnison -- ^ /unison/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml TrillStep where
emitXml TrillStepWhole = XLit "whole"
emitXml TrillStepHalf = XLit "half"
emitXml TrillStepUnison = XLit "unison"
parseTrillStep :: String -> P.XParse TrillStep
parseTrillStep s
| s == "whole" = return $ TrillStepWhole
| s == "half" = return $ TrillStepHalf
| s == "unison" = return $ TrillStepUnison
| otherwise = P.xfail $ "TrillStep: " ++ s
-- | @two-note-turn@ /(simple)/
--
-- The two-note-turn type describes the ending notes of trills and mordents for playback, relative to the current note.
data TwoNoteTurn =
TwoNoteTurnWhole -- ^ /whole/
| TwoNoteTurnHalf -- ^ /half/
| TwoNoteTurnNone -- ^ /none/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml TwoNoteTurn where
emitXml TwoNoteTurnWhole = XLit "whole"
emitXml TwoNoteTurnHalf = XLit "half"
emitXml TwoNoteTurnNone = XLit "none"
parseTwoNoteTurn :: String -> P.XParse TwoNoteTurn
parseTwoNoteTurn s
| s == "whole" = return $ TwoNoteTurnWhole
| s == "half" = return $ TwoNoteTurnHalf
| s == "none" = return $ TwoNoteTurnNone
| otherwise = P.xfail $ "TwoNoteTurn: " ++ s
-- | @xlink:type@ /(simple)/
data Type =
TypeSimple -- ^ /simple/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml Type where
emitXml TypeSimple = XLit "simple"
parseType :: String -> P.XParse Type
parseType s
| s == "simple" = return $ TypeSimple
| otherwise = P.xfail $ "Type: " ++ s
-- | @up-down@ /(simple)/
--
-- The up-down type is used for the direction of arrows and other pointed symbols like vertical accents, indicating which way the tip is pointing.
data UpDown =
UpDownUp -- ^ /up/
| UpDownDown -- ^ /down/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml UpDown where
emitXml UpDownUp = XLit "up"
emitXml UpDownDown = XLit "down"
parseUpDown :: String -> P.XParse UpDown
parseUpDown s
| s == "up" = return $ UpDownUp
| s == "down" = return $ UpDownDown
| otherwise = P.xfail $ "UpDown: " ++ s
-- | @up-down-stop-continue@ /(simple)/
--
-- The up-down-stop-continue type is used for octave-shift elements, indicating the direction of the shift from their true pitched values because of printing difficulty.
data UpDownStopContinue =
UpDownStopContinueUp -- ^ /up/
| UpDownStopContinueDown -- ^ /down/
| UpDownStopContinueStop -- ^ /stop/
| UpDownStopContinueContinue -- ^ /continue/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml UpDownStopContinue where
emitXml UpDownStopContinueUp = XLit "up"
emitXml UpDownStopContinueDown = XLit "down"
emitXml UpDownStopContinueStop = XLit "stop"
emitXml UpDownStopContinueContinue = XLit "continue"
parseUpDownStopContinue :: String -> P.XParse UpDownStopContinue
parseUpDownStopContinue s
| s == "up" = return $ UpDownStopContinueUp
| s == "down" = return $ UpDownStopContinueDown
| s == "stop" = return $ UpDownStopContinueStop
| s == "continue" = return $ UpDownStopContinueContinue
| otherwise = P.xfail $ "UpDownStopContinue: " ++ s
-- | @upright-inverted@ /(simple)/
--
-- The upright-inverted type describes the appearance of a fermata element. The value is upright if not specified.
data UprightInverted =
UprightInvertedUpright -- ^ /upright/
| UprightInvertedInverted -- ^ /inverted/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml UprightInverted where
emitXml UprightInvertedUpright = XLit "upright"
emitXml UprightInvertedInverted = XLit "inverted"
parseUprightInverted :: String -> P.XParse UprightInverted
parseUprightInverted s
| s == "upright" = return $ UprightInvertedUpright
| s == "inverted" = return $ UprightInvertedInverted
| otherwise = P.xfail $ "UprightInverted: " ++ s
-- | @valign@ /(simple)/
--
-- The valign type is used to indicate vertical alignment to the top, middle, bottom, or baseline of the text. Defaults are implementation-dependent.
data Valign =
ValignTop -- ^ /top/
| ValignMiddle -- ^ /middle/
| ValignBottom -- ^ /bottom/
| ValignBaseline -- ^ /baseline/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml Valign where
emitXml ValignTop = XLit "top"
emitXml ValignMiddle = XLit "middle"
emitXml ValignBottom = XLit "bottom"
emitXml ValignBaseline = XLit "baseline"
parseValign :: String -> P.XParse Valign
parseValign s
| s == "top" = return $ ValignTop
| s == "middle" = return $ ValignMiddle
| s == "bottom" = return $ ValignBottom
| s == "baseline" = return $ ValignBaseline
| otherwise = P.xfail $ "Valign: " ++ s
-- | @valign-image@ /(simple)/
--
-- The valign-image type is used to indicate vertical alignment for images and graphics, so it does not include a baseline value. Defaults are implementation-dependent.
data ValignImage =
ValignImageTop -- ^ /top/
| ValignImageMiddle -- ^ /middle/
| ValignImageBottom -- ^ /bottom/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml ValignImage where
emitXml ValignImageTop = XLit "top"
emitXml ValignImageMiddle = XLit "middle"
emitXml ValignImageBottom = XLit "bottom"
parseValignImage :: String -> P.XParse ValignImage
parseValignImage s
| s == "top" = return $ ValignImageTop
| s == "middle" = return $ ValignImageMiddle
| s == "bottom" = return $ ValignImageBottom
| otherwise = P.xfail $ "ValignImage: " ++ s
-- | @wedge-type@ /(simple)/
--
-- The wedge type is crescendo for the start of a wedge that is closed at the left side, diminuendo for the start of a wedge that is closed on the right side, and stop for the end of a wedge. The continue type is used for formatting wedges over a system break, or for other situations where a single wedge is divided into multiple segments.
data WedgeType =
WedgeTypeCrescendo -- ^ /crescendo/
| WedgeTypeDiminuendo -- ^ /diminuendo/
| WedgeTypeStop -- ^ /stop/
| WedgeTypeContinue -- ^ /continue/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml WedgeType where
emitXml WedgeTypeCrescendo = XLit "crescendo"
emitXml WedgeTypeDiminuendo = XLit "diminuendo"
emitXml WedgeTypeStop = XLit "stop"
emitXml WedgeTypeContinue = XLit "continue"
parseWedgeType :: String -> P.XParse WedgeType
parseWedgeType s
| s == "crescendo" = return $ WedgeTypeCrescendo
| s == "diminuendo" = return $ WedgeTypeDiminuendo
| s == "stop" = return $ WedgeTypeStop
| s == "continue" = return $ WedgeTypeContinue
| otherwise = P.xfail $ "WedgeType: " ++ s
-- | @winged@ /(simple)/
--
-- The winged attribute indicates whether the repeat has winged extensions that appear above and below the barline. The straight and curved values represent single wings, while the double-straight and double-curved values represent double wings. The none value indicates no wings and is the default.
data Winged =
WingedNone -- ^ /none/
| WingedStraight -- ^ /straight/
| WingedCurved -- ^ /curved/
| WingedDoubleStraight -- ^ /double-straight/
| WingedDoubleCurved -- ^ /double-curved/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml Winged where
emitXml WingedNone = XLit "none"
emitXml WingedStraight = XLit "straight"
emitXml WingedCurved = XLit "curved"
emitXml WingedDoubleStraight = XLit "double-straight"
emitXml WingedDoubleCurved = XLit "double-curved"
parseWinged :: String -> P.XParse Winged
parseWinged s
| s == "none" = return $ WingedNone
| s == "straight" = return $ WingedStraight
| s == "curved" = return $ WingedCurved
| s == "double-straight" = return $ WingedDoubleStraight
| s == "double-curved" = return $ WingedDoubleCurved
| otherwise = P.xfail $ "Winged: " ++ s
-- | @wood@ /(simple)/
--
-- The wood type represents pictograms for wood percussion instruments. The maraca and maracas values distinguish the one- and two-maraca versions of the pictogram. The vibraslap and castanets values are in addition to Stone's list.
data Wood =
WoodBoardClapper -- ^ /board clapper/
| WoodCabasa -- ^ /cabasa/
| WoodCastanets -- ^ /castanets/
| WoodClaves -- ^ /claves/
| WoodGuiro -- ^ /guiro/
| WoodLogDrum -- ^ /log drum/
| WoodMaraca -- ^ /maraca/
| WoodMaracas -- ^ /maracas/
| WoodRatchet -- ^ /ratchet/
| WoodSandpaperBlocks -- ^ /sandpaper blocks/
| WoodSlitDrum -- ^ /slit drum/
| WoodTempleBlock -- ^ /temple block/
| WoodVibraslap -- ^ /vibraslap/
| WoodWoodBlock -- ^ /wood block/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml Wood where
emitXml WoodBoardClapper = XLit "board clapper"
emitXml WoodCabasa = XLit "cabasa"
emitXml WoodCastanets = XLit "castanets"
emitXml WoodClaves = XLit "claves"
emitXml WoodGuiro = XLit "guiro"
emitXml WoodLogDrum = XLit "log drum"
emitXml WoodMaraca = XLit "maraca"
emitXml WoodMaracas = XLit "maracas"
emitXml WoodRatchet = XLit "ratchet"
emitXml WoodSandpaperBlocks = XLit "sandpaper blocks"
emitXml WoodSlitDrum = XLit "slit drum"
emitXml WoodTempleBlock = XLit "temple block"
emitXml WoodVibraslap = XLit "vibraslap"
emitXml WoodWoodBlock = XLit "wood block"
parseWood :: String -> P.XParse Wood
parseWood s
| s == "board clapper" = return $ WoodBoardClapper
| s == "cabasa" = return $ WoodCabasa
| s == "castanets" = return $ WoodCastanets
| s == "claves" = return $ WoodClaves
| s == "guiro" = return $ WoodGuiro
| s == "log drum" = return $ WoodLogDrum
| s == "maraca" = return $ WoodMaraca
| s == "maracas" = return $ WoodMaracas
| s == "ratchet" = return $ WoodRatchet
| s == "sandpaper blocks" = return $ WoodSandpaperBlocks
| s == "slit drum" = return $ WoodSlitDrum
| s == "temple block" = return $ WoodTempleBlock
| s == "vibraslap" = return $ WoodVibraslap
| s == "wood block" = return $ WoodWoodBlock
| otherwise = P.xfail $ "Wood: " ++ s
-- | @yes-no@ /(simple)/
--
-- The yes-no type is used for boolean-like attributes. We cannot use W3C XML Schema booleans due to their restrictions on expression of boolean values.
data YesNo =
YesNoYes -- ^ /yes/
| YesNoNo -- ^ /no/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml YesNo where
emitXml YesNoYes = XLit "yes"
emitXml YesNoNo = XLit "no"
parseYesNo :: String -> P.XParse YesNo
parseYesNo s
| s == "yes" = return $ YesNoYes
| s == "no" = return $ YesNoNo
| otherwise = P.xfail $ "YesNo: " ++ s
-- | @yes-no-number@ /(simple)/
--
-- The yes-no-number type is used for attributes that can be either boolean or numeric values.
data YesNoNumber =
YesNoNumberYesNo {
yesNoNumber1 :: YesNo
}
| YesNoNumberDecimal {
yesNoNumber2 :: Decimal
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml YesNoNumber where
emitXml (YesNoNumberYesNo a) = emitXml a
emitXml (YesNoNumberDecimal a) = emitXml a
parseYesNoNumber :: String -> P.XParse YesNoNumber
parseYesNoNumber s =
YesNoNumberYesNo
<$> parseYesNo s
<|> YesNoNumberDecimal
<$> (P.xread "Decimal") s
-- | @yyyy-mm-dd@ /(simple)/
--
-- Calendar dates are represented yyyy-mm-dd format, following ISO 8601. This is a W3C XML Schema date type, but without the optional timezone data.
newtype YyyyMmDd = YyyyMmDd { yyyyMmDd :: String }
deriving (Eq,Typeable,Generic,Ord,IsString)
instance Show YyyyMmDd where show (YyyyMmDd a) = show a
instance Read YyyyMmDd where readsPrec i = map (A.first YyyyMmDd) . readsPrec i
instance EmitXml YyyyMmDd where
emitXml = emitXml . yyyyMmDd
parseYyyyMmDd :: String -> P.XParse YyyyMmDd
parseYyyyMmDd = return . fromString
-- | @xml:lang@ /(union)/
data SumLang =
SumLang -- ^ //
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml SumLang where
emitXml SumLang = XLit ""
parseSumLang :: String -> P.XParse SumLang
parseSumLang s
| s == "" = return $ SumLang
| otherwise = P.xfail $ "SumLang: " ++ s
-- | @number-or-normal@ /(union)/
data SumNumberOrNormal =
NumberOrNormalNormal -- ^ /normal/
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml SumNumberOrNormal where
emitXml NumberOrNormalNormal = XLit "normal"
parseSumNumberOrNormal :: String -> P.XParse SumNumberOrNormal
parseSumNumberOrNormal s
| s == "normal" = return $ NumberOrNormalNormal
| otherwise = P.xfail $ "SumNumberOrNormal: " ++ s
-- | @positive-integer-or-empty@ /(union)/
data SumPositiveIntegerOrEmpty =
SumPositiveIntegerOrEmpty -- ^ //
deriving (Eq,Typeable,Generic,Show,Ord,Enum,Bounded)
instance EmitXml SumPositiveIntegerOrEmpty where
emitXml SumPositiveIntegerOrEmpty = XLit ""
parseSumPositiveIntegerOrEmpty :: String -> P.XParse SumPositiveIntegerOrEmpty
parseSumPositiveIntegerOrEmpty s
| s == "" = return $ SumPositiveIntegerOrEmpty
| otherwise = P.xfail $ "SumPositiveIntegerOrEmpty: " ++ s
-- | @accidental@ /(complex)/
--
-- The accidental type represents actual notated accidentals. Editorial and cautionary indications are indicated by attributes. Values for these attributes are "no" if not present. Specific graphic display such as parentheses, brackets, and size are controlled by the level-display attribute group.
data Accidental =
Accidental {
accidentalAccidentalValue :: AccidentalValue -- ^ text content
, accidentalCautionary :: (Maybe YesNo) -- ^ /cautionary/ attribute
, accidentalEditorial :: (Maybe YesNo) -- ^ /editorial/ attribute
, accidentalParentheses :: (Maybe YesNo) -- ^ /parentheses/ attribute
, accidentalBracket :: (Maybe YesNo) -- ^ /bracket/ attribute
, accidentalSize :: (Maybe SymbolSize) -- ^ /size/ attribute
, accidentalDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, accidentalDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, accidentalRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, accidentalRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, accidentalFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, accidentalFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, accidentalFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, accidentalFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, accidentalColor :: (Maybe Color) -- ^ /color/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Accidental where
emitXml (Accidental a b c d e f g h i j k l m n o) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "cautionary" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "editorial" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "parentheses" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "bracket" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "size" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) l] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) m] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) n] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) o])
[]
parseAccidental :: P.XParse Accidental
parseAccidental =
Accidental
<$> (P.xtext >>= parseAccidentalValue)
<*> P.optional (P.xattr (P.name "cautionary") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "editorial") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "parentheses") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "bracket") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "size") >>= parseSymbolSize)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
-- | Smart constructor for 'Accidental'
mkAccidental :: AccidentalValue -> Accidental
mkAccidental a = Accidental a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @accidental-mark@ /(complex)/
--
-- An accidental-mark can be used as a separate notation or as part of an ornament. When used in an ornament, position and placement are relative to the ornament, not relative to the note.
data AccidentalMark =
AccidentalMark {
accidentalMarkAccidentalValue :: AccidentalValue -- ^ text content
, accidentalMarkDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, accidentalMarkDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, accidentalMarkRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, accidentalMarkRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, accidentalMarkFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, accidentalMarkFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, accidentalMarkFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, accidentalMarkFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, accidentalMarkColor :: (Maybe Color) -- ^ /color/ attribute
, accidentalMarkPlacement :: (Maybe AboveBelow) -- ^ /placement/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml AccidentalMark where
emitXml (AccidentalMark a b c d e f g h i j k) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "placement" Nothing).emitXml) k])
[]
parseAccidentalMark :: P.XParse AccidentalMark
parseAccidentalMark =
AccidentalMark
<$> (P.xtext >>= parseAccidentalValue)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "placement") >>= parseAboveBelow)
-- | Smart constructor for 'AccidentalMark'
mkAccidentalMark :: AccidentalValue -> AccidentalMark
mkAccidentalMark a = AccidentalMark a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @accidental-text@ /(complex)/
--
-- The accidental-text type represents an element with an accidental value and text-formatting attributes.
data AccidentalText =
AccidentalText {
accidentalTextAccidentalValue :: AccidentalValue -- ^ text content
, accidentalTextLang :: (Maybe Lang) -- ^ /xml:lang/ attribute
, accidentalTextSpace :: (Maybe Space) -- ^ /xml:space/ attribute
, accidentalTextJustify :: (Maybe LeftCenterRight) -- ^ /justify/ attribute
, accidentalTextDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, accidentalTextDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, accidentalTextRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, accidentalTextRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, accidentalTextFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, accidentalTextFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, accidentalTextFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, accidentalTextFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, accidentalTextColor :: (Maybe Color) -- ^ /color/ attribute
, accidentalTextHalign :: (Maybe LeftCenterRight) -- ^ /halign/ attribute
, accidentalTextValign :: (Maybe Valign) -- ^ /valign/ attribute
, accidentalTextUnderline :: (Maybe NumberOfLines) -- ^ /underline/ attribute
, accidentalTextOverline :: (Maybe NumberOfLines) -- ^ /overline/ attribute
, accidentalTextLineThrough :: (Maybe NumberOfLines) -- ^ /line-through/ attribute
, accidentalTextRotation :: (Maybe RotationDegrees) -- ^ /rotation/ attribute
, accidentalTextLetterSpacing :: (Maybe NumberOrNormal) -- ^ /letter-spacing/ attribute
, accidentalTextLineHeight :: (Maybe NumberOrNormal) -- ^ /line-height/ attribute
, accidentalTextDir :: (Maybe TextDirection) -- ^ /dir/ attribute
, accidentalTextEnclosure :: (Maybe EnclosureShape) -- ^ /enclosure/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml AccidentalText where
emitXml (AccidentalText a b c d e f g h i j k l m n o p q r s t u v w) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "lang" (Just "xml")).emitXml) b] ++
[maybe XEmpty (XAttr (QN "space" (Just "xml")).emitXml) c] ++
[maybe XEmpty (XAttr (QN "justify" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) l] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) m] ++
[maybe XEmpty (XAttr (QN "halign" Nothing).emitXml) n] ++
[maybe XEmpty (XAttr (QN "valign" Nothing).emitXml) o] ++
[maybe XEmpty (XAttr (QN "underline" Nothing).emitXml) p] ++
[maybe XEmpty (XAttr (QN "overline" Nothing).emitXml) q] ++
[maybe XEmpty (XAttr (QN "line-through" Nothing).emitXml) r] ++
[maybe XEmpty (XAttr (QN "rotation" Nothing).emitXml) s] ++
[maybe XEmpty (XAttr (QN "letter-spacing" Nothing).emitXml) t] ++
[maybe XEmpty (XAttr (QN "line-height" Nothing).emitXml) u] ++
[maybe XEmpty (XAttr (QN "dir" Nothing).emitXml) v] ++
[maybe XEmpty (XAttr (QN "enclosure" Nothing).emitXml) w])
[]
parseAccidentalText :: P.XParse AccidentalText
parseAccidentalText =
AccidentalText
<$> (P.xtext >>= parseAccidentalValue)
<*> P.optional (P.xattr (P.name "xml:lang") >>= parseLang)
<*> P.optional (P.xattr (P.name "xml:space") >>= parseSpace)
<*> P.optional (P.xattr (P.name "justify") >>= parseLeftCenterRight)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "halign") >>= parseLeftCenterRight)
<*> P.optional (P.xattr (P.name "valign") >>= parseValign)
<*> P.optional (P.xattr (P.name "underline") >>= parseNumberOfLines)
<*> P.optional (P.xattr (P.name "overline") >>= parseNumberOfLines)
<*> P.optional (P.xattr (P.name "line-through") >>= parseNumberOfLines)
<*> P.optional (P.xattr (P.name "rotation") >>= parseRotationDegrees)
<*> P.optional (P.xattr (P.name "letter-spacing") >>= parseNumberOrNormal)
<*> P.optional (P.xattr (P.name "line-height") >>= parseNumberOrNormal)
<*> P.optional (P.xattr (P.name "dir") >>= parseTextDirection)
<*> P.optional (P.xattr (P.name "enclosure") >>= parseEnclosureShape)
-- | Smart constructor for 'AccidentalText'
mkAccidentalText :: AccidentalValue -> AccidentalText
mkAccidentalText a = AccidentalText a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @accord@ /(complex)/
--
-- The accord type represents the tuning of a single string in the scordatura element. It uses the same group of elements as the staff-tuning element. Strings are numbered from high to low.
data Accord =
Accord {
accordString :: (Maybe StringNumber) -- ^ /string/ attribute
, accordTuning :: Tuning
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Accord where
emitXml (Accord a b) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "string" Nothing).emitXml) a])
([emitXml b])
parseAccord :: P.XParse Accord
parseAccord =
Accord
<$> P.optional (P.xattr (P.name "string") >>= parseStringNumber)
<*> parseTuning
-- | Smart constructor for 'Accord'
mkAccord :: Tuning -> Accord
mkAccord b = Accord Nothing b
-- | @accordion-registration@ /(complex)/
--
-- The accordion-registration type is use for accordion registration symbols. These are circular symbols divided horizontally into high, middle, and low sections that correspond to 4', 8', and 16' pipes. Each accordion-high, accordion-middle, and accordion-low element represents the presence of one or more dots in the registration diagram. An accordion-registration element needs to have at least one of the child elements present.
data AccordionRegistration =
AccordionRegistration {
accordionRegistrationDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, accordionRegistrationDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, accordionRegistrationRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, accordionRegistrationRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, accordionRegistrationFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, accordionRegistrationFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, accordionRegistrationFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, accordionRegistrationFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, accordionRegistrationColor :: (Maybe Color) -- ^ /color/ attribute
, accordionRegistrationHalign :: (Maybe LeftCenterRight) -- ^ /halign/ attribute
, accordionRegistrationValign :: (Maybe Valign) -- ^ /valign/ attribute
, accordionRegistrationAccordionHigh :: (Maybe Empty) -- ^ /accordion-high/ child element
, accordionRegistrationAccordionMiddle :: (Maybe AccordionMiddle) -- ^ /accordion-middle/ child element
, accordionRegistrationAccordionLow :: (Maybe Empty) -- ^ /accordion-low/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml AccordionRegistration where
emitXml (AccordionRegistration a b c d e f g h i j k l m n) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "halign" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "valign" Nothing).emitXml) k])
([maybe XEmpty (XElement (QN "accordion-high" Nothing).emitXml) l] ++
[maybe XEmpty (XElement (QN "accordion-middle" Nothing).emitXml) m] ++
[maybe XEmpty (XElement (QN "accordion-low" Nothing).emitXml) n])
parseAccordionRegistration :: P.XParse AccordionRegistration
parseAccordionRegistration =
AccordionRegistration
<$> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "halign") >>= parseLeftCenterRight)
<*> P.optional (P.xattr (P.name "valign") >>= parseValign)
<*> P.optional (P.xchild (P.name "accordion-high") (parseEmpty))
<*> P.optional (P.xchild (P.name "accordion-middle") (P.xtext >>= parseAccordionMiddle))
<*> P.optional (P.xchild (P.name "accordion-low") (parseEmpty))
-- | Smart constructor for 'AccordionRegistration'
mkAccordionRegistration :: AccordionRegistration
mkAccordionRegistration = AccordionRegistration Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @appearance@ /(complex)/
--
-- The appearance type controls general graphical settings for the music's final form appearance on a printed page of display. This includes support for line widths, definitions for note sizes, and standard distances between notation elements, plus an extension element for other aspects of appearance.
data Appearance =
Appearance {
appearanceLineWidth :: [LineWidth] -- ^ /line-width/ child element
, appearanceNoteSize :: [NoteSize] -- ^ /note-size/ child element
, appearanceDistance :: [Distance] -- ^ /distance/ child element
, appearanceOtherAppearance :: [OtherAppearance] -- ^ /other-appearance/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Appearance where
emitXml (Appearance a b c d) =
XContent XEmpty
[]
(map (XElement (QN "line-width" Nothing).emitXml) a ++
map (XElement (QN "note-size" Nothing).emitXml) b ++
map (XElement (QN "distance" Nothing).emitXml) c ++
map (XElement (QN "other-appearance" Nothing).emitXml) d)
parseAppearance :: P.XParse Appearance
parseAppearance =
Appearance
<$> P.many (P.xchild (P.name "line-width") (parseLineWidth))
<*> P.many (P.xchild (P.name "note-size") (parseNoteSize))
<*> P.many (P.xchild (P.name "distance") (parseDistance))
<*> P.many (P.xchild (P.name "other-appearance") (parseOtherAppearance))
-- | Smart constructor for 'Appearance'
mkAppearance :: Appearance
mkAppearance = Appearance [] [] [] []
-- | @arpeggiate@ /(complex)/
--
-- The arpeggiate type indicates that this note is part of an arpeggiated chord. The number attribute can be used to distinguish between two simultaneous chords arpeggiated separately (different numbers) or together (same number). The up-down attribute is used if there is an arrow on the arpeggio sign. By default, arpeggios go from the lowest to highest note.
data Arpeggiate =
Arpeggiate {
arpeggiateNumber :: (Maybe NumberLevel) -- ^ /number/ attribute
, arpeggiateDirection :: (Maybe UpDown) -- ^ /direction/ attribute
, arpeggiateDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, arpeggiateDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, arpeggiateRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, arpeggiateRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, arpeggiatePlacement :: (Maybe AboveBelow) -- ^ /placement/ attribute
, arpeggiateColor :: (Maybe Color) -- ^ /color/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Arpeggiate where
emitXml (Arpeggiate a b c d e f g h) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "number" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "direction" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "placement" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) h])
[]
parseArpeggiate :: P.XParse Arpeggiate
parseArpeggiate =
Arpeggiate
<$> P.optional (P.xattr (P.name "number") >>= parseNumberLevel)
<*> P.optional (P.xattr (P.name "direction") >>= parseUpDown)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "placement") >>= parseAboveBelow)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
-- | Smart constructor for 'Arpeggiate'
mkArpeggiate :: Arpeggiate
mkArpeggiate = Arpeggiate Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @arrow@ /(complex)/
--
-- The arrow element represents an arrow used for a musical technical indication..
data Arrow =
Arrow {
arrowDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, arrowDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, arrowRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, arrowRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, arrowFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, arrowFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, arrowFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, arrowFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, arrowColor :: (Maybe Color) -- ^ /color/ attribute
, arrowPlacement :: (Maybe AboveBelow) -- ^ /placement/ attribute
, arrowArrow :: ChxArrow
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Arrow where
emitXml (Arrow a b c d e f g h i j k) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "placement" Nothing).emitXml) j])
([emitXml k])
parseArrow :: P.XParse Arrow
parseArrow =
Arrow
<$> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "placement") >>= parseAboveBelow)
<*> parseChxArrow
-- | Smart constructor for 'Arrow'
mkArrow :: ChxArrow -> Arrow
mkArrow k = Arrow Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing k
-- | @articulations@ /(complex)/
--
-- Articulations and accents are grouped together here.
data Articulations =
Articulations {
articulationsArticulations :: [ChxArticulations]
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Articulations where
emitXml (Articulations a) =
XReps [emitXml a]
parseArticulations :: P.XParse Articulations
parseArticulations =
Articulations
<$> P.many (parseChxArticulations)
-- | Smart constructor for 'Articulations'
mkArticulations :: Articulations
mkArticulations = Articulations []
-- | @attributes@ /(complex)/
--
-- The attributes element contains musical information that typically changes on measure boundaries. This includes key and time signatures, clefs, transpositions, and staving. When attributes are changed mid-measure, it affects the music in score order, not in MusicXML document order.
data Attributes =
Attributes {
attributesEditorial :: Editorial
, attributesDivisions :: (Maybe PositiveDivisions) -- ^ /divisions/ child element
, attributesKey :: [Key] -- ^ /key/ child element
, attributesTime :: [Time] -- ^ /time/ child element
, attributesStaves :: (Maybe NonNegativeInteger) -- ^ /staves/ child element
, attributesPartSymbol :: (Maybe PartSymbol) -- ^ /part-symbol/ child element
, attributesInstruments :: (Maybe NonNegativeInteger) -- ^ /instruments/ child element
, attributesClef :: [Clef] -- ^ /clef/ child element
, attributesStaffDetails :: [StaffDetails] -- ^ /staff-details/ child element
, attributesTranspose :: [Transpose] -- ^ /transpose/ child element
, attributesDirective :: [Directive] -- ^ /directive/ child element
, attributesMeasureStyle :: [MeasureStyle] -- ^ /measure-style/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Attributes where
emitXml (Attributes a b c d e f g h i j k l) =
XContent XEmpty
[]
([emitXml a] ++
[maybe XEmpty (XElement (QN "divisions" Nothing).emitXml) b] ++
map (XElement (QN "key" Nothing).emitXml) c ++
map (XElement (QN "time" Nothing).emitXml) d ++
[maybe XEmpty (XElement (QN "staves" Nothing).emitXml) e] ++
[maybe XEmpty (XElement (QN "part-symbol" Nothing).emitXml) f] ++
[maybe XEmpty (XElement (QN "instruments" Nothing).emitXml) g] ++
map (XElement (QN "clef" Nothing).emitXml) h ++
map (XElement (QN "staff-details" Nothing).emitXml) i ++
map (XElement (QN "transpose" Nothing).emitXml) j ++
map (XElement (QN "directive" Nothing).emitXml) k ++
map (XElement (QN "measure-style" Nothing).emitXml) l)
parseAttributes :: P.XParse Attributes
parseAttributes =
Attributes
<$> parseEditorial
<*> P.optional (P.xchild (P.name "divisions") (P.xtext >>= parsePositiveDivisions))
<*> P.many (P.xchild (P.name "key") (parseKey))
<*> P.many (P.xchild (P.name "time") (parseTime))
<*> P.optional (P.xchild (P.name "staves") (P.xtext >>= parseNonNegativeInteger))
<*> P.optional (P.xchild (P.name "part-symbol") (parsePartSymbol))
<*> P.optional (P.xchild (P.name "instruments") (P.xtext >>= parseNonNegativeInteger))
<*> P.many (P.xchild (P.name "clef") (parseClef))
<*> P.many (P.xchild (P.name "staff-details") (parseStaffDetails))
<*> P.many (P.xchild (P.name "transpose") (parseTranspose))
<*> P.many (P.xchild (P.name "directive") (parseDirective))
<*> P.many (P.xchild (P.name "measure-style") (parseMeasureStyle))
-- | Smart constructor for 'Attributes'
mkAttributes :: Editorial -> Attributes
mkAttributes a = Attributes a Nothing [] [] Nothing Nothing Nothing [] [] [] [] []
-- | @backup@ /(complex)/
--
-- The backup and forward elements are required to coordinate multiple voices in one part, including music on multiple staves. The backup type is generally used to move between voices and staves. Thus the backup element does not include voice or staff elements. Duration values should always be positive, and should not cross measure boundaries or mid-measure changes in the divisions value.
data Backup =
Backup {
backupDuration :: Duration
, backupEditorial :: Editorial
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Backup where
emitXml (Backup a b) =
XReps [emitXml a,emitXml b]
parseBackup :: P.XParse Backup
parseBackup =
Backup
<$> parseDuration
<*> parseEditorial
-- | Smart constructor for 'Backup'
mkBackup :: Duration -> Editorial -> Backup
mkBackup a b = Backup a b
-- | @bar-style-color@ /(complex)/
--
-- The bar-style-color type contains barline style and color information.
data BarStyleColor =
BarStyleColor {
barStyleColorBarStyle :: BarStyle -- ^ text content
, barStyleColorColor :: (Maybe Color) -- ^ /color/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml BarStyleColor where
emitXml (BarStyleColor a b) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "color" Nothing).emitXml) b])
[]
parseBarStyleColor :: P.XParse BarStyleColor
parseBarStyleColor =
BarStyleColor
<$> (P.xtext >>= parseBarStyle)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
-- | Smart constructor for 'BarStyleColor'
mkBarStyleColor :: BarStyle -> BarStyleColor
mkBarStyleColor a = BarStyleColor a Nothing
-- | @barline@ /(complex)/
--
-- If a barline is other than a normal single barline, it should be represented by a barline type that describes it. This includes information about repeats and multiple endings, as well as line style. Barline data is on the same level as the other musical data in a score - a child of a measure in a partwise score, or a part in a timewise score. This allows for barlines within measures, as in dotted barlines that subdivide measures in complex meters. The two fermata elements allow for fermatas on both sides of the barline (the lower one inverted).
--
-- Barlines have a location attribute to make it easier to process barlines independently of the other musical data in a score. It is often easier to set up measures separately from entering notes. The location attribute must match where the barline element occurs within the rest of the musical data in the score. If location is left, it should be the first element in the measure, aside from the print, bookmark, and link elements. If location is right, it should be the last element, again with the possible exception of the print, bookmark, and link elements. If no location is specified, the right barline is the default. The segno, coda, and divisions attributes work the same way as in the sound element. They are used for playback when barline elements contain segno or coda child elements.
data Barline =
Barline {
barlineLocation :: (Maybe RightLeftMiddle) -- ^ /location/ attribute
, barlineSegno :: (Maybe Token) -- ^ /segno/ attribute
, barlineCoda :: (Maybe Token) -- ^ /coda/ attribute
, barlineDivisions :: (Maybe Divisions) -- ^ /divisions/ attribute
, barlineBarStyle :: (Maybe BarStyleColor) -- ^ /bar-style/ child element
, barlineEditorial :: Editorial
, barlineWavyLine :: (Maybe WavyLine) -- ^ /wavy-line/ child element
, barlineSegno1 :: (Maybe EmptyPrintStyleAlign) -- ^ /segno/ child element
, barlineCoda1 :: (Maybe EmptyPrintStyleAlign) -- ^ /coda/ child element
, barlineFermata :: [Fermata] -- ^ /fermata/ child element
, barlineEnding :: (Maybe Ending) -- ^ /ending/ child element
, barlineRepeat :: (Maybe Repeat) -- ^ /repeat/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Barline where
emitXml (Barline a b c d e f g h i j k l) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "location" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "segno" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "coda" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "divisions" Nothing).emitXml) d])
([maybe XEmpty (XElement (QN "bar-style" Nothing).emitXml) e] ++
[emitXml f] ++
[maybe XEmpty (XElement (QN "wavy-line" Nothing).emitXml) g] ++
[maybe XEmpty (XElement (QN "segno" Nothing).emitXml) h] ++
[maybe XEmpty (XElement (QN "coda" Nothing).emitXml) i] ++
map (XElement (QN "fermata" Nothing).emitXml) j ++
[maybe XEmpty (XElement (QN "ending" Nothing).emitXml) k] ++
[maybe XEmpty (XElement (QN "repeat" Nothing).emitXml) l])
parseBarline :: P.XParse Barline
parseBarline =
Barline
<$> P.optional (P.xattr (P.name "location") >>= parseRightLeftMiddle)
<*> P.optional (P.xattr (P.name "segno") >>= parseToken)
<*> P.optional (P.xattr (P.name "coda") >>= parseToken)
<*> P.optional (P.xattr (P.name "divisions") >>= parseDivisions)
<*> P.optional (P.xchild (P.name "bar-style") (parseBarStyleColor))
<*> parseEditorial
<*> P.optional (P.xchild (P.name "wavy-line") (parseWavyLine))
<*> P.optional (P.xchild (P.name "segno") (parseEmptyPrintStyleAlign))
<*> P.optional (P.xchild (P.name "coda") (parseEmptyPrintStyleAlign))
<*> P.many (P.xchild (P.name "fermata") (parseFermata))
<*> P.optional (P.xchild (P.name "ending") (parseEnding))
<*> P.optional (P.xchild (P.name "repeat") (parseRepeat))
-- | Smart constructor for 'Barline'
mkBarline :: Editorial -> Barline
mkBarline f = Barline Nothing Nothing Nothing Nothing Nothing f Nothing Nothing Nothing [] Nothing Nothing
-- | @barre@ /(complex)/
--
-- The barre element indicates placing a finger over multiple strings on a single fret. The type is "start" for the lowest pitched string (e.g., the string with the highest MusicXML number) and is "stop" for the highest pitched string.
data Barre =
Barre {
barreType :: StartStop -- ^ /type/ attribute
, barreColor :: (Maybe Color) -- ^ /color/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Barre where
emitXml (Barre a b) =
XContent XEmpty
([XAttr (QN "type" Nothing) (emitXml a)] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) b])
[]
parseBarre :: P.XParse Barre
parseBarre =
Barre
<$> (P.xattr (P.name "type") >>= parseStartStop)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
-- | Smart constructor for 'Barre'
mkBarre :: StartStop -> Barre
mkBarre a = Barre a Nothing
-- | @bass@ /(complex)/
--
-- The bass type is used to indicate a bass note in popular music chord symbols, e.g. G/C. It is generally not used in functional harmony, as inversion is generally not used in pop chord symbols. As with root, it is divided into step and alter elements, similar to pitches.
data Bass =
Bass {
bassBassStep :: BassStep -- ^ /bass-step/ child element
, bassBassAlter :: (Maybe BassAlter) -- ^ /bass-alter/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Bass where
emitXml (Bass a b) =
XContent XEmpty
[]
([XElement (QN "bass-step" Nothing) (emitXml a)] ++
[maybe XEmpty (XElement (QN "bass-alter" Nothing).emitXml) b])
parseBass :: P.XParse Bass
parseBass =
Bass
<$> (P.xchild (P.name "bass-step") (parseBassStep))
<*> P.optional (P.xchild (P.name "bass-alter") (parseBassAlter))
-- | Smart constructor for 'Bass'
mkBass :: BassStep -> Bass
mkBass a = Bass a Nothing
-- | @bass-alter@ /(complex)/
--
-- The bass-alter type represents the chromatic alteration of the bass of the current chord within the harmony element. In some chord styles, the text for the bass-step element may include bass-alter information. In that case, the print-object attribute of the bass-alter element can be set to no. The location attribute indicates whether the alteration should appear to the left or the right of the bass-step; it is right by default.
data BassAlter =
BassAlter {
bassAlterSemitones :: Semitones -- ^ text content
, bassAlterLocation :: (Maybe LeftRight) -- ^ /location/ attribute
, bassAlterPrintObject :: (Maybe YesNo) -- ^ /print-object/ attribute
, bassAlterDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, bassAlterDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, bassAlterRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, bassAlterRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, bassAlterFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, bassAlterFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, bassAlterFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, bassAlterFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, bassAlterColor :: (Maybe Color) -- ^ /color/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml BassAlter where
emitXml (BassAlter a b c d e f g h i j k l) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "location" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "print-object" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) l])
[]
parseBassAlter :: P.XParse BassAlter
parseBassAlter =
BassAlter
<$> (P.xtext >>= parseSemitones)
<*> P.optional (P.xattr (P.name "location") >>= parseLeftRight)
<*> P.optional (P.xattr (P.name "print-object") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
-- | Smart constructor for 'BassAlter'
mkBassAlter :: Semitones -> BassAlter
mkBassAlter a = BassAlter a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @bass-step@ /(complex)/
--
-- The bass-step type represents the pitch step of the bass of the current chord within the harmony element. The text attribute indicates how the bass should appear in a score if not using the element contents.
data BassStep =
BassStep {
bassStepStep :: Step -- ^ text content
, bassStepText :: (Maybe Token) -- ^ /text/ attribute
, bassStepDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, bassStepDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, bassStepRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, bassStepRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, bassStepFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, bassStepFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, bassStepFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, bassStepFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, bassStepColor :: (Maybe Color) -- ^ /color/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml BassStep where
emitXml (BassStep a b c d e f g h i j k) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "text" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) k])
[]
parseBassStep :: P.XParse BassStep
parseBassStep =
BassStep
<$> (P.xtext >>= parseStep)
<*> P.optional (P.xattr (P.name "text") >>= parseToken)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
-- | Smart constructor for 'BassStep'
mkBassStep :: Step -> BassStep
mkBassStep a = BassStep a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @beam@ /(complex)/
--
-- Beam values include begin, continue, end, forward hook, and backward hook. Up to eight concurrent beams are available to cover up to 1024th notes. Each beam in a note is represented with a separate beam element, starting with the eighth note beam using a number attribute of 1.
--
-- Note that the beam number does not distinguish sets of beams that overlap, as it does for slur and other elements. Beaming groups are distinguished by being in different voices and/or the presence or absence of grace and cue elements.
--
-- Beams that have a begin value can also have a fan attribute to indicate accelerandos and ritardandos using fanned beams. The fan attribute may also be used with a continue value if the fanning direction changes on that note. The value is "none" if not specified.
--
-- The repeater attribute has been deprecated in MusicXML 3.0. Formerly used for tremolos, it needs to be specified with a "yes" value for each beam using it.
data Beam =
Beam {
beamBeamValue :: BeamValue -- ^ text content
, beamNumber :: (Maybe BeamLevel) -- ^ /number/ attribute
, beamRepeater :: (Maybe YesNo) -- ^ /repeater/ attribute
, beamFan :: (Maybe Fan) -- ^ /fan/ attribute
, beamColor :: (Maybe Color) -- ^ /color/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Beam where
emitXml (Beam a b c d e) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "number" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "repeater" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "fan" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) e])
[]
parseBeam :: P.XParse Beam
parseBeam =
Beam
<$> (P.xtext >>= parseBeamValue)
<*> P.optional (P.xattr (P.name "number") >>= parseBeamLevel)
<*> P.optional (P.xattr (P.name "repeater") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "fan") >>= parseFan)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
-- | Smart constructor for 'Beam'
mkBeam :: BeamValue -> Beam
mkBeam a = Beam a Nothing Nothing Nothing Nothing
-- | @beat-repeat@ /(complex)/
--
-- The beat-repeat type is used to indicate that a single beat (but possibly many notes) is repeated. Both the start and stop of the beat being repeated should be specified. The slashes attribute specifies the number of slashes to use in the symbol. The use-dots attribute indicates whether or not to use dots as well (for instance, with mixed rhythm patterns). By default, the value for slashes is 1 and the value for use-dots is no.
--
-- The beat-repeat element specifies a notation style for repetitions. The actual music being repeated needs to be repeated within the MusicXML file. This element specifies the notation that indicates the repeat.
data BeatRepeat =
BeatRepeat {
beatRepeatType :: StartStop -- ^ /type/ attribute
, beatRepeatSlashes :: (Maybe PositiveInteger) -- ^ /slashes/ attribute
, beatRepeatUseDots :: (Maybe YesNo) -- ^ /use-dots/ attribute
, beatRepeatSlash :: (Maybe Slash)
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml BeatRepeat where
emitXml (BeatRepeat a b c d) =
XContent XEmpty
([XAttr (QN "type" Nothing) (emitXml a)] ++
[maybe XEmpty (XAttr (QN "slashes" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "use-dots" Nothing).emitXml) c])
([emitXml d])
parseBeatRepeat :: P.XParse BeatRepeat
parseBeatRepeat =
BeatRepeat
<$> (P.xattr (P.name "type") >>= parseStartStop)
<*> P.optional (P.xattr (P.name "slashes") >>= parsePositiveInteger)
<*> P.optional (P.xattr (P.name "use-dots") >>= parseYesNo)
<*> P.optional (parseSlash)
-- | Smart constructor for 'BeatRepeat'
mkBeatRepeat :: StartStop -> BeatRepeat
mkBeatRepeat a = BeatRepeat a Nothing Nothing Nothing
-- | @beater@ /(complex)/
--
-- The beater type represents pictograms for beaters, mallets, and sticks that do not have different materials represented in the pictogram.
data Beater =
Beater {
beaterBeaterValue :: BeaterValue -- ^ text content
, beaterTip :: (Maybe TipDirection) -- ^ /tip/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Beater where
emitXml (Beater a b) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "tip" Nothing).emitXml) b])
[]
parseBeater :: P.XParse Beater
parseBeater =
Beater
<$> (P.xtext >>= parseBeaterValue)
<*> P.optional (P.xattr (P.name "tip") >>= parseTipDirection)
-- | Smart constructor for 'Beater'
mkBeater :: BeaterValue -> Beater
mkBeater a = Beater a Nothing
-- | @bend@ /(complex)/
--
-- The bend type is used in guitar and tablature. The bend-alter element indicates the number of steps in the bend, similar to the alter element. As with the alter element, numbers like 0.5 can be used to indicate microtones. Negative numbers indicate pre-bends or releases; the pre-bend and release elements are used to distinguish what is intended. A with-bar element indicates that the bend is to be done at the bridge with a whammy or vibrato bar. The content of the element indicates how this should be notated.
data Bend =
Bend {
bendDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, bendDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, bendRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, bendRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, bendFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, bendFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, bendFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, bendFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, bendColor :: (Maybe Color) -- ^ /color/ attribute
, bendAccelerate :: (Maybe YesNo) -- ^ /accelerate/ attribute
, bendBeats :: (Maybe TrillBeats) -- ^ /beats/ attribute
, bendFirstBeat :: (Maybe Percent) -- ^ /first-beat/ attribute
, bendLastBeat :: (Maybe Percent) -- ^ /last-beat/ attribute
, bendBendAlter :: Semitones -- ^ /bend-alter/ child element
, bendBend :: (Maybe ChxBend)
, bendWithBar :: (Maybe PlacementText) -- ^ /with-bar/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Bend where
emitXml (Bend a b c d e f g h i j k l m n o p) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "accelerate" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "beats" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "first-beat" Nothing).emitXml) l] ++
[maybe XEmpty (XAttr (QN "last-beat" Nothing).emitXml) m])
([XElement (QN "bend-alter" Nothing) (emitXml n)] ++
[emitXml o] ++
[maybe XEmpty (XElement (QN "with-bar" Nothing).emitXml) p])
parseBend :: P.XParse Bend
parseBend =
Bend
<$> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "accelerate") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "beats") >>= parseTrillBeats)
<*> P.optional (P.xattr (P.name "first-beat") >>= parsePercent)
<*> P.optional (P.xattr (P.name "last-beat") >>= parsePercent)
<*> (P.xchild (P.name "bend-alter") (P.xtext >>= parseSemitones))
<*> P.optional (parseChxBend)
<*> P.optional (P.xchild (P.name "with-bar") (parsePlacementText))
-- | Smart constructor for 'Bend'
mkBend :: Semitones -> Bend
mkBend n = Bend Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing n Nothing Nothing
-- | @bookmark@ /(complex)/
--
-- The bookmark type serves as a well-defined target for an incoming simple XLink.
data Bookmark =
Bookmark {
bookmarkId :: ID -- ^ /id/ attribute
, bookmarkName :: (Maybe Token) -- ^ /name/ attribute
, bookmarkElement :: (Maybe NMTOKEN) -- ^ /element/ attribute
, bookmarkPosition :: (Maybe PositiveInteger) -- ^ /position/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Bookmark where
emitXml (Bookmark a b c d) =
XContent XEmpty
([XAttr (QN "id" Nothing) (emitXml a)] ++
[maybe XEmpty (XAttr (QN "name" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "element" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "position" Nothing).emitXml) d])
[]
parseBookmark :: P.XParse Bookmark
parseBookmark =
Bookmark
<$> (P.xattr (P.name "id") >>= parseID)
<*> P.optional (P.xattr (P.name "name") >>= parseToken)
<*> P.optional (P.xattr (P.name "element") >>= parseNMTOKEN)
<*> P.optional (P.xattr (P.name "position") >>= parsePositiveInteger)
-- | Smart constructor for 'Bookmark'
mkBookmark :: ID -> Bookmark
mkBookmark a = Bookmark a Nothing Nothing Nothing
-- | @bracket@ /(complex)/
--
-- Brackets are combined with words in a variety of modern directions. The line-end attribute specifies if there is a jog up or down (or both), an arrow, or nothing at the start or end of the bracket. If the line-end is up or down, the length of the jog can be specified using the end-length attribute. The line-type is solid by default.
data Bracket =
Bracket {
bracketType :: StartStopContinue -- ^ /type/ attribute
, bracketNumber :: (Maybe NumberLevel) -- ^ /number/ attribute
, bracketLineEnd :: LineEnd -- ^ /line-end/ attribute
, bracketEndLength :: (Maybe Tenths) -- ^ /end-length/ attribute
, bracketLineType :: (Maybe LineType) -- ^ /line-type/ attribute
, bracketDashLength :: (Maybe Tenths) -- ^ /dash-length/ attribute
, bracketSpaceLength :: (Maybe Tenths) -- ^ /space-length/ attribute
, bracketDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, bracketDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, bracketRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, bracketRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, bracketColor :: (Maybe Color) -- ^ /color/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Bracket where
emitXml (Bracket a b c d e f g h i j k l) =
XContent XEmpty
([XAttr (QN "type" Nothing) (emitXml a)] ++
[maybe XEmpty (XAttr (QN "number" Nothing).emitXml) b] ++
[XAttr (QN "line-end" Nothing) (emitXml c)] ++
[maybe XEmpty (XAttr (QN "end-length" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "line-type" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "dash-length" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "space-length" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) l])
[]
parseBracket :: P.XParse Bracket
parseBracket =
Bracket
<$> (P.xattr (P.name "type") >>= parseStartStopContinue)
<*> P.optional (P.xattr (P.name "number") >>= parseNumberLevel)
<*> (P.xattr (P.name "line-end") >>= parseLineEnd)
<*> P.optional (P.xattr (P.name "end-length") >>= parseTenths)
<*> P.optional (P.xattr (P.name "line-type") >>= parseLineType)
<*> P.optional (P.xattr (P.name "dash-length") >>= parseTenths)
<*> P.optional (P.xattr (P.name "space-length") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
-- | Smart constructor for 'Bracket'
mkBracket :: StartStopContinue -> LineEnd -> Bracket
mkBracket a c = Bracket a Nothing c Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @breath-mark@ /(complex)/
--
-- The breath-mark element indicates a place to take a breath.
data BreathMark =
BreathMark {
breathMarkBreathMarkValue :: BreathMarkValue -- ^ text content
, breathMarkDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, breathMarkDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, breathMarkRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, breathMarkRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, breathMarkFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, breathMarkFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, breathMarkFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, breathMarkFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, breathMarkColor :: (Maybe Color) -- ^ /color/ attribute
, breathMarkPlacement :: (Maybe AboveBelow) -- ^ /placement/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml BreathMark where
emitXml (BreathMark a b c d e f g h i j k) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "placement" Nothing).emitXml) k])
[]
parseBreathMark :: P.XParse BreathMark
parseBreathMark =
BreathMark
<$> (P.xtext >>= parseBreathMarkValue)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "placement") >>= parseAboveBelow)
-- | Smart constructor for 'BreathMark'
mkBreathMark :: BreathMarkValue -> BreathMark
mkBreathMark a = BreathMark a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @cancel@ /(complex)/
--
-- A cancel element indicates that the old key signature should be cancelled before the new one appears. This will always happen when changing to C major or A minor and need not be specified then. The cancel value matches the fifths value of the cancelled key signature (e.g., a cancel of -2 will provide an explicit cancellation for changing from B flat major to F major). The optional location attribute indicates whether the cancellation appears relative to the new key signature.
data Cancel =
Cancel {
cancelFifths :: Fifths -- ^ text content
, cancelLocation :: (Maybe CancelLocation) -- ^ /location/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Cancel where
emitXml (Cancel a b) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "location" Nothing).emitXml) b])
[]
parseCancel :: P.XParse Cancel
parseCancel =
Cancel
<$> (P.xtext >>= parseFifths)
<*> P.optional (P.xattr (P.name "location") >>= parseCancelLocation)
-- | Smart constructor for 'Cancel'
mkCancel :: Fifths -> Cancel
mkCancel a = Cancel a Nothing
-- | @clef@ /(complex)/
--
-- Clefs are represented by a combination of sign, line, and clef-octave-change elements. The optional number attribute refers to staff numbers within the part. A value of 1 is assumed if not present.
--
-- Sometimes clefs are added to the staff in non-standard line positions, either to indicate cue passages, or when there are multiple clefs present simultaneously on one staff. In this situation, the additional attribute is set to "yes" and the line value is ignored. The size attribute is used for clefs where the additional attribute is "yes". It is typically used to indicate cue clefs.
--
-- Sometimes clefs at the start of a measure need to appear after the barline rather than before, as for cues or for use after a repeated section. The after-barline attribute is set to "yes" in this situation. The attribute is ignored for mid-measure clefs.
--
-- Clefs appear at the start of each system unless the print-object attribute has been set to "no" or the additional attribute has been set to "yes".
data Clef =
Clef {
clefNumber :: (Maybe StaffNumber) -- ^ /number/ attribute
, clefAdditional :: (Maybe YesNo) -- ^ /additional/ attribute
, clefSize :: (Maybe SymbolSize) -- ^ /size/ attribute
, clefAfterBarline :: (Maybe YesNo) -- ^ /after-barline/ attribute
, clefDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, clefDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, clefRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, clefRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, clefFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, clefFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, clefFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, clefFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, clefColor :: (Maybe Color) -- ^ /color/ attribute
, clefPrintObject :: (Maybe YesNo) -- ^ /print-object/ attribute
, clefSign :: ClefSign -- ^ /sign/ child element
, clefLine :: (Maybe StaffLine) -- ^ /line/ child element
, clefClefOctaveChange :: (Maybe Int) -- ^ /clef-octave-change/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Clef where
emitXml (Clef a b c d e f g h i j k l m n o p q) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "number" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "additional" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "size" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "after-barline" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) l] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) m] ++
[maybe XEmpty (XAttr (QN "print-object" Nothing).emitXml) n])
([XElement (QN "sign" Nothing) (emitXml o)] ++
[maybe XEmpty (XElement (QN "line" Nothing).emitXml) p] ++
[maybe XEmpty (XElement (QN "clef-octave-change" Nothing).emitXml) q])
parseClef :: P.XParse Clef
parseClef =
Clef
<$> P.optional (P.xattr (P.name "number") >>= parseStaffNumber)
<*> P.optional (P.xattr (P.name "additional") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "size") >>= parseSymbolSize)
<*> P.optional (P.xattr (P.name "after-barline") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "print-object") >>= parseYesNo)
<*> (P.xchild (P.name "sign") (P.xtext >>= parseClefSign))
<*> P.optional (P.xchild (P.name "line") (P.xtext >>= parseStaffLine))
<*> P.optional (P.xchild (P.name "clef-octave-change") (P.xtext >>= (P.xread "Integer")))
-- | Smart constructor for 'Clef'
mkClef :: ClefSign -> Clef
mkClef o = Clef Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing o Nothing Nothing
-- | @credit@ /(complex)/
--
-- The credit type represents the appearance of the title, composer, arranger, lyricist, copyright, dedication, and other text and graphics that commonly appears on the first page of a score. The credit-words and credit-image elements are similar to the words and image elements for directions. However, since the credit is not part of a measure, the default-x and default-y attributes adjust the origin relative to the bottom left-hand corner of the first page. The enclosure for credit-words is none by default.
--
-- By default, a series of credit-words elements within a single credit element follow one another in sequence visually. Non-positional formatting attributes are carried over from the previous element by default.
--
-- The page attribute for the credit element, new in Version 2.0, specifies the page number where the credit should appear. This is an integer value that starts with 1 for the first page. Its value is 1 by default. Since credits occur before the music, these page numbers do not refer to the page numbering specified by the print element's page-number attribute.
--
-- The credit-type element, new in Version 3.0, indicates the purpose behind a credit. Multiple types of data may be combined in a single credit, so multiple elements may be used. Standard values include page number, title, subtitle, composer, arranger, lyricist, and rights.
data Credit =
Credit {
creditPage :: (Maybe PositiveInteger) -- ^ /page/ attribute
, creditCreditType :: [String] -- ^ /credit-type/ child element
, creditLink :: [Link] -- ^ /link/ child element
, creditBookmark :: [Bookmark] -- ^ /bookmark/ child element
, creditCredit :: ChxCredit
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Credit where
emitXml (Credit a b c d e) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "page" Nothing).emitXml) a])
(map (XElement (QN "credit-type" Nothing).emitXml) b ++
map (XElement (QN "link" Nothing).emitXml) c ++
map (XElement (QN "bookmark" Nothing).emitXml) d ++
[emitXml e])
parseCredit :: P.XParse Credit
parseCredit =
Credit
<$> P.optional (P.xattr (P.name "page") >>= parsePositiveInteger)
<*> P.many (P.xchild (P.name "credit-type") (P.xtext >>= return))
<*> P.many (P.xchild (P.name "link") (parseLink))
<*> P.many (P.xchild (P.name "bookmark") (parseBookmark))
<*> parseChxCredit
-- | Smart constructor for 'Credit'
mkCredit :: ChxCredit -> Credit
mkCredit e = Credit Nothing [] [] [] e
-- | @dashes@ /(complex)/
--
-- The dashes type represents dashes, used for instance with cresc. and dim. marks.
data Dashes =
Dashes {
dashesType :: StartStopContinue -- ^ /type/ attribute
, dashesNumber :: (Maybe NumberLevel) -- ^ /number/ attribute
, dashesDashLength :: (Maybe Tenths) -- ^ /dash-length/ attribute
, dashesSpaceLength :: (Maybe Tenths) -- ^ /space-length/ attribute
, dashesDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, dashesDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, dashesRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, dashesRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, dashesColor :: (Maybe Color) -- ^ /color/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Dashes where
emitXml (Dashes a b c d e f g h i) =
XContent XEmpty
([XAttr (QN "type" Nothing) (emitXml a)] ++
[maybe XEmpty (XAttr (QN "number" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "dash-length" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "space-length" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) i])
[]
parseDashes :: P.XParse Dashes
parseDashes =
Dashes
<$> (P.xattr (P.name "type") >>= parseStartStopContinue)
<*> P.optional (P.xattr (P.name "number") >>= parseNumberLevel)
<*> P.optional (P.xattr (P.name "dash-length") >>= parseTenths)
<*> P.optional (P.xattr (P.name "space-length") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
-- | Smart constructor for 'Dashes'
mkDashes :: StartStopContinue -> Dashes
mkDashes a = Dashes a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @defaults@ /(complex)/
--
-- The defaults type specifies score-wide defaults for scaling, layout, and appearance.
data Defaults =
Defaults {
defaultsScaling :: (Maybe Scaling) -- ^ /scaling/ child element
, defaultsLayout :: Layout
, defaultsAppearance :: (Maybe Appearance) -- ^ /appearance/ child element
, defaultsMusicFont :: (Maybe EmptyFont) -- ^ /music-font/ child element
, defaultsWordFont :: (Maybe EmptyFont) -- ^ /word-font/ child element
, defaultsLyricFont :: [LyricFont] -- ^ /lyric-font/ child element
, defaultsLyricLanguage :: [LyricLanguage] -- ^ /lyric-language/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Defaults where
emitXml (Defaults a b c d e f g) =
XContent XEmpty
[]
([maybe XEmpty (XElement (QN "scaling" Nothing).emitXml) a] ++
[emitXml b] ++
[maybe XEmpty (XElement (QN "appearance" Nothing).emitXml) c] ++
[maybe XEmpty (XElement (QN "music-font" Nothing).emitXml) d] ++
[maybe XEmpty (XElement (QN "word-font" Nothing).emitXml) e] ++
map (XElement (QN "lyric-font" Nothing).emitXml) f ++
map (XElement (QN "lyric-language" Nothing).emitXml) g)
parseDefaults :: P.XParse Defaults
parseDefaults =
Defaults
<$> P.optional (P.xchild (P.name "scaling") (parseScaling))
<*> parseLayout
<*> P.optional (P.xchild (P.name "appearance") (parseAppearance))
<*> P.optional (P.xchild (P.name "music-font") (parseEmptyFont))
<*> P.optional (P.xchild (P.name "word-font") (parseEmptyFont))
<*> P.many (P.xchild (P.name "lyric-font") (parseLyricFont))
<*> P.many (P.xchild (P.name "lyric-language") (parseLyricLanguage))
-- | Smart constructor for 'Defaults'
mkDefaults :: Layout -> Defaults
mkDefaults b = Defaults Nothing b Nothing Nothing Nothing [] []
-- | @degree@ /(complex)/
--
-- The degree type is used to add, alter, or subtract individual notes in the chord. The print-object attribute can be used to keep the degree from printing separately when it has already taken into account in the text attribute of the kind element. The degree-value and degree-type text attributes specify how the value and type of the degree should be displayed.
--
-- A harmony of kind "other" can be spelled explicitly by using a series of degree elements together with a root.
data Degree =
Degree {
degreePrintObject :: (Maybe YesNo) -- ^ /print-object/ attribute
, degreeDegreeValue :: DegreeValue -- ^ /degree-value/ child element
, degreeDegreeAlter :: DegreeAlter -- ^ /degree-alter/ child element
, degreeDegreeType :: DegreeType -- ^ /degree-type/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Degree where
emitXml (Degree a b c d) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "print-object" Nothing).emitXml) a])
([XElement (QN "degree-value" Nothing) (emitXml b)] ++
[XElement (QN "degree-alter" Nothing) (emitXml c)] ++
[XElement (QN "degree-type" Nothing) (emitXml d)])
parseDegree :: P.XParse Degree
parseDegree =
Degree
<$> P.optional (P.xattr (P.name "print-object") >>= parseYesNo)
<*> (P.xchild (P.name "degree-value") (parseDegreeValue))
<*> (P.xchild (P.name "degree-alter") (parseDegreeAlter))
<*> (P.xchild (P.name "degree-type") (parseDegreeType))
-- | Smart constructor for 'Degree'
mkDegree :: DegreeValue -> DegreeAlter -> DegreeType -> Degree
mkDegree b c d = Degree Nothing b c d
-- | @degree-alter@ /(complex)/
--
-- The degree-alter type represents the chromatic alteration for the current degree. If the degree-type value is alter or subtract, the degree-alter value is relative to the degree already in the chord based on its kind element. If the degree-type value is add, the degree-alter is relative to a dominant chord (major and perfect intervals except for a minor seventh). The plus-minus attribute is used to indicate if plus and minus symbols should be used instead of sharp and flat symbols to display the degree alteration; it is no by default.
data DegreeAlter =
DegreeAlter {
degreeAlterSemitones :: Semitones -- ^ text content
, degreeAlterPlusMinus :: (Maybe YesNo) -- ^ /plus-minus/ attribute
, degreeAlterDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, degreeAlterDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, degreeAlterRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, degreeAlterRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, degreeAlterFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, degreeAlterFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, degreeAlterFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, degreeAlterFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, degreeAlterColor :: (Maybe Color) -- ^ /color/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml DegreeAlter where
emitXml (DegreeAlter a b c d e f g h i j k) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "plus-minus" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) k])
[]
parseDegreeAlter :: P.XParse DegreeAlter
parseDegreeAlter =
DegreeAlter
<$> (P.xtext >>= parseSemitones)
<*> P.optional (P.xattr (P.name "plus-minus") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
-- | Smart constructor for 'DegreeAlter'
mkDegreeAlter :: Semitones -> DegreeAlter
mkDegreeAlter a = DegreeAlter a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @degree-type@ /(complex)/
--
-- The degree-type type indicates if this degree is an addition, alteration, or subtraction relative to the kind of the current chord. The value of the degree-type element affects the interpretation of the value of the degree-alter element. The text attribute specifies how the type of the degree should be displayed in a score.
data DegreeType =
DegreeType {
degreeTypeDegreeTypeValue :: DegreeTypeValue -- ^ text content
, degreeTypeText :: (Maybe Token) -- ^ /text/ attribute
, degreeTypeDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, degreeTypeDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, degreeTypeRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, degreeTypeRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, degreeTypeFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, degreeTypeFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, degreeTypeFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, degreeTypeFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, degreeTypeColor :: (Maybe Color) -- ^ /color/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml DegreeType where
emitXml (DegreeType a b c d e f g h i j k) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "text" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) k])
[]
parseDegreeType :: P.XParse DegreeType
parseDegreeType =
DegreeType
<$> (P.xtext >>= parseDegreeTypeValue)
<*> P.optional (P.xattr (P.name "text") >>= parseToken)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
-- | Smart constructor for 'DegreeType'
mkDegreeType :: DegreeTypeValue -> DegreeType
mkDegreeType a = DegreeType a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @degree-value@ /(complex)/
--
-- The content of the degree-value type is a number indicating the degree of the chord (1 for the root, 3 for third, etc). The text attribute specifies how the type of the degree should be displayed in a score. The degree-value symbol attribute indicates that a symbol should be used in specifying the degree. If the symbol attribute is present, the value of the text attribute follows the symbol.
data DegreeValue =
DegreeValue {
degreeValuePositiveInteger :: PositiveInteger -- ^ text content
, degreeValueSymbol :: (Maybe DegreeSymbolValue) -- ^ /symbol/ attribute
, degreeValueText :: (Maybe Token) -- ^ /text/ attribute
, degreeValueDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, degreeValueDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, degreeValueRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, degreeValueRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, degreeValueFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, degreeValueFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, degreeValueFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, degreeValueFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, degreeValueColor :: (Maybe Color) -- ^ /color/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml DegreeValue where
emitXml (DegreeValue a b c d e f g h i j k l) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "symbol" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "text" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) l])
[]
parseDegreeValue :: P.XParse DegreeValue
parseDegreeValue =
DegreeValue
<$> (P.xtext >>= parsePositiveInteger)
<*> P.optional (P.xattr (P.name "symbol") >>= parseDegreeSymbolValue)
<*> P.optional (P.xattr (P.name "text") >>= parseToken)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
-- | Smart constructor for 'DegreeValue'
mkDegreeValue :: PositiveInteger -> DegreeValue
mkDegreeValue a = DegreeValue a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @direction@ /(complex)/
--
-- A direction is a musical indication that is not attached to a specific note. Two or more may be combined to indicate starts and stops of wedges, dashes, etc.
--
-- By default, a series of direction-type elements and a series of child elements of a direction-type within a single direction element follow one another in sequence visually. For a series of direction-type children, non-positional formatting attributes are carried over from the previous element by default.
data Direction =
Direction {
directionPlacement :: (Maybe AboveBelow) -- ^ /placement/ attribute
, directionDirective :: (Maybe YesNo) -- ^ /directive/ attribute
, directionDirectionType :: [DirectionType] -- ^ /direction-type/ child element
, directionOffset :: (Maybe Offset) -- ^ /offset/ child element
, directionEditorialVoiceDirection :: EditorialVoiceDirection
, directionStaff :: (Maybe Staff)
, directionSound :: (Maybe Sound) -- ^ /sound/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Direction where
emitXml (Direction a b c d e f g) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "placement" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "directive" Nothing).emitXml) b])
(map (XElement (QN "direction-type" Nothing).emitXml) c ++
[maybe XEmpty (XElement (QN "offset" Nothing).emitXml) d] ++
[emitXml e] ++
[emitXml f] ++
[maybe XEmpty (XElement (QN "sound" Nothing).emitXml) g])
parseDirection :: P.XParse Direction
parseDirection =
Direction
<$> P.optional (P.xattr (P.name "placement") >>= parseAboveBelow)
<*> P.optional (P.xattr (P.name "directive") >>= parseYesNo)
<*> P.many (P.xchild (P.name "direction-type") (parseDirectionType))
<*> P.optional (P.xchild (P.name "offset") (parseOffset))
<*> parseEditorialVoiceDirection
<*> P.optional (parseStaff)
<*> P.optional (P.xchild (P.name "sound") (parseSound))
-- | Smart constructor for 'Direction'
mkDirection :: EditorialVoiceDirection -> Direction
mkDirection e = Direction Nothing Nothing [] Nothing e Nothing Nothing
-- | @direction-type@ /(complex)/
--
-- Textual direction types may have more than 1 component due to multiple fonts. The dynamics element may also be used in the notations element. Attribute groups related to print suggestions apply to the individual direction-type, not to the overall direction.
data DirectionType =
DirectionType {
directionTypeDirectionType :: ChxDirectionType
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml DirectionType where
emitXml (DirectionType a) =
XReps [emitXml a]
parseDirectionType :: P.XParse DirectionType
parseDirectionType =
DirectionType
<$> parseChxDirectionType
-- | Smart constructor for 'DirectionType'
mkDirectionType :: ChxDirectionType -> DirectionType
mkDirectionType a = DirectionType a
-- | @directive@ /(complex)/
data Directive =
Directive {
directiveString :: String -- ^ text content
, directiveLang :: (Maybe Lang) -- ^ /xml:lang/ attribute
, directiveDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, directiveDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, directiveRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, directiveRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, directiveFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, directiveFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, directiveFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, directiveFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, directiveColor :: (Maybe Color) -- ^ /color/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Directive where
emitXml (Directive a b c d e f g h i j k) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "lang" (Just "xml")).emitXml) b] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) k])
[]
parseDirective :: P.XParse Directive
parseDirective =
Directive
<$> (P.xtext >>= return)
<*> P.optional (P.xattr (P.name "xml:lang") >>= parseLang)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
-- | Smart constructor for 'Directive'
mkDirective :: String -> Directive
mkDirective a = Directive a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @distance@ /(complex)/
--
-- The distance element represents standard distances between notation elements in tenths. The type attribute defines what type of distance is being defined. Valid values include hyphen (for hyphens in lyrics) and beam.
data Distance =
Distance {
distanceTenths :: Tenths -- ^ text content
, cmpdistanceType :: DistanceType -- ^ /type/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Distance where
emitXml (Distance a b) =
XContent (emitXml a)
([XAttr (QN "type" Nothing) (emitXml b)])
[]
parseDistance :: P.XParse Distance
parseDistance =
Distance
<$> (P.xtext >>= parseTenths)
<*> (P.xattr (P.name "type") >>= parseDistanceType)
-- | Smart constructor for 'Distance'
mkDistance :: Tenths -> DistanceType -> Distance
mkDistance a b = Distance a b
-- | @dynamics@ /(complex)/
--
-- Dynamics can be associated either with a note or a general musical direction. To avoid inconsistencies between and amongst the letter abbreviations for dynamics (what is sf vs. sfz, standing alone or with a trailing dynamic that is not always piano), we use the actual letters as the names of these dynamic elements. The other-dynamics element allows other dynamic marks that are not covered here, but many of those should perhaps be included in a more general musical direction element. Dynamics elements may also be combined to create marks not covered by a single element, such as sfmp.
--
-- These letter dynamic symbols are separated from crescendo, decrescendo, and wedge indications. Dynamic representation is inconsistent in scores. Many things are assumed by the composer and left out, such as returns to original dynamics. Systematic representations are quite complex: for example, Humdrum has at least 3 representation formats related to dynamics. The MusicXML format captures what is in the score, but does not try to be optimal for analysis or synthesis of dynamics.
data Dynamics =
Dynamics {
dynamicsDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, dynamicsDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, dynamicsRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, dynamicsRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, dynamicsFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, dynamicsFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, dynamicsFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, dynamicsFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, dynamicsColor :: (Maybe Color) -- ^ /color/ attribute
, dynamicsHalign :: (Maybe LeftCenterRight) -- ^ /halign/ attribute
, dynamicsValign :: (Maybe Valign) -- ^ /valign/ attribute
, dynamicsPlacement :: (Maybe AboveBelow) -- ^ /placement/ attribute
, dynamicsUnderline :: (Maybe NumberOfLines) -- ^ /underline/ attribute
, dynamicsOverline :: (Maybe NumberOfLines) -- ^ /overline/ attribute
, dynamicsLineThrough :: (Maybe NumberOfLines) -- ^ /line-through/ attribute
, dynamicsEnclosure :: (Maybe EnclosureShape) -- ^ /enclosure/ attribute
, dynamicsDynamics :: [ChxDynamics]
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Dynamics where
emitXml (Dynamics a b c d e f g h i j k l m n o p q) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "halign" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "valign" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "placement" Nothing).emitXml) l] ++
[maybe XEmpty (XAttr (QN "underline" Nothing).emitXml) m] ++
[maybe XEmpty (XAttr (QN "overline" Nothing).emitXml) n] ++
[maybe XEmpty (XAttr (QN "line-through" Nothing).emitXml) o] ++
[maybe XEmpty (XAttr (QN "enclosure" Nothing).emitXml) p])
([emitXml q])
parseDynamics :: P.XParse Dynamics
parseDynamics =
Dynamics
<$> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "halign") >>= parseLeftCenterRight)
<*> P.optional (P.xattr (P.name "valign") >>= parseValign)
<*> P.optional (P.xattr (P.name "placement") >>= parseAboveBelow)
<*> P.optional (P.xattr (P.name "underline") >>= parseNumberOfLines)
<*> P.optional (P.xattr (P.name "overline") >>= parseNumberOfLines)
<*> P.optional (P.xattr (P.name "line-through") >>= parseNumberOfLines)
<*> P.optional (P.xattr (P.name "enclosure") >>= parseEnclosureShape)
<*> P.many (parseChxDynamics)
-- | Smart constructor for 'Dynamics'
mkDynamics :: Dynamics
mkDynamics = Dynamics Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing []
-- | @empty@ /(complex)/
--
-- The empty type represents an empty element with no attributes.
data Empty =
Empty
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Empty where
emitXml (Empty) =
XReps []
parseEmpty :: P.XParse Empty
parseEmpty =
return Empty
-- | Smart constructor for 'Empty'
mkEmpty :: Empty
mkEmpty = Empty
-- | @empty-font@ /(complex)/
--
-- The empty-font type represents an empty element with font attributes.
data EmptyFont =
EmptyFont {
emptyFontFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, emptyFontFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, emptyFontFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, emptyFontFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml EmptyFont where
emitXml (EmptyFont a b c d) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) d])
[]
parseEmptyFont :: P.XParse EmptyFont
parseEmptyFont =
EmptyFont
<$> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
-- | Smart constructor for 'EmptyFont'
mkEmptyFont :: EmptyFont
mkEmptyFont = EmptyFont Nothing Nothing Nothing Nothing
-- | @empty-line@ /(complex)/
--
-- The empty-line type represents an empty element with line-shape, line-type, dashed-formatting, print-style and placement attributes.
data EmptyLine =
EmptyLine {
emptyLineLineShape :: (Maybe LineShape) -- ^ /line-shape/ attribute
, emptyLineLineType :: (Maybe LineType) -- ^ /line-type/ attribute
, emptyLineDashLength :: (Maybe Tenths) -- ^ /dash-length/ attribute
, emptyLineSpaceLength :: (Maybe Tenths) -- ^ /space-length/ attribute
, emptyLineDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, emptyLineDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, emptyLineRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, emptyLineRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, emptyLineFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, emptyLineFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, emptyLineFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, emptyLineFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, emptyLineColor :: (Maybe Color) -- ^ /color/ attribute
, emptyLinePlacement :: (Maybe AboveBelow) -- ^ /placement/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml EmptyLine where
emitXml (EmptyLine a b c d e f g h i j k l m n) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "line-shape" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "line-type" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "dash-length" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "space-length" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) l] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) m] ++
[maybe XEmpty (XAttr (QN "placement" Nothing).emitXml) n])
[]
parseEmptyLine :: P.XParse EmptyLine
parseEmptyLine =
EmptyLine
<$> P.optional (P.xattr (P.name "line-shape") >>= parseLineShape)
<*> P.optional (P.xattr (P.name "line-type") >>= parseLineType)
<*> P.optional (P.xattr (P.name "dash-length") >>= parseTenths)
<*> P.optional (P.xattr (P.name "space-length") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "placement") >>= parseAboveBelow)
-- | Smart constructor for 'EmptyLine'
mkEmptyLine :: EmptyLine
mkEmptyLine = EmptyLine Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @empty-placement@ /(complex)/
--
-- The empty-placement type represents an empty element with print-style and placement attributes.
data EmptyPlacement =
EmptyPlacement {
emptyPlacementDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, emptyPlacementDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, emptyPlacementRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, emptyPlacementRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, emptyPlacementFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, emptyPlacementFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, emptyPlacementFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, emptyPlacementFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, emptyPlacementColor :: (Maybe Color) -- ^ /color/ attribute
, emptyPlacementPlacement :: (Maybe AboveBelow) -- ^ /placement/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml EmptyPlacement where
emitXml (EmptyPlacement a b c d e f g h i j) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "placement" Nothing).emitXml) j])
[]
parseEmptyPlacement :: P.XParse EmptyPlacement
parseEmptyPlacement =
EmptyPlacement
<$> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "placement") >>= parseAboveBelow)
-- | Smart constructor for 'EmptyPlacement'
mkEmptyPlacement :: EmptyPlacement
mkEmptyPlacement = EmptyPlacement Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @empty-print-object-style-align@ /(complex)/
--
-- The empty-print-style-align-object type represents an empty element with print-object and print-style-align attribute groups.
data EmptyPrintObjectStyleAlign =
EmptyPrintObjectStyleAlign {
emptyPrintObjectStyleAlignPrintObject :: (Maybe YesNo) -- ^ /print-object/ attribute
, emptyPrintObjectStyleAlignDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, emptyPrintObjectStyleAlignDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, emptyPrintObjectStyleAlignRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, emptyPrintObjectStyleAlignRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, emptyPrintObjectStyleAlignFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, emptyPrintObjectStyleAlignFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, emptyPrintObjectStyleAlignFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, emptyPrintObjectStyleAlignFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, emptyPrintObjectStyleAlignColor :: (Maybe Color) -- ^ /color/ attribute
, emptyPrintObjectStyleAlignHalign :: (Maybe LeftCenterRight) -- ^ /halign/ attribute
, emptyPrintObjectStyleAlignValign :: (Maybe Valign) -- ^ /valign/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml EmptyPrintObjectStyleAlign where
emitXml (EmptyPrintObjectStyleAlign a b c d e f g h i j k l) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "print-object" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "halign" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "valign" Nothing).emitXml) l])
[]
parseEmptyPrintObjectStyleAlign :: P.XParse EmptyPrintObjectStyleAlign
parseEmptyPrintObjectStyleAlign =
EmptyPrintObjectStyleAlign
<$> P.optional (P.xattr (P.name "print-object") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "halign") >>= parseLeftCenterRight)
<*> P.optional (P.xattr (P.name "valign") >>= parseValign)
-- | Smart constructor for 'EmptyPrintObjectStyleAlign'
mkEmptyPrintObjectStyleAlign :: EmptyPrintObjectStyleAlign
mkEmptyPrintObjectStyleAlign = EmptyPrintObjectStyleAlign Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @empty-print-style-align@ /(complex)/
--
-- The empty-print-style-align type represents an empty element with print-style-align attribute group.
data EmptyPrintStyleAlign =
EmptyPrintStyleAlign {
emptyPrintStyleAlignDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, emptyPrintStyleAlignDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, emptyPrintStyleAlignRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, emptyPrintStyleAlignRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, emptyPrintStyleAlignFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, emptyPrintStyleAlignFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, emptyPrintStyleAlignFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, emptyPrintStyleAlignFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, emptyPrintStyleAlignColor :: (Maybe Color) -- ^ /color/ attribute
, emptyPrintStyleAlignHalign :: (Maybe LeftCenterRight) -- ^ /halign/ attribute
, emptyPrintStyleAlignValign :: (Maybe Valign) -- ^ /valign/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml EmptyPrintStyleAlign where
emitXml (EmptyPrintStyleAlign a b c d e f g h i j k) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "halign" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "valign" Nothing).emitXml) k])
[]
parseEmptyPrintStyleAlign :: P.XParse EmptyPrintStyleAlign
parseEmptyPrintStyleAlign =
EmptyPrintStyleAlign
<$> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "halign") >>= parseLeftCenterRight)
<*> P.optional (P.xattr (P.name "valign") >>= parseValign)
-- | Smart constructor for 'EmptyPrintStyleAlign'
mkEmptyPrintStyleAlign :: EmptyPrintStyleAlign
mkEmptyPrintStyleAlign = EmptyPrintStyleAlign Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @empty-trill-sound@ /(complex)/
--
-- The empty-trill-sound type represents an empty element with print-style, placement, and trill-sound attributes.
data EmptyTrillSound =
EmptyTrillSound {
emptyTrillSoundDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, emptyTrillSoundDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, emptyTrillSoundRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, emptyTrillSoundRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, emptyTrillSoundFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, emptyTrillSoundFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, emptyTrillSoundFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, emptyTrillSoundFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, emptyTrillSoundColor :: (Maybe Color) -- ^ /color/ attribute
, emptyTrillSoundPlacement :: (Maybe AboveBelow) -- ^ /placement/ attribute
, emptyTrillSoundStartNote :: (Maybe StartNote) -- ^ /start-note/ attribute
, emptyTrillSoundTrillStep :: (Maybe TrillStep) -- ^ /trill-step/ attribute
, emptyTrillSoundTwoNoteTurn :: (Maybe TwoNoteTurn) -- ^ /two-note-turn/ attribute
, emptyTrillSoundAccelerate :: (Maybe YesNo) -- ^ /accelerate/ attribute
, emptyTrillSoundBeats :: (Maybe TrillBeats) -- ^ /beats/ attribute
, emptyTrillSoundSecondBeat :: (Maybe Percent) -- ^ /second-beat/ attribute
, emptyTrillSoundLastBeat :: (Maybe Percent) -- ^ /last-beat/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml EmptyTrillSound where
emitXml (EmptyTrillSound a b c d e f g h i j k l m n o p q) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "placement" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "start-note" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "trill-step" Nothing).emitXml) l] ++
[maybe XEmpty (XAttr (QN "two-note-turn" Nothing).emitXml) m] ++
[maybe XEmpty (XAttr (QN "accelerate" Nothing).emitXml) n] ++
[maybe XEmpty (XAttr (QN "beats" Nothing).emitXml) o] ++
[maybe XEmpty (XAttr (QN "second-beat" Nothing).emitXml) p] ++
[maybe XEmpty (XAttr (QN "last-beat" Nothing).emitXml) q])
[]
parseEmptyTrillSound :: P.XParse EmptyTrillSound
parseEmptyTrillSound =
EmptyTrillSound
<$> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "placement") >>= parseAboveBelow)
<*> P.optional (P.xattr (P.name "start-note") >>= parseStartNote)
<*> P.optional (P.xattr (P.name "trill-step") >>= parseTrillStep)
<*> P.optional (P.xattr (P.name "two-note-turn") >>= parseTwoNoteTurn)
<*> P.optional (P.xattr (P.name "accelerate") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "beats") >>= parseTrillBeats)
<*> P.optional (P.xattr (P.name "second-beat") >>= parsePercent)
<*> P.optional (P.xattr (P.name "last-beat") >>= parsePercent)
-- | Smart constructor for 'EmptyTrillSound'
mkEmptyTrillSound :: EmptyTrillSound
mkEmptyTrillSound = EmptyTrillSound Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @encoding@ /(complex)/
--
-- The encoding element contains information about who did the digital encoding, when, with what software, and in what aspects. Standard type values for the encoder element are music, words, and arrangement, but other types may be used. The type attribute is only needed when there are multiple encoder elements.
data Encoding =
Encoding {
encodingEncoding :: [ChxEncoding]
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Encoding where
emitXml (Encoding a) =
XReps [emitXml a]
parseEncoding :: P.XParse Encoding
parseEncoding =
Encoding
<$> P.many (parseChxEncoding)
-- | Smart constructor for 'Encoding'
mkEncoding :: Encoding
mkEncoding = Encoding []
-- | @ending@ /(complex)/
--
-- The ending type represents multiple (e.g. first and second) endings. Typically, the start type is associated with the left barline of the first measure in an ending. The stop and discontinue types are associated with the right barline of the last measure in an ending. Stop is used when the ending mark concludes with a downward jog, as is typical for first endings. Discontinue is used when there is no downward jog, as is typical for second endings that do not conclude a piece. The length of the jog can be specified using the end-length attribute. The text-x and text-y attributes are offsets that specify where the baseline of the start of the ending text appears, relative to the start of the ending line.
--
-- The number attribute reflects the numeric values of what is under the ending line. Single endings such as "1" or comma-separated multiple endings such as "1,2" may be used. The ending element text is used when the text displayed in the ending is different than what appears in the number attribute. The print-object element is used to indicate when an ending is present but not printed, as is often the case for many parts in a full score.
data Ending =
Ending {
endingString :: String -- ^ text content
, cmpendingNumber :: EndingNumber -- ^ /number/ attribute
, endingType :: StartStopDiscontinue -- ^ /type/ attribute
, endingEndLength :: (Maybe Tenths) -- ^ /end-length/ attribute
, endingTextX :: (Maybe Tenths) -- ^ /text-x/ attribute
, endingTextY :: (Maybe Tenths) -- ^ /text-y/ attribute
, endingPrintObject :: (Maybe YesNo) -- ^ /print-object/ attribute
, endingDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, endingDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, endingRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, endingRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, endingFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, endingFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, endingFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, endingFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, endingColor :: (Maybe Color) -- ^ /color/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Ending where
emitXml (Ending a b c d e f g h i j k l m n o p) =
XContent (emitXml a)
([XAttr (QN "number" Nothing) (emitXml b)] ++
[XAttr (QN "type" Nothing) (emitXml c)] ++
[maybe XEmpty (XAttr (QN "end-length" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "text-x" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "text-y" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "print-object" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) l] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) m] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) n] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) o] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) p])
[]
parseEnding :: P.XParse Ending
parseEnding =
Ending
<$> (P.xtext >>= return)
<*> (P.xattr (P.name "number") >>= parseEndingNumber)
<*> (P.xattr (P.name "type") >>= parseStartStopDiscontinue)
<*> P.optional (P.xattr (P.name "end-length") >>= parseTenths)
<*> P.optional (P.xattr (P.name "text-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "text-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "print-object") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
-- | Smart constructor for 'Ending'
mkEnding :: String -> EndingNumber -> StartStopDiscontinue -> Ending
mkEnding a b c = Ending a b c Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @extend@ /(complex)/
--
-- The extend type represents lyric word extension / melisma lines as well as figured bass extensions. The optional type and position attributes are added in Version 3.0 to provide better formatting control.
data Extend =
Extend {
extendType :: (Maybe StartStopContinue) -- ^ /type/ attribute
, extendDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, extendDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, extendRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, extendRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, extendFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, extendFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, extendFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, extendFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, extendColor :: (Maybe Color) -- ^ /color/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Extend where
emitXml (Extend a b c d e f g h i j) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "type" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) j])
[]
parseExtend :: P.XParse Extend
parseExtend =
Extend
<$> P.optional (P.xattr (P.name "type") >>= parseStartStopContinue)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
-- | Smart constructor for 'Extend'
mkExtend :: Extend
mkExtend = Extend Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @feature@ /(complex)/
--
-- The feature type is a part of the grouping element used for musical analysis. The type attribute represents the type of the feature and the element content represents its value. This type is flexible to allow for different analyses.
data Feature =
Feature {
featureString :: String -- ^ text content
, featureType :: (Maybe Token) -- ^ /type/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Feature where
emitXml (Feature a b) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "type" Nothing).emitXml) b])
[]
parseFeature :: P.XParse Feature
parseFeature =
Feature
<$> (P.xtext >>= return)
<*> P.optional (P.xattr (P.name "type") >>= parseToken)
-- | Smart constructor for 'Feature'
mkFeature :: String -> Feature
mkFeature a = Feature a Nothing
-- | @fermata@ /(complex)/
--
-- The fermata text content represents the shape of the fermata sign. An empty fermata element represents a normal fermata. The fermata type is upright if not specified.
data Fermata =
Fermata {
fermataFermataShape :: FermataShape -- ^ text content
, fermataType :: (Maybe UprightInverted) -- ^ /type/ attribute
, fermataDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, fermataDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, fermataRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, fermataRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, fermataFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, fermataFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, fermataFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, fermataFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, fermataColor :: (Maybe Color) -- ^ /color/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Fermata where
emitXml (Fermata a b c d e f g h i j k) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "type" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) k])
[]
parseFermata :: P.XParse Fermata
parseFermata =
Fermata
<$> (P.xtext >>= parseFermataShape)
<*> P.optional (P.xattr (P.name "type") >>= parseUprightInverted)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
-- | Smart constructor for 'Fermata'
mkFermata :: FermataShape -> Fermata
mkFermata a = Fermata a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @figure@ /(complex)/
--
-- The figure type represents a single figure within a figured-bass element.
data Figure =
Figure {
figurePrefix :: (Maybe StyleText) -- ^ /prefix/ child element
, figureFigureNumber :: (Maybe StyleText) -- ^ /figure-number/ child element
, figureSuffix :: (Maybe StyleText) -- ^ /suffix/ child element
, figureExtend :: (Maybe Extend) -- ^ /extend/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Figure where
emitXml (Figure a b c d) =
XContent XEmpty
[]
([maybe XEmpty (XElement (QN "prefix" Nothing).emitXml) a] ++
[maybe XEmpty (XElement (QN "figure-number" Nothing).emitXml) b] ++
[maybe XEmpty (XElement (QN "suffix" Nothing).emitXml) c] ++
[maybe XEmpty (XElement (QN "extend" Nothing).emitXml) d])
parseFigure :: P.XParse Figure
parseFigure =
Figure
<$> P.optional (P.xchild (P.name "prefix") (parseStyleText))
<*> P.optional (P.xchild (P.name "figure-number") (parseStyleText))
<*> P.optional (P.xchild (P.name "suffix") (parseStyleText))
<*> P.optional (P.xchild (P.name "extend") (parseExtend))
-- | Smart constructor for 'Figure'
mkFigure :: Figure
mkFigure = Figure Nothing Nothing Nothing Nothing
-- | @figured-bass@ /(complex)/
--
-- The figured-bass element represents figured bass notation. Figured bass elements take their position from the first regular note (not a grace note or chord note) that follows in score order. The optional duration element is used to indicate changes of figures under a note.
--
-- Figures are ordered from top to bottom. The value of parentheses is "no" if not present.
data FiguredBass =
FiguredBass {
figuredBassParentheses :: (Maybe YesNo) -- ^ /parentheses/ attribute
, figuredBassDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, figuredBassDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, figuredBassRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, figuredBassRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, figuredBassFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, figuredBassFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, figuredBassFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, figuredBassFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, figuredBassColor :: (Maybe Color) -- ^ /color/ attribute
, figuredBassPrintDot :: (Maybe YesNo) -- ^ /print-dot/ attribute
, figuredBassPrintLyric :: (Maybe YesNo) -- ^ /print-lyric/ attribute
, figuredBassPrintObject :: (Maybe YesNo) -- ^ /print-object/ attribute
, figuredBassPrintSpacing :: (Maybe YesNo) -- ^ /print-spacing/ attribute
, figuredBassFigure :: [Figure] -- ^ /figure/ child element
, figuredBassDuration :: (Maybe Duration)
, figuredBassEditorial :: Editorial
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml FiguredBass where
emitXml (FiguredBass a b c d e f g h i j k l m n o p q) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "parentheses" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "print-dot" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "print-lyric" Nothing).emitXml) l] ++
[maybe XEmpty (XAttr (QN "print-object" Nothing).emitXml) m] ++
[maybe XEmpty (XAttr (QN "print-spacing" Nothing).emitXml) n])
(map (XElement (QN "figure" Nothing).emitXml) o ++
[emitXml p] ++
[emitXml q])
parseFiguredBass :: P.XParse FiguredBass
parseFiguredBass =
FiguredBass
<$> P.optional (P.xattr (P.name "parentheses") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "print-dot") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "print-lyric") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "print-object") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "print-spacing") >>= parseYesNo)
<*> P.many (P.xchild (P.name "figure") (parseFigure))
<*> P.optional (parseDuration)
<*> parseEditorial
-- | Smart constructor for 'FiguredBass'
mkFiguredBass :: Editorial -> FiguredBass
mkFiguredBass q = FiguredBass Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing [] Nothing q
-- | @fingering@ /(complex)/
--
-- Fingering is typically indicated 1,2,3,4,5. Multiple fingerings may be given, typically to substitute fingerings in the middle of a note. The substitution and alternate values are "no" if the attribute is not present. For guitar and other fretted instruments, the fingering element represents the fretting finger; the pluck element represents the plucking finger.
data Fingering =
Fingering {
fingeringString :: String -- ^ text content
, fingeringSubstitution :: (Maybe YesNo) -- ^ /substitution/ attribute
, fingeringAlternate :: (Maybe YesNo) -- ^ /alternate/ attribute
, fingeringDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, fingeringDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, fingeringRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, fingeringRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, fingeringFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, fingeringFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, fingeringFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, fingeringFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, fingeringColor :: (Maybe Color) -- ^ /color/ attribute
, fingeringPlacement :: (Maybe AboveBelow) -- ^ /placement/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Fingering where
emitXml (Fingering a b c d e f g h i j k l m) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "substitution" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "alternate" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) l] ++
[maybe XEmpty (XAttr (QN "placement" Nothing).emitXml) m])
[]
parseFingering :: P.XParse Fingering
parseFingering =
Fingering
<$> (P.xtext >>= return)
<*> P.optional (P.xattr (P.name "substitution") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "alternate") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "placement") >>= parseAboveBelow)
-- | Smart constructor for 'Fingering'
mkFingering :: String -> Fingering
mkFingering a = Fingering a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @first-fret@ /(complex)/
--
-- The first-fret type indicates which fret is shown in the top space of the frame; it is fret 1 if the element is not present. The optional text attribute indicates how this is represented in the fret diagram, while the location attribute indicates whether the text appears to the left or right of the frame.
data FirstFret =
FirstFret {
firstFretPositiveInteger :: PositiveInteger -- ^ text content
, firstFretText :: (Maybe Token) -- ^ /text/ attribute
, firstFretLocation :: (Maybe LeftRight) -- ^ /location/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml FirstFret where
emitXml (FirstFret a b c) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "text" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "location" Nothing).emitXml) c])
[]
parseFirstFret :: P.XParse FirstFret
parseFirstFret =
FirstFret
<$> (P.xtext >>= parsePositiveInteger)
<*> P.optional (P.xattr (P.name "text") >>= parseToken)
<*> P.optional (P.xattr (P.name "location") >>= parseLeftRight)
-- | Smart constructor for 'FirstFret'
mkFirstFret :: PositiveInteger -> FirstFret
mkFirstFret a = FirstFret a Nothing Nothing
-- | @formatted-text@ /(complex)/
--
-- The formatted-text type represents a text element with text-formatting attributes.
data FormattedText =
FormattedText {
formattedTextString :: String -- ^ text content
, formattedTextLang :: (Maybe Lang) -- ^ /xml:lang/ attribute
, formattedTextSpace :: (Maybe Space) -- ^ /xml:space/ attribute
, formattedTextJustify :: (Maybe LeftCenterRight) -- ^ /justify/ attribute
, formattedTextDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, formattedTextDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, formattedTextRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, formattedTextRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, formattedTextFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, formattedTextFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, formattedTextFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, formattedTextFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, formattedTextColor :: (Maybe Color) -- ^ /color/ attribute
, formattedTextHalign :: (Maybe LeftCenterRight) -- ^ /halign/ attribute
, formattedTextValign :: (Maybe Valign) -- ^ /valign/ attribute
, formattedTextUnderline :: (Maybe NumberOfLines) -- ^ /underline/ attribute
, formattedTextOverline :: (Maybe NumberOfLines) -- ^ /overline/ attribute
, formattedTextLineThrough :: (Maybe NumberOfLines) -- ^ /line-through/ attribute
, formattedTextRotation :: (Maybe RotationDegrees) -- ^ /rotation/ attribute
, formattedTextLetterSpacing :: (Maybe NumberOrNormal) -- ^ /letter-spacing/ attribute
, formattedTextLineHeight :: (Maybe NumberOrNormal) -- ^ /line-height/ attribute
, formattedTextDir :: (Maybe TextDirection) -- ^ /dir/ attribute
, formattedTextEnclosure :: (Maybe EnclosureShape) -- ^ /enclosure/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml FormattedText where
emitXml (FormattedText a b c d e f g h i j k l m n o p q r s t u v w) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "lang" (Just "xml")).emitXml) b] ++
[maybe XEmpty (XAttr (QN "space" (Just "xml")).emitXml) c] ++
[maybe XEmpty (XAttr (QN "justify" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) l] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) m] ++
[maybe XEmpty (XAttr (QN "halign" Nothing).emitXml) n] ++
[maybe XEmpty (XAttr (QN "valign" Nothing).emitXml) o] ++
[maybe XEmpty (XAttr (QN "underline" Nothing).emitXml) p] ++
[maybe XEmpty (XAttr (QN "overline" Nothing).emitXml) q] ++
[maybe XEmpty (XAttr (QN "line-through" Nothing).emitXml) r] ++
[maybe XEmpty (XAttr (QN "rotation" Nothing).emitXml) s] ++
[maybe XEmpty (XAttr (QN "letter-spacing" Nothing).emitXml) t] ++
[maybe XEmpty (XAttr (QN "line-height" Nothing).emitXml) u] ++
[maybe XEmpty (XAttr (QN "dir" Nothing).emitXml) v] ++
[maybe XEmpty (XAttr (QN "enclosure" Nothing).emitXml) w])
[]
parseFormattedText :: P.XParse FormattedText
parseFormattedText =
FormattedText
<$> (P.xtext >>= return)
<*> P.optional (P.xattr (P.name "xml:lang") >>= parseLang)
<*> P.optional (P.xattr (P.name "xml:space") >>= parseSpace)
<*> P.optional (P.xattr (P.name "justify") >>= parseLeftCenterRight)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "halign") >>= parseLeftCenterRight)
<*> P.optional (P.xattr (P.name "valign") >>= parseValign)
<*> P.optional (P.xattr (P.name "underline") >>= parseNumberOfLines)
<*> P.optional (P.xattr (P.name "overline") >>= parseNumberOfLines)
<*> P.optional (P.xattr (P.name "line-through") >>= parseNumberOfLines)
<*> P.optional (P.xattr (P.name "rotation") >>= parseRotationDegrees)
<*> P.optional (P.xattr (P.name "letter-spacing") >>= parseNumberOrNormal)
<*> P.optional (P.xattr (P.name "line-height") >>= parseNumberOrNormal)
<*> P.optional (P.xattr (P.name "dir") >>= parseTextDirection)
<*> P.optional (P.xattr (P.name "enclosure") >>= parseEnclosureShape)
-- | Smart constructor for 'FormattedText'
mkFormattedText :: String -> FormattedText
mkFormattedText a = FormattedText a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @forward@ /(complex)/
--
-- The backup and forward elements are required to coordinate multiple voices in one part, including music on multiple staves. The forward element is generally used within voices and staves. Duration values should always be positive, and should not cross measure boundaries or mid-measure changes in the divisions value.
data Forward =
Forward {
forwardDuration :: Duration
, forwardEditorialVoice :: EditorialVoice
, forwardStaff :: (Maybe Staff)
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Forward where
emitXml (Forward a b c) =
XReps [emitXml a,emitXml b,emitXml c]
parseForward :: P.XParse Forward
parseForward =
Forward
<$> parseDuration
<*> parseEditorialVoice
<*> P.optional (parseStaff)
-- | Smart constructor for 'Forward'
mkForward :: Duration -> EditorialVoice -> Forward
mkForward a b = Forward a b Nothing
-- | @frame@ /(complex)/
--
-- The frame type represents a frame or fretboard diagram used together with a chord symbol. The representation is based on the NIFF guitar grid with additional information. The frame type's unplayed attribute indicates what to display above a string that has no associated frame-note element. Typical values are x and the empty string. If the attribute is not present, the display of the unplayed string is application-defined.
data Frame =
Frame {
frameHeight :: (Maybe Tenths) -- ^ /height/ attribute
, frameWidth :: (Maybe Tenths) -- ^ /width/ attribute
, frameUnplayed :: (Maybe Token) -- ^ /unplayed/ attribute
, frameDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, frameDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, frameRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, frameRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, frameColor :: (Maybe Color) -- ^ /color/ attribute
, frameHalign :: (Maybe LeftCenterRight) -- ^ /halign/ attribute
, frameValign :: (Maybe ValignImage) -- ^ /valign/ attribute
, frameFrameStrings :: PositiveInteger -- ^ /frame-strings/ child element
, frameFrameFrets :: PositiveInteger -- ^ /frame-frets/ child element
, frameFirstFret :: (Maybe FirstFret) -- ^ /first-fret/ child element
, frameFrameNote :: [FrameNote] -- ^ /frame-note/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Frame where
emitXml (Frame a b c d e f g h i j k l m n) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "height" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "width" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "unplayed" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "halign" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "valign" Nothing).emitXml) j])
([XElement (QN "frame-strings" Nothing) (emitXml k)] ++
[XElement (QN "frame-frets" Nothing) (emitXml l)] ++
[maybe XEmpty (XElement (QN "first-fret" Nothing).emitXml) m] ++
map (XElement (QN "frame-note" Nothing).emitXml) n)
parseFrame :: P.XParse Frame
parseFrame =
Frame
<$> P.optional (P.xattr (P.name "height") >>= parseTenths)
<*> P.optional (P.xattr (P.name "width") >>= parseTenths)
<*> P.optional (P.xattr (P.name "unplayed") >>= parseToken)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "halign") >>= parseLeftCenterRight)
<*> P.optional (P.xattr (P.name "valign") >>= parseValignImage)
<*> (P.xchild (P.name "frame-strings") (P.xtext >>= parsePositiveInteger))
<*> (P.xchild (P.name "frame-frets") (P.xtext >>= parsePositiveInteger))
<*> P.optional (P.xchild (P.name "first-fret") (parseFirstFret))
<*> P.many (P.xchild (P.name "frame-note") (parseFrameNote))
-- | Smart constructor for 'Frame'
mkFrame :: PositiveInteger -> PositiveInteger -> Frame
mkFrame k l = Frame Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing k l Nothing []
-- | @frame-note@ /(complex)/
--
-- The frame-note type represents each note included in the frame. An open string will have a fret value of 0, while a muted string will not be associated with a frame-note element.
data FrameNote =
FrameNote {
frameNoteString :: CmpString -- ^ /string/ child element
, frameNoteFret :: Fret -- ^ /fret/ child element
, frameNoteFingering :: (Maybe Fingering) -- ^ /fingering/ child element
, frameNoteBarre :: (Maybe Barre) -- ^ /barre/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml FrameNote where
emitXml (FrameNote a b c d) =
XContent XEmpty
[]
([XElement (QN "string" Nothing) (emitXml a)] ++
[XElement (QN "fret" Nothing) (emitXml b)] ++
[maybe XEmpty (XElement (QN "fingering" Nothing).emitXml) c] ++
[maybe XEmpty (XElement (QN "barre" Nothing).emitXml) d])
parseFrameNote :: P.XParse FrameNote
parseFrameNote =
FrameNote
<$> (P.xchild (P.name "string") (parseCmpString))
<*> (P.xchild (P.name "fret") (parseFret))
<*> P.optional (P.xchild (P.name "fingering") (parseFingering))
<*> P.optional (P.xchild (P.name "barre") (parseBarre))
-- | Smart constructor for 'FrameNote'
mkFrameNote :: CmpString -> Fret -> FrameNote
mkFrameNote a b = FrameNote a b Nothing Nothing
-- | @fret@ /(complex)/
--
-- The fret element is used with tablature notation and chord diagrams. Fret numbers start with 0 for an open string and 1 for the first fret.
data Fret =
Fret {
fretNonNegativeInteger :: NonNegativeInteger -- ^ text content
, fretFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, fretFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, fretFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, fretFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, fretColor :: (Maybe Color) -- ^ /color/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Fret where
emitXml (Fret a b c d e f) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) f])
[]
parseFret :: P.XParse Fret
parseFret =
Fret
<$> (P.xtext >>= parseNonNegativeInteger)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
-- | Smart constructor for 'Fret'
mkFret :: NonNegativeInteger -> Fret
mkFret a = Fret a Nothing Nothing Nothing Nothing Nothing
-- | @glissando@ /(complex)/
--
-- Glissando and slide types both indicate rapidly moving from one pitch to the other so that individual notes are not discerned. The distinction is similar to that between NIFF's glissando and portamento elements. A glissando sounds the half notes in between the slide and defaults to a wavy line. The optional text is printed alongside the line.
data Glissando =
Glissando {
glissandoString :: String -- ^ text content
, glissandoType :: StartStop -- ^ /type/ attribute
, glissandoNumber :: (Maybe NumberLevel) -- ^ /number/ attribute
, glissandoLineType :: (Maybe LineType) -- ^ /line-type/ attribute
, glissandoDashLength :: (Maybe Tenths) -- ^ /dash-length/ attribute
, glissandoSpaceLength :: (Maybe Tenths) -- ^ /space-length/ attribute
, glissandoDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, glissandoDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, glissandoRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, glissandoRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, glissandoFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, glissandoFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, glissandoFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, glissandoFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, glissandoColor :: (Maybe Color) -- ^ /color/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Glissando where
emitXml (Glissando a b c d e f g h i j k l m n o) =
XContent (emitXml a)
([XAttr (QN "type" Nothing) (emitXml b)] ++
[maybe XEmpty (XAttr (QN "number" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "line-type" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "dash-length" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "space-length" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) l] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) m] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) n] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) o])
[]
parseGlissando :: P.XParse Glissando
parseGlissando =
Glissando
<$> (P.xtext >>= return)
<*> (P.xattr (P.name "type") >>= parseStartStop)
<*> P.optional (P.xattr (P.name "number") >>= parseNumberLevel)
<*> P.optional (P.xattr (P.name "line-type") >>= parseLineType)
<*> P.optional (P.xattr (P.name "dash-length") >>= parseTenths)
<*> P.optional (P.xattr (P.name "space-length") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
-- | Smart constructor for 'Glissando'
mkGlissando :: String -> StartStop -> Glissando
mkGlissando a b = Glissando a b Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @grace@ /(complex)/
--
-- The grace type indicates the presence of a grace note. The slash attribute for a grace note is yes for slashed eighth notes. The other grace note attributes come from MuseData sound suggestions. The steal-time-previous attribute indicates the percentage of time to steal from the previous note for the grace note. The steal-time-following attribute indicates the percentage of time to steal from the following note for the grace note, as for appoggiaturas. The make-time attribute indicates to make time, not steal time; the units are in real-time divisions for the grace note.
data Grace =
Grace {
graceStealTimePrevious :: (Maybe Percent) -- ^ /steal-time-previous/ attribute
, graceStealTimeFollowing :: (Maybe Percent) -- ^ /steal-time-following/ attribute
, graceMakeTime :: (Maybe Divisions) -- ^ /make-time/ attribute
, graceSlash :: (Maybe YesNo) -- ^ /slash/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Grace where
emitXml (Grace a b c d) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "steal-time-previous" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "steal-time-following" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "make-time" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "slash" Nothing).emitXml) d])
[]
parseGrace :: P.XParse Grace
parseGrace =
Grace
<$> P.optional (P.xattr (P.name "steal-time-previous") >>= parsePercent)
<*> P.optional (P.xattr (P.name "steal-time-following") >>= parsePercent)
<*> P.optional (P.xattr (P.name "make-time") >>= parseDivisions)
<*> P.optional (P.xattr (P.name "slash") >>= parseYesNo)
-- | Smart constructor for 'Grace'
mkGrace :: Grace
mkGrace = Grace Nothing Nothing Nothing Nothing
-- | @group-barline@ /(complex)/
--
-- The group-barline type indicates if the group should have common barlines.
data GroupBarline =
GroupBarline {
groupBarlineGroupBarlineValue :: GroupBarlineValue -- ^ text content
, groupBarlineColor :: (Maybe Color) -- ^ /color/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml GroupBarline where
emitXml (GroupBarline a b) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "color" Nothing).emitXml) b])
[]
parseGroupBarline :: P.XParse GroupBarline
parseGroupBarline =
GroupBarline
<$> (P.xtext >>= parseGroupBarlineValue)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
-- | Smart constructor for 'GroupBarline'
mkGroupBarline :: GroupBarlineValue -> GroupBarline
mkGroupBarline a = GroupBarline a Nothing
-- | @group-name@ /(complex)/
--
-- The group-name type describes the name or abbreviation of a part-group element. Formatting attributes in the group-name type are deprecated in Version 2.0 in favor of the new group-name-display and group-abbreviation-display elements.
data GroupName =
GroupName {
groupNameString :: String -- ^ text content
, groupNameDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, groupNameDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, groupNameRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, groupNameRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, groupNameFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, groupNameFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, groupNameFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, groupNameFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, groupNameColor :: (Maybe Color) -- ^ /color/ attribute
, groupNameJustify :: (Maybe LeftCenterRight) -- ^ /justify/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml GroupName where
emitXml (GroupName a b c d e f g h i j k) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "justify" Nothing).emitXml) k])
[]
parseGroupName :: P.XParse GroupName
parseGroupName =
GroupName
<$> (P.xtext >>= return)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "justify") >>= parseLeftCenterRight)
-- | Smart constructor for 'GroupName'
mkGroupName :: String -> GroupName
mkGroupName a = GroupName a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @group-symbol@ /(complex)/
--
-- The group-symbol type indicates how the symbol for a group is indicated in the score.
data GroupSymbol =
GroupSymbol {
groupSymbolGroupSymbolValue :: GroupSymbolValue -- ^ text content
, groupSymbolDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, groupSymbolDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, groupSymbolRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, groupSymbolRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, groupSymbolColor :: (Maybe Color) -- ^ /color/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml GroupSymbol where
emitXml (GroupSymbol a b c d e f) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) f])
[]
parseGroupSymbol :: P.XParse GroupSymbol
parseGroupSymbol =
GroupSymbol
<$> (P.xtext >>= parseGroupSymbolValue)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
-- | Smart constructor for 'GroupSymbol'
mkGroupSymbol :: GroupSymbolValue -> GroupSymbol
mkGroupSymbol a = GroupSymbol a Nothing Nothing Nothing Nothing Nothing
-- | @grouping@ /(complex)/
--
-- The grouping type is used for musical analysis. When the type attribute is "start" or "single", it usually contains one or more feature elements. The number attribute is used for distinguishing between overlapping and hierarchical groupings. The member-of attribute allows for easy distinguishing of what grouping elements are in what hierarchy. Feature elements contained within a "stop" type of grouping may be ignored.
--
-- This element is flexible to allow for different types of analyses. Future versions of the MusicXML format may add elements that can represent more standardized categories of analysis data, allowing for easier data sharing.
data Grouping =
Grouping {
groupingType :: StartStopSingle -- ^ /type/ attribute
, groupingNumber :: (Maybe Token) -- ^ /number/ attribute
, groupingMemberOf :: (Maybe Token) -- ^ /member-of/ attribute
, groupingFeature :: [Feature] -- ^ /feature/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Grouping where
emitXml (Grouping a b c d) =
XContent XEmpty
([XAttr (QN "type" Nothing) (emitXml a)] ++
[maybe XEmpty (XAttr (QN "number" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "member-of" Nothing).emitXml) c])
(map (XElement (QN "feature" Nothing).emitXml) d)
parseGrouping :: P.XParse Grouping
parseGrouping =
Grouping
<$> (P.xattr (P.name "type") >>= parseStartStopSingle)
<*> P.optional (P.xattr (P.name "number") >>= parseToken)
<*> P.optional (P.xattr (P.name "member-of") >>= parseToken)
<*> P.many (P.xchild (P.name "feature") (parseFeature))
-- | Smart constructor for 'Grouping'
mkGrouping :: StartStopSingle -> Grouping
mkGrouping a = Grouping a Nothing Nothing []
-- | @hammer-on-pull-off@ /(complex)/
--
-- The hammer-on and pull-off elements are used in guitar and fretted instrument notation. Since a single slur can be marked over many notes, the hammer-on and pull-off elements are separate so the individual pair of notes can be specified. The element content can be used to specify how the hammer-on or pull-off should be notated. An empty element leaves this choice up to the application.
data HammerOnPullOff =
HammerOnPullOff {
hammerOnPullOffString :: String -- ^ text content
, hammerOnPullOffType :: StartStop -- ^ /type/ attribute
, hammerOnPullOffNumber :: (Maybe NumberLevel) -- ^ /number/ attribute
, hammerOnPullOffDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, hammerOnPullOffDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, hammerOnPullOffRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, hammerOnPullOffRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, hammerOnPullOffFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, hammerOnPullOffFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, hammerOnPullOffFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, hammerOnPullOffFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, hammerOnPullOffColor :: (Maybe Color) -- ^ /color/ attribute
, hammerOnPullOffPlacement :: (Maybe AboveBelow) -- ^ /placement/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml HammerOnPullOff where
emitXml (HammerOnPullOff a b c d e f g h i j k l m) =
XContent (emitXml a)
([XAttr (QN "type" Nothing) (emitXml b)] ++
[maybe XEmpty (XAttr (QN "number" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) l] ++
[maybe XEmpty (XAttr (QN "placement" Nothing).emitXml) m])
[]
parseHammerOnPullOff :: P.XParse HammerOnPullOff
parseHammerOnPullOff =
HammerOnPullOff
<$> (P.xtext >>= return)
<*> (P.xattr (P.name "type") >>= parseStartStop)
<*> P.optional (P.xattr (P.name "number") >>= parseNumberLevel)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "placement") >>= parseAboveBelow)
-- | Smart constructor for 'HammerOnPullOff'
mkHammerOnPullOff :: String -> StartStop -> HammerOnPullOff
mkHammerOnPullOff a b = HammerOnPullOff a b Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @handbell@ /(complex)/
--
-- The handbell element represents notation for various techniques used in handbell and handchime music.
data Handbell =
Handbell {
handbellHandbellValue :: HandbellValue -- ^ text content
, handbellDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, handbellDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, handbellRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, handbellRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, handbellFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, handbellFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, handbellFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, handbellFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, handbellColor :: (Maybe Color) -- ^ /color/ attribute
, handbellPlacement :: (Maybe AboveBelow) -- ^ /placement/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Handbell where
emitXml (Handbell a b c d e f g h i j k) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "placement" Nothing).emitXml) k])
[]
parseHandbell :: P.XParse Handbell
parseHandbell =
Handbell
<$> (P.xtext >>= parseHandbellValue)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "placement") >>= parseAboveBelow)
-- | Smart constructor for 'Handbell'
mkHandbell :: HandbellValue -> Handbell
mkHandbell a = Handbell a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @harmonic@ /(complex)/
--
-- The harmonic type indicates natural and artificial harmonics. Allowing the type of pitch to be specified, combined with controls for appearance/playback differences, allows both the notation and the sound to be represented. Artificial harmonics can add a notated touching-pitch; artificial pinch harmonics will usually not notate a touching pitch. The attributes for the harmonic element refer to the use of the circular harmonic symbol, typically but not always used with natural harmonics.
data Harmonic =
Harmonic {
harmonicPrintObject :: (Maybe YesNo) -- ^ /print-object/ attribute
, harmonicDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, harmonicDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, harmonicRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, harmonicRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, harmonicFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, harmonicFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, harmonicFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, harmonicFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, harmonicColor :: (Maybe Color) -- ^ /color/ attribute
, harmonicPlacement :: (Maybe AboveBelow) -- ^ /placement/ attribute
, harmonicHarmonic :: (Maybe ChxHarmonic)
, harmonicHarmonic1 :: (Maybe ChxHarmonic1)
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Harmonic where
emitXml (Harmonic a b c d e f g h i j k l m) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "print-object" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "placement" Nothing).emitXml) k])
([emitXml l] ++
[emitXml m])
parseHarmonic :: P.XParse Harmonic
parseHarmonic =
Harmonic
<$> P.optional (P.xattr (P.name "print-object") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "placement") >>= parseAboveBelow)
<*> P.optional (parseChxHarmonic)
<*> P.optional (parseChxHarmonic1)
-- | Smart constructor for 'Harmonic'
mkHarmonic :: Harmonic
mkHarmonic = Harmonic Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @harmony@ /(complex)/
--
-- The harmony type is based on Humdrum's **harm encoding, extended to support chord symbols in popular music as well as functional harmony analysis in classical music.
--
-- If there are alternate harmonies possible, this can be specified using multiple harmony elements differentiated by type. Explicit harmonies have all note present in the music; implied have some notes missing but implied; alternate represents alternate analyses.
--
-- The harmony object may be used for analysis or for chord symbols. The print-object attribute controls whether or not anything is printed due to the harmony element. The print-frame attribute controls printing of a frame or fretboard diagram. The print-style attribute group sets the default for the harmony, but individual elements can override this with their own print-style values.
data Harmony =
Harmony {
harmonyType :: (Maybe HarmonyType) -- ^ /type/ attribute
, harmonyPrintFrame :: (Maybe YesNo) -- ^ /print-frame/ attribute
, harmonyPrintObject :: (Maybe YesNo) -- ^ /print-object/ attribute
, harmonyDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, harmonyDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, harmonyRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, harmonyRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, harmonyFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, harmonyFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, harmonyFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, harmonyFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, harmonyColor :: (Maybe Color) -- ^ /color/ attribute
, harmonyPlacement :: (Maybe AboveBelow) -- ^ /placement/ attribute
, harmonyHarmonyChord :: [HarmonyChord]
, harmonyFrame :: (Maybe Frame) -- ^ /frame/ child element
, harmonyOffset :: (Maybe Offset) -- ^ /offset/ child element
, harmonyEditorial :: Editorial
, harmonyStaff :: (Maybe Staff)
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Harmony where
emitXml (Harmony a b c d e f g h i j k l m n o p q r) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "type" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "print-frame" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "print-object" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) l] ++
[maybe XEmpty (XAttr (QN "placement" Nothing).emitXml) m])
([emitXml n] ++
[maybe XEmpty (XElement (QN "frame" Nothing).emitXml) o] ++
[maybe XEmpty (XElement (QN "offset" Nothing).emitXml) p] ++
[emitXml q] ++
[emitXml r])
parseHarmony :: P.XParse Harmony
parseHarmony =
Harmony
<$> P.optional (P.xattr (P.name "type") >>= parseHarmonyType)
<*> P.optional (P.xattr (P.name "print-frame") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "print-object") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "placement") >>= parseAboveBelow)
<*> P.many (parseHarmonyChord)
<*> P.optional (P.xchild (P.name "frame") (parseFrame))
<*> P.optional (P.xchild (P.name "offset") (parseOffset))
<*> parseEditorial
<*> P.optional (parseStaff)
-- | Smart constructor for 'Harmony'
mkHarmony :: Editorial -> Harmony
mkHarmony q = Harmony Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing [] Nothing Nothing q Nothing
-- | @harp-pedals@ /(complex)/
--
-- The harp-pedals type is used to create harp pedal diagrams. The pedal-step and pedal-alter elements use the same values as the step and alter elements. For easiest reading, the pedal-tuning elements should follow standard harp pedal order, with pedal-step values of D, C, B, E, F, G, and A.
data HarpPedals =
HarpPedals {
harpPedalsDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, harpPedalsDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, harpPedalsRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, harpPedalsRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, harpPedalsFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, harpPedalsFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, harpPedalsFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, harpPedalsFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, harpPedalsColor :: (Maybe Color) -- ^ /color/ attribute
, harpPedalsHalign :: (Maybe LeftCenterRight) -- ^ /halign/ attribute
, harpPedalsValign :: (Maybe Valign) -- ^ /valign/ attribute
, harpPedalsPedalTuning :: [PedalTuning] -- ^ /pedal-tuning/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml HarpPedals where
emitXml (HarpPedals a b c d e f g h i j k l) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "halign" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "valign" Nothing).emitXml) k])
(map (XElement (QN "pedal-tuning" Nothing).emitXml) l)
parseHarpPedals :: P.XParse HarpPedals
parseHarpPedals =
HarpPedals
<$> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "halign") >>= parseLeftCenterRight)
<*> P.optional (P.xattr (P.name "valign") >>= parseValign)
<*> P.many (P.xchild (P.name "pedal-tuning") (parsePedalTuning))
-- | Smart constructor for 'HarpPedals'
mkHarpPedals :: HarpPedals
mkHarpPedals = HarpPedals Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing []
-- | @heel-toe@ /(complex)/
--
-- The heel and toe elements are used with organ pedals. The substitution value is "no" if the attribute is not present.
data HeelToe =
HeelToe {
heelToeEmptyPlacement :: HeelToe
, heelToeSubstitution :: (Maybe YesNo) -- ^ /substitution/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml HeelToe where
emitXml (HeelToe a b) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "substitution" Nothing).emitXml) b])
([emitXml a])
parseHeelToe :: P.XParse HeelToe
parseHeelToe =
HeelToe
<$> parseHeelToe
<*> P.optional (P.xattr (P.name "substitution") >>= parseYesNo)
-- | Smart constructor for 'HeelToe'
mkHeelToe :: HeelToe -> HeelToe
mkHeelToe a = HeelToe a Nothing
-- | @hole@ /(complex)/
--
-- The hole type represents the symbols used for woodwind and brass fingerings as well as other notations.
data Hole =
Hole {
holeDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, holeDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, holeRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, holeRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, holeFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, holeFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, holeFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, holeFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, holeColor :: (Maybe Color) -- ^ /color/ attribute
, holePlacement :: (Maybe AboveBelow) -- ^ /placement/ attribute
, holeHoleType :: (Maybe String) -- ^ /hole-type/ child element
, holeHoleClosed :: HoleClosed -- ^ /hole-closed/ child element
, holeHoleShape :: (Maybe String) -- ^ /hole-shape/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Hole where
emitXml (Hole a b c d e f g h i j k l m) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "placement" Nothing).emitXml) j])
([maybe XEmpty (XElement (QN "hole-type" Nothing).emitXml) k] ++
[XElement (QN "hole-closed" Nothing) (emitXml l)] ++
[maybe XEmpty (XElement (QN "hole-shape" Nothing).emitXml) m])
parseHole :: P.XParse Hole
parseHole =
Hole
<$> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "placement") >>= parseAboveBelow)
<*> P.optional (P.xchild (P.name "hole-type") (P.xtext >>= return))
<*> (P.xchild (P.name "hole-closed") (parseHoleClosed))
<*> P.optional (P.xchild (P.name "hole-shape") (P.xtext >>= return))
-- | Smart constructor for 'Hole'
mkHole :: HoleClosed -> Hole
mkHole l = Hole Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing l Nothing
-- | @hole-closed@ /(complex)/
--
-- The hole-closed type represents whether the hole is closed, open, or half-open. The optional location attribute indicates which portion of the hole is filled in when the element value is half.
data HoleClosed =
HoleClosed {
holeClosedHoleClosedValue :: HoleClosedValue -- ^ text content
, holeClosedLocation :: (Maybe HoleClosedLocation) -- ^ /location/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml HoleClosed where
emitXml (HoleClosed a b) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "location" Nothing).emitXml) b])
[]
parseHoleClosed :: P.XParse HoleClosed
parseHoleClosed =
HoleClosed
<$> (P.xtext >>= parseHoleClosedValue)
<*> P.optional (P.xattr (P.name "location") >>= parseHoleClosedLocation)
-- | Smart constructor for 'HoleClosed'
mkHoleClosed :: HoleClosedValue -> HoleClosed
mkHoleClosed a = HoleClosed a Nothing
-- | @horizontal-turn@ /(complex)/
--
-- The horizontal-turn type represents turn elements that are horizontal rather than vertical. These are empty elements with print-style, placement, trill-sound, and slash attributes. If the slash attribute is yes, then a vertical line is used to slash the turn; it is no by default.
data HorizontalTurn =
HorizontalTurn {
horizontalTurnSlash :: (Maybe YesNo) -- ^ /slash/ attribute
, horizontalTurnDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, horizontalTurnDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, horizontalTurnRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, horizontalTurnRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, horizontalTurnFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, horizontalTurnFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, horizontalTurnFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, horizontalTurnFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, horizontalTurnColor :: (Maybe Color) -- ^ /color/ attribute
, horizontalTurnPlacement :: (Maybe AboveBelow) -- ^ /placement/ attribute
, horizontalTurnStartNote :: (Maybe StartNote) -- ^ /start-note/ attribute
, horizontalTurnTrillStep :: (Maybe TrillStep) -- ^ /trill-step/ attribute
, horizontalTurnTwoNoteTurn :: (Maybe TwoNoteTurn) -- ^ /two-note-turn/ attribute
, horizontalTurnAccelerate :: (Maybe YesNo) -- ^ /accelerate/ attribute
, horizontalTurnBeats :: (Maybe TrillBeats) -- ^ /beats/ attribute
, horizontalTurnSecondBeat :: (Maybe Percent) -- ^ /second-beat/ attribute
, horizontalTurnLastBeat :: (Maybe Percent) -- ^ /last-beat/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml HorizontalTurn where
emitXml (HorizontalTurn a b c d e f g h i j k l m n o p q r) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "slash" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "placement" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "start-note" Nothing).emitXml) l] ++
[maybe XEmpty (XAttr (QN "trill-step" Nothing).emitXml) m] ++
[maybe XEmpty (XAttr (QN "two-note-turn" Nothing).emitXml) n] ++
[maybe XEmpty (XAttr (QN "accelerate" Nothing).emitXml) o] ++
[maybe XEmpty (XAttr (QN "beats" Nothing).emitXml) p] ++
[maybe XEmpty (XAttr (QN "second-beat" Nothing).emitXml) q] ++
[maybe XEmpty (XAttr (QN "last-beat" Nothing).emitXml) r])
[]
parseHorizontalTurn :: P.XParse HorizontalTurn
parseHorizontalTurn =
HorizontalTurn
<$> P.optional (P.xattr (P.name "slash") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "placement") >>= parseAboveBelow)
<*> P.optional (P.xattr (P.name "start-note") >>= parseStartNote)
<*> P.optional (P.xattr (P.name "trill-step") >>= parseTrillStep)
<*> P.optional (P.xattr (P.name "two-note-turn") >>= parseTwoNoteTurn)
<*> P.optional (P.xattr (P.name "accelerate") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "beats") >>= parseTrillBeats)
<*> P.optional (P.xattr (P.name "second-beat") >>= parsePercent)
<*> P.optional (P.xattr (P.name "last-beat") >>= parsePercent)
-- | Smart constructor for 'HorizontalTurn'
mkHorizontalTurn :: HorizontalTurn
mkHorizontalTurn = HorizontalTurn Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @identification@ /(complex)/
--
-- Identification contains basic metadata about the score. It includes the information in MuseData headers that may apply at a score-wide, movement-wide, or part-wide level. The creator, rights, source, and relation elements are based on Dublin Core.
data Identification =
Identification {
identificationCreator :: [TypedText] -- ^ /creator/ child element
, identificationRights :: [TypedText] -- ^ /rights/ child element
, identificationEncoding :: (Maybe Encoding) -- ^ /encoding/ child element
, identificationSource :: (Maybe String) -- ^ /source/ child element
, identificationRelation :: [TypedText] -- ^ /relation/ child element
, identificationMiscellaneous :: (Maybe Miscellaneous) -- ^ /miscellaneous/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Identification where
emitXml (Identification a b c d e f) =
XContent XEmpty
[]
(map (XElement (QN "creator" Nothing).emitXml) a ++
map (XElement (QN "rights" Nothing).emitXml) b ++
[maybe XEmpty (XElement (QN "encoding" Nothing).emitXml) c] ++
[maybe XEmpty (XElement (QN "source" Nothing).emitXml) d] ++
map (XElement (QN "relation" Nothing).emitXml) e ++
[maybe XEmpty (XElement (QN "miscellaneous" Nothing).emitXml) f])
parseIdentification :: P.XParse Identification
parseIdentification =
Identification
<$> P.many (P.xchild (P.name "creator") (parseTypedText))
<*> P.many (P.xchild (P.name "rights") (parseTypedText))
<*> P.optional (P.xchild (P.name "encoding") (parseEncoding))
<*> P.optional (P.xchild (P.name "source") (P.xtext >>= return))
<*> P.many (P.xchild (P.name "relation") (parseTypedText))
<*> P.optional (P.xchild (P.name "miscellaneous") (parseMiscellaneous))
-- | Smart constructor for 'Identification'
mkIdentification :: Identification
mkIdentification = Identification [] [] Nothing Nothing [] Nothing
-- | @image@ /(complex)/
--
-- The image type is used to include graphical images in a score.
data Image =
Image {
imageSource :: String -- ^ /source/ attribute
, imageType :: Token -- ^ /type/ attribute
, imageDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, imageDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, imageRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, imageRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, imageHalign :: (Maybe LeftCenterRight) -- ^ /halign/ attribute
, imageValign :: (Maybe ValignImage) -- ^ /valign/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Image where
emitXml (Image a b c d e f g h) =
XContent XEmpty
([XAttr (QN "source" Nothing) (emitXml a)] ++
[XAttr (QN "type" Nothing) (emitXml b)] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "halign" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "valign" Nothing).emitXml) h])
[]
parseImage :: P.XParse Image
parseImage =
Image
<$> (P.xattr (P.name "source") >>= return)
<*> (P.xattr (P.name "type") >>= parseToken)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "halign") >>= parseLeftCenterRight)
<*> P.optional (P.xattr (P.name "valign") >>= parseValignImage)
-- | Smart constructor for 'Image'
mkImage :: String -> Token -> Image
mkImage a b = Image a b Nothing Nothing Nothing Nothing Nothing Nothing
-- | @instrument@ /(complex)/
--
-- The instrument type distinguishes between score-instrument elements in a score-part. The id attribute is an IDREF back to the score-instrument ID. If multiple score-instruments are specified on a score-part, there should be an instrument element for each note in the part.
data Instrument =
Instrument {
instrumentId :: IDREF -- ^ /id/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Instrument where
emitXml (Instrument a) =
XContent XEmpty
([XAttr (QN "id" Nothing) (emitXml a)])
[]
parseInstrument :: P.XParse Instrument
parseInstrument =
Instrument
<$> (P.xattr (P.name "id") >>= parseIDREF)
-- | Smart constructor for 'Instrument'
mkInstrument :: IDREF -> Instrument
mkInstrument a = Instrument a
-- | @interchangeable@ /(complex)/
--
-- The interchangeable type is used to represent the second in a pair of interchangeable dual time signatures, such as the 6/8 in 3/4 (6/8). A separate symbol attribute value is available compared to the time element's symbol attribute, which applies to the first of the dual time signatures. The parentheses attribute value is yes by default.
data Interchangeable =
Interchangeable {
interchangeableSymbol :: (Maybe TimeSymbol) -- ^ /symbol/ attribute
, interchangeableSeparator :: (Maybe TimeSeparator) -- ^ /separator/ attribute
, interchangeableTimeRelation :: (Maybe TimeRelation) -- ^ /time-relation/ child element
, interchangeableTimeSignature :: [TimeSignature]
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Interchangeable where
emitXml (Interchangeable a b c d) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "symbol" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "separator" Nothing).emitXml) b])
([maybe XEmpty (XElement (QN "time-relation" Nothing).emitXml) c] ++
[emitXml d])
parseInterchangeable :: P.XParse Interchangeable
parseInterchangeable =
Interchangeable
<$> P.optional (P.xattr (P.name "symbol") >>= parseTimeSymbol)
<*> P.optional (P.xattr (P.name "separator") >>= parseTimeSeparator)
<*> P.optional (P.xchild (P.name "time-relation") (P.xtext >>= parseTimeRelation))
<*> P.many (parseTimeSignature)
-- | Smart constructor for 'Interchangeable'
mkInterchangeable :: Interchangeable
mkInterchangeable = Interchangeable Nothing Nothing Nothing []
-- | @inversion@ /(complex)/
--
-- The inversion type represents harmony inversions. The value is a number indicating which inversion is used: 0 for root position, 1 for first inversion, etc.
data Inversion =
Inversion {
inversionNonNegativeInteger :: NonNegativeInteger -- ^ text content
, inversionDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, inversionDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, inversionRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, inversionRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, inversionFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, inversionFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, inversionFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, inversionFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, inversionColor :: (Maybe Color) -- ^ /color/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Inversion where
emitXml (Inversion a b c d e f g h i j) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) j])
[]
parseInversion :: P.XParse Inversion
parseInversion =
Inversion
<$> (P.xtext >>= parseNonNegativeInteger)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
-- | Smart constructor for 'Inversion'
mkInversion :: NonNegativeInteger -> Inversion
mkInversion a = Inversion a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @key@ /(complex)/
--
-- The key type represents a key signature. Both traditional and non-traditional key signatures are supported. The optional number attribute refers to staff numbers. If absent, the key signature applies to all staves in the part. Key signatures appear at the start of each system unless the print-object attribute has been set to "no".
data Key =
Key {
keyNumber :: (Maybe StaffNumber) -- ^ /number/ attribute
, keyDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, keyDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, keyRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, keyRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, keyFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, keyFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, keyFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, keyFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, keyColor :: (Maybe Color) -- ^ /color/ attribute
, keyPrintObject :: (Maybe YesNo) -- ^ /print-object/ attribute
, keyKey :: ChxKey
, keyKeyOctave :: [KeyOctave] -- ^ /key-octave/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Key where
emitXml (Key a b c d e f g h i j k l m) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "number" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "print-object" Nothing).emitXml) k])
([emitXml l] ++
map (XElement (QN "key-octave" Nothing).emitXml) m)
parseKey :: P.XParse Key
parseKey =
Key
<$> P.optional (P.xattr (P.name "number") >>= parseStaffNumber)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "print-object") >>= parseYesNo)
<*> parseChxKey
<*> P.many (P.xchild (P.name "key-octave") (parseKeyOctave))
-- | Smart constructor for 'Key'
mkKey :: ChxKey -> Key
mkKey l = Key Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing l []
-- | @key-octave@ /(complex)/
--
-- The key-octave element specifies in which octave an element of a key signature appears. The content specifies the octave value using the same values as the display-octave element. The number attribute is a positive integer that refers to the key signature element in left-to-right order. If the cancel attribute is set to yes, then this number refers to an element specified by the cancel element. It is no by default.
data KeyOctave =
KeyOctave {
keyOctaveOctave :: Octave -- ^ text content
, keyOctaveNumber :: PositiveInteger -- ^ /number/ attribute
, keyOctaveCancel :: (Maybe YesNo) -- ^ /cancel/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml KeyOctave where
emitXml (KeyOctave a b c) =
XContent (emitXml a)
([XAttr (QN "number" Nothing) (emitXml b)] ++
[maybe XEmpty (XAttr (QN "cancel" Nothing).emitXml) c])
[]
parseKeyOctave :: P.XParse KeyOctave
parseKeyOctave =
KeyOctave
<$> (P.xtext >>= parseOctave)
<*> (P.xattr (P.name "number") >>= parsePositiveInteger)
<*> P.optional (P.xattr (P.name "cancel") >>= parseYesNo)
-- | Smart constructor for 'KeyOctave'
mkKeyOctave :: Octave -> PositiveInteger -> KeyOctave
mkKeyOctave a b = KeyOctave a b Nothing
-- | @kind@ /(complex)/
--
-- Kind indicates the type of chord. Degree elements can then add, subtract, or alter from these starting points
--
-- @
--
-- The attributes are used to indicate the formatting of the symbol. Since the kind element is the constant in all the harmony-chord groups that can make up a polychord, many formatting attributes are here.
--
-- The use-symbols attribute is yes if the kind should be represented when possible with harmony symbols rather than letters and numbers. These symbols include:
--
-- major: a triangle, like Unicode 25B3
-- minor: -, like Unicode 002D
-- augmented: +, like Unicode 002B
-- diminished: °, like Unicode 00B0
-- half-diminished: ø, like Unicode 00F8
--
-- For the major-minor kind, only the minor symbol is used when use-symbols is yes. The major symbol is set using the symbol attribute in the degree-value element. The corresponding degree-alter value will usually be 0 in this case.
--
-- The text attribute describes how the kind should be spelled in a score. If use-symbols is yes, the value of the text attribute follows the symbol. The stack-degrees attribute is yes if the degree elements should be stacked above each other. The parentheses-degrees attribute is yes if all the degrees should be in parentheses. The bracket-degrees attribute is yes if all the degrees should be in a bracket. If not specified, these values are implementation-specific. The alignment attributes are for the entire harmony-chord group of which this kind element is a part.
-- @
data Kind =
Kind {
kindKindValue :: KindValue -- ^ text content
, kindUseSymbols :: (Maybe YesNo) -- ^ /use-symbols/ attribute
, kindText :: (Maybe Token) -- ^ /text/ attribute
, kindStackDegrees :: (Maybe YesNo) -- ^ /stack-degrees/ attribute
, kindParenthesesDegrees :: (Maybe YesNo) -- ^ /parentheses-degrees/ attribute
, kindBracketDegrees :: (Maybe YesNo) -- ^ /bracket-degrees/ attribute
, kindDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, kindDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, kindRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, kindRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, kindFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, kindFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, kindFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, kindFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, kindColor :: (Maybe Color) -- ^ /color/ attribute
, kindHalign :: (Maybe LeftCenterRight) -- ^ /halign/ attribute
, kindValign :: (Maybe Valign) -- ^ /valign/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Kind where
emitXml (Kind a b c d e f g h i j k l m n o p q) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "use-symbols" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "text" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "stack-degrees" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "parentheses-degrees" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "bracket-degrees" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) l] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) m] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) n] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) o] ++
[maybe XEmpty (XAttr (QN "halign" Nothing).emitXml) p] ++
[maybe XEmpty (XAttr (QN "valign" Nothing).emitXml) q])
[]
parseKind :: P.XParse Kind
parseKind =
Kind
<$> (P.xtext >>= parseKindValue)
<*> P.optional (P.xattr (P.name "use-symbols") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "text") >>= parseToken)
<*> P.optional (P.xattr (P.name "stack-degrees") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "parentheses-degrees") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "bracket-degrees") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "halign") >>= parseLeftCenterRight)
<*> P.optional (P.xattr (P.name "valign") >>= parseValign)
-- | Smart constructor for 'Kind'
mkKind :: KindValue -> Kind
mkKind a = Kind a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @level@ /(complex)/
--
-- The level type is used to specify editorial information for different MusicXML elements. If the reference attribute for the level element is yes, this indicates editorial information that is for display only and should not affect playback. For instance, a modern edition of older music may set reference="yes" on the attributes containing the music's original clef, key, and time signature. It is no by default.
data Level =
Level {
levelString :: String -- ^ text content
, levelReference :: (Maybe YesNo) -- ^ /reference/ attribute
, levelParentheses :: (Maybe YesNo) -- ^ /parentheses/ attribute
, levelBracket :: (Maybe YesNo) -- ^ /bracket/ attribute
, levelSize :: (Maybe SymbolSize) -- ^ /size/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Level where
emitXml (Level a b c d e) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "reference" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "parentheses" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "bracket" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "size" Nothing).emitXml) e])
[]
parseLevel :: P.XParse Level
parseLevel =
Level
<$> (P.xtext >>= return)
<*> P.optional (P.xattr (P.name "reference") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "parentheses") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "bracket") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "size") >>= parseSymbolSize)
-- | Smart constructor for 'Level'
mkLevel :: String -> Level
mkLevel a = Level a Nothing Nothing Nothing Nothing
-- | @line-width@ /(complex)/
--
-- The line-width type indicates the width of a line type in tenths. The type attribute defines what type of line is being defined. Values include beam, bracket, dashes, enclosure, ending, extend, heavy barline, leger, light barline, octave shift, pedal, slur middle, slur tip, staff, stem, tie middle, tie tip, tuplet bracket, and wedge. The text content is expressed in tenths.
data LineWidth =
LineWidth {
lineWidthTenths :: Tenths -- ^ text content
, cmplineWidthType :: LineWidthType -- ^ /type/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml LineWidth where
emitXml (LineWidth a b) =
XContent (emitXml a)
([XAttr (QN "type" Nothing) (emitXml b)])
[]
parseLineWidth :: P.XParse LineWidth
parseLineWidth =
LineWidth
<$> (P.xtext >>= parseTenths)
<*> (P.xattr (P.name "type") >>= parseLineWidthType)
-- | Smart constructor for 'LineWidth'
mkLineWidth :: Tenths -> LineWidthType -> LineWidth
mkLineWidth a b = LineWidth a b
-- | @link@ /(complex)/
--
-- The link type serves as an outgoing simple XLink. It is also used to connect a MusicXML score with a MusicXML opus. If a relative link is used within a document that is part of a compressed MusicXML file, the link is relative to the root folder of the zip file.
data Link =
Link {
linkName :: (Maybe Token) -- ^ /name/ attribute
, linkHref :: String -- ^ /xlink:href/ attribute
, linkType :: (Maybe Type) -- ^ /xlink:type/ attribute
, linkRole :: (Maybe Token) -- ^ /xlink:role/ attribute
, linkTitle :: (Maybe Token) -- ^ /xlink:title/ attribute
, linkShow :: (Maybe SmpShow) -- ^ /xlink:show/ attribute
, linkActuate :: (Maybe Actuate) -- ^ /xlink:actuate/ attribute
, linkElement :: (Maybe NMTOKEN) -- ^ /element/ attribute
, linkPosition :: (Maybe PositiveInteger) -- ^ /position/ attribute
, linkDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, linkDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, linkRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, linkRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Link where
emitXml (Link a b c d e f g h i j k l m) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "name" Nothing).emitXml) a] ++
[XAttr (QN "href" (Just "xlink")) (emitXml b)] ++
[maybe XEmpty (XAttr (QN "type" (Just "xlink")).emitXml) c] ++
[maybe XEmpty (XAttr (QN "role" (Just "xlink")).emitXml) d] ++
[maybe XEmpty (XAttr (QN "title" (Just "xlink")).emitXml) e] ++
[maybe XEmpty (XAttr (QN "show" (Just "xlink")).emitXml) f] ++
[maybe XEmpty (XAttr (QN "actuate" (Just "xlink")).emitXml) g] ++
[maybe XEmpty (XAttr (QN "element" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "position" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) l] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) m])
[]
parseLink :: P.XParse Link
parseLink =
Link
<$> P.optional (P.xattr (P.name "name") >>= parseToken)
<*> (P.xattr (P.name "xlink:href") >>= return)
<*> P.optional (P.xattr (P.name "xlink:type") >>= parseType)
<*> P.optional (P.xattr (P.name "xlink:role") >>= parseToken)
<*> P.optional (P.xattr (P.name "xlink:title") >>= parseToken)
<*> P.optional (P.xattr (P.name "xlink:show") >>= parseSmpShow)
<*> P.optional (P.xattr (P.name "xlink:actuate") >>= parseActuate)
<*> P.optional (P.xattr (P.name "element") >>= parseNMTOKEN)
<*> P.optional (P.xattr (P.name "position") >>= parsePositiveInteger)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
-- | Smart constructor for 'Link'
mkLink :: String -> Link
mkLink b = Link Nothing b Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @lyric@ /(complex)/
--
-- The lyric type represents text underlays for lyrics, based on Humdrum with support for other formats. Two text elements that are not separated by an elision element are part of the same syllable, but may have different text formatting. The MusicXML 2.0 XSD is more strict than the 2.0 DTD in enforcing this by disallowing a second syllabic element unless preceded by an elision element. The lyric number indicates multiple lines, though a name can be used as well (as in Finale's verse / chorus / section specification). Justification is center by default; placement is below by default. The content of the elision type is used to specify the symbol used to display the elision. Common values are a no-break space (Unicode 00A0), an underscore (Unicode 005F), or an undertie (Unicode 203F).
data Lyric =
Lyric {
lyricNumber :: (Maybe NMTOKEN) -- ^ /number/ attribute
, lyricName :: (Maybe Token) -- ^ /name/ attribute
, lyricJustify :: (Maybe LeftCenterRight) -- ^ /justify/ attribute
, lyricDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, lyricDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, lyricRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, lyricRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, lyricPlacement :: (Maybe AboveBelow) -- ^ /placement/ attribute
, lyricColor :: (Maybe Color) -- ^ /color/ attribute
, lyricPrintObject :: (Maybe YesNo) -- ^ /print-object/ attribute
, lyricLyric :: ChxLyric
, lyricEndLine :: (Maybe Empty) -- ^ /end-line/ child element
, lyricEndParagraph :: (Maybe Empty) -- ^ /end-paragraph/ child element
, lyricEditorial :: Editorial
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Lyric where
emitXml (Lyric a b c d e f g h i j k l m n) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "number" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "name" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "justify" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "placement" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "print-object" Nothing).emitXml) j])
([emitXml k] ++
[maybe XEmpty (XElement (QN "end-line" Nothing).emitXml) l] ++
[maybe XEmpty (XElement (QN "end-paragraph" Nothing).emitXml) m] ++
[emitXml n])
parseLyric :: P.XParse Lyric
parseLyric =
Lyric
<$> P.optional (P.xattr (P.name "number") >>= parseNMTOKEN)
<*> P.optional (P.xattr (P.name "name") >>= parseToken)
<*> P.optional (P.xattr (P.name "justify") >>= parseLeftCenterRight)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "placement") >>= parseAboveBelow)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "print-object") >>= parseYesNo)
<*> parseChxLyric
<*> P.optional (P.xchild (P.name "end-line") (parseEmpty))
<*> P.optional (P.xchild (P.name "end-paragraph") (parseEmpty))
<*> parseEditorial
-- | Smart constructor for 'Lyric'
mkLyric :: ChxLyric -> Editorial -> Lyric
mkLyric k n = Lyric Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing k Nothing Nothing n
-- | @lyric-font@ /(complex)/
--
-- The lyric-font type specifies the default font for a particular name and number of lyric.
data LyricFont =
LyricFont {
lyricFontNumber :: (Maybe NMTOKEN) -- ^ /number/ attribute
, lyricFontName :: (Maybe Token) -- ^ /name/ attribute
, lyricFontFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, lyricFontFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, lyricFontFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, lyricFontFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml LyricFont where
emitXml (LyricFont a b c d e f) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "number" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "name" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) f])
[]
parseLyricFont :: P.XParse LyricFont
parseLyricFont =
LyricFont
<$> P.optional (P.xattr (P.name "number") >>= parseNMTOKEN)
<*> P.optional (P.xattr (P.name "name") >>= parseToken)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
-- | Smart constructor for 'LyricFont'
mkLyricFont :: LyricFont
mkLyricFont = LyricFont Nothing Nothing Nothing Nothing Nothing Nothing
-- | @lyric-language@ /(complex)/
--
-- The lyric-language type specifies the default language for a particular name and number of lyric.
data LyricLanguage =
LyricLanguage {
lyricLanguageNumber :: (Maybe NMTOKEN) -- ^ /number/ attribute
, lyricLanguageName :: (Maybe Token) -- ^ /name/ attribute
, lyricLanguageLang :: Lang -- ^ /xml:lang/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml LyricLanguage where
emitXml (LyricLanguage a b c) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "number" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "name" Nothing).emitXml) b] ++
[XAttr (QN "lang" (Just "xml")) (emitXml c)])
[]
parseLyricLanguage :: P.XParse LyricLanguage
parseLyricLanguage =
LyricLanguage
<$> P.optional (P.xattr (P.name "number") >>= parseNMTOKEN)
<*> P.optional (P.xattr (P.name "name") >>= parseToken)
<*> (P.xattr (P.name "xml:lang") >>= parseLang)
-- | Smart constructor for 'LyricLanguage'
mkLyricLanguage :: Lang -> LyricLanguage
mkLyricLanguage c = LyricLanguage Nothing Nothing c
-- | @measure@ /(complex)/
data Measure =
Measure {
measureNumber :: Token -- ^ /number/ attribute
, measureImplicit :: (Maybe YesNo) -- ^ /implicit/ attribute
, measureNonControlling :: (Maybe YesNo) -- ^ /non-controlling/ attribute
, measureWidth :: (Maybe Tenths) -- ^ /width/ attribute
, measureMusicData :: MusicData
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Measure where
emitXml (Measure a b c d e) =
XContent XEmpty
([XAttr (QN "number" Nothing) (emitXml a)] ++
[maybe XEmpty (XAttr (QN "implicit" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "non-controlling" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "width" Nothing).emitXml) d])
([emitXml e])
parseMeasure :: P.XParse Measure
parseMeasure =
Measure
<$> (P.xattr (P.name "number") >>= parseToken)
<*> P.optional (P.xattr (P.name "implicit") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "non-controlling") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "width") >>= parseTenths)
<*> parseMusicData
-- | Smart constructor for 'Measure'
mkMeasure :: Token -> MusicData -> Measure
mkMeasure a e = Measure a Nothing Nothing Nothing e
-- | @measure@ /(complex)/
-- mangled: 1
data CmpMeasure =
CmpMeasure {
cmpmeasureNumber :: Token -- ^ /number/ attribute
, cmpmeasureImplicit :: (Maybe YesNo) -- ^ /implicit/ attribute
, cmpmeasureNonControlling :: (Maybe YesNo) -- ^ /non-controlling/ attribute
, cmpmeasureWidth :: (Maybe Tenths) -- ^ /width/ attribute
, measurePart :: [Part] -- ^ /part/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml CmpMeasure where
emitXml (CmpMeasure a b c d e) =
XContent XEmpty
([XAttr (QN "number" Nothing) (emitXml a)] ++
[maybe XEmpty (XAttr (QN "implicit" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "non-controlling" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "width" Nothing).emitXml) d])
(map (XElement (QN "part" Nothing).emitXml) e)
parseCmpMeasure :: P.XParse CmpMeasure
parseCmpMeasure =
CmpMeasure
<$> (P.xattr (P.name "number") >>= parseToken)
<*> P.optional (P.xattr (P.name "implicit") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "non-controlling") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "width") >>= parseTenths)
<*> P.many (P.xchild (P.name "part") (parsePart))
-- | Smart constructor for 'CmpMeasure'
mkCmpMeasure :: Token -> CmpMeasure
mkCmpMeasure a = CmpMeasure a Nothing Nothing Nothing []
-- | @measure-layout@ /(complex)/
--
-- The measure-layout type includes the horizontal distance from the previous measure.
data MeasureLayout =
MeasureLayout {
measureLayoutMeasureDistance :: (Maybe Tenths) -- ^ /measure-distance/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml MeasureLayout where
emitXml (MeasureLayout a) =
XContent XEmpty
[]
([maybe XEmpty (XElement (QN "measure-distance" Nothing).emitXml) a])
parseMeasureLayout :: P.XParse MeasureLayout
parseMeasureLayout =
MeasureLayout
<$> P.optional (P.xchild (P.name "measure-distance") (P.xtext >>= parseTenths))
-- | Smart constructor for 'MeasureLayout'
mkMeasureLayout :: MeasureLayout
mkMeasureLayout = MeasureLayout Nothing
-- | @measure-numbering@ /(complex)/
--
-- The measure-numbering type describes how frequently measure numbers are displayed on this part. The number attribute from the measure element is used for printing. Measures with an implicit attribute set to "yes" never display a measure number, regardless of the measure-numbering setting.
data MeasureNumbering =
MeasureNumbering {
measureNumberingMeasureNumberingValue :: MeasureNumberingValue -- ^ text content
, measureNumberingDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, measureNumberingDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, measureNumberingRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, measureNumberingRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, measureNumberingFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, measureNumberingFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, measureNumberingFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, measureNumberingFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, measureNumberingColor :: (Maybe Color) -- ^ /color/ attribute
, measureNumberingHalign :: (Maybe LeftCenterRight) -- ^ /halign/ attribute
, measureNumberingValign :: (Maybe Valign) -- ^ /valign/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml MeasureNumbering where
emitXml (MeasureNumbering a b c d e f g h i j k l) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "halign" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "valign" Nothing).emitXml) l])
[]
parseMeasureNumbering :: P.XParse MeasureNumbering
parseMeasureNumbering =
MeasureNumbering
<$> (P.xtext >>= parseMeasureNumberingValue)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "halign") >>= parseLeftCenterRight)
<*> P.optional (P.xattr (P.name "valign") >>= parseValign)
-- | Smart constructor for 'MeasureNumbering'
mkMeasureNumbering :: MeasureNumberingValue -> MeasureNumbering
mkMeasureNumbering a = MeasureNumbering a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @measure-repeat@ /(complex)/
--
-- The measure-repeat type is used for both single and multiple measure repeats. The text of the element indicates the number of measures to be repeated in a single pattern. The slashes attribute specifies the number of slashes to use in the repeat sign. It is 1 if not specified. Both the start and the stop of the measure-repeat must be specified. The text of the element is ignored when the type is stop.
--
-- The measure-repeat element specifies a notation style for repetitions. The actual music being repeated needs to be repeated within the MusicXML file. This element specifies the notation that indicates the repeat.
data MeasureRepeat =
MeasureRepeat {
measureRepeatPositiveIntegerOrEmpty :: PositiveIntegerOrEmpty -- ^ text content
, measureRepeatType :: StartStop -- ^ /type/ attribute
, measureRepeatSlashes :: (Maybe PositiveInteger) -- ^ /slashes/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml MeasureRepeat where
emitXml (MeasureRepeat a b c) =
XContent (emitXml a)
([XAttr (QN "type" Nothing) (emitXml b)] ++
[maybe XEmpty (XAttr (QN "slashes" Nothing).emitXml) c])
[]
parseMeasureRepeat :: P.XParse MeasureRepeat
parseMeasureRepeat =
MeasureRepeat
<$> (P.xtext >>= parsePositiveIntegerOrEmpty)
<*> (P.xattr (P.name "type") >>= parseStartStop)
<*> P.optional (P.xattr (P.name "slashes") >>= parsePositiveInteger)
-- | Smart constructor for 'MeasureRepeat'
mkMeasureRepeat :: PositiveIntegerOrEmpty -> StartStop -> MeasureRepeat
mkMeasureRepeat a b = MeasureRepeat a b Nothing
-- | @measure-style@ /(complex)/
--
-- A measure-style indicates a special way to print partial to multiple measures within a part. This includes multiple rests over several measures, repeats of beats, single, or multiple measures, and use of slash notation.
--
-- The multiple-rest and measure-repeat symbols indicate the number of measures covered in the element content. The beat-repeat and slash elements can cover partial measures. All but the multiple-rest element use a type attribute to indicate starting and stopping the use of the style. The optional number attribute specifies the staff number from top to bottom on the system, as with clef.
data MeasureStyle =
MeasureStyle {
measureStyleNumber :: (Maybe StaffNumber) -- ^ /number/ attribute
, measureStyleFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, measureStyleFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, measureStyleFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, measureStyleFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, measureStyleColor :: (Maybe Color) -- ^ /color/ attribute
, measureStyleMeasureStyle :: ChxMeasureStyle
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml MeasureStyle where
emitXml (MeasureStyle a b c d e f g) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "number" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) f])
([emitXml g])
parseMeasureStyle :: P.XParse MeasureStyle
parseMeasureStyle =
MeasureStyle
<$> P.optional (P.xattr (P.name "number") >>= parseStaffNumber)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> parseChxMeasureStyle
-- | Smart constructor for 'MeasureStyle'
mkMeasureStyle :: ChxMeasureStyle -> MeasureStyle
mkMeasureStyle g = MeasureStyle Nothing Nothing Nothing Nothing Nothing Nothing g
-- | @metronome@ /(complex)/
--
-- The metronome type represents metronome marks and other metric relationships. The beat-unit group and per-minute element specify regular metronome marks. The metronome-note and metronome-relation elements allow for the specification of more complicated metric relationships, such as swing tempo marks where two eighths are equated to a quarter note / eighth note triplet. The parentheses attribute indicates whether or not to put the metronome mark in parentheses; its value is no if not specified.
data Metronome =
Metronome {
metronomeParentheses :: (Maybe YesNo) -- ^ /parentheses/ attribute
, metronomeDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, metronomeDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, metronomeRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, metronomeRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, metronomeFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, metronomeFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, metronomeFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, metronomeFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, metronomeColor :: (Maybe Color) -- ^ /color/ attribute
, metronomeHalign :: (Maybe LeftCenterRight) -- ^ /halign/ attribute
, metronomeValign :: (Maybe Valign) -- ^ /valign/ attribute
, metronomeJustify :: (Maybe LeftCenterRight) -- ^ /justify/ attribute
, metronomeMetronome :: ChxMetronome
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Metronome where
emitXml (Metronome a b c d e f g h i j k l m n) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "parentheses" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "halign" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "valign" Nothing).emitXml) l] ++
[maybe XEmpty (XAttr (QN "justify" Nothing).emitXml) m])
([emitXml n])
parseMetronome :: P.XParse Metronome
parseMetronome =
Metronome
<$> P.optional (P.xattr (P.name "parentheses") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "halign") >>= parseLeftCenterRight)
<*> P.optional (P.xattr (P.name "valign") >>= parseValign)
<*> P.optional (P.xattr (P.name "justify") >>= parseLeftCenterRight)
<*> parseChxMetronome
-- | Smart constructor for 'Metronome'
mkMetronome :: ChxMetronome -> Metronome
mkMetronome n = Metronome Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing n
-- | @metronome-beam@ /(complex)/
--
-- The metronome-beam type works like the beam type in defining metric relationships, but does not include all the attributes available in the beam type.
data MetronomeBeam =
MetronomeBeam {
metronomeBeamBeamValue :: BeamValue -- ^ text content
, metronomeBeamNumber :: (Maybe BeamLevel) -- ^ /number/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml MetronomeBeam where
emitXml (MetronomeBeam a b) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "number" Nothing).emitXml) b])
[]
parseMetronomeBeam :: P.XParse MetronomeBeam
parseMetronomeBeam =
MetronomeBeam
<$> (P.xtext >>= parseBeamValue)
<*> P.optional (P.xattr (P.name "number") >>= parseBeamLevel)
-- | Smart constructor for 'MetronomeBeam'
mkMetronomeBeam :: BeamValue -> MetronomeBeam
mkMetronomeBeam a = MetronomeBeam a Nothing
-- | @metronome-note@ /(complex)/
--
-- The metronome-note type defines the appearance of a note within a metric relationship mark.
data MetronomeNote =
MetronomeNote {
metronomeNoteMetronomeType :: NoteTypeValue -- ^ /metronome-type/ child element
, metronomeNoteMetronomeDot :: [Empty] -- ^ /metronome-dot/ child element
, metronomeNoteMetronomeBeam :: [MetronomeBeam] -- ^ /metronome-beam/ child element
, metronomeNoteMetronomeTuplet :: (Maybe MetronomeTuplet) -- ^ /metronome-tuplet/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml MetronomeNote where
emitXml (MetronomeNote a b c d) =
XContent XEmpty
[]
([XElement (QN "metronome-type" Nothing) (emitXml a)] ++
map (XElement (QN "metronome-dot" Nothing).emitXml) b ++
map (XElement (QN "metronome-beam" Nothing).emitXml) c ++
[maybe XEmpty (XElement (QN "metronome-tuplet" Nothing).emitXml) d])
parseMetronomeNote :: P.XParse MetronomeNote
parseMetronomeNote =
MetronomeNote
<$> (P.xchild (P.name "metronome-type") (P.xtext >>= parseNoteTypeValue))
<*> P.many (P.xchild (P.name "metronome-dot") (parseEmpty))
<*> P.many (P.xchild (P.name "metronome-beam") (parseMetronomeBeam))
<*> P.optional (P.xchild (P.name "metronome-tuplet") (parseMetronomeTuplet))
-- | Smart constructor for 'MetronomeNote'
mkMetronomeNote :: NoteTypeValue -> MetronomeNote
mkMetronomeNote a = MetronomeNote a [] [] Nothing
-- | @metronome-tuplet@ /(complex)/
--
-- The metronome-tuplet type uses the same element structure as the time-modification element along with some attributes from the tuplet element.
data MetronomeTuplet =
MetronomeTuplet {
metronomeTupletTimeModification :: MetronomeTuplet
, metronomeTupletType :: StartStop -- ^ /type/ attribute
, metronomeTupletBracket :: (Maybe YesNo) -- ^ /bracket/ attribute
, metronomeTupletShowNumber :: (Maybe ShowTuplet) -- ^ /show-number/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml MetronomeTuplet where
emitXml (MetronomeTuplet a b c d) =
XContent XEmpty
([XAttr (QN "type" Nothing) (emitXml b)] ++
[maybe XEmpty (XAttr (QN "bracket" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "show-number" Nothing).emitXml) d])
([emitXml a])
parseMetronomeTuplet :: P.XParse MetronomeTuplet
parseMetronomeTuplet =
MetronomeTuplet
<$> parseMetronomeTuplet
<*> (P.xattr (P.name "type") >>= parseStartStop)
<*> P.optional (P.xattr (P.name "bracket") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "show-number") >>= parseShowTuplet)
-- | Smart constructor for 'MetronomeTuplet'
mkMetronomeTuplet :: MetronomeTuplet -> StartStop -> MetronomeTuplet
mkMetronomeTuplet a b = MetronomeTuplet a b Nothing Nothing
-- | @midi-device@ /(complex)/
--
-- The midi-device type corresponds to the DeviceName meta event in Standard MIDI Files. The optional port attribute is a number from 1 to 16 that can be used with the unofficial MIDI port (or cable) meta event. Unlike the DeviceName meta event, there can be multiple midi-device elements per MusicXML part starting in MusicXML 3.0. The optional id attribute refers to the score-instrument assigned to this device. If missing, the device assignment affects all score-instrument elements in the score-part.
data MidiDevice =
MidiDevice {
midiDeviceString :: String -- ^ text content
, midiDevicePort :: (Maybe Midi16) -- ^ /port/ attribute
, midiDeviceId :: (Maybe IDREF) -- ^ /id/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml MidiDevice where
emitXml (MidiDevice a b c) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "port" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "id" Nothing).emitXml) c])
[]
parseMidiDevice :: P.XParse MidiDevice
parseMidiDevice =
MidiDevice
<$> (P.xtext >>= return)
<*> P.optional (P.xattr (P.name "port") >>= parseMidi16)
<*> P.optional (P.xattr (P.name "id") >>= parseIDREF)
-- | Smart constructor for 'MidiDevice'
mkMidiDevice :: String -> MidiDevice
mkMidiDevice a = MidiDevice a Nothing Nothing
-- | @midi-instrument@ /(complex)/
--
-- The midi-instrument type defines MIDI 1.0 instrument playback. The midi-instrument element can be a part of either the score-instrument element at the start of a part, or the sound element within a part. The id attribute refers to the score-instrument affected by the change.
data MidiInstrument =
MidiInstrument {
midiInstrumentId :: IDREF -- ^ /id/ attribute
, midiInstrumentMidiChannel :: (Maybe Midi16) -- ^ /midi-channel/ child element
, midiInstrumentMidiName :: (Maybe String) -- ^ /midi-name/ child element
, midiInstrumentMidiBank :: (Maybe Midi16384) -- ^ /midi-bank/ child element
, midiInstrumentMidiProgram :: (Maybe Midi128) -- ^ /midi-program/ child element
, midiInstrumentMidiUnpitched :: (Maybe Midi128) -- ^ /midi-unpitched/ child element
, midiInstrumentVolume :: (Maybe Percent) -- ^ /volume/ child element
, midiInstrumentPan :: (Maybe RotationDegrees) -- ^ /pan/ child element
, midiInstrumentElevation :: (Maybe RotationDegrees) -- ^ /elevation/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml MidiInstrument where
emitXml (MidiInstrument a b c d e f g h i) =
XContent XEmpty
([XAttr (QN "id" Nothing) (emitXml a)])
([maybe XEmpty (XElement (QN "midi-channel" Nothing).emitXml) b] ++
[maybe XEmpty (XElement (QN "midi-name" Nothing).emitXml) c] ++
[maybe XEmpty (XElement (QN "midi-bank" Nothing).emitXml) d] ++
[maybe XEmpty (XElement (QN "midi-program" Nothing).emitXml) e] ++
[maybe XEmpty (XElement (QN "midi-unpitched" Nothing).emitXml) f] ++
[maybe XEmpty (XElement (QN "volume" Nothing).emitXml) g] ++
[maybe XEmpty (XElement (QN "pan" Nothing).emitXml) h] ++
[maybe XEmpty (XElement (QN "elevation" Nothing).emitXml) i])
parseMidiInstrument :: P.XParse MidiInstrument
parseMidiInstrument =
MidiInstrument
<$> (P.xattr (P.name "id") >>= parseIDREF)
<*> P.optional (P.xchild (P.name "midi-channel") (P.xtext >>= parseMidi16))
<*> P.optional (P.xchild (P.name "midi-name") (P.xtext >>= return))
<*> P.optional (P.xchild (P.name "midi-bank") (P.xtext >>= parseMidi16384))
<*> P.optional (P.xchild (P.name "midi-program") (P.xtext >>= parseMidi128))
<*> P.optional (P.xchild (P.name "midi-unpitched") (P.xtext >>= parseMidi128))
<*> P.optional (P.xchild (P.name "volume") (P.xtext >>= parsePercent))
<*> P.optional (P.xchild (P.name "pan") (P.xtext >>= parseRotationDegrees))
<*> P.optional (P.xchild (P.name "elevation") (P.xtext >>= parseRotationDegrees))
-- | Smart constructor for 'MidiInstrument'
mkMidiInstrument :: IDREF -> MidiInstrument
mkMidiInstrument a = MidiInstrument a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @miscellaneous@ /(complex)/
--
-- If a program has other metadata not yet supported in the MusicXML format, it can go in the miscellaneous element. The miscellaneous type puts each separate part of metadata into its own miscellaneous-field type.
data Miscellaneous =
Miscellaneous {
miscellaneousMiscellaneousField :: [MiscellaneousField] -- ^ /miscellaneous-field/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Miscellaneous where
emitXml (Miscellaneous a) =
XContent XEmpty
[]
(map (XElement (QN "miscellaneous-field" Nothing).emitXml) a)
parseMiscellaneous :: P.XParse Miscellaneous
parseMiscellaneous =
Miscellaneous
<$> P.many (P.xchild (P.name "miscellaneous-field") (parseMiscellaneousField))
-- | Smart constructor for 'Miscellaneous'
mkMiscellaneous :: Miscellaneous
mkMiscellaneous = Miscellaneous []
-- | @miscellaneous-field@ /(complex)/
--
-- If a program has other metadata not yet supported in the MusicXML format, each type of metadata can go in a miscellaneous-field element. The required name attribute indicates the type of metadata the element content represents.
data MiscellaneousField =
MiscellaneousField {
miscellaneousFieldString :: String -- ^ text content
, miscellaneousFieldName :: Token -- ^ /name/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml MiscellaneousField where
emitXml (MiscellaneousField a b) =
XContent (emitXml a)
([XAttr (QN "name" Nothing) (emitXml b)])
[]
parseMiscellaneousField :: P.XParse MiscellaneousField
parseMiscellaneousField =
MiscellaneousField
<$> (P.xtext >>= return)
<*> (P.xattr (P.name "name") >>= parseToken)
-- | Smart constructor for 'MiscellaneousField'
mkMiscellaneousField :: String -> Token -> MiscellaneousField
mkMiscellaneousField a b = MiscellaneousField a b
-- | @mordent@ /(complex)/
--
-- The mordent type is used for both represents the mordent sign with the vertical line and the inverted-mordent sign without the line. The long attribute is "no" by default. The approach and departure attributes are used for compound ornaments, indicating how the beginning and ending of the ornament look relative to the main part of the mordent.
data Mordent =
Mordent {
mordentEmptyTrillSound :: Mordent
, mordentLong :: (Maybe YesNo) -- ^ /long/ attribute
, mordentApproach :: (Maybe AboveBelow) -- ^ /approach/ attribute
, mordentDeparture :: (Maybe AboveBelow) -- ^ /departure/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Mordent where
emitXml (Mordent a b c d) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "long" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "approach" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "departure" Nothing).emitXml) d])
([emitXml a])
parseMordent :: P.XParse Mordent
parseMordent =
Mordent
<$> parseMordent
<*> P.optional (P.xattr (P.name "long") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "approach") >>= parseAboveBelow)
<*> P.optional (P.xattr (P.name "departure") >>= parseAboveBelow)
-- | Smart constructor for 'Mordent'
mkMordent :: Mordent -> Mordent
mkMordent a = Mordent a Nothing Nothing Nothing
-- | @multiple-rest@ /(complex)/
--
-- The text of the multiple-rest type indicates the number of measures in the multiple rest. Multiple rests may use the 1-bar / 2-bar / 4-bar rest symbols, or a single shape. The use-symbols attribute indicates which to use; it is no if not specified. The element text is ignored when the type is stop.
data MultipleRest =
MultipleRest {
multipleRestPositiveIntegerOrEmpty :: PositiveIntegerOrEmpty -- ^ text content
, multipleRestUseSymbols :: (Maybe YesNo) -- ^ /use-symbols/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml MultipleRest where
emitXml (MultipleRest a b) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "use-symbols" Nothing).emitXml) b])
[]
parseMultipleRest :: P.XParse MultipleRest
parseMultipleRest =
MultipleRest
<$> (P.xtext >>= parsePositiveIntegerOrEmpty)
<*> P.optional (P.xattr (P.name "use-symbols") >>= parseYesNo)
-- | Smart constructor for 'MultipleRest'
mkMultipleRest :: PositiveIntegerOrEmpty -> MultipleRest
mkMultipleRest a = MultipleRest a Nothing
-- | @name-display@ /(complex)/
--
-- The name-display type is used for exact formatting of multi-font text in part and group names to the left of the system. The print-object attribute can be used to determine what, if anything, is printed at the start of each system. Enclosure for the display-text element is none by default. Language for the display-text element is Italian ("it") by default.
data NameDisplay =
NameDisplay {
nameDisplayPrintObject :: (Maybe YesNo) -- ^ /print-object/ attribute
, nameDisplayNameDisplay :: [ChxNameDisplay]
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml NameDisplay where
emitXml (NameDisplay a b) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "print-object" Nothing).emitXml) a])
([emitXml b])
parseNameDisplay :: P.XParse NameDisplay
parseNameDisplay =
NameDisplay
<$> P.optional (P.xattr (P.name "print-object") >>= parseYesNo)
<*> P.many (parseChxNameDisplay)
-- | Smart constructor for 'NameDisplay'
mkNameDisplay :: NameDisplay
mkNameDisplay = NameDisplay Nothing []
-- | @non-arpeggiate@ /(complex)/
--
-- The non-arpeggiate type indicates that this note is at the top or bottom of a bracket indicating to not arpeggiate these notes. Since this does not involve playback, it is only used on the top or bottom notes, not on each note as for the arpeggiate type.
data NonArpeggiate =
NonArpeggiate {
nonArpeggiateType :: TopBottom -- ^ /type/ attribute
, nonArpeggiateNumber :: (Maybe NumberLevel) -- ^ /number/ attribute
, nonArpeggiateDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, nonArpeggiateDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, nonArpeggiateRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, nonArpeggiateRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, nonArpeggiatePlacement :: (Maybe AboveBelow) -- ^ /placement/ attribute
, nonArpeggiateColor :: (Maybe Color) -- ^ /color/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml NonArpeggiate where
emitXml (NonArpeggiate a b c d e f g h) =
XContent XEmpty
([XAttr (QN "type" Nothing) (emitXml a)] ++
[maybe XEmpty (XAttr (QN "number" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "placement" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) h])
[]
parseNonArpeggiate :: P.XParse NonArpeggiate
parseNonArpeggiate =
NonArpeggiate
<$> (P.xattr (P.name "type") >>= parseTopBottom)
<*> P.optional (P.xattr (P.name "number") >>= parseNumberLevel)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "placement") >>= parseAboveBelow)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
-- | Smart constructor for 'NonArpeggiate'
mkNonArpeggiate :: TopBottom -> NonArpeggiate
mkNonArpeggiate a = NonArpeggiate a Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @notations@ /(complex)/
--
-- Notations refer to musical notations, not XML notations. Multiple notations are allowed in order to represent multiple editorial levels. The print-object attribute, added in Version 3.0, allows notations to represent details of performance technique, such as fingerings, without having them appear in the score.
data Notations =
Notations {
notationsPrintObject :: (Maybe YesNo) -- ^ /print-object/ attribute
, notationsEditorial :: Editorial
, notationsNotations :: [ChxNotations]
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Notations where
emitXml (Notations a b c) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "print-object" Nothing).emitXml) a])
([emitXml b] ++
[emitXml c])
parseNotations :: P.XParse Notations
parseNotations =
Notations
<$> P.optional (P.xattr (P.name "print-object") >>= parseYesNo)
<*> parseEditorial
<*> P.many (parseChxNotations)
-- | Smart constructor for 'Notations'
mkNotations :: Editorial -> Notations
mkNotations b = Notations Nothing b []
-- | @note@ /(complex)/
--
-- Notes are the most common type of MusicXML data. The MusicXML format keeps the MuseData distinction between elements used for sound information and elements used for notation information (e.g., tie is used for sound, tied for notation). Thus grace notes do not have a duration element. Cue notes have a duration element, as do forward elements, but no tie elements. Having these two types of information available can make interchange considerably easier, as some programs handle one type of information much more readily than the other.
--
-- The dynamics and end-dynamics attributes correspond to MIDI 1.0's Note On and Note Off velocities, respectively. They are expressed in terms of percentages of the default forte value (90 for MIDI 1.0). The attack and release attributes are used to alter the starting and stopping time of the note from when it would otherwise occur based on the flow of durations - information that is specific to a performance. They are expressed in terms of divisions, either positive or negative. A note that starts a tie should not have a release attribute, and a note that stops a tie should not have an attack attribute. If a note is played only particular times through a repeat, the time-only attribute shows which times to play the note. The pizzicato attribute is used when just this note is sounded pizzicato, vs. the pizzicato element which changes overall playback between pizzicato and arco.
data Note =
Note {
noteDynamics :: (Maybe NonNegativeDecimal) -- ^ /dynamics/ attribute
, noteEndDynamics :: (Maybe NonNegativeDecimal) -- ^ /end-dynamics/ attribute
, noteAttack :: (Maybe Divisions) -- ^ /attack/ attribute
, noteRelease :: (Maybe Divisions) -- ^ /release/ attribute
, noteTimeOnly :: (Maybe TimeOnly) -- ^ /time-only/ attribute
, notePizzicato :: (Maybe YesNo) -- ^ /pizzicato/ attribute
, noteDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, noteDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, noteRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, noteRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, noteFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, noteFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, noteFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, noteFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, noteColor :: (Maybe Color) -- ^ /color/ attribute
, notePrintDot :: (Maybe YesNo) -- ^ /print-dot/ attribute
, notePrintLyric :: (Maybe YesNo) -- ^ /print-lyric/ attribute
, notePrintObject :: (Maybe YesNo) -- ^ /print-object/ attribute
, notePrintSpacing :: (Maybe YesNo) -- ^ /print-spacing/ attribute
, noteNote :: ChxNote
, noteInstrument :: (Maybe Instrument) -- ^ /instrument/ child element
, noteEditorialVoice :: EditorialVoice
, noteType :: (Maybe NoteType) -- ^ /type/ child element
, noteDot :: [EmptyPlacement] -- ^ /dot/ child element
, noteAccidental :: (Maybe Accidental) -- ^ /accidental/ child element
, noteTimeModification :: (Maybe TimeModification) -- ^ /time-modification/ child element
, noteStem :: (Maybe Stem) -- ^ /stem/ child element
, noteNotehead :: (Maybe Notehead) -- ^ /notehead/ child element
, noteNoteheadText :: (Maybe NoteheadText) -- ^ /notehead-text/ child element
, noteStaff :: (Maybe Staff)
, noteBeam :: [Beam] -- ^ /beam/ child element
, noteNotations :: [Notations] -- ^ /notations/ child element
, noteLyric :: [Lyric] -- ^ /lyric/ child element
, notePlay :: (Maybe Play) -- ^ /play/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Note where
emitXml (Note a b c d e f g h i j k l m n o p q r s t u v w x y z a1 b1 c1 d1 e1 f1 g1 h1) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "dynamics" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "end-dynamics" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "attack" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "release" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "time-only" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "pizzicato" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) l] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) m] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) n] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) o] ++
[maybe XEmpty (XAttr (QN "print-dot" Nothing).emitXml) p] ++
[maybe XEmpty (XAttr (QN "print-lyric" Nothing).emitXml) q] ++
[maybe XEmpty (XAttr (QN "print-object" Nothing).emitXml) r] ++
[maybe XEmpty (XAttr (QN "print-spacing" Nothing).emitXml) s])
([emitXml t] ++
[maybe XEmpty (XElement (QN "instrument" Nothing).emitXml) u] ++
[emitXml v] ++
[maybe XEmpty (XElement (QN "type" Nothing).emitXml) w] ++
map (XElement (QN "dot" Nothing).emitXml) x ++
[maybe XEmpty (XElement (QN "accidental" Nothing).emitXml) y] ++
[maybe XEmpty (XElement (QN "time-modification" Nothing).emitXml) z] ++
[maybe XEmpty (XElement (QN "stem" Nothing).emitXml) a1] ++
[maybe XEmpty (XElement (QN "notehead" Nothing).emitXml) b1] ++
[maybe XEmpty (XElement (QN "notehead-text" Nothing).emitXml) c1] ++
[emitXml d1] ++
map (XElement (QN "beam" Nothing).emitXml) e1 ++
map (XElement (QN "notations" Nothing).emitXml) f1 ++
map (XElement (QN "lyric" Nothing).emitXml) g1 ++
[maybe XEmpty (XElement (QN "play" Nothing).emitXml) h1])
parseNote :: P.XParse Note
parseNote =
Note
<$> P.optional (P.xattr (P.name "dynamics") >>= parseNonNegativeDecimal)
<*> P.optional (P.xattr (P.name "end-dynamics") >>= parseNonNegativeDecimal)
<*> P.optional (P.xattr (P.name "attack") >>= parseDivisions)
<*> P.optional (P.xattr (P.name "release") >>= parseDivisions)
<*> P.optional (P.xattr (P.name "time-only") >>= parseTimeOnly)
<*> P.optional (P.xattr (P.name "pizzicato") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "print-dot") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "print-lyric") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "print-object") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "print-spacing") >>= parseYesNo)
<*> parseChxNote
<*> P.optional (P.xchild (P.name "instrument") (parseInstrument))
<*> parseEditorialVoice
<*> P.optional (P.xchild (P.name "type") (parseNoteType))
<*> P.many (P.xchild (P.name "dot") (parseEmptyPlacement))
<*> P.optional (P.xchild (P.name "accidental") (parseAccidental))
<*> P.optional (P.xchild (P.name "time-modification") (parseTimeModification))
<*> P.optional (P.xchild (P.name "stem") (parseStem))
<*> P.optional (P.xchild (P.name "notehead") (parseNotehead))
<*> P.optional (P.xchild (P.name "notehead-text") (parseNoteheadText))
<*> P.optional (parseStaff)
<*> P.many (P.xchild (P.name "beam") (parseBeam))
<*> P.many (P.xchild (P.name "notations") (parseNotations))
<*> P.many (P.xchild (P.name "lyric") (parseLyric))
<*> P.optional (P.xchild (P.name "play") (parsePlay))
-- | Smart constructor for 'Note'
mkNote :: ChxNote -> EditorialVoice -> Note
mkNote t v = Note Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing t Nothing v Nothing [] Nothing Nothing Nothing Nothing Nothing Nothing [] [] [] Nothing
-- | @note-size@ /(complex)/
--
-- The note-size type indicates the percentage of the regular note size to use for notes with a cue and large size as defined in the type element. The grace type is used for notes of cue size that that include a grace element. The cue type is used for all other notes with cue size, whether defined explicitly or implicitly via a cue element. The large type is used for notes of large size. The text content represent the numeric percentage. A value of 100 would be identical to the size of a regular note as defined by the music font.
data NoteSize =
NoteSize {
noteSizeNonNegativeDecimal :: NonNegativeDecimal -- ^ text content
, noteSizeType :: NoteSizeType -- ^ /type/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml NoteSize where
emitXml (NoteSize a b) =
XContent (emitXml a)
([XAttr (QN "type" Nothing) (emitXml b)])
[]
parseNoteSize :: P.XParse NoteSize
parseNoteSize =
NoteSize
<$> (P.xtext >>= parseNonNegativeDecimal)
<*> (P.xattr (P.name "type") >>= parseNoteSizeType)
-- | Smart constructor for 'NoteSize'
mkNoteSize :: NonNegativeDecimal -> NoteSizeType -> NoteSize
mkNoteSize a b = NoteSize a b
-- | @note-type@ /(complex)/
--
-- The note-type type indicates the graphic note type. Values range from 256th to long. The size attribute indicates full, cue, or large size, with full the default for regular notes and cue the default for cue and grace notes.
data NoteType =
NoteType {
noteTypeNoteTypeValue :: NoteTypeValue -- ^ text content
, noteTypeSize :: (Maybe SymbolSize) -- ^ /size/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml NoteType where
emitXml (NoteType a b) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "size" Nothing).emitXml) b])
[]
parseNoteType :: P.XParse NoteType
parseNoteType =
NoteType
<$> (P.xtext >>= parseNoteTypeValue)
<*> P.optional (P.xattr (P.name "size") >>= parseSymbolSize)
-- | Smart constructor for 'NoteType'
mkNoteType :: NoteTypeValue -> NoteType
mkNoteType a = NoteType a Nothing
-- | @notehead@ /(complex)/
--
-- The notehead element indicates shapes other than the open and closed ovals associated with note durations.
--
-- For the enclosed shapes, the default is to be hollow for half notes and longer, and filled otherwise. The filled attribute can be set to change this if needed.
--
-- If the parentheses attribute is set to yes, the notehead is parenthesized. It is no by default.
data Notehead =
Notehead {
noteheadNoteheadValue :: NoteheadValue -- ^ text content
, noteheadFilled :: (Maybe YesNo) -- ^ /filled/ attribute
, noteheadParentheses :: (Maybe YesNo) -- ^ /parentheses/ attribute
, noteheadFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, noteheadFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, noteheadFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, noteheadFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, noteheadColor :: (Maybe Color) -- ^ /color/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Notehead where
emitXml (Notehead a b c d e f g h) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "filled" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "parentheses" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) h])
[]
parseNotehead :: P.XParse Notehead
parseNotehead =
Notehead
<$> (P.xtext >>= parseNoteheadValue)
<*> P.optional (P.xattr (P.name "filled") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "parentheses") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
-- | Smart constructor for 'Notehead'
mkNotehead :: NoteheadValue -> Notehead
mkNotehead a = Notehead a Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @notehead-text@ /(complex)/
--
-- The notehead-text type represents text that is displayed inside a notehead, as is done in some educational music. It is not needed for the numbers used in tablature or jianpu notation. The presence of a TAB or jianpu clefs is sufficient to indicate that numbers are used. The display-text and accidental-text elements allow display of fully formatted text and accidentals.
data NoteheadText =
NoteheadText {
noteheadTextNoteheadText :: [ChxNoteheadText]
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml NoteheadText where
emitXml (NoteheadText a) =
XReps [emitXml a]
parseNoteheadText :: P.XParse NoteheadText
parseNoteheadText =
NoteheadText
<$> P.many (parseChxNoteheadText)
-- | Smart constructor for 'NoteheadText'
mkNoteheadText :: NoteheadText
mkNoteheadText = NoteheadText []
-- | @octave-shift@ /(complex)/
--
-- The octave shift type indicates where notes are shifted up or down from their true pitched values because of printing difficulty. Thus a treble clef line noted with 8va will be indicated with an octave-shift down from the pitch data indicated in the notes. A size of 8 indicates one octave; a size of 15 indicates two octaves.
data OctaveShift =
OctaveShift {
octaveShiftType :: UpDownStopContinue -- ^ /type/ attribute
, octaveShiftNumber :: (Maybe NumberLevel) -- ^ /number/ attribute
, octaveShiftSize :: (Maybe PositiveInteger) -- ^ /size/ attribute
, octaveShiftDashLength :: (Maybe Tenths) -- ^ /dash-length/ attribute
, octaveShiftSpaceLength :: (Maybe Tenths) -- ^ /space-length/ attribute
, octaveShiftDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, octaveShiftDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, octaveShiftRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, octaveShiftRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, octaveShiftFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, octaveShiftFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, octaveShiftFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, octaveShiftFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, octaveShiftColor :: (Maybe Color) -- ^ /color/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml OctaveShift where
emitXml (OctaveShift a b c d e f g h i j k l m n) =
XContent XEmpty
([XAttr (QN "type" Nothing) (emitXml a)] ++
[maybe XEmpty (XAttr (QN "number" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "size" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "dash-length" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "space-length" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) l] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) m] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) n])
[]
parseOctaveShift :: P.XParse OctaveShift
parseOctaveShift =
OctaveShift
<$> (P.xattr (P.name "type") >>= parseUpDownStopContinue)
<*> P.optional (P.xattr (P.name "number") >>= parseNumberLevel)
<*> P.optional (P.xattr (P.name "size") >>= parsePositiveInteger)
<*> P.optional (P.xattr (P.name "dash-length") >>= parseTenths)
<*> P.optional (P.xattr (P.name "space-length") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
-- | Smart constructor for 'OctaveShift'
mkOctaveShift :: UpDownStopContinue -> OctaveShift
mkOctaveShift a = OctaveShift a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @offset@ /(complex)/
--
-- An offset is represented in terms of divisions, and indicates where the direction will appear relative to the current musical location. This affects the visual appearance of the direction. If the sound attribute is "yes", then the offset affects playback too. If the sound attribute is "no", then any sound associated with the direction takes effect at the current location. The sound attribute is "no" by default for compatibility with earlier versions of the MusicXML format. If an element within a direction includes a default-x attribute, the offset value will be ignored when determining the appearance of that element.
data Offset =
Offset {
offsetDivisions :: Divisions -- ^ text content
, offsetSound :: (Maybe YesNo) -- ^ /sound/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Offset where
emitXml (Offset a b) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "sound" Nothing).emitXml) b])
[]
parseOffset :: P.XParse Offset
parseOffset =
Offset
<$> (P.xtext >>= parseDivisions)
<*> P.optional (P.xattr (P.name "sound") >>= parseYesNo)
-- | Smart constructor for 'Offset'
mkOffset :: Divisions -> Offset
mkOffset a = Offset a Nothing
-- | @opus@ /(complex)/
--
-- The opus type represents a link to a MusicXML opus document that composes multiple MusicXML scores into a collection.
data Opus =
Opus {
opusHref :: String -- ^ /xlink:href/ attribute
, opusType :: (Maybe Type) -- ^ /xlink:type/ attribute
, opusRole :: (Maybe Token) -- ^ /xlink:role/ attribute
, opusTitle :: (Maybe Token) -- ^ /xlink:title/ attribute
, opusShow :: (Maybe SmpShow) -- ^ /xlink:show/ attribute
, opusActuate :: (Maybe Actuate) -- ^ /xlink:actuate/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Opus where
emitXml (Opus a b c d e f) =
XContent XEmpty
([XAttr (QN "href" (Just "xlink")) (emitXml a)] ++
[maybe XEmpty (XAttr (QN "type" (Just "xlink")).emitXml) b] ++
[maybe XEmpty (XAttr (QN "role" (Just "xlink")).emitXml) c] ++
[maybe XEmpty (XAttr (QN "title" (Just "xlink")).emitXml) d] ++
[maybe XEmpty (XAttr (QN "show" (Just "xlink")).emitXml) e] ++
[maybe XEmpty (XAttr (QN "actuate" (Just "xlink")).emitXml) f])
[]
parseOpus :: P.XParse Opus
parseOpus =
Opus
<$> (P.xattr (P.name "xlink:href") >>= return)
<*> P.optional (P.xattr (P.name "xlink:type") >>= parseType)
<*> P.optional (P.xattr (P.name "xlink:role") >>= parseToken)
<*> P.optional (P.xattr (P.name "xlink:title") >>= parseToken)
<*> P.optional (P.xattr (P.name "xlink:show") >>= parseSmpShow)
<*> P.optional (P.xattr (P.name "xlink:actuate") >>= parseActuate)
-- | Smart constructor for 'Opus'
mkOpus :: String -> Opus
mkOpus a = Opus a Nothing Nothing Nothing Nothing Nothing
-- | @ornaments@ /(complex)/
--
-- Ornaments can be any of several types, followed optionally by accidentals. The accidental-mark element's content is represented the same as an accidental element, but with a different name to reflect the different musical meaning.
data Ornaments =
Ornaments {
ornamentsOrnaments :: [SeqOrnaments]
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Ornaments where
emitXml (Ornaments a) =
XReps [emitXml a]
parseOrnaments :: P.XParse Ornaments
parseOrnaments =
Ornaments
<$> P.many (parseSeqOrnaments)
-- | Smart constructor for 'Ornaments'
mkOrnaments :: Ornaments
mkOrnaments = Ornaments []
-- | @other-appearance@ /(complex)/
--
-- The other-appearance type is used to define any graphical settings not yet in the current version of the MusicXML format. This allows extended representation, though without application interoperability.
data OtherAppearance =
OtherAppearance {
otherAppearanceString :: String -- ^ text content
, otherAppearanceType :: Token -- ^ /type/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml OtherAppearance where
emitXml (OtherAppearance a b) =
XContent (emitXml a)
([XAttr (QN "type" Nothing) (emitXml b)])
[]
parseOtherAppearance :: P.XParse OtherAppearance
parseOtherAppearance =
OtherAppearance
<$> (P.xtext >>= return)
<*> (P.xattr (P.name "type") >>= parseToken)
-- | Smart constructor for 'OtherAppearance'
mkOtherAppearance :: String -> Token -> OtherAppearance
mkOtherAppearance a b = OtherAppearance a b
-- | @other-direction@ /(complex)/
--
-- The other-direction type is used to define any direction symbols not yet in the current version of the MusicXML format. This allows extended representation, though without application interoperability.
data OtherDirection =
OtherDirection {
otherDirectionString :: String -- ^ text content
, otherDirectionPrintObject :: (Maybe YesNo) -- ^ /print-object/ attribute
, otherDirectionDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, otherDirectionDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, otherDirectionRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, otherDirectionRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, otherDirectionFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, otherDirectionFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, otherDirectionFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, otherDirectionFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, otherDirectionColor :: (Maybe Color) -- ^ /color/ attribute
, otherDirectionHalign :: (Maybe LeftCenterRight) -- ^ /halign/ attribute
, otherDirectionValign :: (Maybe Valign) -- ^ /valign/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml OtherDirection where
emitXml (OtherDirection a b c d e f g h i j k l m) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "print-object" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "halign" Nothing).emitXml) l] ++
[maybe XEmpty (XAttr (QN "valign" Nothing).emitXml) m])
[]
parseOtherDirection :: P.XParse OtherDirection
parseOtherDirection =
OtherDirection
<$> (P.xtext >>= return)
<*> P.optional (P.xattr (P.name "print-object") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "halign") >>= parseLeftCenterRight)
<*> P.optional (P.xattr (P.name "valign") >>= parseValign)
-- | Smart constructor for 'OtherDirection'
mkOtherDirection :: String -> OtherDirection
mkOtherDirection a = OtherDirection a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @other-notation@ /(complex)/
--
-- The other-notation type is used to define any notations not yet in the MusicXML format. This allows extended representation, though without application interoperability. It handles notations where more specific extension elements such as other-dynamics and other-technical are not appropriate.
data OtherNotation =
OtherNotation {
otherNotationString :: String -- ^ text content
, otherNotationType :: StartStopSingle -- ^ /type/ attribute
, otherNotationNumber :: (Maybe NumberLevel) -- ^ /number/ attribute
, otherNotationPrintObject :: (Maybe YesNo) -- ^ /print-object/ attribute
, otherNotationDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, otherNotationDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, otherNotationRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, otherNotationRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, otherNotationFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, otherNotationFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, otherNotationFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, otherNotationFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, otherNotationColor :: (Maybe Color) -- ^ /color/ attribute
, otherNotationPlacement :: (Maybe AboveBelow) -- ^ /placement/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml OtherNotation where
emitXml (OtherNotation a b c d e f g h i j k l m n) =
XContent (emitXml a)
([XAttr (QN "type" Nothing) (emitXml b)] ++
[maybe XEmpty (XAttr (QN "number" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "print-object" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) l] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) m] ++
[maybe XEmpty (XAttr (QN "placement" Nothing).emitXml) n])
[]
parseOtherNotation :: P.XParse OtherNotation
parseOtherNotation =
OtherNotation
<$> (P.xtext >>= return)
<*> (P.xattr (P.name "type") >>= parseStartStopSingle)
<*> P.optional (P.xattr (P.name "number") >>= parseNumberLevel)
<*> P.optional (P.xattr (P.name "print-object") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "placement") >>= parseAboveBelow)
-- | Smart constructor for 'OtherNotation'
mkOtherNotation :: String -> StartStopSingle -> OtherNotation
mkOtherNotation a b = OtherNotation a b Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @other-play@ /(complex)/
--
-- The other-play element represents other types of playback. The required type attribute indicates the type of playback to which the element content applies.
data OtherPlay =
OtherPlay {
otherPlayString :: String -- ^ text content
, otherPlayType :: Token -- ^ /type/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml OtherPlay where
emitXml (OtherPlay a b) =
XContent (emitXml a)
([XAttr (QN "type" Nothing) (emitXml b)])
[]
parseOtherPlay :: P.XParse OtherPlay
parseOtherPlay =
OtherPlay
<$> (P.xtext >>= return)
<*> (P.xattr (P.name "type") >>= parseToken)
-- | Smart constructor for 'OtherPlay'
mkOtherPlay :: String -> Token -> OtherPlay
mkOtherPlay a b = OtherPlay a b
-- | @page-layout@ /(complex)/
--
-- Page layout can be defined both in score-wide defaults and in the print element. Page margins are specified either for both even and odd pages, or via separate odd and even page number values. The type is not needed when used as part of a print element. If omitted when used in the defaults element, "both" is the default.
data PageLayout =
PageLayout {
pageLayoutPageLayout :: (Maybe SeqPageLayout)
, pageLayoutPageMargins :: [PageMargins] -- ^ /page-margins/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml PageLayout where
emitXml (PageLayout a b) =
XContent XEmpty
[]
([emitXml a] ++
map (XElement (QN "page-margins" Nothing).emitXml) b)
parsePageLayout :: P.XParse PageLayout
parsePageLayout =
PageLayout
<$> P.optional (parseSeqPageLayout)
<*> P.many (P.xchild (P.name "page-margins") (parsePageMargins))
-- | Smart constructor for 'PageLayout'
mkPageLayout :: PageLayout
mkPageLayout = PageLayout Nothing []
-- | @page-margins@ /(complex)/
--
-- Page margins are specified either for both even and odd pages, or via separate odd and even page number values. The type attribute is not needed when used as part of a print element. If omitted when the page-margins type is used in the defaults element, "both" is the default value.
data PageMargins =
PageMargins {
pageMarginsType :: (Maybe MarginType) -- ^ /type/ attribute
, pageMarginsAllMargins :: AllMargins
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml PageMargins where
emitXml (PageMargins a b) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "type" Nothing).emitXml) a])
([emitXml b])
parsePageMargins :: P.XParse PageMargins
parsePageMargins =
PageMargins
<$> P.optional (P.xattr (P.name "type") >>= parseMarginType)
<*> parseAllMargins
-- | Smart constructor for 'PageMargins'
mkPageMargins :: AllMargins -> PageMargins
mkPageMargins b = PageMargins Nothing b
-- | @part@ /(complex)/
data CmpPart =
CmpPart {
partId :: IDREF -- ^ /id/ attribute
, partMeasure :: [Measure] -- ^ /measure/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml CmpPart where
emitXml (CmpPart a b) =
XContent XEmpty
([XAttr (QN "id" Nothing) (emitXml a)])
(map (XElement (QN "measure" Nothing).emitXml) b)
parseCmpPart :: P.XParse CmpPart
parseCmpPart =
CmpPart
<$> (P.xattr (P.name "id") >>= parseIDREF)
<*> P.many (P.xchild (P.name "measure") (parseMeasure))
-- | Smart constructor for 'CmpPart'
mkCmpPart :: IDREF -> CmpPart
mkCmpPart a = CmpPart a []
-- | @part@ /(complex)/
-- mangled: 1
data Part =
Part {
cmppartId :: IDREF -- ^ /id/ attribute
, partMusicData :: MusicData
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Part where
emitXml (Part a b) =
XContent XEmpty
([XAttr (QN "id" Nothing) (emitXml a)])
([emitXml b])
parsePart :: P.XParse Part
parsePart =
Part
<$> (P.xattr (P.name "id") >>= parseIDREF)
<*> parseMusicData
-- | Smart constructor for 'Part'
mkPart :: IDREF -> MusicData -> Part
mkPart a b = Part a b
-- | @part-group@ /(complex)/
--
-- The part-group element indicates groupings of parts in the score, usually indicated by braces and brackets. Braces that are used for multi-staff parts should be defined in the attributes element for that part. The part-group start element appears before the first score-part in the group. The part-group stop element appears after the last score-part in the group.
--
-- The number attribute is used to distinguish overlapping and nested part-groups, not the sequence of groups. As with parts, groups can have a name and abbreviation. Values for the child elements are ignored at the stop of a group.
--
-- A part-group element is not needed for a single multi-staff part. By default, multi-staff parts include a brace symbol and (if appropriate given the bar-style) common barlines. The symbol formatting for a multi-staff part can be more fully specified using the part-symbol element.
data PartGroup =
PartGroup {
partGroupType :: StartStop -- ^ /type/ attribute
, partGroupNumber :: (Maybe Token) -- ^ /number/ attribute
, partGroupGroupName :: (Maybe GroupName) -- ^ /group-name/ child element
, partGroupGroupNameDisplay :: (Maybe NameDisplay) -- ^ /group-name-display/ child element
, partGroupGroupAbbreviation :: (Maybe GroupName) -- ^ /group-abbreviation/ child element
, partGroupGroupAbbreviationDisplay :: (Maybe NameDisplay) -- ^ /group-abbreviation-display/ child element
, partGroupGroupSymbol :: (Maybe GroupSymbol) -- ^ /group-symbol/ child element
, partGroupGroupBarline :: (Maybe GroupBarline) -- ^ /group-barline/ child element
, partGroupGroupTime :: (Maybe Empty) -- ^ /group-time/ child element
, partGroupEditorial :: Editorial
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml PartGroup where
emitXml (PartGroup a b c d e f g h i j) =
XContent XEmpty
([XAttr (QN "type" Nothing) (emitXml a)] ++
[maybe XEmpty (XAttr (QN "number" Nothing).emitXml) b])
([maybe XEmpty (XElement (QN "group-name" Nothing).emitXml) c] ++
[maybe XEmpty (XElement (QN "group-name-display" Nothing).emitXml) d] ++
[maybe XEmpty (XElement (QN "group-abbreviation" Nothing).emitXml) e] ++
[maybe XEmpty (XElement (QN "group-abbreviation-display" Nothing).emitXml) f] ++
[maybe XEmpty (XElement (QN "group-symbol" Nothing).emitXml) g] ++
[maybe XEmpty (XElement (QN "group-barline" Nothing).emitXml) h] ++
[maybe XEmpty (XElement (QN "group-time" Nothing).emitXml) i] ++
[emitXml j])
parsePartGroup :: P.XParse PartGroup
parsePartGroup =
PartGroup
<$> (P.xattr (P.name "type") >>= parseStartStop)
<*> P.optional (P.xattr (P.name "number") >>= parseToken)
<*> P.optional (P.xchild (P.name "group-name") (parseGroupName))
<*> P.optional (P.xchild (P.name "group-name-display") (parseNameDisplay))
<*> P.optional (P.xchild (P.name "group-abbreviation") (parseGroupName))
<*> P.optional (P.xchild (P.name "group-abbreviation-display") (parseNameDisplay))
<*> P.optional (P.xchild (P.name "group-symbol") (parseGroupSymbol))
<*> P.optional (P.xchild (P.name "group-barline") (parseGroupBarline))
<*> P.optional (P.xchild (P.name "group-time") (parseEmpty))
<*> parseEditorial
-- | Smart constructor for 'PartGroup'
mkPartGroup :: StartStop -> Editorial -> PartGroup
mkPartGroup a j = PartGroup a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing j
-- | @part-list@ /(complex)/
--
-- The part-list identifies the different musical parts in this movement. Each part has an ID that is used later within the musical data. Since parts may be encoded separately and combined later, identification elements are present at both the score and score-part levels. There must be at least one score-part, combined as desired with part-group elements that indicate braces and brackets. Parts are ordered from top to bottom in a score based on the order in which they appear in the part-list.
data PartList =
PartList {
partListPartGroup :: [GrpPartGroup]
, partListScorePart :: ScorePart
, partListPartList :: [ChxPartList]
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml PartList where
emitXml (PartList a b c) =
XReps [emitXml a,emitXml b,emitXml c]
parsePartList :: P.XParse PartList
parsePartList =
PartList
<$> P.many (parseGrpPartGroup)
<*> parseScorePart
<*> P.many (parseChxPartList)
-- | Smart constructor for 'PartList'
mkPartList :: ScorePart -> PartList
mkPartList b = PartList [] b []
-- | @part-name@ /(complex)/
--
-- The part-name type describes the name or abbreviation of a score-part element. Formatting attributes for the part-name element are deprecated in Version 2.0 in favor of the new part-name-display and part-abbreviation-display elements.
data PartName =
PartName {
partNameString :: String -- ^ text content
, partNameDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, partNameDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, partNameRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, partNameRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, partNameFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, partNameFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, partNameFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, partNameFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, partNameColor :: (Maybe Color) -- ^ /color/ attribute
, partNamePrintObject :: (Maybe YesNo) -- ^ /print-object/ attribute
, partNameJustify :: (Maybe LeftCenterRight) -- ^ /justify/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml PartName where
emitXml (PartName a b c d e f g h i j k l) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "print-object" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "justify" Nothing).emitXml) l])
[]
parsePartName :: P.XParse PartName
parsePartName =
PartName
<$> (P.xtext >>= return)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "print-object") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "justify") >>= parseLeftCenterRight)
-- | Smart constructor for 'PartName'
mkPartName :: String -> PartName
mkPartName a = PartName a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @part-symbol@ /(complex)/
--
-- The part-symbol type indicates how a symbol for a multi-staff part is indicated in the score; brace is the default value. The top-staff and bottom-staff elements are used when the brace does not extend across the entire part. For example, in a 3-staff organ part, the top-staff will typically be 1 for the right hand, while the bottom-staff will typically be 2 for the left hand. Staff 3 for the pedals is usually outside the brace.
data PartSymbol =
PartSymbol {
partSymbolGroupSymbolValue :: GroupSymbolValue -- ^ text content
, partSymbolTopStaff :: (Maybe StaffNumber) -- ^ /top-staff/ attribute
, partSymbolBottomStaff :: (Maybe StaffNumber) -- ^ /bottom-staff/ attribute
, partSymbolDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, partSymbolDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, partSymbolRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, partSymbolRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, partSymbolColor :: (Maybe Color) -- ^ /color/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml PartSymbol where
emitXml (PartSymbol a b c d e f g h) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "top-staff" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "bottom-staff" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) h])
[]
parsePartSymbol :: P.XParse PartSymbol
parsePartSymbol =
PartSymbol
<$> (P.xtext >>= parseGroupSymbolValue)
<*> P.optional (P.xattr (P.name "top-staff") >>= parseStaffNumber)
<*> P.optional (P.xattr (P.name "bottom-staff") >>= parseStaffNumber)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
-- | Smart constructor for 'PartSymbol'
mkPartSymbol :: GroupSymbolValue -> PartSymbol
mkPartSymbol a = PartSymbol a Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @pedal@ /(complex)/
--
-- The pedal type represents piano pedal marks. The line attribute is yes if pedal lines are used. The sign attribute is yes if Ped and * signs are used. For MusicXML 2.0 compatibility, the sign attribute is yes by default if the line attribute is no, and is no by default if the line attribute is yes. The change and continue types are used when the line attribute is yes. The change type indicates a pedal lift and retake indicated with an inverted V marking. The continue type allows more precise formatting across system breaks and for more complex pedaling lines. The alignment attributes are ignored if the line attribute is yes.
data Pedal =
Pedal {
pedalType :: StartStopChangeContinue -- ^ /type/ attribute
, pedalLine :: (Maybe YesNo) -- ^ /line/ attribute
, pedalSign :: (Maybe YesNo) -- ^ /sign/ attribute
, pedalDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, pedalDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, pedalRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, pedalRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, pedalFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, pedalFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, pedalFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, pedalFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, pedalColor :: (Maybe Color) -- ^ /color/ attribute
, pedalHalign :: (Maybe LeftCenterRight) -- ^ /halign/ attribute
, pedalValign :: (Maybe Valign) -- ^ /valign/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Pedal where
emitXml (Pedal a b c d e f g h i j k l m n) =
XContent XEmpty
([XAttr (QN "type" Nothing) (emitXml a)] ++
[maybe XEmpty (XAttr (QN "line" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "sign" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) l] ++
[maybe XEmpty (XAttr (QN "halign" Nothing).emitXml) m] ++
[maybe XEmpty (XAttr (QN "valign" Nothing).emitXml) n])
[]
parsePedal :: P.XParse Pedal
parsePedal =
Pedal
<$> (P.xattr (P.name "type") >>= parseStartStopChangeContinue)
<*> P.optional (P.xattr (P.name "line") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "sign") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "halign") >>= parseLeftCenterRight)
<*> P.optional (P.xattr (P.name "valign") >>= parseValign)
-- | Smart constructor for 'Pedal'
mkPedal :: StartStopChangeContinue -> Pedal
mkPedal a = Pedal a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @pedal-tuning@ /(complex)/
--
-- The pedal-tuning type specifies the tuning of a single harp pedal.
data PedalTuning =
PedalTuning {
pedalTuningPedalStep :: Step -- ^ /pedal-step/ child element
, pedalTuningPedalAlter :: Semitones -- ^ /pedal-alter/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml PedalTuning where
emitXml (PedalTuning a b) =
XContent XEmpty
[]
([XElement (QN "pedal-step" Nothing) (emitXml a)] ++
[XElement (QN "pedal-alter" Nothing) (emitXml b)])
parsePedalTuning :: P.XParse PedalTuning
parsePedalTuning =
PedalTuning
<$> (P.xchild (P.name "pedal-step") (P.xtext >>= parseStep))
<*> (P.xchild (P.name "pedal-alter") (P.xtext >>= parseSemitones))
-- | Smart constructor for 'PedalTuning'
mkPedalTuning :: Step -> Semitones -> PedalTuning
mkPedalTuning a b = PedalTuning a b
-- | @per-minute@ /(complex)/
--
-- The per-minute type can be a number, or a text description including numbers. If a font is specified, it overrides the font specified for the overall metronome element. This allows separate specification of a music font for the beat-unit and a text font for the numeric value, in cases where a single metronome font is not used.
data PerMinute =
PerMinute {
perMinuteString :: String -- ^ text content
, perMinuteFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, perMinuteFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, perMinuteFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, perMinuteFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml PerMinute where
emitXml (PerMinute a b c d e) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) e])
[]
parsePerMinute :: P.XParse PerMinute
parsePerMinute =
PerMinute
<$> (P.xtext >>= return)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
-- | Smart constructor for 'PerMinute'
mkPerMinute :: String -> PerMinute
mkPerMinute a = PerMinute a Nothing Nothing Nothing Nothing
-- | @percussion@ /(complex)/
--
-- The percussion element is used to define percussion pictogram symbols. Definitions for these symbols can be found in Kurt Stone's "Music Notation in the Twentieth Century" on pages 206-212 and 223. Some values are added to these based on how usage has evolved in the 30 years since Stone's book was published.
data Percussion =
Percussion {
percussionDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, percussionDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, percussionRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, percussionRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, percussionFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, percussionFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, percussionFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, percussionFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, percussionColor :: (Maybe Color) -- ^ /color/ attribute
, percussionHalign :: (Maybe LeftCenterRight) -- ^ /halign/ attribute
, percussionValign :: (Maybe Valign) -- ^ /valign/ attribute
, percussionEnclosure :: (Maybe EnclosureShape) -- ^ /enclosure/ attribute
, percussionPercussion :: ChxPercussion
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Percussion where
emitXml (Percussion a b c d e f g h i j k l m) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "halign" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "valign" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "enclosure" Nothing).emitXml) l])
([emitXml m])
parsePercussion :: P.XParse Percussion
parsePercussion =
Percussion
<$> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "halign") >>= parseLeftCenterRight)
<*> P.optional (P.xattr (P.name "valign") >>= parseValign)
<*> P.optional (P.xattr (P.name "enclosure") >>= parseEnclosureShape)
<*> parseChxPercussion
-- | Smart constructor for 'Percussion'
mkPercussion :: ChxPercussion -> Percussion
mkPercussion m = Percussion Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing m
-- | @pitch@ /(complex)/
--
-- Pitch is represented as a combination of the step of the diatonic scale, the chromatic alteration, and the octave.
data Pitch =
Pitch {
pitchStep :: Step -- ^ /step/ child element
, pitchAlter :: (Maybe Semitones) -- ^ /alter/ child element
, pitchOctave :: Octave -- ^ /octave/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Pitch where
emitXml (Pitch a b c) =
XContent XEmpty
[]
([XElement (QN "step" Nothing) (emitXml a)] ++
[maybe XEmpty (XElement (QN "alter" Nothing).emitXml) b] ++
[XElement (QN "octave" Nothing) (emitXml c)])
parsePitch :: P.XParse Pitch
parsePitch =
Pitch
<$> (P.xchild (P.name "step") (P.xtext >>= parseStep))
<*> P.optional (P.xchild (P.name "alter") (P.xtext >>= parseSemitones))
<*> (P.xchild (P.name "octave") (P.xtext >>= parseOctave))
-- | Smart constructor for 'Pitch'
mkPitch :: Step -> Octave -> Pitch
mkPitch a c = Pitch a Nothing c
-- | @placement-text@ /(complex)/
--
-- The placement-text type represents a text element with print-style and placement attribute groups.
data PlacementText =
PlacementText {
placementTextString :: String -- ^ text content
, placementTextDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, placementTextDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, placementTextRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, placementTextRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, placementTextFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, placementTextFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, placementTextFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, placementTextFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, placementTextColor :: (Maybe Color) -- ^ /color/ attribute
, placementTextPlacement :: (Maybe AboveBelow) -- ^ /placement/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml PlacementText where
emitXml (PlacementText a b c d e f g h i j k) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "placement" Nothing).emitXml) k])
[]
parsePlacementText :: P.XParse PlacementText
parsePlacementText =
PlacementText
<$> (P.xtext >>= return)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "placement") >>= parseAboveBelow)
-- | Smart constructor for 'PlacementText'
mkPlacementText :: String -> PlacementText
mkPlacementText a = PlacementText a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @play@ /(complex)/
--
-- The play type, new in Version 3.0, specifies playback techniques to be used in conjunction with the instrument-sound element. When used as part of a sound element, it applies to all notes going forward in score order. In multi-instrument parts, the affected instrument should be specified using the id attribute. When used as part of a note element, it applies to the current note only.
data Play =
Play {
playId :: (Maybe IDREF) -- ^ /id/ attribute
, playPlay :: [ChxPlay]
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Play where
emitXml (Play a b) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "id" Nothing).emitXml) a])
([emitXml b])
parsePlay :: P.XParse Play
parsePlay =
Play
<$> P.optional (P.xattr (P.name "id") >>= parseIDREF)
<*> P.many (parseChxPlay)
-- | Smart constructor for 'Play'
mkPlay :: Play
mkPlay = Play Nothing []
-- | @principal-voice@ /(complex)/
--
-- The principal-voice element represents principal and secondary voices in a score, either for analysis or for square bracket symbols that appear in a score. The symbol attribute indicates the type of symbol used at the start of the principal-voice. The content of the principal-voice element is used for analysis and may be any text value. When used for analysis separate from any printed score markings, the symbol attribute should be set to "none".
data PrincipalVoice =
PrincipalVoice {
principalVoiceString :: String -- ^ text content
, principalVoiceType :: StartStop -- ^ /type/ attribute
, principalVoiceSymbol :: PrincipalVoiceSymbol -- ^ /symbol/ attribute
, principalVoiceDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, principalVoiceDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, principalVoiceRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, principalVoiceRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, principalVoiceFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, principalVoiceFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, principalVoiceFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, principalVoiceFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, principalVoiceColor :: (Maybe Color) -- ^ /color/ attribute
, principalVoiceHalign :: (Maybe LeftCenterRight) -- ^ /halign/ attribute
, principalVoiceValign :: (Maybe Valign) -- ^ /valign/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml PrincipalVoice where
emitXml (PrincipalVoice a b c d e f g h i j k l m n) =
XContent (emitXml a)
([XAttr (QN "type" Nothing) (emitXml b)] ++
[XAttr (QN "symbol" Nothing) (emitXml c)] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) l] ++
[maybe XEmpty (XAttr (QN "halign" Nothing).emitXml) m] ++
[maybe XEmpty (XAttr (QN "valign" Nothing).emitXml) n])
[]
parsePrincipalVoice :: P.XParse PrincipalVoice
parsePrincipalVoice =
PrincipalVoice
<$> (P.xtext >>= return)
<*> (P.xattr (P.name "type") >>= parseStartStop)
<*> (P.xattr (P.name "symbol") >>= parsePrincipalVoiceSymbol)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "halign") >>= parseLeftCenterRight)
<*> P.optional (P.xattr (P.name "valign") >>= parseValign)
-- | Smart constructor for 'PrincipalVoice'
mkPrincipalVoice :: String -> StartStop -> PrincipalVoiceSymbol -> PrincipalVoice
mkPrincipalVoice a b c = PrincipalVoice a b c Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @print@ /(complex)/
--
-- The print type contains general printing parameters, including the layout elements defined in the layout.mod file. The part-name-display and part-abbreviation-display elements used in the score.mod file may also be used here to change how a part name or abbreviation is displayed over the course of a piece. They take effect when the current measure or a succeeding measure starts a new system.
--
-- Layout elements in a print statement only apply to the current page, system, staff, or measure. Music that follows continues to take the default values from the layout included in the defaults element.
data Print =
Print {
printStaffSpacing :: (Maybe Tenths) -- ^ /staff-spacing/ attribute
, printNewSystem :: (Maybe YesNo) -- ^ /new-system/ attribute
, printNewPage :: (Maybe YesNo) -- ^ /new-page/ attribute
, printBlankPage :: (Maybe PositiveInteger) -- ^ /blank-page/ attribute
, printPageNumber :: (Maybe Token) -- ^ /page-number/ attribute
, printLayout :: Layout
, printMeasureLayout :: (Maybe MeasureLayout) -- ^ /measure-layout/ child element
, printMeasureNumbering :: (Maybe MeasureNumbering) -- ^ /measure-numbering/ child element
, printPartNameDisplay :: (Maybe NameDisplay) -- ^ /part-name-display/ child element
, printPartAbbreviationDisplay :: (Maybe NameDisplay) -- ^ /part-abbreviation-display/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Print where
emitXml (Print a b c d e f g h i j) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "staff-spacing" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "new-system" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "new-page" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "blank-page" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "page-number" Nothing).emitXml) e])
([emitXml f] ++
[maybe XEmpty (XElement (QN "measure-layout" Nothing).emitXml) g] ++
[maybe XEmpty (XElement (QN "measure-numbering" Nothing).emitXml) h] ++
[maybe XEmpty (XElement (QN "part-name-display" Nothing).emitXml) i] ++
[maybe XEmpty (XElement (QN "part-abbreviation-display" Nothing).emitXml) j])
parsePrint :: P.XParse Print
parsePrint =
Print
<$> P.optional (P.xattr (P.name "staff-spacing") >>= parseTenths)
<*> P.optional (P.xattr (P.name "new-system") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "new-page") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "blank-page") >>= parsePositiveInteger)
<*> P.optional (P.xattr (P.name "page-number") >>= parseToken)
<*> parseLayout
<*> P.optional (P.xchild (P.name "measure-layout") (parseMeasureLayout))
<*> P.optional (P.xchild (P.name "measure-numbering") (parseMeasureNumbering))
<*> P.optional (P.xchild (P.name "part-name-display") (parseNameDisplay))
<*> P.optional (P.xchild (P.name "part-abbreviation-display") (parseNameDisplay))
-- | Smart constructor for 'Print'
mkPrint :: Layout -> Print
mkPrint f = Print Nothing Nothing Nothing Nothing Nothing f Nothing Nothing Nothing Nothing
-- | @repeat@ /(complex)/
--
-- The repeat type represents repeat marks. The start of the repeat has a forward direction while the end of the repeat has a backward direction. Backward repeats that are not part of an ending can use the times attribute to indicate the number of times the repeated section is played.
data Repeat =
Repeat {
repeatDirection :: BackwardForward -- ^ /direction/ attribute
, repeatTimes :: (Maybe NonNegativeInteger) -- ^ /times/ attribute
, repeatWinged :: (Maybe Winged) -- ^ /winged/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Repeat where
emitXml (Repeat a b c) =
XContent XEmpty
([XAttr (QN "direction" Nothing) (emitXml a)] ++
[maybe XEmpty (XAttr (QN "times" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "winged" Nothing).emitXml) c])
[]
parseRepeat :: P.XParse Repeat
parseRepeat =
Repeat
<$> (P.xattr (P.name "direction") >>= parseBackwardForward)
<*> P.optional (P.xattr (P.name "times") >>= parseNonNegativeInteger)
<*> P.optional (P.xattr (P.name "winged") >>= parseWinged)
-- | Smart constructor for 'Repeat'
mkRepeat :: BackwardForward -> Repeat
mkRepeat a = Repeat a Nothing Nothing
-- | @rest@ /(complex)/
--
-- The rest element indicates notated rests or silences. Rest elements are usually empty, but placement on the staff can be specified using display-step and display-octave elements. If the measure attribute is set to yes, this indicates this is a complete measure rest.
data Rest =
Rest {
restMeasure :: (Maybe YesNo) -- ^ /measure/ attribute
, restDisplayStepOctave :: (Maybe DisplayStepOctave)
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Rest where
emitXml (Rest a b) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "measure" Nothing).emitXml) a])
([emitXml b])
parseRest :: P.XParse Rest
parseRest =
Rest
<$> P.optional (P.xattr (P.name "measure") >>= parseYesNo)
<*> P.optional (parseDisplayStepOctave)
-- | Smart constructor for 'Rest'
mkRest :: Rest
mkRest = Rest Nothing Nothing
-- | @root@ /(complex)/
--
-- The root type indicates a pitch like C, D, E vs. a function indication like I, II, III. It is used with chord symbols in popular music. The root element has a root-step and optional root-alter element similar to the step and alter elements, but renamed to distinguish the different musical meanings.
data Root =
Root {
rootRootStep :: RootStep -- ^ /root-step/ child element
, rootRootAlter :: (Maybe RootAlter) -- ^ /root-alter/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Root where
emitXml (Root a b) =
XContent XEmpty
[]
([XElement (QN "root-step" Nothing) (emitXml a)] ++
[maybe XEmpty (XElement (QN "root-alter" Nothing).emitXml) b])
parseRoot :: P.XParse Root
parseRoot =
Root
<$> (P.xchild (P.name "root-step") (parseRootStep))
<*> P.optional (P.xchild (P.name "root-alter") (parseRootAlter))
-- | Smart constructor for 'Root'
mkRoot :: RootStep -> Root
mkRoot a = Root a Nothing
-- | @root-alter@ /(complex)/
--
-- The root-alter type represents the chromatic alteration of the root of the current chord within the harmony element. In some chord styles, the text for the root-step element may include root-alter information. In that case, the print-object attribute of the root-alter element can be set to no. The location attribute indicates whether the alteration should appear to the left or the right of the root-step; it is right by default.
data RootAlter =
RootAlter {
rootAlterSemitones :: Semitones -- ^ text content
, rootAlterLocation :: (Maybe LeftRight) -- ^ /location/ attribute
, rootAlterPrintObject :: (Maybe YesNo) -- ^ /print-object/ attribute
, rootAlterDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, rootAlterDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, rootAlterRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, rootAlterRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, rootAlterFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, rootAlterFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, rootAlterFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, rootAlterFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, rootAlterColor :: (Maybe Color) -- ^ /color/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml RootAlter where
emitXml (RootAlter a b c d e f g h i j k l) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "location" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "print-object" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) l])
[]
parseRootAlter :: P.XParse RootAlter
parseRootAlter =
RootAlter
<$> (P.xtext >>= parseSemitones)
<*> P.optional (P.xattr (P.name "location") >>= parseLeftRight)
<*> P.optional (P.xattr (P.name "print-object") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
-- | Smart constructor for 'RootAlter'
mkRootAlter :: Semitones -> RootAlter
mkRootAlter a = RootAlter a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @root-step@ /(complex)/
--
-- The root-step type represents the pitch step of the root of the current chord within the harmony element. The text attribute indicates how the root should appear in a score if not using the element contents.
data RootStep =
RootStep {
rootStepStep :: Step -- ^ text content
, rootStepText :: (Maybe Token) -- ^ /text/ attribute
, rootStepDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, rootStepDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, rootStepRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, rootStepRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, rootStepFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, rootStepFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, rootStepFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, rootStepFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, rootStepColor :: (Maybe Color) -- ^ /color/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml RootStep where
emitXml (RootStep a b c d e f g h i j k) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "text" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) k])
[]
parseRootStep :: P.XParse RootStep
parseRootStep =
RootStep
<$> (P.xtext >>= parseStep)
<*> P.optional (P.xattr (P.name "text") >>= parseToken)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
-- | Smart constructor for 'RootStep'
mkRootStep :: Step -> RootStep
mkRootStep a = RootStep a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @scaling@ /(complex)/
--
-- Margins, page sizes, and distances are all measured in tenths to keep MusicXML data in a consistent coordinate system as much as possible. The translation to absolute units is done with the scaling type, which specifies how many millimeters are equal to how many tenths. For a staff height of 7 mm, millimeters would be set to 7 while tenths is set to 40. The ability to set a formula rather than a single scaling factor helps avoid roundoff errors.
data Scaling =
Scaling {
scalingMillimeters :: Millimeters -- ^ /millimeters/ child element
, scalingTenths :: Tenths -- ^ /tenths/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Scaling where
emitXml (Scaling a b) =
XContent XEmpty
[]
([XElement (QN "millimeters" Nothing) (emitXml a)] ++
[XElement (QN "tenths" Nothing) (emitXml b)])
parseScaling :: P.XParse Scaling
parseScaling =
Scaling
<$> (P.xchild (P.name "millimeters") (P.xtext >>= parseMillimeters))
<*> (P.xchild (P.name "tenths") (P.xtext >>= parseTenths))
-- | Smart constructor for 'Scaling'
mkScaling :: Millimeters -> Tenths -> Scaling
mkScaling a b = Scaling a b
-- | @scordatura@ /(complex)/
--
-- Scordatura string tunings are represented by a series of accord elements, similar to the staff-tuning elements. Strings are numbered from high to low.
data Scordatura =
Scordatura {
scordaturaAccord :: [Accord] -- ^ /accord/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Scordatura where
emitXml (Scordatura a) =
XContent XEmpty
[]
(map (XElement (QN "accord" Nothing).emitXml) a)
parseScordatura :: P.XParse Scordatura
parseScordatura =
Scordatura
<$> P.many (P.xchild (P.name "accord") (parseAccord))
-- | Smart constructor for 'Scordatura'
mkScordatura :: Scordatura
mkScordatura = Scordatura []
-- | @score-instrument@ /(complex)/
--
-- The score-instrument type represents a single instrument within a score-part. As with the score-part type, each score-instrument has a required ID attribute, a name, and an optional abbreviation.
--
-- A score-instrument type is also required if the score specifies MIDI 1.0 channels, banks, or programs. An initial midi-instrument assignment can also be made here. MusicXML software should be able to automatically assign reasonable channels and instruments without these elements in simple cases, such as where part names match General MIDI instrument names.
data ScoreInstrument =
ScoreInstrument {
scoreInstrumentId :: ID -- ^ /id/ attribute
, scoreInstrumentInstrumentName :: String -- ^ /instrument-name/ child element
, scoreInstrumentInstrumentAbbreviation :: (Maybe String) -- ^ /instrument-abbreviation/ child element
, scoreInstrumentInstrumentSound :: (Maybe String) -- ^ /instrument-sound/ child element
, scoreInstrumentScoreInstrument :: (Maybe ChxScoreInstrument)
, scoreInstrumentVirtualInstrument :: (Maybe VirtualInstrument) -- ^ /virtual-instrument/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml ScoreInstrument where
emitXml (ScoreInstrument a b c d e f) =
XContent XEmpty
([XAttr (QN "id" Nothing) (emitXml a)])
([XElement (QN "instrument-name" Nothing) (emitXml b)] ++
[maybe XEmpty (XElement (QN "instrument-abbreviation" Nothing).emitXml) c] ++
[maybe XEmpty (XElement (QN "instrument-sound" Nothing).emitXml) d] ++
[emitXml e] ++
[maybe XEmpty (XElement (QN "virtual-instrument" Nothing).emitXml) f])
parseScoreInstrument :: P.XParse ScoreInstrument
parseScoreInstrument =
ScoreInstrument
<$> (P.xattr (P.name "id") >>= parseID)
<*> (P.xchild (P.name "instrument-name") (P.xtext >>= return))
<*> P.optional (P.xchild (P.name "instrument-abbreviation") (P.xtext >>= return))
<*> P.optional (P.xchild (P.name "instrument-sound") (P.xtext >>= return))
<*> P.optional (parseChxScoreInstrument)
<*> P.optional (P.xchild (P.name "virtual-instrument") (parseVirtualInstrument))
-- | Smart constructor for 'ScoreInstrument'
mkScoreInstrument :: ID -> String -> ScoreInstrument
mkScoreInstrument a b = ScoreInstrument a b Nothing Nothing Nothing Nothing
-- | @score-part@ /(complex)/
--
-- Each MusicXML part corresponds to a track in a Standard MIDI Format 1 file. The score-instrument elements are used when there are multiple instruments per track. The midi-device element is used to make a MIDI device or port assignment for the given track or specific MIDI instruments. Initial midi-instrument assignments may be made here as well.
data CmpScorePart =
CmpScorePart {
scorePartId :: ID -- ^ /id/ attribute
, scorePartIdentification :: (Maybe Identification) -- ^ /identification/ child element
, scorePartPartName :: PartName -- ^ /part-name/ child element
, scorePartPartNameDisplay :: (Maybe NameDisplay) -- ^ /part-name-display/ child element
, scorePartPartAbbreviation :: (Maybe PartName) -- ^ /part-abbreviation/ child element
, scorePartPartAbbreviationDisplay :: (Maybe NameDisplay) -- ^ /part-abbreviation-display/ child element
, scorePartGroup :: [String] -- ^ /group/ child element
, scorePartScoreInstrument :: [ScoreInstrument] -- ^ /score-instrument/ child element
, scorePartScorePart :: [SeqScorePart]
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml CmpScorePart where
emitXml (CmpScorePart a b c d e f g h i) =
XContent XEmpty
([XAttr (QN "id" Nothing) (emitXml a)])
([maybe XEmpty (XElement (QN "identification" Nothing).emitXml) b] ++
[XElement (QN "part-name" Nothing) (emitXml c)] ++
[maybe XEmpty (XElement (QN "part-name-display" Nothing).emitXml) d] ++
[maybe XEmpty (XElement (QN "part-abbreviation" Nothing).emitXml) e] ++
[maybe XEmpty (XElement (QN "part-abbreviation-display" Nothing).emitXml) f] ++
map (XElement (QN "group" Nothing).emitXml) g ++
map (XElement (QN "score-instrument" Nothing).emitXml) h ++
[emitXml i])
parseCmpScorePart :: P.XParse CmpScorePart
parseCmpScorePart =
CmpScorePart
<$> (P.xattr (P.name "id") >>= parseID)
<*> P.optional (P.xchild (P.name "identification") (parseIdentification))
<*> (P.xchild (P.name "part-name") (parsePartName))
<*> P.optional (P.xchild (P.name "part-name-display") (parseNameDisplay))
<*> P.optional (P.xchild (P.name "part-abbreviation") (parsePartName))
<*> P.optional (P.xchild (P.name "part-abbreviation-display") (parseNameDisplay))
<*> P.many (P.xchild (P.name "group") (P.xtext >>= return))
<*> P.many (P.xchild (P.name "score-instrument") (parseScoreInstrument))
<*> P.many (parseSeqScorePart)
-- | Smart constructor for 'CmpScorePart'
mkCmpScorePart :: ID -> PartName -> CmpScorePart
mkCmpScorePart a c = CmpScorePart a Nothing c Nothing Nothing Nothing [] [] []
-- | @score-partwise@ /(complex)/
data ScorePartwise =
ScorePartwise {
scorePartwiseVersion :: (Maybe Token) -- ^ /version/ attribute
, scorePartwiseScoreHeader :: ScoreHeader
, scorePartwisePart :: [CmpPart] -- ^ /part/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml ScorePartwise where
emitXml (ScorePartwise a b c) =
XElement (QN "score-partwise" Nothing) $ XContent XEmpty
([maybe XEmpty (XAttr (QN "version" Nothing).emitXml) a])
([emitXml b] ++
map (XElement (QN "part" Nothing).emitXml) c)
parseScorePartwise :: P.XParse ScorePartwise
parseScorePartwise =
ScorePartwise
<$> P.optional (P.xattr (P.name "version") >>= parseToken)
<*> parseScoreHeader
<*> P.many (P.xchild (P.name "part") (parseCmpPart))
-- | Smart constructor for 'ScorePartwise'
mkScorePartwise :: ScoreHeader -> ScorePartwise
mkScorePartwise b = ScorePartwise Nothing b []
-- | @score-timewise@ /(complex)/
data ScoreTimewise =
ScoreTimewise {
scoreTimewiseVersion :: (Maybe Token) -- ^ /version/ attribute
, scoreTimewiseScoreHeader :: ScoreHeader
, scoreTimewiseMeasure :: [CmpMeasure] -- ^ /measure/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml ScoreTimewise where
emitXml (ScoreTimewise a b c) =
XElement (QN "score-timewise" Nothing) $ XContent XEmpty
([maybe XEmpty (XAttr (QN "version" Nothing).emitXml) a])
([emitXml b] ++
map (XElement (QN "measure" Nothing).emitXml) c)
parseScoreTimewise :: P.XParse ScoreTimewise
parseScoreTimewise =
ScoreTimewise
<$> P.optional (P.xattr (P.name "version") >>= parseToken)
<*> parseScoreHeader
<*> P.many (P.xchild (P.name "measure") (parseCmpMeasure))
-- | Smart constructor for 'ScoreTimewise'
mkScoreTimewise :: ScoreHeader -> ScoreTimewise
mkScoreTimewise b = ScoreTimewise Nothing b []
-- | @slash@ /(complex)/
--
-- The slash type is used to indicate that slash notation is to be used. If the slash is on every beat, use-stems is no (the default). To indicate rhythms but not pitches, use-stems is set to yes. The type attribute indicates whether this is the start or stop of a slash notation style. The use-dots attribute works as for the beat-repeat element, and only has effect if use-stems is no.
data CmpSlash =
CmpSlash {
slashType :: StartStop -- ^ /type/ attribute
, slashUseDots :: (Maybe YesNo) -- ^ /use-dots/ attribute
, slashUseStems :: (Maybe YesNo) -- ^ /use-stems/ attribute
, slashSlash :: (Maybe Slash)
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml CmpSlash where
emitXml (CmpSlash a b c d) =
XContent XEmpty
([XAttr (QN "type" Nothing) (emitXml a)] ++
[maybe XEmpty (XAttr (QN "use-dots" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "use-stems" Nothing).emitXml) c])
([emitXml d])
parseCmpSlash :: P.XParse CmpSlash
parseCmpSlash =
CmpSlash
<$> (P.xattr (P.name "type") >>= parseStartStop)
<*> P.optional (P.xattr (P.name "use-dots") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "use-stems") >>= parseYesNo)
<*> P.optional (parseSlash)
-- | Smart constructor for 'CmpSlash'
mkCmpSlash :: StartStop -> CmpSlash
mkCmpSlash a = CmpSlash a Nothing Nothing Nothing
-- | @slide@ /(complex)/
--
-- Glissando and slide types both indicate rapidly moving from one pitch to the other so that individual notes are not discerned. The distinction is similar to that between NIFF's glissando and portamento elements. A slide is continuous between two notes and defaults to a solid line. The optional text for a is printed alongside the line.
data Slide =
Slide {
slideString :: String -- ^ text content
, slideType :: StartStop -- ^ /type/ attribute
, slideNumber :: (Maybe NumberLevel) -- ^ /number/ attribute
, slideLineType :: (Maybe LineType) -- ^ /line-type/ attribute
, slideDashLength :: (Maybe Tenths) -- ^ /dash-length/ attribute
, slideSpaceLength :: (Maybe Tenths) -- ^ /space-length/ attribute
, slideDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, slideDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, slideRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, slideRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, slideFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, slideFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, slideFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, slideFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, slideColor :: (Maybe Color) -- ^ /color/ attribute
, slideAccelerate :: (Maybe YesNo) -- ^ /accelerate/ attribute
, slideBeats :: (Maybe TrillBeats) -- ^ /beats/ attribute
, slideFirstBeat :: (Maybe Percent) -- ^ /first-beat/ attribute
, slideLastBeat :: (Maybe Percent) -- ^ /last-beat/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Slide where
emitXml (Slide a b c d e f g h i j k l m n o p q r s) =
XContent (emitXml a)
([XAttr (QN "type" Nothing) (emitXml b)] ++
[maybe XEmpty (XAttr (QN "number" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "line-type" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "dash-length" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "space-length" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) l] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) m] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) n] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) o] ++
[maybe XEmpty (XAttr (QN "accelerate" Nothing).emitXml) p] ++
[maybe XEmpty (XAttr (QN "beats" Nothing).emitXml) q] ++
[maybe XEmpty (XAttr (QN "first-beat" Nothing).emitXml) r] ++
[maybe XEmpty (XAttr (QN "last-beat" Nothing).emitXml) s])
[]
parseSlide :: P.XParse Slide
parseSlide =
Slide
<$> (P.xtext >>= return)
<*> (P.xattr (P.name "type") >>= parseStartStop)
<*> P.optional (P.xattr (P.name "number") >>= parseNumberLevel)
<*> P.optional (P.xattr (P.name "line-type") >>= parseLineType)
<*> P.optional (P.xattr (P.name "dash-length") >>= parseTenths)
<*> P.optional (P.xattr (P.name "space-length") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "accelerate") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "beats") >>= parseTrillBeats)
<*> P.optional (P.xattr (P.name "first-beat") >>= parsePercent)
<*> P.optional (P.xattr (P.name "last-beat") >>= parsePercent)
-- | Smart constructor for 'Slide'
mkSlide :: String -> StartStop -> Slide
mkSlide a b = Slide a b Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @slur@ /(complex)/
--
-- Slur types are empty. Most slurs are represented with two elements: one with a start type, and one with a stop type. Slurs can add more elements using a continue type. This is typically used to specify the formatting of cross-system slurs, or to specify the shape of very complex slurs.
data Slur =
Slur {
slurType :: StartStopContinue -- ^ /type/ attribute
, slurNumber :: (Maybe NumberLevel) -- ^ /number/ attribute
, slurLineType :: (Maybe LineType) -- ^ /line-type/ attribute
, slurDashLength :: (Maybe Tenths) -- ^ /dash-length/ attribute
, slurSpaceLength :: (Maybe Tenths) -- ^ /space-length/ attribute
, slurDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, slurDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, slurRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, slurRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, slurPlacement :: (Maybe AboveBelow) -- ^ /placement/ attribute
, slurOrientation :: (Maybe OverUnder) -- ^ /orientation/ attribute
, slurBezierOffset :: (Maybe Divisions) -- ^ /bezier-offset/ attribute
, slurBezierOffset2 :: (Maybe Divisions) -- ^ /bezier-offset2/ attribute
, slurBezierX :: (Maybe Tenths) -- ^ /bezier-x/ attribute
, slurBezierY :: (Maybe Tenths) -- ^ /bezier-y/ attribute
, slurBezierX2 :: (Maybe Tenths) -- ^ /bezier-x2/ attribute
, slurBezierY2 :: (Maybe Tenths) -- ^ /bezier-y2/ attribute
, slurColor :: (Maybe Color) -- ^ /color/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Slur where
emitXml (Slur a b c d e f g h i j k l m n o p q r) =
XContent XEmpty
([XAttr (QN "type" Nothing) (emitXml a)] ++
[maybe XEmpty (XAttr (QN "number" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "line-type" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "dash-length" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "space-length" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "placement" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "orientation" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "bezier-offset" Nothing).emitXml) l] ++
[maybe XEmpty (XAttr (QN "bezier-offset2" Nothing).emitXml) m] ++
[maybe XEmpty (XAttr (QN "bezier-x" Nothing).emitXml) n] ++
[maybe XEmpty (XAttr (QN "bezier-y" Nothing).emitXml) o] ++
[maybe XEmpty (XAttr (QN "bezier-x2" Nothing).emitXml) p] ++
[maybe XEmpty (XAttr (QN "bezier-y2" Nothing).emitXml) q] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) r])
[]
parseSlur :: P.XParse Slur
parseSlur =
Slur
<$> (P.xattr (P.name "type") >>= parseStartStopContinue)
<*> P.optional (P.xattr (P.name "number") >>= parseNumberLevel)
<*> P.optional (P.xattr (P.name "line-type") >>= parseLineType)
<*> P.optional (P.xattr (P.name "dash-length") >>= parseTenths)
<*> P.optional (P.xattr (P.name "space-length") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "placement") >>= parseAboveBelow)
<*> P.optional (P.xattr (P.name "orientation") >>= parseOverUnder)
<*> P.optional (P.xattr (P.name "bezier-offset") >>= parseDivisions)
<*> P.optional (P.xattr (P.name "bezier-offset2") >>= parseDivisions)
<*> P.optional (P.xattr (P.name "bezier-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "bezier-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "bezier-x2") >>= parseTenths)
<*> P.optional (P.xattr (P.name "bezier-y2") >>= parseTenths)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
-- | Smart constructor for 'Slur'
mkSlur :: StartStopContinue -> Slur
mkSlur a = Slur a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @sound@ /(complex)/
--
-- The sound element contains general playback parameters. They can stand alone within a part/measure, or be a component element within a direction.
--
-- @
--
-- Tempo is expressed in quarter notes per minute. If 0, the sound-generating program should prompt the user at the time of compiling a sound (MIDI) file.
--
-- Dynamics (or MIDI velocity) are expressed as a percentage of the default forte value (90 for MIDI 1.0).
--
-- Dacapo indicates to go back to the beginning of the movement. When used it always has the value "yes".
--
-- Segno and dalsegno are used for backwards jumps to a segno sign; coda and tocoda are used for forward jumps to a coda sign. If there are multiple jumps, the value of these parameters can be used to name and distinguish them. If segno or coda is used, the divisions attribute can also be used to indicate the number of divisions per quarter note. Otherwise sound and MIDI generating programs may have to recompute this.
--
-- By default, a dalsegno or dacapo attribute indicates that the jump should occur the first time through, while a tocoda attribute indicates the jump should occur the second time through. The time that jumps occur can be changed by using the time-only attribute.
--
-- Forward-repeat is used when a forward repeat sign is implied, and usually follows a bar line. When used it always has the value of "yes".
--
-- The fine attribute follows the final note or rest in a movement with a da capo or dal segno direction. If numeric, the value represents the actual duration of the final note or rest, which can be ambiguous in written notation and different among parts and voices. The value may also be "yes" to indicate no change to the final duration.
--
-- If the sound element applies only particular times through a repeat, the time-only attribute indicates which times to apply the sound element.
--
-- Pizzicato in a sound element effects all following notes. Yes indicates pizzicato, no indicates arco.
--
-- The pan and elevation attributes are deprecated in Version 2.0. The pan and elevation elements in the midi-instrument element should be used instead. The meaning of the pan and elevation attributes is the same as for the pan and elevation elements. If both are present, the mid-instrument elements take priority.
--
-- The damper-pedal, soft-pedal, and sostenuto-pedal attributes effect playback of the three common piano pedals and their MIDI controller equivalents. The yes value indicates the pedal is depressed; no indicates the pedal is released. A numeric value from 0 to 100 may also be used for half pedaling. This value is the percentage that the pedal is depressed. A value of 0 is equivalent to no, and a value of 100 is equivalent to yes.
--
-- MIDI devices, MIDI instruments, and playback techniques are changed using the midi-device, midi-instrument, and play elements. When there are multiple instances of these elements, they should be grouped together by instrument using the id attribute values.
--
-- The offset element is used to indicate that the sound takes place offset from the current score position. If the sound element is a child of a direction element, the sound offset element overrides the direction offset element if both elements are present. Note that the offset reflects the intended musical position for the change in sound. It should not be used to compensate for latency issues in particular hardware configurations.
-- @
data Sound =
Sound {
soundTempo :: (Maybe NonNegativeDecimal) -- ^ /tempo/ attribute
, soundDynamics :: (Maybe NonNegativeDecimal) -- ^ /dynamics/ attribute
, soundDacapo :: (Maybe YesNo) -- ^ /dacapo/ attribute
, soundSegno :: (Maybe Token) -- ^ /segno/ attribute
, soundDalsegno :: (Maybe Token) -- ^ /dalsegno/ attribute
, soundCoda :: (Maybe Token) -- ^ /coda/ attribute
, soundTocoda :: (Maybe Token) -- ^ /tocoda/ attribute
, soundDivisions :: (Maybe Divisions) -- ^ /divisions/ attribute
, soundForwardRepeat :: (Maybe YesNo) -- ^ /forward-repeat/ attribute
, soundFine :: (Maybe Token) -- ^ /fine/ attribute
, soundTimeOnly :: (Maybe TimeOnly) -- ^ /time-only/ attribute
, soundPizzicato :: (Maybe YesNo) -- ^ /pizzicato/ attribute
, soundPan :: (Maybe RotationDegrees) -- ^ /pan/ attribute
, soundElevation :: (Maybe RotationDegrees) -- ^ /elevation/ attribute
, soundDamperPedal :: (Maybe YesNoNumber) -- ^ /damper-pedal/ attribute
, soundSoftPedal :: (Maybe YesNoNumber) -- ^ /soft-pedal/ attribute
, soundSostenutoPedal :: (Maybe YesNoNumber) -- ^ /sostenuto-pedal/ attribute
, soundSound :: [SeqSound]
, soundOffset :: (Maybe Offset) -- ^ /offset/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Sound where
emitXml (Sound a b c d e f g h i j k l m n o p q r s) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "tempo" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "dynamics" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "dacapo" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "segno" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "dalsegno" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "coda" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "tocoda" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "divisions" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "forward-repeat" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "fine" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "time-only" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "pizzicato" Nothing).emitXml) l] ++
[maybe XEmpty (XAttr (QN "pan" Nothing).emitXml) m] ++
[maybe XEmpty (XAttr (QN "elevation" Nothing).emitXml) n] ++
[maybe XEmpty (XAttr (QN "damper-pedal" Nothing).emitXml) o] ++
[maybe XEmpty (XAttr (QN "soft-pedal" Nothing).emitXml) p] ++
[maybe XEmpty (XAttr (QN "sostenuto-pedal" Nothing).emitXml) q])
([emitXml r] ++
[maybe XEmpty (XElement (QN "offset" Nothing).emitXml) s])
parseSound :: P.XParse Sound
parseSound =
Sound
<$> P.optional (P.xattr (P.name "tempo") >>= parseNonNegativeDecimal)
<*> P.optional (P.xattr (P.name "dynamics") >>= parseNonNegativeDecimal)
<*> P.optional (P.xattr (P.name "dacapo") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "segno") >>= parseToken)
<*> P.optional (P.xattr (P.name "dalsegno") >>= parseToken)
<*> P.optional (P.xattr (P.name "coda") >>= parseToken)
<*> P.optional (P.xattr (P.name "tocoda") >>= parseToken)
<*> P.optional (P.xattr (P.name "divisions") >>= parseDivisions)
<*> P.optional (P.xattr (P.name "forward-repeat") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "fine") >>= parseToken)
<*> P.optional (P.xattr (P.name "time-only") >>= parseTimeOnly)
<*> P.optional (P.xattr (P.name "pizzicato") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "pan") >>= parseRotationDegrees)
<*> P.optional (P.xattr (P.name "elevation") >>= parseRotationDegrees)
<*> P.optional (P.xattr (P.name "damper-pedal") >>= parseYesNoNumber)
<*> P.optional (P.xattr (P.name "soft-pedal") >>= parseYesNoNumber)
<*> P.optional (P.xattr (P.name "sostenuto-pedal") >>= parseYesNoNumber)
<*> P.many (parseSeqSound)
<*> P.optional (P.xchild (P.name "offset") (parseOffset))
-- | Smart constructor for 'Sound'
mkSound :: Sound
mkSound = Sound Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing [] Nothing
-- | @staff-details@ /(complex)/
--
-- The staff-details element is used to indicate different types of staves. The optional number attribute specifies the staff number from top to bottom on the system, as with clef. The print-object attribute is used to indicate when a staff is not printed in a part, usually in large scores where empty parts are omitted. It is yes by default. If print-spacing is yes while print-object is no, the score is printed in cutaway format where vertical space is left for the empty part.
data StaffDetails =
StaffDetails {
staffDetailsNumber :: (Maybe StaffNumber) -- ^ /number/ attribute
, staffDetailsShowFrets :: (Maybe ShowFrets) -- ^ /show-frets/ attribute
, staffDetailsPrintObject :: (Maybe YesNo) -- ^ /print-object/ attribute
, staffDetailsPrintSpacing :: (Maybe YesNo) -- ^ /print-spacing/ attribute
, staffDetailsStaffType :: (Maybe StaffType) -- ^ /staff-type/ child element
, staffDetailsStaffLines :: (Maybe NonNegativeInteger) -- ^ /staff-lines/ child element
, staffDetailsStaffTuning :: [StaffTuning] -- ^ /staff-tuning/ child element
, staffDetailsCapo :: (Maybe NonNegativeInteger) -- ^ /capo/ child element
, staffDetailsStaffSize :: (Maybe NonNegativeDecimal) -- ^ /staff-size/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml StaffDetails where
emitXml (StaffDetails a b c d e f g h i) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "number" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "show-frets" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "print-object" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "print-spacing" Nothing).emitXml) d])
([maybe XEmpty (XElement (QN "staff-type" Nothing).emitXml) e] ++
[maybe XEmpty (XElement (QN "staff-lines" Nothing).emitXml) f] ++
map (XElement (QN "staff-tuning" Nothing).emitXml) g ++
[maybe XEmpty (XElement (QN "capo" Nothing).emitXml) h] ++
[maybe XEmpty (XElement (QN "staff-size" Nothing).emitXml) i])
parseStaffDetails :: P.XParse StaffDetails
parseStaffDetails =
StaffDetails
<$> P.optional (P.xattr (P.name "number") >>= parseStaffNumber)
<*> P.optional (P.xattr (P.name "show-frets") >>= parseShowFrets)
<*> P.optional (P.xattr (P.name "print-object") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "print-spacing") >>= parseYesNo)
<*> P.optional (P.xchild (P.name "staff-type") (P.xtext >>= parseStaffType))
<*> P.optional (P.xchild (P.name "staff-lines") (P.xtext >>= parseNonNegativeInteger))
<*> P.many (P.xchild (P.name "staff-tuning") (parseStaffTuning))
<*> P.optional (P.xchild (P.name "capo") (P.xtext >>= parseNonNegativeInteger))
<*> P.optional (P.xchild (P.name "staff-size") (P.xtext >>= parseNonNegativeDecimal))
-- | Smart constructor for 'StaffDetails'
mkStaffDetails :: StaffDetails
mkStaffDetails = StaffDetails Nothing Nothing Nothing Nothing Nothing Nothing [] Nothing Nothing
-- | @staff-layout@ /(complex)/
--
-- Staff layout includes the vertical distance from the bottom line of the previous staff in this system to the top line of the staff specified by the number attribute. The optional number attribute refers to staff numbers within the part, from top to bottom on the system. A value of 1 is assumed if not present. When used in the defaults element, the values apply to all parts. This value is ignored for the first staff in a system.
data StaffLayout =
StaffLayout {
staffLayoutNumber :: (Maybe StaffNumber) -- ^ /number/ attribute
, staffLayoutStaffDistance :: (Maybe Tenths) -- ^ /staff-distance/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml StaffLayout where
emitXml (StaffLayout a b) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "number" Nothing).emitXml) a])
([maybe XEmpty (XElement (QN "staff-distance" Nothing).emitXml) b])
parseStaffLayout :: P.XParse StaffLayout
parseStaffLayout =
StaffLayout
<$> P.optional (P.xattr (P.name "number") >>= parseStaffNumber)
<*> P.optional (P.xchild (P.name "staff-distance") (P.xtext >>= parseTenths))
-- | Smart constructor for 'StaffLayout'
mkStaffLayout :: StaffLayout
mkStaffLayout = StaffLayout Nothing Nothing
-- | @staff-tuning@ /(complex)/
--
-- The staff-tuning type specifies the open, non-capo tuning of the lines on a tablature staff.
data StaffTuning =
StaffTuning {
staffTuningLine :: (Maybe StaffLine) -- ^ /line/ attribute
, staffTuningTuning :: Tuning
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml StaffTuning where
emitXml (StaffTuning a b) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "line" Nothing).emitXml) a])
([emitXml b])
parseStaffTuning :: P.XParse StaffTuning
parseStaffTuning =
StaffTuning
<$> P.optional (P.xattr (P.name "line") >>= parseStaffLine)
<*> parseTuning
-- | Smart constructor for 'StaffTuning'
mkStaffTuning :: Tuning -> StaffTuning
mkStaffTuning b = StaffTuning Nothing b
-- | @stem@ /(complex)/
--
-- Stems can be down, up, none, or double. For down and up stems, the position attributes can be used to specify stem length. The relative values specify the end of the stem relative to the program default. Default values specify an absolute end stem position. Negative values of relative-y that would flip a stem instead of shortening it are ignored. A stem element associated with a rest refers to a stemlet.
data Stem =
Stem {
stemStemValue :: StemValue -- ^ text content
, stemDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, stemDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, stemRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, stemRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, stemColor :: (Maybe Color) -- ^ /color/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Stem where
emitXml (Stem a b c d e f) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) f])
[]
parseStem :: P.XParse Stem
parseStem =
Stem
<$> (P.xtext >>= parseStemValue)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
-- | Smart constructor for 'Stem'
mkStem :: StemValue -> Stem
mkStem a = Stem a Nothing Nothing Nothing Nothing Nothing
-- | @stick@ /(complex)/
--
-- The stick type represents pictograms where the material of the stick, mallet, or beater is included.
data Stick =
Stick {
stickTip :: (Maybe TipDirection) -- ^ /tip/ attribute
, stickStickType :: StickType -- ^ /stick-type/ child element
, stickStickMaterial :: StickMaterial -- ^ /stick-material/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Stick where
emitXml (Stick a b c) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "tip" Nothing).emitXml) a])
([XElement (QN "stick-type" Nothing) (emitXml b)] ++
[XElement (QN "stick-material" Nothing) (emitXml c)])
parseStick :: P.XParse Stick
parseStick =
Stick
<$> P.optional (P.xattr (P.name "tip") >>= parseTipDirection)
<*> (P.xchild (P.name "stick-type") (P.xtext >>= parseStickType))
<*> (P.xchild (P.name "stick-material") (P.xtext >>= parseStickMaterial))
-- | Smart constructor for 'Stick'
mkStick :: StickType -> StickMaterial -> Stick
mkStick b c = Stick Nothing b c
-- | @string@ /(complex)/
--
-- The string type is used with tablature notation, regular notation (where it is often circled), and chord diagrams. String numbers start with 1 for the highest string.
data CmpString =
CmpString {
stringStringNumber :: StringNumber -- ^ text content
, stringDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, stringDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, stringRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, stringRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, stringFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, stringFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, stringFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, stringFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, stringColor :: (Maybe Color) -- ^ /color/ attribute
, stringPlacement :: (Maybe AboveBelow) -- ^ /placement/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml CmpString where
emitXml (CmpString a b c d e f g h i j k) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "placement" Nothing).emitXml) k])
[]
parseCmpString :: P.XParse CmpString
parseCmpString =
CmpString
<$> (P.xtext >>= parseStringNumber)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "placement") >>= parseAboveBelow)
-- | Smart constructor for 'CmpString'
mkCmpString :: StringNumber -> CmpString
mkCmpString a = CmpString a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @string-mute@ /(complex)/
--
-- The string-mute type represents string mute on and mute off symbols.
data StringMute =
StringMute {
stringMuteType :: OnOff -- ^ /type/ attribute
, stringMuteDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, stringMuteDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, stringMuteRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, stringMuteRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, stringMuteFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, stringMuteFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, stringMuteFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, stringMuteFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, stringMuteColor :: (Maybe Color) -- ^ /color/ attribute
, stringMuteHalign :: (Maybe LeftCenterRight) -- ^ /halign/ attribute
, stringMuteValign :: (Maybe Valign) -- ^ /valign/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml StringMute where
emitXml (StringMute a b c d e f g h i j k l) =
XContent XEmpty
([XAttr (QN "type" Nothing) (emitXml a)] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "halign" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "valign" Nothing).emitXml) l])
[]
parseStringMute :: P.XParse StringMute
parseStringMute =
StringMute
<$> (P.xattr (P.name "type") >>= parseOnOff)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "halign") >>= parseLeftCenterRight)
<*> P.optional (P.xattr (P.name "valign") >>= parseValign)
-- | Smart constructor for 'StringMute'
mkStringMute :: OnOff -> StringMute
mkStringMute a = StringMute a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @strong-accent@ /(complex)/
--
-- The strong-accent type indicates a vertical accent mark. The type attribute indicates if the point of the accent is down or up.
data StrongAccent =
StrongAccent {
strongAccentEmptyPlacement :: StrongAccent
, strongAccentType :: (Maybe UpDown) -- ^ /type/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml StrongAccent where
emitXml (StrongAccent a b) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "type" Nothing).emitXml) b])
([emitXml a])
parseStrongAccent :: P.XParse StrongAccent
parseStrongAccent =
StrongAccent
<$> parseStrongAccent
<*> P.optional (P.xattr (P.name "type") >>= parseUpDown)
-- | Smart constructor for 'StrongAccent'
mkStrongAccent :: StrongAccent -> StrongAccent
mkStrongAccent a = StrongAccent a Nothing
-- | @style-text@ /(complex)/
--
-- The style-text type represents a text element with a print-style attribute group.
data StyleText =
StyleText {
styleTextString :: String -- ^ text content
, styleTextDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, styleTextDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, styleTextRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, styleTextRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, styleTextFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, styleTextFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, styleTextFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, styleTextFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, styleTextColor :: (Maybe Color) -- ^ /color/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml StyleText where
emitXml (StyleText a b c d e f g h i j) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) j])
[]
parseStyleText :: P.XParse StyleText
parseStyleText =
StyleText
<$> (P.xtext >>= return)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
-- | Smart constructor for 'StyleText'
mkStyleText :: String -> StyleText
mkStyleText a = StyleText a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @supports@ /(complex)/
--
-- The supports type indicates if a MusicXML encoding supports a particular MusicXML element. This is recommended for elements like beam, stem, and accidental, where the absence of an element is ambiguous if you do not know if the encoding supports that element. For Version 2.0, the supports element is expanded to allow programs to indicate support for particular attributes or particular values. This lets applications communicate, for example, that all system and/or page breaks are contained in the MusicXML file.
data Supports =
Supports {
supportsType :: YesNo -- ^ /type/ attribute
, supportsElement :: NMTOKEN -- ^ /element/ attribute
, supportsAttribute :: (Maybe NMTOKEN) -- ^ /attribute/ attribute
, supportsValue :: (Maybe Token) -- ^ /value/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Supports where
emitXml (Supports a b c d) =
XContent XEmpty
([XAttr (QN "type" Nothing) (emitXml a)] ++
[XAttr (QN "element" Nothing) (emitXml b)] ++
[maybe XEmpty (XAttr (QN "attribute" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "value" Nothing).emitXml) d])
[]
parseSupports :: P.XParse Supports
parseSupports =
Supports
<$> (P.xattr (P.name "type") >>= parseYesNo)
<*> (P.xattr (P.name "element") >>= parseNMTOKEN)
<*> P.optional (P.xattr (P.name "attribute") >>= parseNMTOKEN)
<*> P.optional (P.xattr (P.name "value") >>= parseToken)
-- | Smart constructor for 'Supports'
mkSupports :: YesNo -> NMTOKEN -> Supports
mkSupports a b = Supports a b Nothing Nothing
-- | @system-dividers@ /(complex)/
--
-- The system-dividers element indicates the presence or absence of system dividers (also known as system separation marks) between systems displayed on the same page. Dividers on the left and right side of the page are controlled by the left-divider and right-divider elements respectively. The default vertical position is half the system-distance value from the top of the system that is below the divider. The default horizontal position is the left and right system margin, respectively.
--
-- When used in the print element, the system-dividers element affects the dividers that would appear between the current system and the previous system.
data SystemDividers =
SystemDividers {
systemDividersLeftDivider :: EmptyPrintObjectStyleAlign -- ^ /left-divider/ child element
, systemDividersRightDivider :: EmptyPrintObjectStyleAlign -- ^ /right-divider/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml SystemDividers where
emitXml (SystemDividers a b) =
XContent XEmpty
[]
([XElement (QN "left-divider" Nothing) (emitXml a)] ++
[XElement (QN "right-divider" Nothing) (emitXml b)])
parseSystemDividers :: P.XParse SystemDividers
parseSystemDividers =
SystemDividers
<$> (P.xchild (P.name "left-divider") (parseEmptyPrintObjectStyleAlign))
<*> (P.xchild (P.name "right-divider") (parseEmptyPrintObjectStyleAlign))
-- | Smart constructor for 'SystemDividers'
mkSystemDividers :: EmptyPrintObjectStyleAlign -> EmptyPrintObjectStyleAlign -> SystemDividers
mkSystemDividers a b = SystemDividers a b
-- | @system-layout@ /(complex)/
--
-- A system is a group of staves that are read and played simultaneously. System layout includes left and right margins and the vertical distance from the previous system. The system distance is measured from the bottom line of the previous system to the top line of the current system. It is ignored for the first system on a page. The top system distance is measured from the page's top margin to the top line of the first system. It is ignored for all but the first system on a page.
--
-- Sometimes the sum of measure widths in a system may not equal the system width specified by the layout elements due to roundoff or other errors. The behavior when reading MusicXML files in these cases is application-dependent. For instance, applications may find that the system layout data is more reliable than the sum of the measure widths, and adjust the measure widths accordingly.
data SystemLayout =
SystemLayout {
systemLayoutSystemMargins :: (Maybe SystemMargins) -- ^ /system-margins/ child element
, systemLayoutSystemDistance :: (Maybe Tenths) -- ^ /system-distance/ child element
, systemLayoutTopSystemDistance :: (Maybe Tenths) -- ^ /top-system-distance/ child element
, systemLayoutSystemDividers :: (Maybe SystemDividers) -- ^ /system-dividers/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml SystemLayout where
emitXml (SystemLayout a b c d) =
XContent XEmpty
[]
([maybe XEmpty (XElement (QN "system-margins" Nothing).emitXml) a] ++
[maybe XEmpty (XElement (QN "system-distance" Nothing).emitXml) b] ++
[maybe XEmpty (XElement (QN "top-system-distance" Nothing).emitXml) c] ++
[maybe XEmpty (XElement (QN "system-dividers" Nothing).emitXml) d])
parseSystemLayout :: P.XParse SystemLayout
parseSystemLayout =
SystemLayout
<$> P.optional (P.xchild (P.name "system-margins") (parseSystemMargins))
<*> P.optional (P.xchild (P.name "system-distance") (P.xtext >>= parseTenths))
<*> P.optional (P.xchild (P.name "top-system-distance") (P.xtext >>= parseTenths))
<*> P.optional (P.xchild (P.name "system-dividers") (parseSystemDividers))
-- | Smart constructor for 'SystemLayout'
mkSystemLayout :: SystemLayout
mkSystemLayout = SystemLayout Nothing Nothing Nothing Nothing
-- | @system-margins@ /(complex)/
--
-- System margins are relative to the page margins. Positive values indent and negative values reduce the margin size.
data SystemMargins =
SystemMargins {
systemMarginsLeftRightMargins :: LeftRightMargins
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml SystemMargins where
emitXml (SystemMargins a) =
XReps [emitXml a]
parseSystemMargins :: P.XParse SystemMargins
parseSystemMargins =
SystemMargins
<$> parseLeftRightMargins
-- | Smart constructor for 'SystemMargins'
mkSystemMargins :: LeftRightMargins -> SystemMargins
mkSystemMargins a = SystemMargins a
-- | @technical@ /(complex)/
--
-- Technical indications give performance information for individual instruments.
data Technical =
Technical {
technicalTechnical :: [ChxTechnical]
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Technical where
emitXml (Technical a) =
XReps [emitXml a]
parseTechnical :: P.XParse Technical
parseTechnical =
Technical
<$> P.many (parseChxTechnical)
-- | Smart constructor for 'Technical'
mkTechnical :: Technical
mkTechnical = Technical []
-- | @text-element-data@ /(complex)/
--
-- The text-element-data type represents a syllable or portion of a syllable for lyric text underlay. A hyphen in the string content should only be used for an actual hyphenated word. Language names for text elements come from ISO 639, with optional country subcodes from ISO 3166.
data TextElementData =
TextElementData {
textElementDataString :: String -- ^ text content
, textElementDataLang :: (Maybe Lang) -- ^ /xml:lang/ attribute
, textElementDataFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, textElementDataFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, textElementDataFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, textElementDataFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, textElementDataColor :: (Maybe Color) -- ^ /color/ attribute
, textElementDataUnderline :: (Maybe NumberOfLines) -- ^ /underline/ attribute
, textElementDataOverline :: (Maybe NumberOfLines) -- ^ /overline/ attribute
, textElementDataLineThrough :: (Maybe NumberOfLines) -- ^ /line-through/ attribute
, textElementDataRotation :: (Maybe RotationDegrees) -- ^ /rotation/ attribute
, textElementDataLetterSpacing :: (Maybe NumberOrNormal) -- ^ /letter-spacing/ attribute
, textElementDataDir :: (Maybe TextDirection) -- ^ /dir/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml TextElementData where
emitXml (TextElementData a b c d e f g h i j k l m) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "lang" (Just "xml")).emitXml) b] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "underline" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "overline" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "line-through" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "rotation" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "letter-spacing" Nothing).emitXml) l] ++
[maybe XEmpty (XAttr (QN "dir" Nothing).emitXml) m])
[]
parseTextElementData :: P.XParse TextElementData
parseTextElementData =
TextElementData
<$> (P.xtext >>= return)
<*> P.optional (P.xattr (P.name "xml:lang") >>= parseLang)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "underline") >>= parseNumberOfLines)
<*> P.optional (P.xattr (P.name "overline") >>= parseNumberOfLines)
<*> P.optional (P.xattr (P.name "line-through") >>= parseNumberOfLines)
<*> P.optional (P.xattr (P.name "rotation") >>= parseRotationDegrees)
<*> P.optional (P.xattr (P.name "letter-spacing") >>= parseNumberOrNormal)
<*> P.optional (P.xattr (P.name "dir") >>= parseTextDirection)
-- | Smart constructor for 'TextElementData'
mkTextElementData :: String -> TextElementData
mkTextElementData a = TextElementData a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @text-font-color@ /(complex)/
--
-- The text-font-color type represents text with optional font and color information. It is used for the elision element.
data TextFontColor =
TextFontColor {
textFontColorString :: String -- ^ text content
, textFontColorLang :: (Maybe Lang) -- ^ /xml:lang/ attribute
, textFontColorFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, textFontColorFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, textFontColorFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, textFontColorFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, textFontColorColor :: (Maybe Color) -- ^ /color/ attribute
, textFontColorUnderline :: (Maybe NumberOfLines) -- ^ /underline/ attribute
, textFontColorOverline :: (Maybe NumberOfLines) -- ^ /overline/ attribute
, textFontColorLineThrough :: (Maybe NumberOfLines) -- ^ /line-through/ attribute
, textFontColorRotation :: (Maybe RotationDegrees) -- ^ /rotation/ attribute
, textFontColorLetterSpacing :: (Maybe NumberOrNormal) -- ^ /letter-spacing/ attribute
, textFontColorDir :: (Maybe TextDirection) -- ^ /dir/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml TextFontColor where
emitXml (TextFontColor a b c d e f g h i j k l m) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "lang" (Just "xml")).emitXml) b] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "underline" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "overline" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "line-through" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "rotation" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "letter-spacing" Nothing).emitXml) l] ++
[maybe XEmpty (XAttr (QN "dir" Nothing).emitXml) m])
[]
parseTextFontColor :: P.XParse TextFontColor
parseTextFontColor =
TextFontColor
<$> (P.xtext >>= return)
<*> P.optional (P.xattr (P.name "xml:lang") >>= parseLang)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "underline") >>= parseNumberOfLines)
<*> P.optional (P.xattr (P.name "overline") >>= parseNumberOfLines)
<*> P.optional (P.xattr (P.name "line-through") >>= parseNumberOfLines)
<*> P.optional (P.xattr (P.name "rotation") >>= parseRotationDegrees)
<*> P.optional (P.xattr (P.name "letter-spacing") >>= parseNumberOrNormal)
<*> P.optional (P.xattr (P.name "dir") >>= parseTextDirection)
-- | Smart constructor for 'TextFontColor'
mkTextFontColor :: String -> TextFontColor
mkTextFontColor a = TextFontColor a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @tie@ /(complex)/
--
-- The tie element indicates that a tie begins or ends with this note. If the tie element applies only particular times through a repeat, the time-only attribute indicates which times to apply it. The tie element indicates sound; the tied element indicates notation.
data Tie =
Tie {
tieType :: StartStop -- ^ /type/ attribute
, tieTimeOnly :: (Maybe TimeOnly) -- ^ /time-only/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Tie where
emitXml (Tie a b) =
XContent XEmpty
([XAttr (QN "type" Nothing) (emitXml a)] ++
[maybe XEmpty (XAttr (QN "time-only" Nothing).emitXml) b])
[]
parseTie :: P.XParse Tie
parseTie =
Tie
<$> (P.xattr (P.name "type") >>= parseStartStop)
<*> P.optional (P.xattr (P.name "time-only") >>= parseTimeOnly)
-- | Smart constructor for 'Tie'
mkTie :: StartStop -> Tie
mkTie a = Tie a Nothing
-- | @tied@ /(complex)/
--
-- The tied type represents the notated tie. The tie element represents the tie sound.
--
-- The number attribute is rarely needed to disambiguate ties, since note pitches will usually suffice. The attribute is implied rather than defaulting to 1 as with most elements. It is available for use in more complex tied notation situations.
data Tied =
Tied {
tiedType :: StartStopContinue -- ^ /type/ attribute
, tiedNumber :: (Maybe NumberLevel) -- ^ /number/ attribute
, tiedLineType :: (Maybe LineType) -- ^ /line-type/ attribute
, tiedDashLength :: (Maybe Tenths) -- ^ /dash-length/ attribute
, tiedSpaceLength :: (Maybe Tenths) -- ^ /space-length/ attribute
, tiedDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, tiedDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, tiedRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, tiedRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, tiedPlacement :: (Maybe AboveBelow) -- ^ /placement/ attribute
, tiedOrientation :: (Maybe OverUnder) -- ^ /orientation/ attribute
, tiedBezierOffset :: (Maybe Divisions) -- ^ /bezier-offset/ attribute
, tiedBezierOffset2 :: (Maybe Divisions) -- ^ /bezier-offset2/ attribute
, tiedBezierX :: (Maybe Tenths) -- ^ /bezier-x/ attribute
, tiedBezierY :: (Maybe Tenths) -- ^ /bezier-y/ attribute
, tiedBezierX2 :: (Maybe Tenths) -- ^ /bezier-x2/ attribute
, tiedBezierY2 :: (Maybe Tenths) -- ^ /bezier-y2/ attribute
, tiedColor :: (Maybe Color) -- ^ /color/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Tied where
emitXml (Tied a b c d e f g h i j k l m n o p q r) =
XContent XEmpty
([XAttr (QN "type" Nothing) (emitXml a)] ++
[maybe XEmpty (XAttr (QN "number" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "line-type" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "dash-length" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "space-length" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "placement" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "orientation" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "bezier-offset" Nothing).emitXml) l] ++
[maybe XEmpty (XAttr (QN "bezier-offset2" Nothing).emitXml) m] ++
[maybe XEmpty (XAttr (QN "bezier-x" Nothing).emitXml) n] ++
[maybe XEmpty (XAttr (QN "bezier-y" Nothing).emitXml) o] ++
[maybe XEmpty (XAttr (QN "bezier-x2" Nothing).emitXml) p] ++
[maybe XEmpty (XAttr (QN "bezier-y2" Nothing).emitXml) q] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) r])
[]
parseTied :: P.XParse Tied
parseTied =
Tied
<$> (P.xattr (P.name "type") >>= parseStartStopContinue)
<*> P.optional (P.xattr (P.name "number") >>= parseNumberLevel)
<*> P.optional (P.xattr (P.name "line-type") >>= parseLineType)
<*> P.optional (P.xattr (P.name "dash-length") >>= parseTenths)
<*> P.optional (P.xattr (P.name "space-length") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "placement") >>= parseAboveBelow)
<*> P.optional (P.xattr (P.name "orientation") >>= parseOverUnder)
<*> P.optional (P.xattr (P.name "bezier-offset") >>= parseDivisions)
<*> P.optional (P.xattr (P.name "bezier-offset2") >>= parseDivisions)
<*> P.optional (P.xattr (P.name "bezier-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "bezier-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "bezier-x2") >>= parseTenths)
<*> P.optional (P.xattr (P.name "bezier-y2") >>= parseTenths)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
-- | Smart constructor for 'Tied'
mkTied :: StartStopContinue -> Tied
mkTied a = Tied a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @time@ /(complex)/
--
-- Time signatures are represented by the beats element for the numerator and the beat-type element for the denominator. The symbol attribute is used indicate common and cut time symbols as well as a single number display. Multiple pairs of beat and beat-type elements are used for composite time signatures with multiple denominators, such as 2/4 + 3/8. A composite such as 3+2/8 requires only one beat/beat-type pair.
--
-- The print-object attribute allows a time signature to be specified but not printed, as is the case for excerpts from the middle of a score. The value is "yes" if not present. The optional number attribute refers to staff numbers within the part. If absent, the time signature applies to all staves in the part.
data Time =
Time {
timeNumber :: (Maybe StaffNumber) -- ^ /number/ attribute
, timeSymbol :: (Maybe TimeSymbol) -- ^ /symbol/ attribute
, timeSeparator :: (Maybe TimeSeparator) -- ^ /separator/ attribute
, timeDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, timeDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, timeRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, timeRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, timeFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, timeFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, timeFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, timeFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, timeColor :: (Maybe Color) -- ^ /color/ attribute
, timeHalign :: (Maybe LeftCenterRight) -- ^ /halign/ attribute
, timeValign :: (Maybe Valign) -- ^ /valign/ attribute
, timePrintObject :: (Maybe YesNo) -- ^ /print-object/ attribute
, timeTime :: ChxTime
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Time where
emitXml (Time a b c d e f g h i j k l m n o p) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "number" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "symbol" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "separator" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) l] ++
[maybe XEmpty (XAttr (QN "halign" Nothing).emitXml) m] ++
[maybe XEmpty (XAttr (QN "valign" Nothing).emitXml) n] ++
[maybe XEmpty (XAttr (QN "print-object" Nothing).emitXml) o])
([emitXml p])
parseTime :: P.XParse Time
parseTime =
Time
<$> P.optional (P.xattr (P.name "number") >>= parseStaffNumber)
<*> P.optional (P.xattr (P.name "symbol") >>= parseTimeSymbol)
<*> P.optional (P.xattr (P.name "separator") >>= parseTimeSeparator)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "halign") >>= parseLeftCenterRight)
<*> P.optional (P.xattr (P.name "valign") >>= parseValign)
<*> P.optional (P.xattr (P.name "print-object") >>= parseYesNo)
<*> parseChxTime
-- | Smart constructor for 'Time'
mkTime :: ChxTime -> Time
mkTime p = Time Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing p
-- | @time-modification@ /(complex)/
--
-- Time modification indicates tuplets, double-note tremolos, and other durational changes. A time-modification element shows how the cumulative, sounding effect of tuplets and double-note tremolos compare to the written note type represented by the type and dot elements. Nested tuplets and other notations that use more detailed information need both the time-modification and tuplet elements to be represented accurately.
data TimeModification =
TimeModification {
timeModificationActualNotes :: NonNegativeInteger -- ^ /actual-notes/ child element
, timeModificationNormalNotes :: NonNegativeInteger -- ^ /normal-notes/ child element
, timeModificationTimeModification :: (Maybe SeqTimeModification)
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml TimeModification where
emitXml (TimeModification a b c) =
XContent XEmpty
[]
([XElement (QN "actual-notes" Nothing) (emitXml a)] ++
[XElement (QN "normal-notes" Nothing) (emitXml b)] ++
[emitXml c])
parseTimeModification :: P.XParse TimeModification
parseTimeModification =
TimeModification
<$> (P.xchild (P.name "actual-notes") (P.xtext >>= parseNonNegativeInteger))
<*> (P.xchild (P.name "normal-notes") (P.xtext >>= parseNonNegativeInteger))
<*> P.optional (parseSeqTimeModification)
-- | Smart constructor for 'TimeModification'
mkTimeModification :: NonNegativeInteger -> NonNegativeInteger -> TimeModification
mkTimeModification a b = TimeModification a b Nothing
-- | @transpose@ /(complex)/
--
-- The transpose type represents what must be added to a written pitch to get a correct sounding pitch. The optional number attribute refers to staff numbers, from top to bottom on the system. If absent, the transposition applies to all staves in the part. Per-staff transposition is most often used in parts that represent multiple instruments.
data Transpose =
Transpose {
transposeNumber :: (Maybe StaffNumber) -- ^ /number/ attribute
, transposeDiatonic :: (Maybe Int) -- ^ /diatonic/ child element
, transposeChromatic :: Semitones -- ^ /chromatic/ child element
, transposeOctaveChange :: (Maybe Int) -- ^ /octave-change/ child element
, transposeDouble :: (Maybe Empty) -- ^ /double/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Transpose where
emitXml (Transpose a b c d e) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "number" Nothing).emitXml) a])
([maybe XEmpty (XElement (QN "diatonic" Nothing).emitXml) b] ++
[XElement (QN "chromatic" Nothing) (emitXml c)] ++
[maybe XEmpty (XElement (QN "octave-change" Nothing).emitXml) d] ++
[maybe XEmpty (XElement (QN "double" Nothing).emitXml) e])
parseTranspose :: P.XParse Transpose
parseTranspose =
Transpose
<$> P.optional (P.xattr (P.name "number") >>= parseStaffNumber)
<*> P.optional (P.xchild (P.name "diatonic") (P.xtext >>= (P.xread "Integer")))
<*> (P.xchild (P.name "chromatic") (P.xtext >>= parseSemitones))
<*> P.optional (P.xchild (P.name "octave-change") (P.xtext >>= (P.xread "Integer")))
<*> P.optional (P.xchild (P.name "double") (parseEmpty))
-- | Smart constructor for 'Transpose'
mkTranspose :: Semitones -> Transpose
mkTranspose c = Transpose Nothing Nothing c Nothing Nothing
-- | @tremolo@ /(complex)/
--
-- The tremolo ornament can be used to indicate either single-note or double-note tremolos. Single-note tremolos use the single type, while double-note tremolos use the start and stop types. The default is "single" for compatibility with Version 1.1. The text of the element indicates the number of tremolo marks and is an integer from 0 to 8. Note that the number of attached beams is not included in this value, but is represented separately using the beam element.
--
-- When using double-note tremolos, the duration of each note in the tremolo should correspond to half of the notated type value. A time-modification element should also be added with an actual-notes value of 2 and a normal-notes value of 1. If used within a tuplet, this 2/1 ratio should be multiplied by the existing tuplet ratio.
--
-- Using repeater beams for indicating tremolos is deprecated as of MusicXML 3.0.
data Tremolo =
Tremolo {
tremoloTremoloMarks :: TremoloMarks -- ^ text content
, tremoloType :: (Maybe StartStopSingle) -- ^ /type/ attribute
, tremoloDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, tremoloDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, tremoloRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, tremoloRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, tremoloFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, tremoloFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, tremoloFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, tremoloFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, tremoloColor :: (Maybe Color) -- ^ /color/ attribute
, tremoloPlacement :: (Maybe AboveBelow) -- ^ /placement/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Tremolo where
emitXml (Tremolo a b c d e f g h i j k l) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "type" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "placement" Nothing).emitXml) l])
[]
parseTremolo :: P.XParse Tremolo
parseTremolo =
Tremolo
<$> (P.xtext >>= parseTremoloMarks)
<*> P.optional (P.xattr (P.name "type") >>= parseStartStopSingle)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "placement") >>= parseAboveBelow)
-- | Smart constructor for 'Tremolo'
mkTremolo :: TremoloMarks -> Tremolo
mkTremolo a = Tremolo a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @tuplet@ /(complex)/
--
-- A tuplet element is present when a tuplet is to be displayed graphically, in addition to the sound data provided by the time-modification elements. The number attribute is used to distinguish nested tuplets. The bracket attribute is used to indicate the presence of a bracket. If unspecified, the results are implementation-dependent. The line-shape attribute is used to specify whether the bracket is straight or in the older curved or slurred style. It is straight by default.
--
-- Whereas a time-modification element shows how the cumulative, sounding effect of tuplets and double-note tremolos compare to the written note type, the tuplet element describes how this is displayed. The tuplet element also provides more detailed representation information than the time-modification element, and is needed to represent nested tuplets and other complex tuplets accurately.
--
-- The show-number attribute is used to display either the number of actual notes, the number of both actual and normal notes, or neither. It is actual by default. The show-type attribute is used to display either the actual type, both the actual and normal types, or neither. It is none by default.
data Tuplet =
Tuplet {
tupletType :: StartStop -- ^ /type/ attribute
, tupletNumber :: (Maybe NumberLevel) -- ^ /number/ attribute
, tupletBracket :: (Maybe YesNo) -- ^ /bracket/ attribute
, tupletShowNumber :: (Maybe ShowTuplet) -- ^ /show-number/ attribute
, tupletShowType :: (Maybe ShowTuplet) -- ^ /show-type/ attribute
, tupletLineShape :: (Maybe LineShape) -- ^ /line-shape/ attribute
, tupletDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, tupletDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, tupletRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, tupletRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, tupletPlacement :: (Maybe AboveBelow) -- ^ /placement/ attribute
, tupletTupletActual :: (Maybe TupletPortion) -- ^ /tuplet-actual/ child element
, tupletTupletNormal :: (Maybe TupletPortion) -- ^ /tuplet-normal/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Tuplet where
emitXml (Tuplet a b c d e f g h i j k l m) =
XContent XEmpty
([XAttr (QN "type" Nothing) (emitXml a)] ++
[maybe XEmpty (XAttr (QN "number" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "bracket" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "show-number" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "show-type" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "line-shape" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "placement" Nothing).emitXml) k])
([maybe XEmpty (XElement (QN "tuplet-actual" Nothing).emitXml) l] ++
[maybe XEmpty (XElement (QN "tuplet-normal" Nothing).emitXml) m])
parseTuplet :: P.XParse Tuplet
parseTuplet =
Tuplet
<$> (P.xattr (P.name "type") >>= parseStartStop)
<*> P.optional (P.xattr (P.name "number") >>= parseNumberLevel)
<*> P.optional (P.xattr (P.name "bracket") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "show-number") >>= parseShowTuplet)
<*> P.optional (P.xattr (P.name "show-type") >>= parseShowTuplet)
<*> P.optional (P.xattr (P.name "line-shape") >>= parseLineShape)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "placement") >>= parseAboveBelow)
<*> P.optional (P.xchild (P.name "tuplet-actual") (parseTupletPortion))
<*> P.optional (P.xchild (P.name "tuplet-normal") (parseTupletPortion))
-- | Smart constructor for 'Tuplet'
mkTuplet :: StartStop -> Tuplet
mkTuplet a = Tuplet a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @tuplet-dot@ /(complex)/
--
-- The tuplet-dot type is used to specify dotted normal tuplet types.
data TupletDot =
TupletDot {
tupletDotFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, tupletDotFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, tupletDotFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, tupletDotFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, tupletDotColor :: (Maybe Color) -- ^ /color/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml TupletDot where
emitXml (TupletDot a b c d e) =
XContent XEmpty
([maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) a] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) e])
[]
parseTupletDot :: P.XParse TupletDot
parseTupletDot =
TupletDot
<$> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
-- | Smart constructor for 'TupletDot'
mkTupletDot :: TupletDot
mkTupletDot = TupletDot Nothing Nothing Nothing Nothing Nothing
-- | @tuplet-number@ /(complex)/
--
-- The tuplet-number type indicates the number of notes for this portion of the tuplet.
data TupletNumber =
TupletNumber {
tupletNumberNonNegativeInteger :: NonNegativeInteger -- ^ text content
, tupletNumberFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, tupletNumberFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, tupletNumberFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, tupletNumberFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, tupletNumberColor :: (Maybe Color) -- ^ /color/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml TupletNumber where
emitXml (TupletNumber a b c d e f) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) f])
[]
parseTupletNumber :: P.XParse TupletNumber
parseTupletNumber =
TupletNumber
<$> (P.xtext >>= parseNonNegativeInteger)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
-- | Smart constructor for 'TupletNumber'
mkTupletNumber :: NonNegativeInteger -> TupletNumber
mkTupletNumber a = TupletNumber a Nothing Nothing Nothing Nothing Nothing
-- | @tuplet-portion@ /(complex)/
--
-- The tuplet-portion type provides optional full control over tuplet specifications. It allows the number and note type (including dots) to be set for the actual and normal portions of a single tuplet. If any of these elements are absent, their values are based on the time-modification element.
data TupletPortion =
TupletPortion {
tupletPortionTupletNumber :: (Maybe TupletNumber) -- ^ /tuplet-number/ child element
, tupletPortionTupletType :: (Maybe TupletType) -- ^ /tuplet-type/ child element
, tupletPortionTupletDot :: [TupletDot] -- ^ /tuplet-dot/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml TupletPortion where
emitXml (TupletPortion a b c) =
XContent XEmpty
[]
([maybe XEmpty (XElement (QN "tuplet-number" Nothing).emitXml) a] ++
[maybe XEmpty (XElement (QN "tuplet-type" Nothing).emitXml) b] ++
map (XElement (QN "tuplet-dot" Nothing).emitXml) c)
parseTupletPortion :: P.XParse TupletPortion
parseTupletPortion =
TupletPortion
<$> P.optional (P.xchild (P.name "tuplet-number") (parseTupletNumber))
<*> P.optional (P.xchild (P.name "tuplet-type") (parseTupletType))
<*> P.many (P.xchild (P.name "tuplet-dot") (parseTupletDot))
-- | Smart constructor for 'TupletPortion'
mkTupletPortion :: TupletPortion
mkTupletPortion = TupletPortion Nothing Nothing []
-- | @tuplet-type@ /(complex)/
--
-- The tuplet-type type indicates the graphical note type of the notes for this portion of the tuplet.
data TupletType =
TupletType {
tupletTypeNoteTypeValue :: NoteTypeValue -- ^ text content
, tupletTypeFontFamily :: (Maybe CommaSeparatedText) -- ^ /font-family/ attribute
, tupletTypeFontStyle :: (Maybe FontStyle) -- ^ /font-style/ attribute
, tupletTypeFontSize :: (Maybe FontSize) -- ^ /font-size/ attribute
, tupletTypeFontWeight :: (Maybe FontWeight) -- ^ /font-weight/ attribute
, tupletTypeColor :: (Maybe Color) -- ^ /color/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml TupletType where
emitXml (TupletType a b c d e f) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "font-family" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "font-style" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "font-size" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "font-weight" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) f])
[]
parseTupletType :: P.XParse TupletType
parseTupletType =
TupletType
<$> (P.xtext >>= parseNoteTypeValue)
<*> P.optional (P.xattr (P.name "font-family") >>= parseCommaSeparatedText)
<*> P.optional (P.xattr (P.name "font-style") >>= parseFontStyle)
<*> P.optional (P.xattr (P.name "font-size") >>= parseFontSize)
<*> P.optional (P.xattr (P.name "font-weight") >>= parseFontWeight)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
-- | Smart constructor for 'TupletType'
mkTupletType :: NoteTypeValue -> TupletType
mkTupletType a = TupletType a Nothing Nothing Nothing Nothing Nothing
-- | @typed-text@ /(complex)/
--
-- The typed-text type represents a text element with a type attributes.
data TypedText =
TypedText {
typedTextString :: String -- ^ text content
, typedTextType :: (Maybe Token) -- ^ /type/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml TypedText where
emitXml (TypedText a b) =
XContent (emitXml a)
([maybe XEmpty (XAttr (QN "type" Nothing).emitXml) b])
[]
parseTypedText :: P.XParse TypedText
parseTypedText =
TypedText
<$> (P.xtext >>= return)
<*> P.optional (P.xattr (P.name "type") >>= parseToken)
-- | Smart constructor for 'TypedText'
mkTypedText :: String -> TypedText
mkTypedText a = TypedText a Nothing
-- | @unpitched@ /(complex)/
--
-- The unpitched type represents musical elements that are notated on the staff but lack definite pitch, such as unpitched percussion and speaking voice.
data Unpitched =
Unpitched {
unpitchedDisplayStepOctave :: (Maybe DisplayStepOctave)
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Unpitched where
emitXml (Unpitched a) =
XReps [emitXml a]
parseUnpitched :: P.XParse Unpitched
parseUnpitched =
Unpitched
<$> P.optional (parseDisplayStepOctave)
-- | Smart constructor for 'Unpitched'
mkUnpitched :: Unpitched
mkUnpitched = Unpitched Nothing
-- | @virtual-instrument@ /(complex)/
--
-- The virtual-instrument element defines a specific virtual instrument used for an instrument sound.
data VirtualInstrument =
VirtualInstrument {
virtualInstrumentVirtualLibrary :: (Maybe String) -- ^ /virtual-library/ child element
, virtualInstrumentVirtualName :: (Maybe String) -- ^ /virtual-name/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml VirtualInstrument where
emitXml (VirtualInstrument a b) =
XContent XEmpty
[]
([maybe XEmpty (XElement (QN "virtual-library" Nothing).emitXml) a] ++
[maybe XEmpty (XElement (QN "virtual-name" Nothing).emitXml) b])
parseVirtualInstrument :: P.XParse VirtualInstrument
parseVirtualInstrument =
VirtualInstrument
<$> P.optional (P.xchild (P.name "virtual-library") (P.xtext >>= return))
<*> P.optional (P.xchild (P.name "virtual-name") (P.xtext >>= return))
-- | Smart constructor for 'VirtualInstrument'
mkVirtualInstrument :: VirtualInstrument
mkVirtualInstrument = VirtualInstrument Nothing Nothing
-- | @wavy-line@ /(complex)/
--
-- Wavy lines are one way to indicate trills. When used with a measure element, they should always have type="continue" set.
data WavyLine =
WavyLine {
wavyLineType :: StartStopContinue -- ^ /type/ attribute
, wavyLineNumber :: (Maybe NumberLevel) -- ^ /number/ attribute
, wavyLineDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, wavyLineDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, wavyLineRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, wavyLineRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, wavyLinePlacement :: (Maybe AboveBelow) -- ^ /placement/ attribute
, wavyLineColor :: (Maybe Color) -- ^ /color/ attribute
, wavyLineStartNote :: (Maybe StartNote) -- ^ /start-note/ attribute
, wavyLineTrillStep :: (Maybe TrillStep) -- ^ /trill-step/ attribute
, wavyLineTwoNoteTurn :: (Maybe TwoNoteTurn) -- ^ /two-note-turn/ attribute
, wavyLineAccelerate :: (Maybe YesNo) -- ^ /accelerate/ attribute
, wavyLineBeats :: (Maybe TrillBeats) -- ^ /beats/ attribute
, wavyLineSecondBeat :: (Maybe Percent) -- ^ /second-beat/ attribute
, wavyLineLastBeat :: (Maybe Percent) -- ^ /last-beat/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml WavyLine where
emitXml (WavyLine a b c d e f g h i j k l m n o) =
XContent XEmpty
([XAttr (QN "type" Nothing) (emitXml a)] ++
[maybe XEmpty (XAttr (QN "number" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "placement" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "start-note" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "trill-step" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "two-note-turn" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "accelerate" Nothing).emitXml) l] ++
[maybe XEmpty (XAttr (QN "beats" Nothing).emitXml) m] ++
[maybe XEmpty (XAttr (QN "second-beat" Nothing).emitXml) n] ++
[maybe XEmpty (XAttr (QN "last-beat" Nothing).emitXml) o])
[]
parseWavyLine :: P.XParse WavyLine
parseWavyLine =
WavyLine
<$> (P.xattr (P.name "type") >>= parseStartStopContinue)
<*> P.optional (P.xattr (P.name "number") >>= parseNumberLevel)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "placement") >>= parseAboveBelow)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
<*> P.optional (P.xattr (P.name "start-note") >>= parseStartNote)
<*> P.optional (P.xattr (P.name "trill-step") >>= parseTrillStep)
<*> P.optional (P.xattr (P.name "two-note-turn") >>= parseTwoNoteTurn)
<*> P.optional (P.xattr (P.name "accelerate") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "beats") >>= parseTrillBeats)
<*> P.optional (P.xattr (P.name "second-beat") >>= parsePercent)
<*> P.optional (P.xattr (P.name "last-beat") >>= parsePercent)
-- | Smart constructor for 'WavyLine'
mkWavyLine :: StartStopContinue -> WavyLine
mkWavyLine a = WavyLine a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @wedge@ /(complex)/
--
-- The wedge type represents crescendo and diminuendo wedge symbols. The type attribute is crescendo for the start of a wedge that is closed at the left side, and diminuendo for the start of a wedge that is closed on the right side. Spread values are measured in tenths; those at the start of a crescendo wedge or end of a diminuendo wedge are ignored. The niente attribute is yes if a circle appears at the point of the wedge, indicating a crescendo from nothing or diminuendo to nothing. It is no by default, and used only when the type is crescendo, or the type is stop for a wedge that began with a diminuendo type. The line-type is solid by default.
data Wedge =
Wedge {
wedgeType :: WedgeType -- ^ /type/ attribute
, wedgeNumber :: (Maybe NumberLevel) -- ^ /number/ attribute
, wedgeSpread :: (Maybe Tenths) -- ^ /spread/ attribute
, wedgeNiente :: (Maybe YesNo) -- ^ /niente/ attribute
, wedgeLineType :: (Maybe LineType) -- ^ /line-type/ attribute
, wedgeDashLength :: (Maybe Tenths) -- ^ /dash-length/ attribute
, wedgeSpaceLength :: (Maybe Tenths) -- ^ /space-length/ attribute
, wedgeDefaultX :: (Maybe Tenths) -- ^ /default-x/ attribute
, wedgeDefaultY :: (Maybe Tenths) -- ^ /default-y/ attribute
, wedgeRelativeX :: (Maybe Tenths) -- ^ /relative-x/ attribute
, wedgeRelativeY :: (Maybe Tenths) -- ^ /relative-y/ attribute
, wedgeColor :: (Maybe Color) -- ^ /color/ attribute
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Wedge where
emitXml (Wedge a b c d e f g h i j k l) =
XContent XEmpty
([XAttr (QN "type" Nothing) (emitXml a)] ++
[maybe XEmpty (XAttr (QN "number" Nothing).emitXml) b] ++
[maybe XEmpty (XAttr (QN "spread" Nothing).emitXml) c] ++
[maybe XEmpty (XAttr (QN "niente" Nothing).emitXml) d] ++
[maybe XEmpty (XAttr (QN "line-type" Nothing).emitXml) e] ++
[maybe XEmpty (XAttr (QN "dash-length" Nothing).emitXml) f] ++
[maybe XEmpty (XAttr (QN "space-length" Nothing).emitXml) g] ++
[maybe XEmpty (XAttr (QN "default-x" Nothing).emitXml) h] ++
[maybe XEmpty (XAttr (QN "default-y" Nothing).emitXml) i] ++
[maybe XEmpty (XAttr (QN "relative-x" Nothing).emitXml) j] ++
[maybe XEmpty (XAttr (QN "relative-y" Nothing).emitXml) k] ++
[maybe XEmpty (XAttr (QN "color" Nothing).emitXml) l])
[]
parseWedge :: P.XParse Wedge
parseWedge =
Wedge
<$> (P.xattr (P.name "type") >>= parseWedgeType)
<*> P.optional (P.xattr (P.name "number") >>= parseNumberLevel)
<*> P.optional (P.xattr (P.name "spread") >>= parseTenths)
<*> P.optional (P.xattr (P.name "niente") >>= parseYesNo)
<*> P.optional (P.xattr (P.name "line-type") >>= parseLineType)
<*> P.optional (P.xattr (P.name "dash-length") >>= parseTenths)
<*> P.optional (P.xattr (P.name "space-length") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "default-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-x") >>= parseTenths)
<*> P.optional (P.xattr (P.name "relative-y") >>= parseTenths)
<*> P.optional (P.xattr (P.name "color") >>= parseColor)
-- | Smart constructor for 'Wedge'
mkWedge :: WedgeType -> Wedge
mkWedge a = Wedge a Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | @work@ /(complex)/
--
-- Works are optionally identified by number and title. The work type also may indicate a link to the opus document that composes multiple scores into a collection.
data Work =
Work {
workWorkNumber :: (Maybe String) -- ^ /work-number/ child element
, workWorkTitle :: (Maybe String) -- ^ /work-title/ child element
, workOpus :: (Maybe Opus) -- ^ /opus/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Work where
emitXml (Work a b c) =
XContent XEmpty
[]
([maybe XEmpty (XElement (QN "work-number" Nothing).emitXml) a] ++
[maybe XEmpty (XElement (QN "work-title" Nothing).emitXml) b] ++
[maybe XEmpty (XElement (QN "opus" Nothing).emitXml) c])
parseWork :: P.XParse Work
parseWork =
Work
<$> P.optional (P.xchild (P.name "work-number") (P.xtext >>= return))
<*> P.optional (P.xchild (P.name "work-title") (P.xtext >>= return))
<*> P.optional (P.xchild (P.name "opus") (parseOpus))
-- | Smart constructor for 'Work'
mkWork :: Work
mkWork = Work Nothing Nothing Nothing
-- | @arrow@ /(choice)/
data ChxArrow =
ArrowArrowDirection {
arrowArrowDirection :: ArrowDirection -- ^ /arrow-direction/ child element
, arrowArrowStyle :: (Maybe ArrowStyle) -- ^ /arrow-style/ child element
}
| ArrowCircularArrow {
arrowCircularArrow :: CircularArrow -- ^ /circular-arrow/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml ChxArrow where
emitXml (ArrowArrowDirection a b) =
XContent XEmpty
[]
([XElement (QN "arrow-direction" Nothing) (emitXml a)] ++
[maybe XEmpty (XElement (QN "arrow-style" Nothing).emitXml) b])
emitXml (ArrowCircularArrow a) =
XContent XEmpty
[]
([XElement (QN "circular-arrow" Nothing) (emitXml a)])
parseChxArrow :: P.XParse ChxArrow
parseChxArrow =
ArrowArrowDirection
<$> (P.xchild (P.name "arrow-direction") (P.xtext >>= parseArrowDirection))
<*> P.optional (P.xchild (P.name "arrow-style") (P.xtext >>= parseArrowStyle))
<|> ArrowCircularArrow
<$> (P.xchild (P.name "circular-arrow") (P.xtext >>= parseCircularArrow))
-- | Smart constructor for 'ArrowArrowDirection'
mkArrowArrowDirection :: ArrowDirection -> ChxArrow
mkArrowArrowDirection a = ArrowArrowDirection a Nothing
-- | Smart constructor for 'ArrowCircularArrow'
mkArrowCircularArrow :: CircularArrow -> ChxArrow
mkArrowCircularArrow a = ArrowCircularArrow a
-- | @articulations@ /(choice)/
data ChxArticulations =
ArticulationsAccent {
articulationsAccent :: EmptyPlacement -- ^ /accent/ child element
}
| ArticulationsStrongAccent {
articulationsStrongAccent :: StrongAccent -- ^ /strong-accent/ child element
}
| ArticulationsStaccato {
articulationsStaccato :: EmptyPlacement -- ^ /staccato/ child element
}
| ArticulationsTenuto {
articulationsTenuto :: EmptyPlacement -- ^ /tenuto/ child element
}
| ArticulationsDetachedLegato {
articulationsDetachedLegato :: EmptyPlacement -- ^ /detached-legato/ child element
}
| ArticulationsStaccatissimo {
articulationsStaccatissimo :: EmptyPlacement -- ^ /staccatissimo/ child element
}
| ArticulationsSpiccato {
articulationsSpiccato :: EmptyPlacement -- ^ /spiccato/ child element
}
| ArticulationsScoop {
articulationsScoop :: EmptyLine -- ^ /scoop/ child element
}
| ArticulationsPlop {
articulationsPlop :: EmptyLine -- ^ /plop/ child element
}
| ArticulationsDoit {
articulationsDoit :: EmptyLine -- ^ /doit/ child element
}
| ArticulationsFalloff {
articulationsFalloff :: EmptyLine -- ^ /falloff/ child element
}
| ArticulationsBreathMark {
articulationsBreathMark :: BreathMark -- ^ /breath-mark/ child element
}
| ArticulationsCaesura {
articulationsCaesura :: EmptyPlacement -- ^ /caesura/ child element
}
| ArticulationsStress {
articulationsStress :: EmptyPlacement -- ^ /stress/ child element
}
| ArticulationsUnstress {
articulationsUnstress :: EmptyPlacement -- ^ /unstress/ child element
}
| ArticulationsOtherArticulation {
articulationsOtherArticulation :: PlacementText -- ^ /other-articulation/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml ChxArticulations where
emitXml (ArticulationsAccent a) =
XContent XEmpty
[]
([XElement (QN "accent" Nothing) (emitXml a)])
emitXml (ArticulationsStrongAccent a) =
XContent XEmpty
[]
([XElement (QN "strong-accent" Nothing) (emitXml a)])
emitXml (ArticulationsStaccato a) =
XContent XEmpty
[]
([XElement (QN "staccato" Nothing) (emitXml a)])
emitXml (ArticulationsTenuto a) =
XContent XEmpty
[]
([XElement (QN "tenuto" Nothing) (emitXml a)])
emitXml (ArticulationsDetachedLegato a) =
XContent XEmpty
[]
([XElement (QN "detached-legato" Nothing) (emitXml a)])
emitXml (ArticulationsStaccatissimo a) =
XContent XEmpty
[]
([XElement (QN "staccatissimo" Nothing) (emitXml a)])
emitXml (ArticulationsSpiccato a) =
XContent XEmpty
[]
([XElement (QN "spiccato" Nothing) (emitXml a)])
emitXml (ArticulationsScoop a) =
XContent XEmpty
[]
([XElement (QN "scoop" Nothing) (emitXml a)])
emitXml (ArticulationsPlop a) =
XContent XEmpty
[]
([XElement (QN "plop" Nothing) (emitXml a)])
emitXml (ArticulationsDoit a) =
XContent XEmpty
[]
([XElement (QN "doit" Nothing) (emitXml a)])
emitXml (ArticulationsFalloff a) =
XContent XEmpty
[]
([XElement (QN "falloff" Nothing) (emitXml a)])
emitXml (ArticulationsBreathMark a) =
XContent XEmpty
[]
([XElement (QN "breath-mark" Nothing) (emitXml a)])
emitXml (ArticulationsCaesura a) =
XContent XEmpty
[]
([XElement (QN "caesura" Nothing) (emitXml a)])
emitXml (ArticulationsStress a) =
XContent XEmpty
[]
([XElement (QN "stress" Nothing) (emitXml a)])
emitXml (ArticulationsUnstress a) =
XContent XEmpty
[]
([XElement (QN "unstress" Nothing) (emitXml a)])
emitXml (ArticulationsOtherArticulation a) =
XContent XEmpty
[]
([XElement (QN "other-articulation" Nothing) (emitXml a)])
parseChxArticulations :: P.XParse ChxArticulations
parseChxArticulations =
ArticulationsAccent
<$> (P.xchild (P.name "accent") (parseEmptyPlacement))
<|> ArticulationsStrongAccent
<$> (P.xchild (P.name "strong-accent") (parseStrongAccent))
<|> ArticulationsStaccato
<$> (P.xchild (P.name "staccato") (parseEmptyPlacement))
<|> ArticulationsTenuto
<$> (P.xchild (P.name "tenuto") (parseEmptyPlacement))
<|> ArticulationsDetachedLegato
<$> (P.xchild (P.name "detached-legato") (parseEmptyPlacement))
<|> ArticulationsStaccatissimo
<$> (P.xchild (P.name "staccatissimo") (parseEmptyPlacement))
<|> ArticulationsSpiccato
<$> (P.xchild (P.name "spiccato") (parseEmptyPlacement))
<|> ArticulationsScoop
<$> (P.xchild (P.name "scoop") (parseEmptyLine))
<|> ArticulationsPlop
<$> (P.xchild (P.name "plop") (parseEmptyLine))
<|> ArticulationsDoit
<$> (P.xchild (P.name "doit") (parseEmptyLine))
<|> ArticulationsFalloff
<$> (P.xchild (P.name "falloff") (parseEmptyLine))
<|> ArticulationsBreathMark
<$> (P.xchild (P.name "breath-mark") (parseBreathMark))
<|> ArticulationsCaesura
<$> (P.xchild (P.name "caesura") (parseEmptyPlacement))
<|> ArticulationsStress
<$> (P.xchild (P.name "stress") (parseEmptyPlacement))
<|> ArticulationsUnstress
<$> (P.xchild (P.name "unstress") (parseEmptyPlacement))
<|> ArticulationsOtherArticulation
<$> (P.xchild (P.name "other-articulation") (parsePlacementText))
-- | Smart constructor for 'ArticulationsAccent'
mkArticulationsAccent :: EmptyPlacement -> ChxArticulations
mkArticulationsAccent a = ArticulationsAccent a
-- | Smart constructor for 'ArticulationsStrongAccent'
mkArticulationsStrongAccent :: StrongAccent -> ChxArticulations
mkArticulationsStrongAccent a = ArticulationsStrongAccent a
-- | Smart constructor for 'ArticulationsStaccato'
mkArticulationsStaccato :: EmptyPlacement -> ChxArticulations
mkArticulationsStaccato a = ArticulationsStaccato a
-- | Smart constructor for 'ArticulationsTenuto'
mkArticulationsTenuto :: EmptyPlacement -> ChxArticulations
mkArticulationsTenuto a = ArticulationsTenuto a
-- | Smart constructor for 'ArticulationsDetachedLegato'
mkArticulationsDetachedLegato :: EmptyPlacement -> ChxArticulations
mkArticulationsDetachedLegato a = ArticulationsDetachedLegato a
-- | Smart constructor for 'ArticulationsStaccatissimo'
mkArticulationsStaccatissimo :: EmptyPlacement -> ChxArticulations
mkArticulationsStaccatissimo a = ArticulationsStaccatissimo a
-- | Smart constructor for 'ArticulationsSpiccato'
mkArticulationsSpiccato :: EmptyPlacement -> ChxArticulations
mkArticulationsSpiccato a = ArticulationsSpiccato a
-- | Smart constructor for 'ArticulationsScoop'
mkArticulationsScoop :: EmptyLine -> ChxArticulations
mkArticulationsScoop a = ArticulationsScoop a
-- | Smart constructor for 'ArticulationsPlop'
mkArticulationsPlop :: EmptyLine -> ChxArticulations
mkArticulationsPlop a = ArticulationsPlop a
-- | Smart constructor for 'ArticulationsDoit'
mkArticulationsDoit :: EmptyLine -> ChxArticulations
mkArticulationsDoit a = ArticulationsDoit a
-- | Smart constructor for 'ArticulationsFalloff'
mkArticulationsFalloff :: EmptyLine -> ChxArticulations
mkArticulationsFalloff a = ArticulationsFalloff a
-- | Smart constructor for 'ArticulationsBreathMark'
mkArticulationsBreathMark :: BreathMark -> ChxArticulations
mkArticulationsBreathMark a = ArticulationsBreathMark a
-- | Smart constructor for 'ArticulationsCaesura'
mkArticulationsCaesura :: EmptyPlacement -> ChxArticulations
mkArticulationsCaesura a = ArticulationsCaesura a
-- | Smart constructor for 'ArticulationsStress'
mkArticulationsStress :: EmptyPlacement -> ChxArticulations
mkArticulationsStress a = ArticulationsStress a
-- | Smart constructor for 'ArticulationsUnstress'
mkArticulationsUnstress :: EmptyPlacement -> ChxArticulations
mkArticulationsUnstress a = ArticulationsUnstress a
-- | Smart constructor for 'ArticulationsOtherArticulation'
mkArticulationsOtherArticulation :: PlacementText -> ChxArticulations
mkArticulationsOtherArticulation a = ArticulationsOtherArticulation a
-- | @bend@ /(choice)/
data ChxBend =
BendPreBend {
bendPreBend :: Empty -- ^ /pre-bend/ child element
}
| BendRelease {
bendRelease :: Empty -- ^ /release/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml ChxBend where
emitXml (BendPreBend a) =
XContent XEmpty
[]
([XElement (QN "pre-bend" Nothing) (emitXml a)])
emitXml (BendRelease a) =
XContent XEmpty
[]
([XElement (QN "release" Nothing) (emitXml a)])
parseChxBend :: P.XParse ChxBend
parseChxBend =
BendPreBend
<$> (P.xchild (P.name "pre-bend") (parseEmpty))
<|> BendRelease
<$> (P.xchild (P.name "release") (parseEmpty))
-- | Smart constructor for 'BendPreBend'
mkBendPreBend :: Empty -> ChxBend
mkBendPreBend a = BendPreBend a
-- | Smart constructor for 'BendRelease'
mkBendRelease :: Empty -> ChxBend
mkBendRelease a = BendRelease a
-- | @credit@ /(choice)/
data ChxCredit =
CreditCreditImage {
creditCreditImage :: Image -- ^ /credit-image/ child element
}
| CreditCreditWords {
creditCreditWords :: FormattedText -- ^ /credit-words/ child element
, chxcreditCredit :: [SeqCredit]
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml ChxCredit where
emitXml (CreditCreditImage a) =
XContent XEmpty
[]
([XElement (QN "credit-image" Nothing) (emitXml a)])
emitXml (CreditCreditWords a b) =
XContent XEmpty
[]
([XElement (QN "credit-words" Nothing) (emitXml a)] ++
[emitXml b])
parseChxCredit :: P.XParse ChxCredit
parseChxCredit =
CreditCreditImage
<$> (P.xchild (P.name "credit-image") (parseImage))
<|> CreditCreditWords
<$> (P.xchild (P.name "credit-words") (parseFormattedText))
<*> P.many (parseSeqCredit)
-- | Smart constructor for 'CreditCreditImage'
mkCreditCreditImage :: Image -> ChxCredit
mkCreditCreditImage a = CreditCreditImage a
-- | Smart constructor for 'CreditCreditWords'
mkCreditCreditWords :: FormattedText -> ChxCredit
mkCreditCreditWords a = CreditCreditWords a []
-- | @direction-type@ /(choice)/
data ChxDirectionType =
DirectionTypeRehearsal {
directionTypeRehearsal :: [FormattedText] -- ^ /rehearsal/ child element
}
| DirectionTypeSegno {
directionTypeSegno :: [EmptyPrintStyleAlign] -- ^ /segno/ child element
}
| DirectionTypeWords {
directionTypeWords :: [FormattedText] -- ^ /words/ child element
}
| DirectionTypeCoda {
directionTypeCoda :: [EmptyPrintStyleAlign] -- ^ /coda/ child element
}
| DirectionTypeWedge {
directionTypeWedge :: Wedge -- ^ /wedge/ child element
}
| DirectionTypeDynamics {
directionTypeDynamics :: [Dynamics] -- ^ /dynamics/ child element
}
| DirectionTypeDashes {
directionTypeDashes :: Dashes -- ^ /dashes/ child element
}
| DirectionTypeBracket {
directionTypeBracket :: Bracket -- ^ /bracket/ child element
}
| DirectionTypePedal {
directionTypePedal :: Pedal -- ^ /pedal/ child element
}
| DirectionTypeMetronome {
directionTypeMetronome :: Metronome -- ^ /metronome/ child element
}
| DirectionTypeOctaveShift {
directionTypeOctaveShift :: OctaveShift -- ^ /octave-shift/ child element
}
| DirectionTypeHarpPedals {
directionTypeHarpPedals :: HarpPedals -- ^ /harp-pedals/ child element
}
| DirectionTypeDamp {
directionTypeDamp :: EmptyPrintStyleAlign -- ^ /damp/ child element
}
| DirectionTypeDampAll {
directionTypeDampAll :: EmptyPrintStyleAlign -- ^ /damp-all/ child element
}
| DirectionTypeEyeglasses {
directionTypeEyeglasses :: EmptyPrintStyleAlign -- ^ /eyeglasses/ child element
}
| DirectionTypeStringMute {
directionTypeStringMute :: StringMute -- ^ /string-mute/ child element
}
| DirectionTypeScordatura {
directionTypeScordatura :: Scordatura -- ^ /scordatura/ child element
}
| DirectionTypeImage {
directionTypeImage :: Image -- ^ /image/ child element
}
| DirectionTypePrincipalVoice {
directionTypePrincipalVoice :: PrincipalVoice -- ^ /principal-voice/ child element
}
| DirectionTypeAccordionRegistration {
directionTypeAccordionRegistration :: AccordionRegistration -- ^ /accordion-registration/ child element
}
| DirectionTypePercussion {
directionTypePercussion :: [Percussion] -- ^ /percussion/ child element
}
| DirectionTypeOtherDirection {
directionTypeOtherDirection :: OtherDirection -- ^ /other-direction/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml ChxDirectionType where
emitXml (DirectionTypeRehearsal a) =
XContent XEmpty
[]
(map (XElement (QN "rehearsal" Nothing).emitXml) a)
emitXml (DirectionTypeSegno a) =
XContent XEmpty
[]
(map (XElement (QN "segno" Nothing).emitXml) a)
emitXml (DirectionTypeWords a) =
XContent XEmpty
[]
(map (XElement (QN "words" Nothing).emitXml) a)
emitXml (DirectionTypeCoda a) =
XContent XEmpty
[]
(map (XElement (QN "coda" Nothing).emitXml) a)
emitXml (DirectionTypeWedge a) =
XContent XEmpty
[]
([XElement (QN "wedge" Nothing) (emitXml a)])
emitXml (DirectionTypeDynamics a) =
XContent XEmpty
[]
(map (XElement (QN "dynamics" Nothing).emitXml) a)
emitXml (DirectionTypeDashes a) =
XContent XEmpty
[]
([XElement (QN "dashes" Nothing) (emitXml a)])
emitXml (DirectionTypeBracket a) =
XContent XEmpty
[]
([XElement (QN "bracket" Nothing) (emitXml a)])
emitXml (DirectionTypePedal a) =
XContent XEmpty
[]
([XElement (QN "pedal" Nothing) (emitXml a)])
emitXml (DirectionTypeMetronome a) =
XContent XEmpty
[]
([XElement (QN "metronome" Nothing) (emitXml a)])
emitXml (DirectionTypeOctaveShift a) =
XContent XEmpty
[]
([XElement (QN "octave-shift" Nothing) (emitXml a)])
emitXml (DirectionTypeHarpPedals a) =
XContent XEmpty
[]
([XElement (QN "harp-pedals" Nothing) (emitXml a)])
emitXml (DirectionTypeDamp a) =
XContent XEmpty
[]
([XElement (QN "damp" Nothing) (emitXml a)])
emitXml (DirectionTypeDampAll a) =
XContent XEmpty
[]
([XElement (QN "damp-all" Nothing) (emitXml a)])
emitXml (DirectionTypeEyeglasses a) =
XContent XEmpty
[]
([XElement (QN "eyeglasses" Nothing) (emitXml a)])
emitXml (DirectionTypeStringMute a) =
XContent XEmpty
[]
([XElement (QN "string-mute" Nothing) (emitXml a)])
emitXml (DirectionTypeScordatura a) =
XContent XEmpty
[]
([XElement (QN "scordatura" Nothing) (emitXml a)])
emitXml (DirectionTypeImage a) =
XContent XEmpty
[]
([XElement (QN "image" Nothing) (emitXml a)])
emitXml (DirectionTypePrincipalVoice a) =
XContent XEmpty
[]
([XElement (QN "principal-voice" Nothing) (emitXml a)])
emitXml (DirectionTypeAccordionRegistration a) =
XContent XEmpty
[]
([XElement (QN "accordion-registration" Nothing) (emitXml a)])
emitXml (DirectionTypePercussion a) =
XContent XEmpty
[]
(map (XElement (QN "percussion" Nothing).emitXml) a)
emitXml (DirectionTypeOtherDirection a) =
XContent XEmpty
[]
([XElement (QN "other-direction" Nothing) (emitXml a)])
parseChxDirectionType :: P.XParse ChxDirectionType
parseChxDirectionType =
DirectionTypeRehearsal
<$> P.some (P.xchild (P.name "rehearsal") (parseFormattedText))
<|> DirectionTypeSegno
<$> P.some (P.xchild (P.name "segno") (parseEmptyPrintStyleAlign))
<|> DirectionTypeWords
<$> P.some (P.xchild (P.name "words") (parseFormattedText))
<|> DirectionTypeCoda
<$> P.some (P.xchild (P.name "coda") (parseEmptyPrintStyleAlign))
<|> DirectionTypeWedge
<$> (P.xchild (P.name "wedge") (parseWedge))
<|> DirectionTypeDynamics
<$> P.some (P.xchild (P.name "dynamics") (parseDynamics))
<|> DirectionTypeDashes
<$> (P.xchild (P.name "dashes") (parseDashes))
<|> DirectionTypeBracket
<$> (P.xchild (P.name "bracket") (parseBracket))
<|> DirectionTypePedal
<$> (P.xchild (P.name "pedal") (parsePedal))
<|> DirectionTypeMetronome
<$> (P.xchild (P.name "metronome") (parseMetronome))
<|> DirectionTypeOctaveShift
<$> (P.xchild (P.name "octave-shift") (parseOctaveShift))
<|> DirectionTypeHarpPedals
<$> (P.xchild (P.name "harp-pedals") (parseHarpPedals))
<|> DirectionTypeDamp
<$> (P.xchild (P.name "damp") (parseEmptyPrintStyleAlign))
<|> DirectionTypeDampAll
<$> (P.xchild (P.name "damp-all") (parseEmptyPrintStyleAlign))
<|> DirectionTypeEyeglasses
<$> (P.xchild (P.name "eyeglasses") (parseEmptyPrintStyleAlign))
<|> DirectionTypeStringMute
<$> (P.xchild (P.name "string-mute") (parseStringMute))
<|> DirectionTypeScordatura
<$> (P.xchild (P.name "scordatura") (parseScordatura))
<|> DirectionTypeImage
<$> (P.xchild (P.name "image") (parseImage))
<|> DirectionTypePrincipalVoice
<$> (P.xchild (P.name "principal-voice") (parsePrincipalVoice))
<|> DirectionTypeAccordionRegistration
<$> (P.xchild (P.name "accordion-registration") (parseAccordionRegistration))
<|> DirectionTypePercussion
<$> P.some (P.xchild (P.name "percussion") (parsePercussion))
<|> DirectionTypeOtherDirection
<$> (P.xchild (P.name "other-direction") (parseOtherDirection))
-- | Smart constructor for 'DirectionTypeRehearsal'
mkDirectionTypeRehearsal :: ChxDirectionType
mkDirectionTypeRehearsal = DirectionTypeRehearsal []
-- | Smart constructor for 'DirectionTypeSegno'
mkDirectionTypeSegno :: ChxDirectionType
mkDirectionTypeSegno = DirectionTypeSegno []
-- | Smart constructor for 'DirectionTypeWords'
mkDirectionTypeWords :: ChxDirectionType
mkDirectionTypeWords = DirectionTypeWords []
-- | Smart constructor for 'DirectionTypeCoda'
mkDirectionTypeCoda :: ChxDirectionType
mkDirectionTypeCoda = DirectionTypeCoda []
-- | Smart constructor for 'DirectionTypeWedge'
mkDirectionTypeWedge :: Wedge -> ChxDirectionType
mkDirectionTypeWedge a = DirectionTypeWedge a
-- | Smart constructor for 'DirectionTypeDynamics'
mkDirectionTypeDynamics :: ChxDirectionType
mkDirectionTypeDynamics = DirectionTypeDynamics []
-- | Smart constructor for 'DirectionTypeDashes'
mkDirectionTypeDashes :: Dashes -> ChxDirectionType
mkDirectionTypeDashes a = DirectionTypeDashes a
-- | Smart constructor for 'DirectionTypeBracket'
mkDirectionTypeBracket :: Bracket -> ChxDirectionType
mkDirectionTypeBracket a = DirectionTypeBracket a
-- | Smart constructor for 'DirectionTypePedal'
mkDirectionTypePedal :: Pedal -> ChxDirectionType
mkDirectionTypePedal a = DirectionTypePedal a
-- | Smart constructor for 'DirectionTypeMetronome'
mkDirectionTypeMetronome :: Metronome -> ChxDirectionType
mkDirectionTypeMetronome a = DirectionTypeMetronome a
-- | Smart constructor for 'DirectionTypeOctaveShift'
mkDirectionTypeOctaveShift :: OctaveShift -> ChxDirectionType
mkDirectionTypeOctaveShift a = DirectionTypeOctaveShift a
-- | Smart constructor for 'DirectionTypeHarpPedals'
mkDirectionTypeHarpPedals :: HarpPedals -> ChxDirectionType
mkDirectionTypeHarpPedals a = DirectionTypeHarpPedals a
-- | Smart constructor for 'DirectionTypeDamp'
mkDirectionTypeDamp :: EmptyPrintStyleAlign -> ChxDirectionType
mkDirectionTypeDamp a = DirectionTypeDamp a
-- | Smart constructor for 'DirectionTypeDampAll'
mkDirectionTypeDampAll :: EmptyPrintStyleAlign -> ChxDirectionType
mkDirectionTypeDampAll a = DirectionTypeDampAll a
-- | Smart constructor for 'DirectionTypeEyeglasses'
mkDirectionTypeEyeglasses :: EmptyPrintStyleAlign -> ChxDirectionType
mkDirectionTypeEyeglasses a = DirectionTypeEyeglasses a
-- | Smart constructor for 'DirectionTypeStringMute'
mkDirectionTypeStringMute :: StringMute -> ChxDirectionType
mkDirectionTypeStringMute a = DirectionTypeStringMute a
-- | Smart constructor for 'DirectionTypeScordatura'
mkDirectionTypeScordatura :: Scordatura -> ChxDirectionType
mkDirectionTypeScordatura a = DirectionTypeScordatura a
-- | Smart constructor for 'DirectionTypeImage'
mkDirectionTypeImage :: Image -> ChxDirectionType
mkDirectionTypeImage a = DirectionTypeImage a
-- | Smart constructor for 'DirectionTypePrincipalVoice'
mkDirectionTypePrincipalVoice :: PrincipalVoice -> ChxDirectionType
mkDirectionTypePrincipalVoice a = DirectionTypePrincipalVoice a
-- | Smart constructor for 'DirectionTypeAccordionRegistration'
mkDirectionTypeAccordionRegistration :: AccordionRegistration -> ChxDirectionType
mkDirectionTypeAccordionRegistration a = DirectionTypeAccordionRegistration a
-- | Smart constructor for 'DirectionTypePercussion'
mkDirectionTypePercussion :: ChxDirectionType
mkDirectionTypePercussion = DirectionTypePercussion []
-- | Smart constructor for 'DirectionTypeOtherDirection'
mkDirectionTypeOtherDirection :: OtherDirection -> ChxDirectionType
mkDirectionTypeOtherDirection a = DirectionTypeOtherDirection a
-- | @dynamics@ /(choice)/
data ChxDynamics =
DynamicsP {
dynamicsP :: Empty -- ^ /p/ child element
}
| DynamicsPp {
dynamicsPp :: Empty -- ^ /pp/ child element
}
| DynamicsPpp {
dynamicsPpp :: Empty -- ^ /ppp/ child element
}
| DynamicsPppp {
dynamicsPppp :: Empty -- ^ /pppp/ child element
}
| DynamicsPpppp {
dynamicsPpppp :: Empty -- ^ /ppppp/ child element
}
| DynamicsPppppp {
dynamicsPppppp :: Empty -- ^ /pppppp/ child element
}
| DynamicsF {
dynamicsF :: Empty -- ^ /f/ child element
}
| DynamicsFf {
dynamicsFf :: Empty -- ^ /ff/ child element
}
| DynamicsFff {
dynamicsFff :: Empty -- ^ /fff/ child element
}
| DynamicsFfff {
dynamicsFfff :: Empty -- ^ /ffff/ child element
}
| DynamicsFffff {
dynamicsFffff :: Empty -- ^ /fffff/ child element
}
| DynamicsFfffff {
dynamicsFfffff :: Empty -- ^ /ffffff/ child element
}
| DynamicsMp {
dynamicsMp :: Empty -- ^ /mp/ child element
}
| DynamicsMf {
dynamicsMf :: Empty -- ^ /mf/ child element
}
| DynamicsSf {
dynamicsSf :: Empty -- ^ /sf/ child element
}
| DynamicsSfp {
dynamicsSfp :: Empty -- ^ /sfp/ child element
}
| DynamicsSfpp {
dynamicsSfpp :: Empty -- ^ /sfpp/ child element
}
| DynamicsFp {
dynamicsFp :: Empty -- ^ /fp/ child element
}
| DynamicsRf {
dynamicsRf :: Empty -- ^ /rf/ child element
}
| DynamicsRfz {
dynamicsRfz :: Empty -- ^ /rfz/ child element
}
| DynamicsSfz {
dynamicsSfz :: Empty -- ^ /sfz/ child element
}
| DynamicsSffz {
dynamicsSffz :: Empty -- ^ /sffz/ child element
}
| DynamicsFz {
dynamicsFz :: Empty -- ^ /fz/ child element
}
| DynamicsOtherDynamics {
dynamicsOtherDynamics :: String -- ^ /other-dynamics/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml ChxDynamics where
emitXml (DynamicsP a) =
XContent XEmpty
[]
([XElement (QN "p" Nothing) (emitXml a)])
emitXml (DynamicsPp a) =
XContent XEmpty
[]
([XElement (QN "pp" Nothing) (emitXml a)])
emitXml (DynamicsPpp a) =
XContent XEmpty
[]
([XElement (QN "ppp" Nothing) (emitXml a)])
emitXml (DynamicsPppp a) =
XContent XEmpty
[]
([XElement (QN "pppp" Nothing) (emitXml a)])
emitXml (DynamicsPpppp a) =
XContent XEmpty
[]
([XElement (QN "ppppp" Nothing) (emitXml a)])
emitXml (DynamicsPppppp a) =
XContent XEmpty
[]
([XElement (QN "pppppp" Nothing) (emitXml a)])
emitXml (DynamicsF a) =
XContent XEmpty
[]
([XElement (QN "f" Nothing) (emitXml a)])
emitXml (DynamicsFf a) =
XContent XEmpty
[]
([XElement (QN "ff" Nothing) (emitXml a)])
emitXml (DynamicsFff a) =
XContent XEmpty
[]
([XElement (QN "fff" Nothing) (emitXml a)])
emitXml (DynamicsFfff a) =
XContent XEmpty
[]
([XElement (QN "ffff" Nothing) (emitXml a)])
emitXml (DynamicsFffff a) =
XContent XEmpty
[]
([XElement (QN "fffff" Nothing) (emitXml a)])
emitXml (DynamicsFfffff a) =
XContent XEmpty
[]
([XElement (QN "ffffff" Nothing) (emitXml a)])
emitXml (DynamicsMp a) =
XContent XEmpty
[]
([XElement (QN "mp" Nothing) (emitXml a)])
emitXml (DynamicsMf a) =
XContent XEmpty
[]
([XElement (QN "mf" Nothing) (emitXml a)])
emitXml (DynamicsSf a) =
XContent XEmpty
[]
([XElement (QN "sf" Nothing) (emitXml a)])
emitXml (DynamicsSfp a) =
XContent XEmpty
[]
([XElement (QN "sfp" Nothing) (emitXml a)])
emitXml (DynamicsSfpp a) =
XContent XEmpty
[]
([XElement (QN "sfpp" Nothing) (emitXml a)])
emitXml (DynamicsFp a) =
XContent XEmpty
[]
([XElement (QN "fp" Nothing) (emitXml a)])
emitXml (DynamicsRf a) =
XContent XEmpty
[]
([XElement (QN "rf" Nothing) (emitXml a)])
emitXml (DynamicsRfz a) =
XContent XEmpty
[]
([XElement (QN "rfz" Nothing) (emitXml a)])
emitXml (DynamicsSfz a) =
XContent XEmpty
[]
([XElement (QN "sfz" Nothing) (emitXml a)])
emitXml (DynamicsSffz a) =
XContent XEmpty
[]
([XElement (QN "sffz" Nothing) (emitXml a)])
emitXml (DynamicsFz a) =
XContent XEmpty
[]
([XElement (QN "fz" Nothing) (emitXml a)])
emitXml (DynamicsOtherDynamics a) =
XContent XEmpty
[]
([XElement (QN "other-dynamics" Nothing) (emitXml a)])
parseChxDynamics :: P.XParse ChxDynamics
parseChxDynamics =
DynamicsP
<$> (P.xchild (P.name "p") (parseEmpty))
<|> DynamicsPp
<$> (P.xchild (P.name "pp") (parseEmpty))
<|> DynamicsPpp
<$> (P.xchild (P.name "ppp") (parseEmpty))
<|> DynamicsPppp
<$> (P.xchild (P.name "pppp") (parseEmpty))
<|> DynamicsPpppp
<$> (P.xchild (P.name "ppppp") (parseEmpty))
<|> DynamicsPppppp
<$> (P.xchild (P.name "pppppp") (parseEmpty))
<|> DynamicsF
<$> (P.xchild (P.name "f") (parseEmpty))
<|> DynamicsFf
<$> (P.xchild (P.name "ff") (parseEmpty))
<|> DynamicsFff
<$> (P.xchild (P.name "fff") (parseEmpty))
<|> DynamicsFfff
<$> (P.xchild (P.name "ffff") (parseEmpty))
<|> DynamicsFffff
<$> (P.xchild (P.name "fffff") (parseEmpty))
<|> DynamicsFfffff
<$> (P.xchild (P.name "ffffff") (parseEmpty))
<|> DynamicsMp
<$> (P.xchild (P.name "mp") (parseEmpty))
<|> DynamicsMf
<$> (P.xchild (P.name "mf") (parseEmpty))
<|> DynamicsSf
<$> (P.xchild (P.name "sf") (parseEmpty))
<|> DynamicsSfp
<$> (P.xchild (P.name "sfp") (parseEmpty))
<|> DynamicsSfpp
<$> (P.xchild (P.name "sfpp") (parseEmpty))
<|> DynamicsFp
<$> (P.xchild (P.name "fp") (parseEmpty))
<|> DynamicsRf
<$> (P.xchild (P.name "rf") (parseEmpty))
<|> DynamicsRfz
<$> (P.xchild (P.name "rfz") (parseEmpty))
<|> DynamicsSfz
<$> (P.xchild (P.name "sfz") (parseEmpty))
<|> DynamicsSffz
<$> (P.xchild (P.name "sffz") (parseEmpty))
<|> DynamicsFz
<$> (P.xchild (P.name "fz") (parseEmpty))
<|> DynamicsOtherDynamics
<$> (P.xchild (P.name "other-dynamics") (P.xtext >>= return))
-- | Smart constructor for 'DynamicsP'
mkDynamicsP :: Empty -> ChxDynamics
mkDynamicsP a = DynamicsP a
-- | Smart constructor for 'DynamicsPp'
mkDynamicsPp :: Empty -> ChxDynamics
mkDynamicsPp a = DynamicsPp a
-- | Smart constructor for 'DynamicsPpp'
mkDynamicsPpp :: Empty -> ChxDynamics
mkDynamicsPpp a = DynamicsPpp a
-- | Smart constructor for 'DynamicsPppp'
mkDynamicsPppp :: Empty -> ChxDynamics
mkDynamicsPppp a = DynamicsPppp a
-- | Smart constructor for 'DynamicsPpppp'
mkDynamicsPpppp :: Empty -> ChxDynamics
mkDynamicsPpppp a = DynamicsPpppp a
-- | Smart constructor for 'DynamicsPppppp'
mkDynamicsPppppp :: Empty -> ChxDynamics
mkDynamicsPppppp a = DynamicsPppppp a
-- | Smart constructor for 'DynamicsF'
mkDynamicsF :: Empty -> ChxDynamics
mkDynamicsF a = DynamicsF a
-- | Smart constructor for 'DynamicsFf'
mkDynamicsFf :: Empty -> ChxDynamics
mkDynamicsFf a = DynamicsFf a
-- | Smart constructor for 'DynamicsFff'
mkDynamicsFff :: Empty -> ChxDynamics
mkDynamicsFff a = DynamicsFff a
-- | Smart constructor for 'DynamicsFfff'
mkDynamicsFfff :: Empty -> ChxDynamics
mkDynamicsFfff a = DynamicsFfff a
-- | Smart constructor for 'DynamicsFffff'
mkDynamicsFffff :: Empty -> ChxDynamics
mkDynamicsFffff a = DynamicsFffff a
-- | Smart constructor for 'DynamicsFfffff'
mkDynamicsFfffff :: Empty -> ChxDynamics
mkDynamicsFfffff a = DynamicsFfffff a
-- | Smart constructor for 'DynamicsMp'
mkDynamicsMp :: Empty -> ChxDynamics
mkDynamicsMp a = DynamicsMp a
-- | Smart constructor for 'DynamicsMf'
mkDynamicsMf :: Empty -> ChxDynamics
mkDynamicsMf a = DynamicsMf a
-- | Smart constructor for 'DynamicsSf'
mkDynamicsSf :: Empty -> ChxDynamics
mkDynamicsSf a = DynamicsSf a
-- | Smart constructor for 'DynamicsSfp'
mkDynamicsSfp :: Empty -> ChxDynamics
mkDynamicsSfp a = DynamicsSfp a
-- | Smart constructor for 'DynamicsSfpp'
mkDynamicsSfpp :: Empty -> ChxDynamics
mkDynamicsSfpp a = DynamicsSfpp a
-- | Smart constructor for 'DynamicsFp'
mkDynamicsFp :: Empty -> ChxDynamics
mkDynamicsFp a = DynamicsFp a
-- | Smart constructor for 'DynamicsRf'
mkDynamicsRf :: Empty -> ChxDynamics
mkDynamicsRf a = DynamicsRf a
-- | Smart constructor for 'DynamicsRfz'
mkDynamicsRfz :: Empty -> ChxDynamics
mkDynamicsRfz a = DynamicsRfz a
-- | Smart constructor for 'DynamicsSfz'
mkDynamicsSfz :: Empty -> ChxDynamics
mkDynamicsSfz a = DynamicsSfz a
-- | Smart constructor for 'DynamicsSffz'
mkDynamicsSffz :: Empty -> ChxDynamics
mkDynamicsSffz a = DynamicsSffz a
-- | Smart constructor for 'DynamicsFz'
mkDynamicsFz :: Empty -> ChxDynamics
mkDynamicsFz a = DynamicsFz a
-- | Smart constructor for 'DynamicsOtherDynamics'
mkDynamicsOtherDynamics :: String -> ChxDynamics
mkDynamicsOtherDynamics a = DynamicsOtherDynamics a
-- | @encoding@ /(choice)/
data ChxEncoding =
EncodingEncodingDate {
encodingEncodingDate :: YyyyMmDd -- ^ /encoding-date/ child element
}
| EncodingEncoder {
encodingEncoder :: TypedText -- ^ /encoder/ child element
}
| EncodingSoftware {
encodingSoftware :: String -- ^ /software/ child element
}
| EncodingEncodingDescription {
encodingEncodingDescription :: String -- ^ /encoding-description/ child element
}
| EncodingSupports {
encodingSupports :: Supports -- ^ /supports/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml ChxEncoding where
emitXml (EncodingEncodingDate a) =
XContent XEmpty
[]
([XElement (QN "encoding-date" Nothing) (emitXml a)])
emitXml (EncodingEncoder a) =
XContent XEmpty
[]
([XElement (QN "encoder" Nothing) (emitXml a)])
emitXml (EncodingSoftware a) =
XContent XEmpty
[]
([XElement (QN "software" Nothing) (emitXml a)])
emitXml (EncodingEncodingDescription a) =
XContent XEmpty
[]
([XElement (QN "encoding-description" Nothing) (emitXml a)])
emitXml (EncodingSupports a) =
XContent XEmpty
[]
([XElement (QN "supports" Nothing) (emitXml a)])
parseChxEncoding :: P.XParse ChxEncoding
parseChxEncoding =
EncodingEncodingDate
<$> (P.xchild (P.name "encoding-date") (P.xtext >>= parseYyyyMmDd))
<|> EncodingEncoder
<$> (P.xchild (P.name "encoder") (parseTypedText))
<|> EncodingSoftware
<$> (P.xchild (P.name "software") (P.xtext >>= return))
<|> EncodingEncodingDescription
<$> (P.xchild (P.name "encoding-description") (P.xtext >>= return))
<|> EncodingSupports
<$> (P.xchild (P.name "supports") (parseSupports))
-- | Smart constructor for 'EncodingEncodingDate'
mkEncodingEncodingDate :: YyyyMmDd -> ChxEncoding
mkEncodingEncodingDate a = EncodingEncodingDate a
-- | Smart constructor for 'EncodingEncoder'
mkEncodingEncoder :: TypedText -> ChxEncoding
mkEncodingEncoder a = EncodingEncoder a
-- | Smart constructor for 'EncodingSoftware'
mkEncodingSoftware :: String -> ChxEncoding
mkEncodingSoftware a = EncodingSoftware a
-- | Smart constructor for 'EncodingEncodingDescription'
mkEncodingEncodingDescription :: String -> ChxEncoding
mkEncodingEncodingDescription a = EncodingEncodingDescription a
-- | Smart constructor for 'EncodingSupports'
mkEncodingSupports :: Supports -> ChxEncoding
mkEncodingSupports a = EncodingSupports a
-- | @full-note@ /(choice)/
data FullNote =
FullNotePitch {
fullNotePitch :: Pitch -- ^ /pitch/ child element
}
| FullNoteUnpitched {
fullNoteUnpitched :: Unpitched -- ^ /unpitched/ child element
}
| FullNoteRest {
fullNoteRest :: Rest -- ^ /rest/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml FullNote where
emitXml (FullNotePitch a) =
XContent XEmpty
[]
([XElement (QN "pitch" Nothing) (emitXml a)])
emitXml (FullNoteUnpitched a) =
XContent XEmpty
[]
([XElement (QN "unpitched" Nothing) (emitXml a)])
emitXml (FullNoteRest a) =
XContent XEmpty
[]
([XElement (QN "rest" Nothing) (emitXml a)])
parseFullNote :: P.XParse FullNote
parseFullNote =
FullNotePitch
<$> (P.xchild (P.name "pitch") (parsePitch))
<|> FullNoteUnpitched
<$> (P.xchild (P.name "unpitched") (parseUnpitched))
<|> FullNoteRest
<$> (P.xchild (P.name "rest") (parseRest))
-- | Smart constructor for 'FullNotePitch'
mkFullNotePitch :: Pitch -> FullNote
mkFullNotePitch a = FullNotePitch a
-- | Smart constructor for 'FullNoteUnpitched'
mkFullNoteUnpitched :: Unpitched -> FullNote
mkFullNoteUnpitched a = FullNoteUnpitched a
-- | Smart constructor for 'FullNoteRest'
mkFullNoteRest :: Rest -> FullNote
mkFullNoteRest a = FullNoteRest a
-- | @harmonic@ /(choice)/
data ChxHarmonic =
HarmonicNatural {
harmonicNatural :: Empty -- ^ /natural/ child element
}
| HarmonicArtificial {
harmonicArtificial :: Empty -- ^ /artificial/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml ChxHarmonic where
emitXml (HarmonicNatural a) =
XContent XEmpty
[]
([XElement (QN "natural" Nothing) (emitXml a)])
emitXml (HarmonicArtificial a) =
XContent XEmpty
[]
([XElement (QN "artificial" Nothing) (emitXml a)])
parseChxHarmonic :: P.XParse ChxHarmonic
parseChxHarmonic =
HarmonicNatural
<$> (P.xchild (P.name "natural") (parseEmpty))
<|> HarmonicArtificial
<$> (P.xchild (P.name "artificial") (parseEmpty))
-- | Smart constructor for 'HarmonicNatural'
mkHarmonicNatural :: Empty -> ChxHarmonic
mkHarmonicNatural a = HarmonicNatural a
-- | Smart constructor for 'HarmonicArtificial'
mkHarmonicArtificial :: Empty -> ChxHarmonic
mkHarmonicArtificial a = HarmonicArtificial a
-- | @harmonic@ /(choice)/
-- mangled: 1
data ChxHarmonic1 =
HarmonicBasePitch {
harmonicBasePitch :: Empty -- ^ /base-pitch/ child element
}
| HarmonicTouchingPitch {
harmonicTouchingPitch :: Empty -- ^ /touching-pitch/ child element
}
| HarmonicSoundingPitch {
harmonicSoundingPitch :: Empty -- ^ /sounding-pitch/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml ChxHarmonic1 where
emitXml (HarmonicBasePitch a) =
XContent XEmpty
[]
([XElement (QN "base-pitch" Nothing) (emitXml a)])
emitXml (HarmonicTouchingPitch a) =
XContent XEmpty
[]
([XElement (QN "touching-pitch" Nothing) (emitXml a)])
emitXml (HarmonicSoundingPitch a) =
XContent XEmpty
[]
([XElement (QN "sounding-pitch" Nothing) (emitXml a)])
parseChxHarmonic1 :: P.XParse ChxHarmonic1
parseChxHarmonic1 =
HarmonicBasePitch
<$> (P.xchild (P.name "base-pitch") (parseEmpty))
<|> HarmonicTouchingPitch
<$> (P.xchild (P.name "touching-pitch") (parseEmpty))
<|> HarmonicSoundingPitch
<$> (P.xchild (P.name "sounding-pitch") (parseEmpty))
-- | Smart constructor for 'HarmonicBasePitch'
mkHarmonicBasePitch :: Empty -> ChxHarmonic1
mkHarmonicBasePitch a = HarmonicBasePitch a
-- | Smart constructor for 'HarmonicTouchingPitch'
mkHarmonicTouchingPitch :: Empty -> ChxHarmonic1
mkHarmonicTouchingPitch a = HarmonicTouchingPitch a
-- | Smart constructor for 'HarmonicSoundingPitch'
mkHarmonicSoundingPitch :: Empty -> ChxHarmonic1
mkHarmonicSoundingPitch a = HarmonicSoundingPitch a
-- | @harmony-chord@ /(choice)/
data ChxHarmonyChord =
HarmonyChordRoot {
harmonyChordRoot :: Root -- ^ /root/ child element
}
| HarmonyChordFunction {
harmonyChordFunction :: StyleText -- ^ /function/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml ChxHarmonyChord where
emitXml (HarmonyChordRoot a) =
XContent XEmpty
[]
([XElement (QN "root" Nothing) (emitXml a)])
emitXml (HarmonyChordFunction a) =
XContent XEmpty
[]
([XElement (QN "function" Nothing) (emitXml a)])
parseChxHarmonyChord :: P.XParse ChxHarmonyChord
parseChxHarmonyChord =
HarmonyChordRoot
<$> (P.xchild (P.name "root") (parseRoot))
<|> HarmonyChordFunction
<$> (P.xchild (P.name "function") (parseStyleText))
-- | Smart constructor for 'HarmonyChordRoot'
mkHarmonyChordRoot :: Root -> ChxHarmonyChord
mkHarmonyChordRoot a = HarmonyChordRoot a
-- | Smart constructor for 'HarmonyChordFunction'
mkHarmonyChordFunction :: StyleText -> ChxHarmonyChord
mkHarmonyChordFunction a = HarmonyChordFunction a
-- | @key@ /(choice)/
data ChxKey =
KeyTraditionalKey {
keyTraditionalKey :: TraditionalKey
}
| KeyNonTraditionalKey {
keyNonTraditionalKey :: [NonTraditionalKey]
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml ChxKey where
emitXml (KeyTraditionalKey a) =
XReps [emitXml a]
emitXml (KeyNonTraditionalKey a) =
XReps [emitXml a]
parseChxKey :: P.XParse ChxKey
parseChxKey =
KeyTraditionalKey
<$> parseTraditionalKey
<|> KeyNonTraditionalKey
<$> P.many (parseNonTraditionalKey)
-- | Smart constructor for 'KeyTraditionalKey'
mkKeyTraditionalKey :: TraditionalKey -> ChxKey
mkKeyTraditionalKey a = KeyTraditionalKey a
-- | Smart constructor for 'KeyNonTraditionalKey'
mkKeyNonTraditionalKey :: ChxKey
mkKeyNonTraditionalKey = KeyNonTraditionalKey []
-- | @lyric@ /(choice)/
data ChxLyric =
LyricSyllabic {
lyricSyllabic :: (Maybe Syllabic) -- ^ /syllabic/ child element
, lyricText :: TextElementData -- ^ /text/ child element
, chxlyricLyric :: [SeqLyric]
, lyricExtend :: (Maybe Extend) -- ^ /extend/ child element
}
| LyricExtend {
lyricExtend1 :: Extend -- ^ /extend/ child element
}
| LyricLaughing {
lyricLaughing :: Empty -- ^ /laughing/ child element
}
| LyricHumming {
lyricHumming :: Empty -- ^ /humming/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml ChxLyric where
emitXml (LyricSyllabic a b c d) =
XContent XEmpty
[]
([maybe XEmpty (XElement (QN "syllabic" Nothing).emitXml) a] ++
[XElement (QN "text" Nothing) (emitXml b)] ++
[emitXml c] ++
[maybe XEmpty (XElement (QN "extend" Nothing).emitXml) d])
emitXml (LyricExtend a) =
XContent XEmpty
[]
([XElement (QN "extend" Nothing) (emitXml a)])
emitXml (LyricLaughing a) =
XContent XEmpty
[]
([XElement (QN "laughing" Nothing) (emitXml a)])
emitXml (LyricHumming a) =
XContent XEmpty
[]
([XElement (QN "humming" Nothing) (emitXml a)])
parseChxLyric :: P.XParse ChxLyric
parseChxLyric =
LyricSyllabic
<$> P.optional (P.xchild (P.name "syllabic") (P.xtext >>= parseSyllabic))
<*> (P.xchild (P.name "text") (parseTextElementData))
<*> P.many (parseSeqLyric)
<*> P.optional (P.xchild (P.name "extend") (parseExtend))
<|> LyricExtend
<$> (P.xchild (P.name "extend") (parseExtend))
<|> LyricLaughing
<$> (P.xchild (P.name "laughing") (parseEmpty))
<|> LyricHumming
<$> (P.xchild (P.name "humming") (parseEmpty))
-- | Smart constructor for 'LyricSyllabic'
mkLyricSyllabic :: TextElementData -> ChxLyric
mkLyricSyllabic b = LyricSyllabic Nothing b [] Nothing
-- | Smart constructor for 'LyricExtend'
mkLyricExtend :: Extend -> ChxLyric
mkLyricExtend a = LyricExtend a
-- | Smart constructor for 'LyricLaughing'
mkLyricLaughing :: Empty -> ChxLyric
mkLyricLaughing a = LyricLaughing a
-- | Smart constructor for 'LyricHumming'
mkLyricHumming :: Empty -> ChxLyric
mkLyricHumming a = LyricHumming a
-- | @measure-style@ /(choice)/
data ChxMeasureStyle =
MeasureStyleMultipleRest {
measureStyleMultipleRest :: MultipleRest -- ^ /multiple-rest/ child element
}
| MeasureStyleMeasureRepeat {
measureStyleMeasureRepeat :: MeasureRepeat -- ^ /measure-repeat/ child element
}
| MeasureStyleBeatRepeat {
measureStyleBeatRepeat :: BeatRepeat -- ^ /beat-repeat/ child element
}
| MeasureStyleSlash {
measureStyleSlash :: CmpSlash -- ^ /slash/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml ChxMeasureStyle where
emitXml (MeasureStyleMultipleRest a) =
XContent XEmpty
[]
([XElement (QN "multiple-rest" Nothing) (emitXml a)])
emitXml (MeasureStyleMeasureRepeat a) =
XContent XEmpty
[]
([XElement (QN "measure-repeat" Nothing) (emitXml a)])
emitXml (MeasureStyleBeatRepeat a) =
XContent XEmpty
[]
([XElement (QN "beat-repeat" Nothing) (emitXml a)])
emitXml (MeasureStyleSlash a) =
XContent XEmpty
[]
([XElement (QN "slash" Nothing) (emitXml a)])
parseChxMeasureStyle :: P.XParse ChxMeasureStyle
parseChxMeasureStyle =
MeasureStyleMultipleRest
<$> (P.xchild (P.name "multiple-rest") (parseMultipleRest))
<|> MeasureStyleMeasureRepeat
<$> (P.xchild (P.name "measure-repeat") (parseMeasureRepeat))
<|> MeasureStyleBeatRepeat
<$> (P.xchild (P.name "beat-repeat") (parseBeatRepeat))
<|> MeasureStyleSlash
<$> (P.xchild (P.name "slash") (parseCmpSlash))
-- | Smart constructor for 'MeasureStyleMultipleRest'
mkMeasureStyleMultipleRest :: MultipleRest -> ChxMeasureStyle
mkMeasureStyleMultipleRest a = MeasureStyleMultipleRest a
-- | Smart constructor for 'MeasureStyleMeasureRepeat'
mkMeasureStyleMeasureRepeat :: MeasureRepeat -> ChxMeasureStyle
mkMeasureStyleMeasureRepeat a = MeasureStyleMeasureRepeat a
-- | Smart constructor for 'MeasureStyleBeatRepeat'
mkMeasureStyleBeatRepeat :: BeatRepeat -> ChxMeasureStyle
mkMeasureStyleBeatRepeat a = MeasureStyleBeatRepeat a
-- | Smart constructor for 'MeasureStyleSlash'
mkMeasureStyleSlash :: CmpSlash -> ChxMeasureStyle
mkMeasureStyleSlash a = MeasureStyleSlash a
-- | @metronome@ /(choice)/
data ChxMetronome0 =
MetronomePerMinute {
metronomePerMinute :: PerMinute -- ^ /per-minute/ child element
}
| MetronomeBeatUnit {
metronomeBeatUnit :: BeatUnit
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml ChxMetronome0 where
emitXml (MetronomePerMinute a) =
XContent XEmpty
[]
([XElement (QN "per-minute" Nothing) (emitXml a)])
emitXml (MetronomeBeatUnit a) =
XReps [emitXml a]
parseChxMetronome0 :: P.XParse ChxMetronome0
parseChxMetronome0 =
MetronomePerMinute
<$> (P.xchild (P.name "per-minute") (parsePerMinute))
<|> MetronomeBeatUnit
<$> parseBeatUnit
-- | Smart constructor for 'MetronomePerMinute'
mkMetronomePerMinute :: PerMinute -> ChxMetronome0
mkMetronomePerMinute a = MetronomePerMinute a
-- | Smart constructor for 'MetronomeBeatUnit'
mkMetronomeBeatUnit :: BeatUnit -> ChxMetronome0
mkMetronomeBeatUnit a = MetronomeBeatUnit a
-- | @metronome@ /(choice)/
-- mangled: 1
data ChxMetronome =
ChxMetronomeBeatUnit {
chxmetronomeBeatUnit :: BeatUnit
, chxmetronomeMetronome :: ChxMetronome0
}
| MetronomeMetronomeNote {
metronomeMetronomeNote :: [MetronomeNote] -- ^ /metronome-note/ child element
, metronomeMetronome1 :: (Maybe SeqMetronome)
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml ChxMetronome where
emitXml (ChxMetronomeBeatUnit a b) =
XReps [emitXml a,emitXml b]
emitXml (MetronomeMetronomeNote a b) =
XContent XEmpty
[]
(map (XElement (QN "metronome-note" Nothing).emitXml) a ++
[emitXml b])
parseChxMetronome :: P.XParse ChxMetronome
parseChxMetronome =
ChxMetronomeBeatUnit
<$> parseBeatUnit
<*> parseChxMetronome0
<|> MetronomeMetronomeNote
<$> P.many (P.xchild (P.name "metronome-note") (parseMetronomeNote))
<*> P.optional (parseSeqMetronome)
-- | Smart constructor for 'ChxMetronomeBeatUnit'
mkChxMetronomeBeatUnit :: BeatUnit -> ChxMetronome0 -> ChxMetronome
mkChxMetronomeBeatUnit a b = ChxMetronomeBeatUnit a b
-- | Smart constructor for 'MetronomeMetronomeNote'
mkMetronomeMetronomeNote :: ChxMetronome
mkMetronomeMetronomeNote = MetronomeMetronomeNote [] Nothing
-- | @music-data@ /(choice)/
data ChxMusicData =
MusicDataNote {
musicDataNote :: Note -- ^ /note/ child element
}
| MusicDataBackup {
musicDataBackup :: Backup -- ^ /backup/ child element
}
| MusicDataForward {
musicDataForward :: Forward -- ^ /forward/ child element
}
| MusicDataDirection {
musicDataDirection :: Direction -- ^ /direction/ child element
}
| MusicDataAttributes {
musicDataAttributes :: Attributes -- ^ /attributes/ child element
}
| MusicDataHarmony {
musicDataHarmony :: Harmony -- ^ /harmony/ child element
}
| MusicDataFiguredBass {
musicDataFiguredBass :: FiguredBass -- ^ /figured-bass/ child element
}
| MusicDataPrint {
musicDataPrint :: Print -- ^ /print/ child element
}
| MusicDataSound {
musicDataSound :: Sound -- ^ /sound/ child element
}
| MusicDataBarline {
musicDataBarline :: Barline -- ^ /barline/ child element
}
| MusicDataGrouping {
musicDataGrouping :: Grouping -- ^ /grouping/ child element
}
| MusicDataLink {
musicDataLink :: Link -- ^ /link/ child element
}
| MusicDataBookmark {
musicDataBookmark :: Bookmark -- ^ /bookmark/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml ChxMusicData where
emitXml (MusicDataNote a) =
XContent XEmpty
[]
([XElement (QN "note" Nothing) (emitXml a)])
emitXml (MusicDataBackup a) =
XContent XEmpty
[]
([XElement (QN "backup" Nothing) (emitXml a)])
emitXml (MusicDataForward a) =
XContent XEmpty
[]
([XElement (QN "forward" Nothing) (emitXml a)])
emitXml (MusicDataDirection a) =
XContent XEmpty
[]
([XElement (QN "direction" Nothing) (emitXml a)])
emitXml (MusicDataAttributes a) =
XContent XEmpty
[]
([XElement (QN "attributes" Nothing) (emitXml a)])
emitXml (MusicDataHarmony a) =
XContent XEmpty
[]
([XElement (QN "harmony" Nothing) (emitXml a)])
emitXml (MusicDataFiguredBass a) =
XContent XEmpty
[]
([XElement (QN "figured-bass" Nothing) (emitXml a)])
emitXml (MusicDataPrint a) =
XContent XEmpty
[]
([XElement (QN "print" Nothing) (emitXml a)])
emitXml (MusicDataSound a) =
XContent XEmpty
[]
([XElement (QN "sound" Nothing) (emitXml a)])
emitXml (MusicDataBarline a) =
XContent XEmpty
[]
([XElement (QN "barline" Nothing) (emitXml a)])
emitXml (MusicDataGrouping a) =
XContent XEmpty
[]
([XElement (QN "grouping" Nothing) (emitXml a)])
emitXml (MusicDataLink a) =
XContent XEmpty
[]
([XElement (QN "link" Nothing) (emitXml a)])
emitXml (MusicDataBookmark a) =
XContent XEmpty
[]
([XElement (QN "bookmark" Nothing) (emitXml a)])
parseChxMusicData :: P.XParse ChxMusicData
parseChxMusicData =
MusicDataNote
<$> (P.xchild (P.name "note") (parseNote))
<|> MusicDataBackup
<$> (P.xchild (P.name "backup") (parseBackup))
<|> MusicDataForward
<$> (P.xchild (P.name "forward") (parseForward))
<|> MusicDataDirection
<$> (P.xchild (P.name "direction") (parseDirection))
<|> MusicDataAttributes
<$> (P.xchild (P.name "attributes") (parseAttributes))
<|> MusicDataHarmony
<$> (P.xchild (P.name "harmony") (parseHarmony))
<|> MusicDataFiguredBass
<$> (P.xchild (P.name "figured-bass") (parseFiguredBass))
<|> MusicDataPrint
<$> (P.xchild (P.name "print") (parsePrint))
<|> MusicDataSound
<$> (P.xchild (P.name "sound") (parseSound))
<|> MusicDataBarline
<$> (P.xchild (P.name "barline") (parseBarline))
<|> MusicDataGrouping
<$> (P.xchild (P.name "grouping") (parseGrouping))
<|> MusicDataLink
<$> (P.xchild (P.name "link") (parseLink))
<|> MusicDataBookmark
<$> (P.xchild (P.name "bookmark") (parseBookmark))
-- | Smart constructor for 'MusicDataNote'
mkMusicDataNote :: Note -> ChxMusicData
mkMusicDataNote a = MusicDataNote a
-- | Smart constructor for 'MusicDataBackup'
mkMusicDataBackup :: Backup -> ChxMusicData
mkMusicDataBackup a = MusicDataBackup a
-- | Smart constructor for 'MusicDataForward'
mkMusicDataForward :: Forward -> ChxMusicData
mkMusicDataForward a = MusicDataForward a
-- | Smart constructor for 'MusicDataDirection'
mkMusicDataDirection :: Direction -> ChxMusicData
mkMusicDataDirection a = MusicDataDirection a
-- | Smart constructor for 'MusicDataAttributes'
mkMusicDataAttributes :: Attributes -> ChxMusicData
mkMusicDataAttributes a = MusicDataAttributes a
-- | Smart constructor for 'MusicDataHarmony'
mkMusicDataHarmony :: Harmony -> ChxMusicData
mkMusicDataHarmony a = MusicDataHarmony a
-- | Smart constructor for 'MusicDataFiguredBass'
mkMusicDataFiguredBass :: FiguredBass -> ChxMusicData
mkMusicDataFiguredBass a = MusicDataFiguredBass a
-- | Smart constructor for 'MusicDataPrint'
mkMusicDataPrint :: Print -> ChxMusicData
mkMusicDataPrint a = MusicDataPrint a
-- | Smart constructor for 'MusicDataSound'
mkMusicDataSound :: Sound -> ChxMusicData
mkMusicDataSound a = MusicDataSound a
-- | Smart constructor for 'MusicDataBarline'
mkMusicDataBarline :: Barline -> ChxMusicData
mkMusicDataBarline a = MusicDataBarline a
-- | Smart constructor for 'MusicDataGrouping'
mkMusicDataGrouping :: Grouping -> ChxMusicData
mkMusicDataGrouping a = MusicDataGrouping a
-- | Smart constructor for 'MusicDataLink'
mkMusicDataLink :: Link -> ChxMusicData
mkMusicDataLink a = MusicDataLink a
-- | Smart constructor for 'MusicDataBookmark'
mkMusicDataBookmark :: Bookmark -> ChxMusicData
mkMusicDataBookmark a = MusicDataBookmark a
-- | @name-display@ /(choice)/
data ChxNameDisplay =
NameDisplayDisplayText {
nameDisplayDisplayText :: FormattedText -- ^ /display-text/ child element
}
| NameDisplayAccidentalText {
nameDisplayAccidentalText :: AccidentalText -- ^ /accidental-text/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml ChxNameDisplay where
emitXml (NameDisplayDisplayText a) =
XContent XEmpty
[]
([XElement (QN "display-text" Nothing) (emitXml a)])
emitXml (NameDisplayAccidentalText a) =
XContent XEmpty
[]
([XElement (QN "accidental-text" Nothing) (emitXml a)])
parseChxNameDisplay :: P.XParse ChxNameDisplay
parseChxNameDisplay =
NameDisplayDisplayText
<$> (P.xchild (P.name "display-text") (parseFormattedText))
<|> NameDisplayAccidentalText
<$> (P.xchild (P.name "accidental-text") (parseAccidentalText))
-- | Smart constructor for 'NameDisplayDisplayText'
mkNameDisplayDisplayText :: FormattedText -> ChxNameDisplay
mkNameDisplayDisplayText a = NameDisplayDisplayText a
-- | Smart constructor for 'NameDisplayAccidentalText'
mkNameDisplayAccidentalText :: AccidentalText -> ChxNameDisplay
mkNameDisplayAccidentalText a = NameDisplayAccidentalText a
-- | @notations@ /(choice)/
data ChxNotations =
NotationsTied {
notationsTied :: Tied -- ^ /tied/ child element
}
| NotationsSlur {
notationsSlur :: Slur -- ^ /slur/ child element
}
| NotationsTuplet {
notationsTuplet :: Tuplet -- ^ /tuplet/ child element
}
| NotationsGlissando {
notationsGlissando :: Glissando -- ^ /glissando/ child element
}
| NotationsSlide {
notationsSlide :: Slide -- ^ /slide/ child element
}
| NotationsOrnaments {
notationsOrnaments :: Ornaments -- ^ /ornaments/ child element
}
| NotationsTechnical {
notationsTechnical :: Technical -- ^ /technical/ child element
}
| NotationsArticulations {
notationsArticulations :: Articulations -- ^ /articulations/ child element
}
| NotationsDynamics {
notationsDynamics :: Dynamics -- ^ /dynamics/ child element
}
| NotationsFermata {
notationsFermata :: Fermata -- ^ /fermata/ child element
}
| NotationsArpeggiate {
notationsArpeggiate :: Arpeggiate -- ^ /arpeggiate/ child element
}
| NotationsNonArpeggiate {
notationsNonArpeggiate :: NonArpeggiate -- ^ /non-arpeggiate/ child element
}
| NotationsAccidentalMark {
notationsAccidentalMark :: AccidentalMark -- ^ /accidental-mark/ child element
}
| NotationsOtherNotation {
notationsOtherNotation :: OtherNotation -- ^ /other-notation/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml ChxNotations where
emitXml (NotationsTied a) =
XContent XEmpty
[]
([XElement (QN "tied" Nothing) (emitXml a)])
emitXml (NotationsSlur a) =
XContent XEmpty
[]
([XElement (QN "slur" Nothing) (emitXml a)])
emitXml (NotationsTuplet a) =
XContent XEmpty
[]
([XElement (QN "tuplet" Nothing) (emitXml a)])
emitXml (NotationsGlissando a) =
XContent XEmpty
[]
([XElement (QN "glissando" Nothing) (emitXml a)])
emitXml (NotationsSlide a) =
XContent XEmpty
[]
([XElement (QN "slide" Nothing) (emitXml a)])
emitXml (NotationsOrnaments a) =
XContent XEmpty
[]
([XElement (QN "ornaments" Nothing) (emitXml a)])
emitXml (NotationsTechnical a) =
XContent XEmpty
[]
([XElement (QN "technical" Nothing) (emitXml a)])
emitXml (NotationsArticulations a) =
XContent XEmpty
[]
([XElement (QN "articulations" Nothing) (emitXml a)])
emitXml (NotationsDynamics a) =
XContent XEmpty
[]
([XElement (QN "dynamics" Nothing) (emitXml a)])
emitXml (NotationsFermata a) =
XContent XEmpty
[]
([XElement (QN "fermata" Nothing) (emitXml a)])
emitXml (NotationsArpeggiate a) =
XContent XEmpty
[]
([XElement (QN "arpeggiate" Nothing) (emitXml a)])
emitXml (NotationsNonArpeggiate a) =
XContent XEmpty
[]
([XElement (QN "non-arpeggiate" Nothing) (emitXml a)])
emitXml (NotationsAccidentalMark a) =
XContent XEmpty
[]
([XElement (QN "accidental-mark" Nothing) (emitXml a)])
emitXml (NotationsOtherNotation a) =
XContent XEmpty
[]
([XElement (QN "other-notation" Nothing) (emitXml a)])
parseChxNotations :: P.XParse ChxNotations
parseChxNotations =
NotationsTied
<$> (P.xchild (P.name "tied") (parseTied))
<|> NotationsSlur
<$> (P.xchild (P.name "slur") (parseSlur))
<|> NotationsTuplet
<$> (P.xchild (P.name "tuplet") (parseTuplet))
<|> NotationsGlissando
<$> (P.xchild (P.name "glissando") (parseGlissando))
<|> NotationsSlide
<$> (P.xchild (P.name "slide") (parseSlide))
<|> NotationsOrnaments
<$> (P.xchild (P.name "ornaments") (parseOrnaments))
<|> NotationsTechnical
<$> (P.xchild (P.name "technical") (parseTechnical))
<|> NotationsArticulations
<$> (P.xchild (P.name "articulations") (parseArticulations))
<|> NotationsDynamics
<$> (P.xchild (P.name "dynamics") (parseDynamics))
<|> NotationsFermata
<$> (P.xchild (P.name "fermata") (parseFermata))
<|> NotationsArpeggiate
<$> (P.xchild (P.name "arpeggiate") (parseArpeggiate))
<|> NotationsNonArpeggiate
<$> (P.xchild (P.name "non-arpeggiate") (parseNonArpeggiate))
<|> NotationsAccidentalMark
<$> (P.xchild (P.name "accidental-mark") (parseAccidentalMark))
<|> NotationsOtherNotation
<$> (P.xchild (P.name "other-notation") (parseOtherNotation))
-- | Smart constructor for 'NotationsTied'
mkNotationsTied :: Tied -> ChxNotations
mkNotationsTied a = NotationsTied a
-- | Smart constructor for 'NotationsSlur'
mkNotationsSlur :: Slur -> ChxNotations
mkNotationsSlur a = NotationsSlur a
-- | Smart constructor for 'NotationsTuplet'
mkNotationsTuplet :: Tuplet -> ChxNotations
mkNotationsTuplet a = NotationsTuplet a
-- | Smart constructor for 'NotationsGlissando'
mkNotationsGlissando :: Glissando -> ChxNotations
mkNotationsGlissando a = NotationsGlissando a
-- | Smart constructor for 'NotationsSlide'
mkNotationsSlide :: Slide -> ChxNotations
mkNotationsSlide a = NotationsSlide a
-- | Smart constructor for 'NotationsOrnaments'
mkNotationsOrnaments :: Ornaments -> ChxNotations
mkNotationsOrnaments a = NotationsOrnaments a
-- | Smart constructor for 'NotationsTechnical'
mkNotationsTechnical :: Technical -> ChxNotations
mkNotationsTechnical a = NotationsTechnical a
-- | Smart constructor for 'NotationsArticulations'
mkNotationsArticulations :: Articulations -> ChxNotations
mkNotationsArticulations a = NotationsArticulations a
-- | Smart constructor for 'NotationsDynamics'
mkNotationsDynamics :: Dynamics -> ChxNotations
mkNotationsDynamics a = NotationsDynamics a
-- | Smart constructor for 'NotationsFermata'
mkNotationsFermata :: Fermata -> ChxNotations
mkNotationsFermata a = NotationsFermata a
-- | Smart constructor for 'NotationsArpeggiate'
mkNotationsArpeggiate :: Arpeggiate -> ChxNotations
mkNotationsArpeggiate a = NotationsArpeggiate a
-- | Smart constructor for 'NotationsNonArpeggiate'
mkNotationsNonArpeggiate :: NonArpeggiate -> ChxNotations
mkNotationsNonArpeggiate a = NotationsNonArpeggiate a
-- | Smart constructor for 'NotationsAccidentalMark'
mkNotationsAccidentalMark :: AccidentalMark -> ChxNotations
mkNotationsAccidentalMark a = NotationsAccidentalMark a
-- | Smart constructor for 'NotationsOtherNotation'
mkNotationsOtherNotation :: OtherNotation -> ChxNotations
mkNotationsOtherNotation a = NotationsOtherNotation a
-- | @note@ /(choice)/
data ChxNote =
NoteGrace {
noteGrace :: Grace -- ^ /grace/ child element
, noteFullNote :: GrpFullNote
, noteTie :: [Tie] -- ^ /tie/ child element
}
| NoteCue {
noteCue :: Empty -- ^ /cue/ child element
, noteFullNote1 :: GrpFullNote
, noteDuration :: Duration
}
| NoteFullNote {
noteFullNote2 :: GrpFullNote
, noteDuration1 :: Duration
, noteTie1 :: [Tie] -- ^ /tie/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml ChxNote where
emitXml (NoteGrace a b c) =
XContent XEmpty
[]
([XElement (QN "grace" Nothing) (emitXml a)] ++
[emitXml b] ++
map (XElement (QN "tie" Nothing).emitXml) c)
emitXml (NoteCue a b c) =
XContent XEmpty
[]
([XElement (QN "cue" Nothing) (emitXml a)] ++
[emitXml b] ++
[emitXml c])
emitXml (NoteFullNote a b c) =
XContent XEmpty
[]
([emitXml a] ++
[emitXml b] ++
map (XElement (QN "tie" Nothing).emitXml) c)
parseChxNote :: P.XParse ChxNote
parseChxNote =
NoteGrace
<$> (P.xchild (P.name "grace") (parseGrace))
<*> parseGrpFullNote
<*> P.many (P.xchild (P.name "tie") (parseTie))
<|> NoteCue
<$> (P.xchild (P.name "cue") (parseEmpty))
<*> parseGrpFullNote
<*> parseDuration
<|> NoteFullNote
<$> parseGrpFullNote
<*> parseDuration
<*> P.many (P.xchild (P.name "tie") (parseTie))
-- | Smart constructor for 'NoteGrace'
mkNoteGrace :: Grace -> GrpFullNote -> ChxNote
mkNoteGrace a b = NoteGrace a b []
-- | Smart constructor for 'NoteCue'
mkNoteCue :: Empty -> GrpFullNote -> Duration -> ChxNote
mkNoteCue a b c = NoteCue a b c
-- | Smart constructor for 'NoteFullNote'
mkNoteFullNote :: GrpFullNote -> Duration -> ChxNote
mkNoteFullNote a b = NoteFullNote a b []
-- | @notehead-text@ /(choice)/
data ChxNoteheadText =
NoteheadTextDisplayText {
noteheadTextDisplayText :: FormattedText -- ^ /display-text/ child element
}
| NoteheadTextAccidentalText {
noteheadTextAccidentalText :: AccidentalText -- ^ /accidental-text/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml ChxNoteheadText where
emitXml (NoteheadTextDisplayText a) =
XContent XEmpty
[]
([XElement (QN "display-text" Nothing) (emitXml a)])
emitXml (NoteheadTextAccidentalText a) =
XContent XEmpty
[]
([XElement (QN "accidental-text" Nothing) (emitXml a)])
parseChxNoteheadText :: P.XParse ChxNoteheadText
parseChxNoteheadText =
NoteheadTextDisplayText
<$> (P.xchild (P.name "display-text") (parseFormattedText))
<|> NoteheadTextAccidentalText
<$> (P.xchild (P.name "accidental-text") (parseAccidentalText))
-- | Smart constructor for 'NoteheadTextDisplayText'
mkNoteheadTextDisplayText :: FormattedText -> ChxNoteheadText
mkNoteheadTextDisplayText a = NoteheadTextDisplayText a
-- | Smart constructor for 'NoteheadTextAccidentalText'
mkNoteheadTextAccidentalText :: AccidentalText -> ChxNoteheadText
mkNoteheadTextAccidentalText a = NoteheadTextAccidentalText a
-- | @ornaments@ /(choice)/
data ChxOrnaments =
OrnamentsTrillMark {
ornamentsTrillMark :: EmptyTrillSound -- ^ /trill-mark/ child element
}
| OrnamentsTurn {
ornamentsTurn :: HorizontalTurn -- ^ /turn/ child element
}
| OrnamentsDelayedTurn {
ornamentsDelayedTurn :: HorizontalTurn -- ^ /delayed-turn/ child element
}
| OrnamentsInvertedTurn {
ornamentsInvertedTurn :: HorizontalTurn -- ^ /inverted-turn/ child element
}
| OrnamentsDelayedInvertedTurn {
ornamentsDelayedInvertedTurn :: HorizontalTurn -- ^ /delayed-inverted-turn/ child element
}
| OrnamentsVerticalTurn {
ornamentsVerticalTurn :: EmptyTrillSound -- ^ /vertical-turn/ child element
}
| OrnamentsShake {
ornamentsShake :: EmptyTrillSound -- ^ /shake/ child element
}
| OrnamentsWavyLine {
ornamentsWavyLine :: WavyLine -- ^ /wavy-line/ child element
}
| OrnamentsMordent {
ornamentsMordent :: Mordent -- ^ /mordent/ child element
}
| OrnamentsInvertedMordent {
ornamentsInvertedMordent :: Mordent -- ^ /inverted-mordent/ child element
}
| OrnamentsSchleifer {
ornamentsSchleifer :: EmptyPlacement -- ^ /schleifer/ child element
}
| OrnamentsTremolo {
ornamentsTremolo :: Tremolo -- ^ /tremolo/ child element
}
| OrnamentsOtherOrnament {
ornamentsOtherOrnament :: PlacementText -- ^ /other-ornament/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml ChxOrnaments where
emitXml (OrnamentsTrillMark a) =
XContent XEmpty
[]
([XElement (QN "trill-mark" Nothing) (emitXml a)])
emitXml (OrnamentsTurn a) =
XContent XEmpty
[]
([XElement (QN "turn" Nothing) (emitXml a)])
emitXml (OrnamentsDelayedTurn a) =
XContent XEmpty
[]
([XElement (QN "delayed-turn" Nothing) (emitXml a)])
emitXml (OrnamentsInvertedTurn a) =
XContent XEmpty
[]
([XElement (QN "inverted-turn" Nothing) (emitXml a)])
emitXml (OrnamentsDelayedInvertedTurn a) =
XContent XEmpty
[]
([XElement (QN "delayed-inverted-turn" Nothing) (emitXml a)])
emitXml (OrnamentsVerticalTurn a) =
XContent XEmpty
[]
([XElement (QN "vertical-turn" Nothing) (emitXml a)])
emitXml (OrnamentsShake a) =
XContent XEmpty
[]
([XElement (QN "shake" Nothing) (emitXml a)])
emitXml (OrnamentsWavyLine a) =
XContent XEmpty
[]
([XElement (QN "wavy-line" Nothing) (emitXml a)])
emitXml (OrnamentsMordent a) =
XContent XEmpty
[]
([XElement (QN "mordent" Nothing) (emitXml a)])
emitXml (OrnamentsInvertedMordent a) =
XContent XEmpty
[]
([XElement (QN "inverted-mordent" Nothing) (emitXml a)])
emitXml (OrnamentsSchleifer a) =
XContent XEmpty
[]
([XElement (QN "schleifer" Nothing) (emitXml a)])
emitXml (OrnamentsTremolo a) =
XContent XEmpty
[]
([XElement (QN "tremolo" Nothing) (emitXml a)])
emitXml (OrnamentsOtherOrnament a) =
XContent XEmpty
[]
([XElement (QN "other-ornament" Nothing) (emitXml a)])
parseChxOrnaments :: P.XParse ChxOrnaments
parseChxOrnaments =
OrnamentsTrillMark
<$> (P.xchild (P.name "trill-mark") (parseEmptyTrillSound))
<|> OrnamentsTurn
<$> (P.xchild (P.name "turn") (parseHorizontalTurn))
<|> OrnamentsDelayedTurn
<$> (P.xchild (P.name "delayed-turn") (parseHorizontalTurn))
<|> OrnamentsInvertedTurn
<$> (P.xchild (P.name "inverted-turn") (parseHorizontalTurn))
<|> OrnamentsDelayedInvertedTurn
<$> (P.xchild (P.name "delayed-inverted-turn") (parseHorizontalTurn))
<|> OrnamentsVerticalTurn
<$> (P.xchild (P.name "vertical-turn") (parseEmptyTrillSound))
<|> OrnamentsShake
<$> (P.xchild (P.name "shake") (parseEmptyTrillSound))
<|> OrnamentsWavyLine
<$> (P.xchild (P.name "wavy-line") (parseWavyLine))
<|> OrnamentsMordent
<$> (P.xchild (P.name "mordent") (parseMordent))
<|> OrnamentsInvertedMordent
<$> (P.xchild (P.name "inverted-mordent") (parseMordent))
<|> OrnamentsSchleifer
<$> (P.xchild (P.name "schleifer") (parseEmptyPlacement))
<|> OrnamentsTremolo
<$> (P.xchild (P.name "tremolo") (parseTremolo))
<|> OrnamentsOtherOrnament
<$> (P.xchild (P.name "other-ornament") (parsePlacementText))
-- | Smart constructor for 'OrnamentsTrillMark'
mkOrnamentsTrillMark :: EmptyTrillSound -> ChxOrnaments
mkOrnamentsTrillMark a = OrnamentsTrillMark a
-- | Smart constructor for 'OrnamentsTurn'
mkOrnamentsTurn :: HorizontalTurn -> ChxOrnaments
mkOrnamentsTurn a = OrnamentsTurn a
-- | Smart constructor for 'OrnamentsDelayedTurn'
mkOrnamentsDelayedTurn :: HorizontalTurn -> ChxOrnaments
mkOrnamentsDelayedTurn a = OrnamentsDelayedTurn a
-- | Smart constructor for 'OrnamentsInvertedTurn'
mkOrnamentsInvertedTurn :: HorizontalTurn -> ChxOrnaments
mkOrnamentsInvertedTurn a = OrnamentsInvertedTurn a
-- | Smart constructor for 'OrnamentsDelayedInvertedTurn'
mkOrnamentsDelayedInvertedTurn :: HorizontalTurn -> ChxOrnaments
mkOrnamentsDelayedInvertedTurn a = OrnamentsDelayedInvertedTurn a
-- | Smart constructor for 'OrnamentsVerticalTurn'
mkOrnamentsVerticalTurn :: EmptyTrillSound -> ChxOrnaments
mkOrnamentsVerticalTurn a = OrnamentsVerticalTurn a
-- | Smart constructor for 'OrnamentsShake'
mkOrnamentsShake :: EmptyTrillSound -> ChxOrnaments
mkOrnamentsShake a = OrnamentsShake a
-- | Smart constructor for 'OrnamentsWavyLine'
mkOrnamentsWavyLine :: WavyLine -> ChxOrnaments
mkOrnamentsWavyLine a = OrnamentsWavyLine a
-- | Smart constructor for 'OrnamentsMordent'
mkOrnamentsMordent :: Mordent -> ChxOrnaments
mkOrnamentsMordent a = OrnamentsMordent a
-- | Smart constructor for 'OrnamentsInvertedMordent'
mkOrnamentsInvertedMordent :: Mordent -> ChxOrnaments
mkOrnamentsInvertedMordent a = OrnamentsInvertedMordent a
-- | Smart constructor for 'OrnamentsSchleifer'
mkOrnamentsSchleifer :: EmptyPlacement -> ChxOrnaments
mkOrnamentsSchleifer a = OrnamentsSchleifer a
-- | Smart constructor for 'OrnamentsTremolo'
mkOrnamentsTremolo :: Tremolo -> ChxOrnaments
mkOrnamentsTremolo a = OrnamentsTremolo a
-- | Smart constructor for 'OrnamentsOtherOrnament'
mkOrnamentsOtherOrnament :: PlacementText -> ChxOrnaments
mkOrnamentsOtherOrnament a = OrnamentsOtherOrnament a
-- | @part-list@ /(choice)/
data ChxPartList =
PartListPartGroup {
chxpartListPartGroup :: GrpPartGroup
}
| PartListScorePart {
chxpartListScorePart :: ScorePart
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml ChxPartList where
emitXml (PartListPartGroup a) =
XReps [emitXml a]
emitXml (PartListScorePart a) =
XReps [emitXml a]
parseChxPartList :: P.XParse ChxPartList
parseChxPartList =
PartListPartGroup
<$> parseGrpPartGroup
<|> PartListScorePart
<$> parseScorePart
-- | Smart constructor for 'PartListPartGroup'
mkPartListPartGroup :: GrpPartGroup -> ChxPartList
mkPartListPartGroup a = PartListPartGroup a
-- | Smart constructor for 'PartListScorePart'
mkPartListScorePart :: ScorePart -> ChxPartList
mkPartListScorePart a = PartListScorePart a
-- | @percussion@ /(choice)/
data ChxPercussion =
PercussionGlass {
percussionGlass :: Glass -- ^ /glass/ child element
}
| PercussionMetal {
percussionMetal :: Metal -- ^ /metal/ child element
}
| PercussionWood {
percussionWood :: Wood -- ^ /wood/ child element
}
| PercussionPitched {
percussionPitched :: Pitched -- ^ /pitched/ child element
}
| PercussionMembrane {
percussionMembrane :: Membrane -- ^ /membrane/ child element
}
| PercussionEffect {
percussionEffect :: Effect -- ^ /effect/ child element
}
| PercussionTimpani {
percussionTimpani :: Empty -- ^ /timpani/ child element
}
| PercussionBeater {
percussionBeater :: Beater -- ^ /beater/ child element
}
| PercussionStick {
percussionStick :: Stick -- ^ /stick/ child element
}
| PercussionStickLocation {
percussionStickLocation :: StickLocation -- ^ /stick-location/ child element
}
| PercussionOtherPercussion {
percussionOtherPercussion :: String -- ^ /other-percussion/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml ChxPercussion where
emitXml (PercussionGlass a) =
XContent XEmpty
[]
([XElement (QN "glass" Nothing) (emitXml a)])
emitXml (PercussionMetal a) =
XContent XEmpty
[]
([XElement (QN "metal" Nothing) (emitXml a)])
emitXml (PercussionWood a) =
XContent XEmpty
[]
([XElement (QN "wood" Nothing) (emitXml a)])
emitXml (PercussionPitched a) =
XContent XEmpty
[]
([XElement (QN "pitched" Nothing) (emitXml a)])
emitXml (PercussionMembrane a) =
XContent XEmpty
[]
([XElement (QN "membrane" Nothing) (emitXml a)])
emitXml (PercussionEffect a) =
XContent XEmpty
[]
([XElement (QN "effect" Nothing) (emitXml a)])
emitXml (PercussionTimpani a) =
XContent XEmpty
[]
([XElement (QN "timpani" Nothing) (emitXml a)])
emitXml (PercussionBeater a) =
XContent XEmpty
[]
([XElement (QN "beater" Nothing) (emitXml a)])
emitXml (PercussionStick a) =
XContent XEmpty
[]
([XElement (QN "stick" Nothing) (emitXml a)])
emitXml (PercussionStickLocation a) =
XContent XEmpty
[]
([XElement (QN "stick-location" Nothing) (emitXml a)])
emitXml (PercussionOtherPercussion a) =
XContent XEmpty
[]
([XElement (QN "other-percussion" Nothing) (emitXml a)])
parseChxPercussion :: P.XParse ChxPercussion
parseChxPercussion =
PercussionGlass
<$> (P.xchild (P.name "glass") (P.xtext >>= parseGlass))
<|> PercussionMetal
<$> (P.xchild (P.name "metal") (P.xtext >>= parseMetal))
<|> PercussionWood
<$> (P.xchild (P.name "wood") (P.xtext >>= parseWood))
<|> PercussionPitched
<$> (P.xchild (P.name "pitched") (P.xtext >>= parsePitched))
<|> PercussionMembrane
<$> (P.xchild (P.name "membrane") (P.xtext >>= parseMembrane))
<|> PercussionEffect
<$> (P.xchild (P.name "effect") (P.xtext >>= parseEffect))
<|> PercussionTimpani
<$> (P.xchild (P.name "timpani") (parseEmpty))
<|> PercussionBeater
<$> (P.xchild (P.name "beater") (parseBeater))
<|> PercussionStick
<$> (P.xchild (P.name "stick") (parseStick))
<|> PercussionStickLocation
<$> (P.xchild (P.name "stick-location") (P.xtext >>= parseStickLocation))
<|> PercussionOtherPercussion
<$> (P.xchild (P.name "other-percussion") (P.xtext >>= return))
-- | Smart constructor for 'PercussionGlass'
mkPercussionGlass :: Glass -> ChxPercussion
mkPercussionGlass a = PercussionGlass a
-- | Smart constructor for 'PercussionMetal'
mkPercussionMetal :: Metal -> ChxPercussion
mkPercussionMetal a = PercussionMetal a
-- | Smart constructor for 'PercussionWood'
mkPercussionWood :: Wood -> ChxPercussion
mkPercussionWood a = PercussionWood a
-- | Smart constructor for 'PercussionPitched'
mkPercussionPitched :: Pitched -> ChxPercussion
mkPercussionPitched a = PercussionPitched a
-- | Smart constructor for 'PercussionMembrane'
mkPercussionMembrane :: Membrane -> ChxPercussion
mkPercussionMembrane a = PercussionMembrane a
-- | Smart constructor for 'PercussionEffect'
mkPercussionEffect :: Effect -> ChxPercussion
mkPercussionEffect a = PercussionEffect a
-- | Smart constructor for 'PercussionTimpani'
mkPercussionTimpani :: Empty -> ChxPercussion
mkPercussionTimpani a = PercussionTimpani a
-- | Smart constructor for 'PercussionBeater'
mkPercussionBeater :: Beater -> ChxPercussion
mkPercussionBeater a = PercussionBeater a
-- | Smart constructor for 'PercussionStick'
mkPercussionStick :: Stick -> ChxPercussion
mkPercussionStick a = PercussionStick a
-- | Smart constructor for 'PercussionStickLocation'
mkPercussionStickLocation :: StickLocation -> ChxPercussion
mkPercussionStickLocation a = PercussionStickLocation a
-- | Smart constructor for 'PercussionOtherPercussion'
mkPercussionOtherPercussion :: String -> ChxPercussion
mkPercussionOtherPercussion a = PercussionOtherPercussion a
-- | @play@ /(choice)/
data ChxPlay =
PlayIpa {
playIpa :: String -- ^ /ipa/ child element
}
| PlayMute {
playMute :: Mute -- ^ /mute/ child element
}
| PlaySemiPitched {
playSemiPitched :: SemiPitched -- ^ /semi-pitched/ child element
}
| PlayOtherPlay {
playOtherPlay :: OtherPlay -- ^ /other-play/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml ChxPlay where
emitXml (PlayIpa a) =
XContent XEmpty
[]
([XElement (QN "ipa" Nothing) (emitXml a)])
emitXml (PlayMute a) =
XContent XEmpty
[]
([XElement (QN "mute" Nothing) (emitXml a)])
emitXml (PlaySemiPitched a) =
XContent XEmpty
[]
([XElement (QN "semi-pitched" Nothing) (emitXml a)])
emitXml (PlayOtherPlay a) =
XContent XEmpty
[]
([XElement (QN "other-play" Nothing) (emitXml a)])
parseChxPlay :: P.XParse ChxPlay
parseChxPlay =
PlayIpa
<$> (P.xchild (P.name "ipa") (P.xtext >>= return))
<|> PlayMute
<$> (P.xchild (P.name "mute") (P.xtext >>= parseMute))
<|> PlaySemiPitched
<$> (P.xchild (P.name "semi-pitched") (P.xtext >>= parseSemiPitched))
<|> PlayOtherPlay
<$> (P.xchild (P.name "other-play") (parseOtherPlay))
-- | Smart constructor for 'PlayIpa'
mkPlayIpa :: String -> ChxPlay
mkPlayIpa a = PlayIpa a
-- | Smart constructor for 'PlayMute'
mkPlayMute :: Mute -> ChxPlay
mkPlayMute a = PlayMute a
-- | Smart constructor for 'PlaySemiPitched'
mkPlaySemiPitched :: SemiPitched -> ChxPlay
mkPlaySemiPitched a = PlaySemiPitched a
-- | Smart constructor for 'PlayOtherPlay'
mkPlayOtherPlay :: OtherPlay -> ChxPlay
mkPlayOtherPlay a = PlayOtherPlay a
-- | @score-instrument@ /(choice)/
data ChxScoreInstrument =
ScoreInstrumentSolo {
scoreInstrumentSolo :: Empty -- ^ /solo/ child element
}
| ScoreInstrumentEnsemble {
scoreInstrumentEnsemble :: PositiveIntegerOrEmpty -- ^ /ensemble/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml ChxScoreInstrument where
emitXml (ScoreInstrumentSolo a) =
XContent XEmpty
[]
([XElement (QN "solo" Nothing) (emitXml a)])
emitXml (ScoreInstrumentEnsemble a) =
XContent XEmpty
[]
([XElement (QN "ensemble" Nothing) (emitXml a)])
parseChxScoreInstrument :: P.XParse ChxScoreInstrument
parseChxScoreInstrument =
ScoreInstrumentSolo
<$> (P.xchild (P.name "solo") (parseEmpty))
<|> ScoreInstrumentEnsemble
<$> (P.xchild (P.name "ensemble") (P.xtext >>= parsePositiveIntegerOrEmpty))
-- | Smart constructor for 'ScoreInstrumentSolo'
mkScoreInstrumentSolo :: Empty -> ChxScoreInstrument
mkScoreInstrumentSolo a = ScoreInstrumentSolo a
-- | Smart constructor for 'ScoreInstrumentEnsemble'
mkScoreInstrumentEnsemble :: PositiveIntegerOrEmpty -> ChxScoreInstrument
mkScoreInstrumentEnsemble a = ScoreInstrumentEnsemble a
-- | @technical@ /(choice)/
data ChxTechnical =
TechnicalUpBow {
technicalUpBow :: EmptyPlacement -- ^ /up-bow/ child element
}
| TechnicalDownBow {
technicalDownBow :: EmptyPlacement -- ^ /down-bow/ child element
}
| TechnicalHarmonic {
technicalHarmonic :: Harmonic -- ^ /harmonic/ child element
}
| TechnicalOpenString {
technicalOpenString :: EmptyPlacement -- ^ /open-string/ child element
}
| TechnicalThumbPosition {
technicalThumbPosition :: EmptyPlacement -- ^ /thumb-position/ child element
}
| TechnicalFingering {
technicalFingering :: Fingering -- ^ /fingering/ child element
}
| TechnicalPluck {
technicalPluck :: PlacementText -- ^ /pluck/ child element
}
| TechnicalDoubleTongue {
technicalDoubleTongue :: EmptyPlacement -- ^ /double-tongue/ child element
}
| TechnicalTripleTongue {
technicalTripleTongue :: EmptyPlacement -- ^ /triple-tongue/ child element
}
| TechnicalStopped {
technicalStopped :: EmptyPlacement -- ^ /stopped/ child element
}
| TechnicalSnapPizzicato {
technicalSnapPizzicato :: EmptyPlacement -- ^ /snap-pizzicato/ child element
}
| TechnicalFret {
technicalFret :: Fret -- ^ /fret/ child element
}
| TechnicalString {
technicalString :: CmpString -- ^ /string/ child element
}
| TechnicalHammerOn {
technicalHammerOn :: HammerOnPullOff -- ^ /hammer-on/ child element
}
| TechnicalPullOff {
technicalPullOff :: HammerOnPullOff -- ^ /pull-off/ child element
}
| TechnicalBend {
technicalBend :: Bend -- ^ /bend/ child element
}
| TechnicalTap {
technicalTap :: PlacementText -- ^ /tap/ child element
}
| TechnicalHeel {
technicalHeel :: HeelToe -- ^ /heel/ child element
}
| TechnicalToe {
technicalToe :: HeelToe -- ^ /toe/ child element
}
| TechnicalFingernails {
technicalFingernails :: EmptyPlacement -- ^ /fingernails/ child element
}
| TechnicalHole {
technicalHole :: Hole -- ^ /hole/ child element
}
| TechnicalArrow {
technicalArrow :: Arrow -- ^ /arrow/ child element
}
| TechnicalHandbell {
technicalHandbell :: Handbell -- ^ /handbell/ child element
}
| TechnicalOtherTechnical {
technicalOtherTechnical :: PlacementText -- ^ /other-technical/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml ChxTechnical where
emitXml (TechnicalUpBow a) =
XContent XEmpty
[]
([XElement (QN "up-bow" Nothing) (emitXml a)])
emitXml (TechnicalDownBow a) =
XContent XEmpty
[]
([XElement (QN "down-bow" Nothing) (emitXml a)])
emitXml (TechnicalHarmonic a) =
XContent XEmpty
[]
([XElement (QN "harmonic" Nothing) (emitXml a)])
emitXml (TechnicalOpenString a) =
XContent XEmpty
[]
([XElement (QN "open-string" Nothing) (emitXml a)])
emitXml (TechnicalThumbPosition a) =
XContent XEmpty
[]
([XElement (QN "thumb-position" Nothing) (emitXml a)])
emitXml (TechnicalFingering a) =
XContent XEmpty
[]
([XElement (QN "fingering" Nothing) (emitXml a)])
emitXml (TechnicalPluck a) =
XContent XEmpty
[]
([XElement (QN "pluck" Nothing) (emitXml a)])
emitXml (TechnicalDoubleTongue a) =
XContent XEmpty
[]
([XElement (QN "double-tongue" Nothing) (emitXml a)])
emitXml (TechnicalTripleTongue a) =
XContent XEmpty
[]
([XElement (QN "triple-tongue" Nothing) (emitXml a)])
emitXml (TechnicalStopped a) =
XContent XEmpty
[]
([XElement (QN "stopped" Nothing) (emitXml a)])
emitXml (TechnicalSnapPizzicato a) =
XContent XEmpty
[]
([XElement (QN "snap-pizzicato" Nothing) (emitXml a)])
emitXml (TechnicalFret a) =
XContent XEmpty
[]
([XElement (QN "fret" Nothing) (emitXml a)])
emitXml (TechnicalString a) =
XContent XEmpty
[]
([XElement (QN "string" Nothing) (emitXml a)])
emitXml (TechnicalHammerOn a) =
XContent XEmpty
[]
([XElement (QN "hammer-on" Nothing) (emitXml a)])
emitXml (TechnicalPullOff a) =
XContent XEmpty
[]
([XElement (QN "pull-off" Nothing) (emitXml a)])
emitXml (TechnicalBend a) =
XContent XEmpty
[]
([XElement (QN "bend" Nothing) (emitXml a)])
emitXml (TechnicalTap a) =
XContent XEmpty
[]
([XElement (QN "tap" Nothing) (emitXml a)])
emitXml (TechnicalHeel a) =
XContent XEmpty
[]
([XElement (QN "heel" Nothing) (emitXml a)])
emitXml (TechnicalToe a) =
XContent XEmpty
[]
([XElement (QN "toe" Nothing) (emitXml a)])
emitXml (TechnicalFingernails a) =
XContent XEmpty
[]
([XElement (QN "fingernails" Nothing) (emitXml a)])
emitXml (TechnicalHole a) =
XContent XEmpty
[]
([XElement (QN "hole" Nothing) (emitXml a)])
emitXml (TechnicalArrow a) =
XContent XEmpty
[]
([XElement (QN "arrow" Nothing) (emitXml a)])
emitXml (TechnicalHandbell a) =
XContent XEmpty
[]
([XElement (QN "handbell" Nothing) (emitXml a)])
emitXml (TechnicalOtherTechnical a) =
XContent XEmpty
[]
([XElement (QN "other-technical" Nothing) (emitXml a)])
parseChxTechnical :: P.XParse ChxTechnical
parseChxTechnical =
TechnicalUpBow
<$> (P.xchild (P.name "up-bow") (parseEmptyPlacement))
<|> TechnicalDownBow
<$> (P.xchild (P.name "down-bow") (parseEmptyPlacement))
<|> TechnicalHarmonic
<$> (P.xchild (P.name "harmonic") (parseHarmonic))
<|> TechnicalOpenString
<$> (P.xchild (P.name "open-string") (parseEmptyPlacement))
<|> TechnicalThumbPosition
<$> (P.xchild (P.name "thumb-position") (parseEmptyPlacement))
<|> TechnicalFingering
<$> (P.xchild (P.name "fingering") (parseFingering))
<|> TechnicalPluck
<$> (P.xchild (P.name "pluck") (parsePlacementText))
<|> TechnicalDoubleTongue
<$> (P.xchild (P.name "double-tongue") (parseEmptyPlacement))
<|> TechnicalTripleTongue
<$> (P.xchild (P.name "triple-tongue") (parseEmptyPlacement))
<|> TechnicalStopped
<$> (P.xchild (P.name "stopped") (parseEmptyPlacement))
<|> TechnicalSnapPizzicato
<$> (P.xchild (P.name "snap-pizzicato") (parseEmptyPlacement))
<|> TechnicalFret
<$> (P.xchild (P.name "fret") (parseFret))
<|> TechnicalString
<$> (P.xchild (P.name "string") (parseCmpString))
<|> TechnicalHammerOn
<$> (P.xchild (P.name "hammer-on") (parseHammerOnPullOff))
<|> TechnicalPullOff
<$> (P.xchild (P.name "pull-off") (parseHammerOnPullOff))
<|> TechnicalBend
<$> (P.xchild (P.name "bend") (parseBend))
<|> TechnicalTap
<$> (P.xchild (P.name "tap") (parsePlacementText))
<|> TechnicalHeel
<$> (P.xchild (P.name "heel") (parseHeelToe))
<|> TechnicalToe
<$> (P.xchild (P.name "toe") (parseHeelToe))
<|> TechnicalFingernails
<$> (P.xchild (P.name "fingernails") (parseEmptyPlacement))
<|> TechnicalHole
<$> (P.xchild (P.name "hole") (parseHole))
<|> TechnicalArrow
<$> (P.xchild (P.name "arrow") (parseArrow))
<|> TechnicalHandbell
<$> (P.xchild (P.name "handbell") (parseHandbell))
<|> TechnicalOtherTechnical
<$> (P.xchild (P.name "other-technical") (parsePlacementText))
-- | Smart constructor for 'TechnicalUpBow'
mkTechnicalUpBow :: EmptyPlacement -> ChxTechnical
mkTechnicalUpBow a = TechnicalUpBow a
-- | Smart constructor for 'TechnicalDownBow'
mkTechnicalDownBow :: EmptyPlacement -> ChxTechnical
mkTechnicalDownBow a = TechnicalDownBow a
-- | Smart constructor for 'TechnicalHarmonic'
mkTechnicalHarmonic :: Harmonic -> ChxTechnical
mkTechnicalHarmonic a = TechnicalHarmonic a
-- | Smart constructor for 'TechnicalOpenString'
mkTechnicalOpenString :: EmptyPlacement -> ChxTechnical
mkTechnicalOpenString a = TechnicalOpenString a
-- | Smart constructor for 'TechnicalThumbPosition'
mkTechnicalThumbPosition :: EmptyPlacement -> ChxTechnical
mkTechnicalThumbPosition a = TechnicalThumbPosition a
-- | Smart constructor for 'TechnicalFingering'
mkTechnicalFingering :: Fingering -> ChxTechnical
mkTechnicalFingering a = TechnicalFingering a
-- | Smart constructor for 'TechnicalPluck'
mkTechnicalPluck :: PlacementText -> ChxTechnical
mkTechnicalPluck a = TechnicalPluck a
-- | Smart constructor for 'TechnicalDoubleTongue'
mkTechnicalDoubleTongue :: EmptyPlacement -> ChxTechnical
mkTechnicalDoubleTongue a = TechnicalDoubleTongue a
-- | Smart constructor for 'TechnicalTripleTongue'
mkTechnicalTripleTongue :: EmptyPlacement -> ChxTechnical
mkTechnicalTripleTongue a = TechnicalTripleTongue a
-- | Smart constructor for 'TechnicalStopped'
mkTechnicalStopped :: EmptyPlacement -> ChxTechnical
mkTechnicalStopped a = TechnicalStopped a
-- | Smart constructor for 'TechnicalSnapPizzicato'
mkTechnicalSnapPizzicato :: EmptyPlacement -> ChxTechnical
mkTechnicalSnapPizzicato a = TechnicalSnapPizzicato a
-- | Smart constructor for 'TechnicalFret'
mkTechnicalFret :: Fret -> ChxTechnical
mkTechnicalFret a = TechnicalFret a
-- | Smart constructor for 'TechnicalString'
mkTechnicalString :: CmpString -> ChxTechnical
mkTechnicalString a = TechnicalString a
-- | Smart constructor for 'TechnicalHammerOn'
mkTechnicalHammerOn :: HammerOnPullOff -> ChxTechnical
mkTechnicalHammerOn a = TechnicalHammerOn a
-- | Smart constructor for 'TechnicalPullOff'
mkTechnicalPullOff :: HammerOnPullOff -> ChxTechnical
mkTechnicalPullOff a = TechnicalPullOff a
-- | Smart constructor for 'TechnicalBend'
mkTechnicalBend :: Bend -> ChxTechnical
mkTechnicalBend a = TechnicalBend a
-- | Smart constructor for 'TechnicalTap'
mkTechnicalTap :: PlacementText -> ChxTechnical
mkTechnicalTap a = TechnicalTap a
-- | Smart constructor for 'TechnicalHeel'
mkTechnicalHeel :: HeelToe -> ChxTechnical
mkTechnicalHeel a = TechnicalHeel a
-- | Smart constructor for 'TechnicalToe'
mkTechnicalToe :: HeelToe -> ChxTechnical
mkTechnicalToe a = TechnicalToe a
-- | Smart constructor for 'TechnicalFingernails'
mkTechnicalFingernails :: EmptyPlacement -> ChxTechnical
mkTechnicalFingernails a = TechnicalFingernails a
-- | Smart constructor for 'TechnicalHole'
mkTechnicalHole :: Hole -> ChxTechnical
mkTechnicalHole a = TechnicalHole a
-- | Smart constructor for 'TechnicalArrow'
mkTechnicalArrow :: Arrow -> ChxTechnical
mkTechnicalArrow a = TechnicalArrow a
-- | Smart constructor for 'TechnicalHandbell'
mkTechnicalHandbell :: Handbell -> ChxTechnical
mkTechnicalHandbell a = TechnicalHandbell a
-- | Smart constructor for 'TechnicalOtherTechnical'
mkTechnicalOtherTechnical :: PlacementText -> ChxTechnical
mkTechnicalOtherTechnical a = TechnicalOtherTechnical a
-- | @time@ /(choice)/
data ChxTime =
TimeTimeSignature {
timeTimeSignature :: [TimeSignature]
, timeInterchangeable :: (Maybe Interchangeable) -- ^ /interchangeable/ child element
}
| TimeSenzaMisura {
timeSenzaMisura :: String -- ^ /senza-misura/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml ChxTime where
emitXml (TimeTimeSignature a b) =
XContent XEmpty
[]
([emitXml a] ++
[maybe XEmpty (XElement (QN "interchangeable" Nothing).emitXml) b])
emitXml (TimeSenzaMisura a) =
XContent XEmpty
[]
([XElement (QN "senza-misura" Nothing) (emitXml a)])
parseChxTime :: P.XParse ChxTime
parseChxTime =
TimeTimeSignature
<$> P.many (parseTimeSignature)
<*> P.optional (P.xchild (P.name "interchangeable") (parseInterchangeable))
<|> TimeSenzaMisura
<$> (P.xchild (P.name "senza-misura") (P.xtext >>= return))
-- | Smart constructor for 'TimeTimeSignature'
mkTimeTimeSignature :: ChxTime
mkTimeTimeSignature = TimeTimeSignature [] Nothing
-- | Smart constructor for 'TimeSenzaMisura'
mkTimeSenzaMisura :: String -> ChxTime
mkTimeSenzaMisura a = TimeSenzaMisura a
-- | @credit@ /(sequence)/
data SeqCredit =
SeqCredit {
seqcreditLink :: [Link] -- ^ /link/ child element
, seqcreditBookmark :: [Bookmark] -- ^ /bookmark/ child element
, seqcreditCreditWords :: FormattedText -- ^ /credit-words/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml SeqCredit where
emitXml (SeqCredit a b c) =
XContent XEmpty
[]
(map (XElement (QN "link" Nothing).emitXml) a ++
map (XElement (QN "bookmark" Nothing).emitXml) b ++
[XElement (QN "credit-words" Nothing) (emitXml c)])
parseSeqCredit :: P.XParse SeqCredit
parseSeqCredit =
SeqCredit
<$> P.many (P.xchild (P.name "link") (parseLink))
<*> P.many (P.xchild (P.name "bookmark") (parseBookmark))
<*> (P.xchild (P.name "credit-words") (parseFormattedText))
-- | Smart constructor for 'SeqCredit'
mkSeqCredit :: FormattedText -> SeqCredit
mkSeqCredit c = SeqCredit [] [] c
-- | @lyric@ /(sequence)/
data SeqLyric0 =
SeqLyric0 {
lyricElision :: TextFontColor -- ^ /elision/ child element
, seqlyricSyllabic :: (Maybe Syllabic) -- ^ /syllabic/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml SeqLyric0 where
emitXml (SeqLyric0 a b) =
XContent XEmpty
[]
([XElement (QN "elision" Nothing) (emitXml a)] ++
[maybe XEmpty (XElement (QN "syllabic" Nothing).emitXml) b])
parseSeqLyric0 :: P.XParse SeqLyric0
parseSeqLyric0 =
SeqLyric0
<$> (P.xchild (P.name "elision") (parseTextFontColor))
<*> P.optional (P.xchild (P.name "syllabic") (P.xtext >>= parseSyllabic))
-- | Smart constructor for 'SeqLyric0'
mkSeqLyric0 :: TextFontColor -> SeqLyric0
mkSeqLyric0 a = SeqLyric0 a Nothing
-- | @lyric@ /(sequence)/
-- mangled: 1
data SeqLyric =
SeqLyric {
seqlyricLyric :: (Maybe SeqLyric0)
, seqlyricText :: TextElementData -- ^ /text/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml SeqLyric where
emitXml (SeqLyric a b) =
XContent XEmpty
[]
([emitXml a] ++
[XElement (QN "text" Nothing) (emitXml b)])
parseSeqLyric :: P.XParse SeqLyric
parseSeqLyric =
SeqLyric
<$> P.optional (parseSeqLyric0)
<*> (P.xchild (P.name "text") (parseTextElementData))
-- | Smart constructor for 'SeqLyric'
mkSeqLyric :: TextElementData -> SeqLyric
mkSeqLyric b = SeqLyric Nothing b
-- | @metronome@ /(sequence)/
data SeqMetronome =
SeqMetronome {
metronomeMetronomeRelation :: String -- ^ /metronome-relation/ child element
, seqmetronomeMetronomeNote :: [MetronomeNote] -- ^ /metronome-note/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml SeqMetronome where
emitXml (SeqMetronome a b) =
XContent XEmpty
[]
([XElement (QN "metronome-relation" Nothing) (emitXml a)] ++
map (XElement (QN "metronome-note" Nothing).emitXml) b)
parseSeqMetronome :: P.XParse SeqMetronome
parseSeqMetronome =
SeqMetronome
<$> (P.xchild (P.name "metronome-relation") (P.xtext >>= return))
<*> P.many (P.xchild (P.name "metronome-note") (parseMetronomeNote))
-- | Smart constructor for 'SeqMetronome'
mkSeqMetronome :: String -> SeqMetronome
mkSeqMetronome a = SeqMetronome a []
-- | @metronome-tuplet@ /(sequence)/
data SeqMetronomeTuplet =
SeqMetronomeTuplet {
metronomeTupletNormalType :: NoteTypeValue -- ^ /normal-type/ child element
, metronomeTupletNormalDot :: [Empty] -- ^ /normal-dot/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml SeqMetronomeTuplet where
emitXml (SeqMetronomeTuplet a b) =
XContent XEmpty
[]
([XElement (QN "normal-type" Nothing) (emitXml a)] ++
map (XElement (QN "normal-dot" Nothing).emitXml) b)
parseSeqMetronomeTuplet :: P.XParse SeqMetronomeTuplet
parseSeqMetronomeTuplet =
SeqMetronomeTuplet
<$> (P.xchild (P.name "normal-type") (P.xtext >>= parseNoteTypeValue))
<*> P.many (P.xchild (P.name "normal-dot") (parseEmpty))
-- | Smart constructor for 'SeqMetronomeTuplet'
mkSeqMetronomeTuplet :: NoteTypeValue -> SeqMetronomeTuplet
mkSeqMetronomeTuplet a = SeqMetronomeTuplet a []
-- | @ornaments@ /(sequence)/
data SeqOrnaments =
SeqOrnaments {
seqornamentsOrnaments :: ChxOrnaments
, ornamentsAccidentalMark :: [AccidentalMark] -- ^ /accidental-mark/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml SeqOrnaments where
emitXml (SeqOrnaments a b) =
XContent XEmpty
[]
([emitXml a] ++
map (XElement (QN "accidental-mark" Nothing).emitXml) b)
parseSeqOrnaments :: P.XParse SeqOrnaments
parseSeqOrnaments =
SeqOrnaments
<$> parseChxOrnaments
<*> P.many (P.xchild (P.name "accidental-mark") (parseAccidentalMark))
-- | Smart constructor for 'SeqOrnaments'
mkSeqOrnaments :: ChxOrnaments -> SeqOrnaments
mkSeqOrnaments a = SeqOrnaments a []
-- | @page-layout@ /(sequence)/
data SeqPageLayout =
SeqPageLayout {
pageLayoutPageHeight :: Tenths -- ^ /page-height/ child element
, pageLayoutPageWidth :: Tenths -- ^ /page-width/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml SeqPageLayout where
emitXml (SeqPageLayout a b) =
XContent XEmpty
[]
([XElement (QN "page-height" Nothing) (emitXml a)] ++
[XElement (QN "page-width" Nothing) (emitXml b)])
parseSeqPageLayout :: P.XParse SeqPageLayout
parseSeqPageLayout =
SeqPageLayout
<$> (P.xchild (P.name "page-height") (P.xtext >>= parseTenths))
<*> (P.xchild (P.name "page-width") (P.xtext >>= parseTenths))
-- | Smart constructor for 'SeqPageLayout'
mkSeqPageLayout :: Tenths -> Tenths -> SeqPageLayout
mkSeqPageLayout a b = SeqPageLayout a b
-- | @score-part@ /(sequence)/
data SeqScorePart =
SeqScorePart {
scorePartMidiDevice :: (Maybe MidiDevice) -- ^ /midi-device/ child element
, scorePartMidiInstrument :: (Maybe MidiInstrument) -- ^ /midi-instrument/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml SeqScorePart where
emitXml (SeqScorePart a b) =
XContent XEmpty
[]
([maybe XEmpty (XElement (QN "midi-device" Nothing).emitXml) a] ++
[maybe XEmpty (XElement (QN "midi-instrument" Nothing).emitXml) b])
parseSeqScorePart :: P.XParse SeqScorePart
parseSeqScorePart =
SeqScorePart
<$> P.optional (P.xchild (P.name "midi-device") (parseMidiDevice))
<*> P.optional (P.xchild (P.name "midi-instrument") (parseMidiInstrument))
-- | Smart constructor for 'SeqScorePart'
mkSeqScorePart :: SeqScorePart
mkSeqScorePart = SeqScorePart Nothing Nothing
-- | @sound@ /(sequence)/
data SeqSound =
SeqSound {
soundMidiDevice :: (Maybe MidiDevice) -- ^ /midi-device/ child element
, soundMidiInstrument :: (Maybe MidiInstrument) -- ^ /midi-instrument/ child element
, soundPlay :: (Maybe Play) -- ^ /play/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml SeqSound where
emitXml (SeqSound a b c) =
XContent XEmpty
[]
([maybe XEmpty (XElement (QN "midi-device" Nothing).emitXml) a] ++
[maybe XEmpty (XElement (QN "midi-instrument" Nothing).emitXml) b] ++
[maybe XEmpty (XElement (QN "play" Nothing).emitXml) c])
parseSeqSound :: P.XParse SeqSound
parseSeqSound =
SeqSound
<$> P.optional (P.xchild (P.name "midi-device") (parseMidiDevice))
<*> P.optional (P.xchild (P.name "midi-instrument") (parseMidiInstrument))
<*> P.optional (P.xchild (P.name "play") (parsePlay))
-- | Smart constructor for 'SeqSound'
mkSeqSound :: SeqSound
mkSeqSound = SeqSound Nothing Nothing Nothing
-- | @time-modification@ /(sequence)/
data SeqTimeModification =
SeqTimeModification {
timeModificationNormalType :: NoteTypeValue -- ^ /normal-type/ child element
, timeModificationNormalDot :: [Empty] -- ^ /normal-dot/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml SeqTimeModification where
emitXml (SeqTimeModification a b) =
XContent XEmpty
[]
([XElement (QN "normal-type" Nothing) (emitXml a)] ++
map (XElement (QN "normal-dot" Nothing).emitXml) b)
parseSeqTimeModification :: P.XParse SeqTimeModification
parseSeqTimeModification =
SeqTimeModification
<$> (P.xchild (P.name "normal-type") (P.xtext >>= parseNoteTypeValue))
<*> P.many (P.xchild (P.name "normal-dot") (parseEmpty))
-- | Smart constructor for 'SeqTimeModification'
mkSeqTimeModification :: NoteTypeValue -> SeqTimeModification
mkSeqTimeModification a = SeqTimeModification a []
-- | @all-margins@ /(group)/
data AllMargins =
AllMargins {
allMarginsLeftRightMargins :: LeftRightMargins
, allMarginsTopMargin :: Tenths -- ^ /top-margin/ child element
, allMarginsBottomMargin :: Tenths -- ^ /bottom-margin/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml AllMargins where
emitXml (AllMargins a b c) =
XContent XEmpty
[]
([emitXml a] ++
[XElement (QN "top-margin" Nothing) (emitXml b)] ++
[XElement (QN "bottom-margin" Nothing) (emitXml c)])
parseAllMargins :: P.XParse AllMargins
parseAllMargins =
AllMargins
<$> parseLeftRightMargins
<*> (P.xchild (P.name "top-margin") (P.xtext >>= parseTenths))
<*> (P.xchild (P.name "bottom-margin") (P.xtext >>= parseTenths))
-- | Smart constructor for 'AllMargins'
mkAllMargins :: LeftRightMargins -> Tenths -> Tenths -> AllMargins
mkAllMargins a b c = AllMargins a b c
-- | @beat-unit@ /(group)/
data BeatUnit =
BeatUnit {
beatUnitBeatUnit :: NoteTypeValue -- ^ /beat-unit/ child element
, beatUnitBeatUnitDot :: [Empty] -- ^ /beat-unit-dot/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml BeatUnit where
emitXml (BeatUnit a b) =
XContent XEmpty
[]
([XElement (QN "beat-unit" Nothing) (emitXml a)] ++
map (XElement (QN "beat-unit-dot" Nothing).emitXml) b)
parseBeatUnit :: P.XParse BeatUnit
parseBeatUnit =
BeatUnit
<$> (P.xchild (P.name "beat-unit") (P.xtext >>= parseNoteTypeValue))
<*> P.many (P.xchild (P.name "beat-unit-dot") (parseEmpty))
-- | Smart constructor for 'BeatUnit'
mkBeatUnit :: NoteTypeValue -> BeatUnit
mkBeatUnit a = BeatUnit a []
-- | @display-step-octave@ /(group)/
data DisplayStepOctave =
DisplayStepOctave {
displayStepOctaveDisplayStep :: Step -- ^ /display-step/ child element
, displayStepOctaveDisplayOctave :: Octave -- ^ /display-octave/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml DisplayStepOctave where
emitXml (DisplayStepOctave a b) =
XContent XEmpty
[]
([XElement (QN "display-step" Nothing) (emitXml a)] ++
[XElement (QN "display-octave" Nothing) (emitXml b)])
parseDisplayStepOctave :: P.XParse DisplayStepOctave
parseDisplayStepOctave =
DisplayStepOctave
<$> (P.xchild (P.name "display-step") (P.xtext >>= parseStep))
<*> (P.xchild (P.name "display-octave") (P.xtext >>= parseOctave))
-- | Smart constructor for 'DisplayStepOctave'
mkDisplayStepOctave :: Step -> Octave -> DisplayStepOctave
mkDisplayStepOctave a b = DisplayStepOctave a b
-- | @duration@ /(group)/
data Duration =
Duration {
durationDuration :: PositiveDivisions -- ^ /duration/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Duration where
emitXml (Duration a) =
XContent XEmpty
[]
([XElement (QN "duration" Nothing) (emitXml a)])
parseDuration :: P.XParse Duration
parseDuration =
Duration
<$> (P.xchild (P.name "duration") (P.xtext >>= parsePositiveDivisions))
-- | Smart constructor for 'Duration'
mkDuration :: PositiveDivisions -> Duration
mkDuration a = Duration a
-- | @editorial@ /(group)/
data Editorial =
Editorial {
editorialFootnote :: (Maybe Footnote)
, editorialLevel :: (Maybe GrpLevel)
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Editorial where
emitXml (Editorial a b) =
XReps [emitXml a,emitXml b]
parseEditorial :: P.XParse Editorial
parseEditorial =
Editorial
<$> P.optional (parseFootnote)
<*> P.optional (parseGrpLevel)
-- | Smart constructor for 'Editorial'
mkEditorial :: Editorial
mkEditorial = Editorial Nothing Nothing
-- | @editorial-voice@ /(group)/
data EditorialVoice =
EditorialVoice {
editorialVoiceFootnote :: (Maybe Footnote)
, editorialVoiceLevel :: (Maybe GrpLevel)
, editorialVoiceVoice :: (Maybe Voice)
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml EditorialVoice where
emitXml (EditorialVoice a b c) =
XReps [emitXml a,emitXml b,emitXml c]
parseEditorialVoice :: P.XParse EditorialVoice
parseEditorialVoice =
EditorialVoice
<$> P.optional (parseFootnote)
<*> P.optional (parseGrpLevel)
<*> P.optional (parseVoice)
-- | Smart constructor for 'EditorialVoice'
mkEditorialVoice :: EditorialVoice
mkEditorialVoice = EditorialVoice Nothing Nothing Nothing
-- | @editorial-voice-direction@ /(group)/
data EditorialVoiceDirection =
EditorialVoiceDirection {
editorialVoiceDirectionFootnote :: (Maybe Footnote)
, editorialVoiceDirectionLevel :: (Maybe GrpLevel)
, editorialVoiceDirectionVoice :: (Maybe Voice)
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml EditorialVoiceDirection where
emitXml (EditorialVoiceDirection a b c) =
XReps [emitXml a,emitXml b,emitXml c]
parseEditorialVoiceDirection :: P.XParse EditorialVoiceDirection
parseEditorialVoiceDirection =
EditorialVoiceDirection
<$> P.optional (parseFootnote)
<*> P.optional (parseGrpLevel)
<*> P.optional (parseVoice)
-- | Smart constructor for 'EditorialVoiceDirection'
mkEditorialVoiceDirection :: EditorialVoiceDirection
mkEditorialVoiceDirection = EditorialVoiceDirection Nothing Nothing Nothing
-- | @footnote@ /(group)/
data Footnote =
Footnote {
footnoteFootnote :: FormattedText -- ^ /footnote/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Footnote where
emitXml (Footnote a) =
XContent XEmpty
[]
([XElement (QN "footnote" Nothing) (emitXml a)])
parseFootnote :: P.XParse Footnote
parseFootnote =
Footnote
<$> (P.xchild (P.name "footnote") (parseFormattedText))
-- | Smart constructor for 'Footnote'
mkFootnote :: FormattedText -> Footnote
mkFootnote a = Footnote a
-- | @full-note@ /(group)/
data GrpFullNote =
GrpFullNote {
fullNoteChord :: (Maybe Empty) -- ^ /chord/ child element
, fullNoteFullNote :: FullNote
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml GrpFullNote where
emitXml (GrpFullNote a b) =
XContent XEmpty
[]
([maybe XEmpty (XElement (QN "chord" Nothing).emitXml) a] ++
[emitXml b])
parseGrpFullNote :: P.XParse GrpFullNote
parseGrpFullNote =
GrpFullNote
<$> P.optional (P.xchild (P.name "chord") (parseEmpty))
<*> parseFullNote
-- | Smart constructor for 'GrpFullNote'
mkGrpFullNote :: FullNote -> GrpFullNote
mkGrpFullNote b = GrpFullNote Nothing b
-- | @harmony-chord@ /(group)/
data HarmonyChord =
HarmonyChord {
harmonyChordHarmonyChord :: ChxHarmonyChord
, harmonyChordKind :: Kind -- ^ /kind/ child element
, harmonyChordInversion :: (Maybe Inversion) -- ^ /inversion/ child element
, harmonyChordBass :: (Maybe Bass) -- ^ /bass/ child element
, harmonyChordDegree :: [Degree] -- ^ /degree/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml HarmonyChord where
emitXml (HarmonyChord a b c d e) =
XContent XEmpty
[]
([emitXml a] ++
[XElement (QN "kind" Nothing) (emitXml b)] ++
[maybe XEmpty (XElement (QN "inversion" Nothing).emitXml) c] ++
[maybe XEmpty (XElement (QN "bass" Nothing).emitXml) d] ++
map (XElement (QN "degree" Nothing).emitXml) e)
parseHarmonyChord :: P.XParse HarmonyChord
parseHarmonyChord =
HarmonyChord
<$> parseChxHarmonyChord
<*> (P.xchild (P.name "kind") (parseKind))
<*> P.optional (P.xchild (P.name "inversion") (parseInversion))
<*> P.optional (P.xchild (P.name "bass") (parseBass))
<*> P.many (P.xchild (P.name "degree") (parseDegree))
-- | Smart constructor for 'HarmonyChord'
mkHarmonyChord :: ChxHarmonyChord -> Kind -> HarmonyChord
mkHarmonyChord a b = HarmonyChord a b Nothing Nothing []
-- | @layout@ /(group)/
data Layout =
Layout {
layoutPageLayout :: (Maybe PageLayout) -- ^ /page-layout/ child element
, layoutSystemLayout :: (Maybe SystemLayout) -- ^ /system-layout/ child element
, layoutStaffLayout :: [StaffLayout] -- ^ /staff-layout/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Layout where
emitXml (Layout a b c) =
XContent XEmpty
[]
([maybe XEmpty (XElement (QN "page-layout" Nothing).emitXml) a] ++
[maybe XEmpty (XElement (QN "system-layout" Nothing).emitXml) b] ++
map (XElement (QN "staff-layout" Nothing).emitXml) c)
parseLayout :: P.XParse Layout
parseLayout =
Layout
<$> P.optional (P.xchild (P.name "page-layout") (parsePageLayout))
<*> P.optional (P.xchild (P.name "system-layout") (parseSystemLayout))
<*> P.many (P.xchild (P.name "staff-layout") (parseStaffLayout))
-- | Smart constructor for 'Layout'
mkLayout :: Layout
mkLayout = Layout Nothing Nothing []
-- | @left-right-margins@ /(group)/
data LeftRightMargins =
LeftRightMargins {
leftRightMarginsLeftMargin :: Tenths -- ^ /left-margin/ child element
, leftRightMarginsRightMargin :: Tenths -- ^ /right-margin/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml LeftRightMargins where
emitXml (LeftRightMargins a b) =
XContent XEmpty
[]
([XElement (QN "left-margin" Nothing) (emitXml a)] ++
[XElement (QN "right-margin" Nothing) (emitXml b)])
parseLeftRightMargins :: P.XParse LeftRightMargins
parseLeftRightMargins =
LeftRightMargins
<$> (P.xchild (P.name "left-margin") (P.xtext >>= parseTenths))
<*> (P.xchild (P.name "right-margin") (P.xtext >>= parseTenths))
-- | Smart constructor for 'LeftRightMargins'
mkLeftRightMargins :: Tenths -> Tenths -> LeftRightMargins
mkLeftRightMargins a b = LeftRightMargins a b
-- | @level@ /(group)/
data GrpLevel =
GrpLevel {
levelLevel :: Level -- ^ /level/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml GrpLevel where
emitXml (GrpLevel a) =
XContent XEmpty
[]
([XElement (QN "level" Nothing) (emitXml a)])
parseGrpLevel :: P.XParse GrpLevel
parseGrpLevel =
GrpLevel
<$> (P.xchild (P.name "level") (parseLevel))
-- | Smart constructor for 'GrpLevel'
mkGrpLevel :: Level -> GrpLevel
mkGrpLevel a = GrpLevel a
-- | @music-data@ /(group)/
data MusicData =
MusicData {
musicDataMusicData :: [ChxMusicData]
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml MusicData where
emitXml (MusicData a) =
XReps [emitXml a]
parseMusicData :: P.XParse MusicData
parseMusicData =
MusicData
<$> P.many (parseChxMusicData)
-- | Smart constructor for 'MusicData'
mkMusicData :: MusicData
mkMusicData = MusicData []
-- | @non-traditional-key@ /(group)/
data NonTraditionalKey =
NonTraditionalKey {
nonTraditionalKeyKeyStep :: Step -- ^ /key-step/ child element
, nonTraditionalKeyKeyAlter :: Semitones -- ^ /key-alter/ child element
, nonTraditionalKeyKeyAccidental :: (Maybe AccidentalValue) -- ^ /key-accidental/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml NonTraditionalKey where
emitXml (NonTraditionalKey a b c) =
XContent XEmpty
[]
([XElement (QN "key-step" Nothing) (emitXml a)] ++
[XElement (QN "key-alter" Nothing) (emitXml b)] ++
[maybe XEmpty (XElement (QN "key-accidental" Nothing).emitXml) c])
parseNonTraditionalKey :: P.XParse NonTraditionalKey
parseNonTraditionalKey =
NonTraditionalKey
<$> (P.xchild (P.name "key-step") (P.xtext >>= parseStep))
<*> (P.xchild (P.name "key-alter") (P.xtext >>= parseSemitones))
<*> P.optional (P.xchild (P.name "key-accidental") (P.xtext >>= parseAccidentalValue))
-- | Smart constructor for 'NonTraditionalKey'
mkNonTraditionalKey :: Step -> Semitones -> NonTraditionalKey
mkNonTraditionalKey a b = NonTraditionalKey a b Nothing
-- | @part-group@ /(group)/
data GrpPartGroup =
GrpPartGroup {
partGroupPartGroup :: PartGroup -- ^ /part-group/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml GrpPartGroup where
emitXml (GrpPartGroup a) =
XContent XEmpty
[]
([XElement (QN "part-group" Nothing) (emitXml a)])
parseGrpPartGroup :: P.XParse GrpPartGroup
parseGrpPartGroup =
GrpPartGroup
<$> (P.xchild (P.name "part-group") (parsePartGroup))
-- | Smart constructor for 'GrpPartGroup'
mkGrpPartGroup :: PartGroup -> GrpPartGroup
mkGrpPartGroup a = GrpPartGroup a
-- | @score-header@ /(group)/
data ScoreHeader =
ScoreHeader {
scoreHeaderWork :: (Maybe Work) -- ^ /work/ child element
, scoreHeaderMovementNumber :: (Maybe String) -- ^ /movement-number/ child element
, scoreHeaderMovementTitle :: (Maybe String) -- ^ /movement-title/ child element
, scoreHeaderIdentification :: (Maybe Identification) -- ^ /identification/ child element
, scoreHeaderDefaults :: (Maybe Defaults) -- ^ /defaults/ child element
, scoreHeaderCredit :: [Credit] -- ^ /credit/ child element
, scoreHeaderPartList :: PartList -- ^ /part-list/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml ScoreHeader where
emitXml (ScoreHeader a b c d e f g) =
XContent XEmpty
[]
([maybe XEmpty (XElement (QN "work" Nothing).emitXml) a] ++
[maybe XEmpty (XElement (QN "movement-number" Nothing).emitXml) b] ++
[maybe XEmpty (XElement (QN "movement-title" Nothing).emitXml) c] ++
[maybe XEmpty (XElement (QN "identification" Nothing).emitXml) d] ++
[maybe XEmpty (XElement (QN "defaults" Nothing).emitXml) e] ++
map (XElement (QN "credit" Nothing).emitXml) f ++
[XElement (QN "part-list" Nothing) (emitXml g)])
parseScoreHeader :: P.XParse ScoreHeader
parseScoreHeader =
ScoreHeader
<$> P.optional (P.xchild (P.name "work") (parseWork))
<*> P.optional (P.xchild (P.name "movement-number") (P.xtext >>= return))
<*> P.optional (P.xchild (P.name "movement-title") (P.xtext >>= return))
<*> P.optional (P.xchild (P.name "identification") (parseIdentification))
<*> P.optional (P.xchild (P.name "defaults") (parseDefaults))
<*> P.many (P.xchild (P.name "credit") (parseCredit))
<*> (P.xchild (P.name "part-list") (parsePartList))
-- | Smart constructor for 'ScoreHeader'
mkScoreHeader :: PartList -> ScoreHeader
mkScoreHeader g = ScoreHeader Nothing Nothing Nothing Nothing Nothing [] g
-- | @score-part@ /(group)/
data ScorePart =
ScorePart {
grpscorePartScorePart :: CmpScorePart -- ^ /score-part/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml ScorePart where
emitXml (ScorePart a) =
XContent XEmpty
[]
([XElement (QN "score-part" Nothing) (emitXml a)])
parseScorePart :: P.XParse ScorePart
parseScorePart =
ScorePart
<$> (P.xchild (P.name "score-part") (parseCmpScorePart))
-- | Smart constructor for 'ScorePart'
mkScorePart :: CmpScorePart -> ScorePart
mkScorePart a = ScorePart a
-- | @slash@ /(group)/
data Slash =
Slash {
slashSlashType :: NoteTypeValue -- ^ /slash-type/ child element
, slashSlashDot :: [Empty] -- ^ /slash-dot/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Slash where
emitXml (Slash a b) =
XContent XEmpty
[]
([XElement (QN "slash-type" Nothing) (emitXml a)] ++
map (XElement (QN "slash-dot" Nothing).emitXml) b)
parseSlash :: P.XParse Slash
parseSlash =
Slash
<$> (P.xchild (P.name "slash-type") (P.xtext >>= parseNoteTypeValue))
<*> P.many (P.xchild (P.name "slash-dot") (parseEmpty))
-- | Smart constructor for 'Slash'
mkSlash :: NoteTypeValue -> Slash
mkSlash a = Slash a []
-- | @staff@ /(group)/
data Staff =
Staff {
staffStaff :: PositiveInteger -- ^ /staff/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Staff where
emitXml (Staff a) =
XContent XEmpty
[]
([XElement (QN "staff" Nothing) (emitXml a)])
parseStaff :: P.XParse Staff
parseStaff =
Staff
<$> (P.xchild (P.name "staff") (P.xtext >>= parsePositiveInteger))
-- | Smart constructor for 'Staff'
mkStaff :: PositiveInteger -> Staff
mkStaff a = Staff a
-- | @time-signature@ /(group)/
data TimeSignature =
TimeSignature {
timeSignatureBeats :: String -- ^ /beats/ child element
, timeSignatureBeatType :: String -- ^ /beat-type/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml TimeSignature where
emitXml (TimeSignature a b) =
XContent XEmpty
[]
([XElement (QN "beats" Nothing) (emitXml a)] ++
[XElement (QN "beat-type" Nothing) (emitXml b)])
parseTimeSignature :: P.XParse TimeSignature
parseTimeSignature =
TimeSignature
<$> (P.xchild (P.name "beats") (P.xtext >>= return))
<*> (P.xchild (P.name "beat-type") (P.xtext >>= return))
-- | Smart constructor for 'TimeSignature'
mkTimeSignature :: String -> String -> TimeSignature
mkTimeSignature a b = TimeSignature a b
-- | @traditional-key@ /(group)/
data TraditionalKey =
TraditionalKey {
traditionalKeyCancel :: (Maybe Cancel) -- ^ /cancel/ child element
, traditionalKeyFifths :: Fifths -- ^ /fifths/ child element
, traditionalKeyMode :: (Maybe Mode) -- ^ /mode/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml TraditionalKey where
emitXml (TraditionalKey a b c) =
XContent XEmpty
[]
([maybe XEmpty (XElement (QN "cancel" Nothing).emitXml) a] ++
[XElement (QN "fifths" Nothing) (emitXml b)] ++
[maybe XEmpty (XElement (QN "mode" Nothing).emitXml) c])
parseTraditionalKey :: P.XParse TraditionalKey
parseTraditionalKey =
TraditionalKey
<$> P.optional (P.xchild (P.name "cancel") (parseCancel))
<*> (P.xchild (P.name "fifths") (P.xtext >>= parseFifths))
<*> P.optional (P.xchild (P.name "mode") (P.xtext >>= parseMode))
-- | Smart constructor for 'TraditionalKey'
mkTraditionalKey :: Fifths -> TraditionalKey
mkTraditionalKey b = TraditionalKey Nothing b Nothing
-- | @tuning@ /(group)/
data Tuning =
Tuning {
tuningTuningStep :: Step -- ^ /tuning-step/ child element
, tuningTuningAlter :: (Maybe Semitones) -- ^ /tuning-alter/ child element
, tuningTuningOctave :: Octave -- ^ /tuning-octave/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Tuning where
emitXml (Tuning a b c) =
XContent XEmpty
[]
([XElement (QN "tuning-step" Nothing) (emitXml a)] ++
[maybe XEmpty (XElement (QN "tuning-alter" Nothing).emitXml) b] ++
[XElement (QN "tuning-octave" Nothing) (emitXml c)])
parseTuning :: P.XParse Tuning
parseTuning =
Tuning
<$> (P.xchild (P.name "tuning-step") (P.xtext >>= parseStep))
<*> P.optional (P.xchild (P.name "tuning-alter") (P.xtext >>= parseSemitones))
<*> (P.xchild (P.name "tuning-octave") (P.xtext >>= parseOctave))
-- | Smart constructor for 'Tuning'
mkTuning :: Step -> Octave -> Tuning
mkTuning a c = Tuning a Nothing c
-- | @voice@ /(group)/
data Voice =
Voice {
voiceVoice :: String -- ^ /voice/ child element
}
deriving (Eq,Typeable,Generic,Show)
instance EmitXml Voice where
emitXml (Voice a) =
XContent XEmpty
[]
([XElement (QN "voice" Nothing) (emitXml a)])
parseVoice :: P.XParse Voice
parseVoice =
Voice
<$> (P.xchild (P.name "voice") (P.xtext >>= return))
-- | Smart constructor for 'Voice'
mkVoice :: String -> Voice
mkVoice a = Voice a
|
slpopejoy/fadno-xml
|
src/Fadno/MusicXml/MusicXml30.hs
|
bsd-2-clause
| 700,244 | 0 | 56 | 151,409 | 177,124 | 92,011 | 85,113 | 11,418 | 1 |
module Token where
import Prelude
data Token = X | O | Empty deriving (Eq)
instance Show Token where
show X = "X"
show O = "O"
show Empty = "_"
tokenValue X = 1
tokenValue Empty = 0
tokenValue O = (-1)
|
MichaelBaker/haskell-tictactoe
|
src/Token.hs
|
bsd-2-clause
| 228 | 0 | 6 | 69 | 88 | 48 | 40 | 10 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module Types
( Error(..)
) where
import Data.Aeson.TH
import Data.Text.Lazy
data Error = Error { errorStatus :: Int
, errorMessage :: Text
, errorException :: Maybe Text
}
deriving (Read, Show)
$(deriveJSON defaultOptions ''Error)
|
jotrk/webui-service
|
src/Types.hs
|
bsd-2-clause
| 337 | 0 | 9 | 111 | 81 | 48 | 33 | 10 | 0 |
{-# LANGUAGE Rank2Types, GADTs #-}
{-# LANGUAGE ScopedTypeVariables #-}
module CodeSyntaxDump where
{-# LINE 2 "./src-ag/Patterns.ag" #-}
-- Patterns.ag imports
import UU.Scanner.Position(Pos)
import CommonTypes (ConstructorIdent,Identifier)
{-# LINE 11 "dist/build/CodeSyntaxDump.hs" #-}
{-# LINE 2 "./src-ag/CodeSyntax.ag" #-}
import Patterns
import CommonTypes
import Data.Map(Map)
import Data.Set(Set)
{-# LINE 19 "dist/build/CodeSyntaxDump.hs" #-}
{-# LINE 5 "./src-ag/CodeSyntaxDump.ag" #-}
import Data.List
import qualified Data.Map as Map
import Pretty
import PPUtil
import CodeSyntax
{-# LINE 30 "dist/build/CodeSyntaxDump.hs" #-}
import Control.Monad.Identity (Identity)
import qualified Control.Monad.Identity
{-# LINE 15 "./src-ag/CodeSyntaxDump.ag" #-}
ppChild :: (Identifier,Type,ChildKind) -> PP_Doc
ppChild (nm,tp,_)
= pp nm >#< "::" >#< pp (show tp)
ppVertexMap :: Map Int (Identifier,Identifier,Maybe Type) -> PP_Doc
ppVertexMap m
= ppVList [ ppF (show k) $ ppAttr v | (k,v) <- Map.toList m ]
ppAttr :: (Identifier,Identifier,Maybe Type) -> PP_Doc
ppAttr (fld,nm,mTp)
= pp fld >|< "." >|< pp nm >#<
case mTp of
Just tp -> pp "::" >#< show tp
Nothing -> empty
ppBool :: Bool -> PP_Doc
ppBool True = pp "T"
ppBool False = pp "F"
ppMaybeShow :: Show a => Maybe a -> PP_Doc
ppMaybeShow (Just x) = pp (show x)
ppMaybeShow Nothing = pp "_"
ppStrings :: [String] -> PP_Doc
ppStrings = vlist
{-# LINE 60 "dist/build/CodeSyntaxDump.hs" #-}
-- CGrammar ----------------------------------------------------
-- wrapper
data Inh_CGrammar = Inh_CGrammar { }
data Syn_CGrammar = Syn_CGrammar { pp_Syn_CGrammar :: (PP_Doc) }
{-# INLINABLE wrap_CGrammar #-}
wrap_CGrammar :: T_CGrammar -> Inh_CGrammar -> (Syn_CGrammar )
wrap_CGrammar (T_CGrammar act) (Inh_CGrammar ) =
Control.Monad.Identity.runIdentity (
do sem <- act
let arg = T_CGrammar_vIn1
(T_CGrammar_vOut1 _lhsOpp) <- return (inv_CGrammar_s2 sem arg)
return (Syn_CGrammar _lhsOpp)
)
-- cata
{-# INLINE sem_CGrammar #-}
sem_CGrammar :: CGrammar -> T_CGrammar
sem_CGrammar ( CGrammar typeSyns_ derivings_ wrappers_ nonts_ pragmas_ paramMap_ contextMap_ quantMap_ aroundsMap_ mergeMap_ multivisit_ ) = sem_CGrammar_CGrammar typeSyns_ derivings_ wrappers_ ( sem_CNonterminals nonts_ ) pragmas_ paramMap_ contextMap_ quantMap_ aroundsMap_ mergeMap_ multivisit_
-- semantic domain
newtype T_CGrammar = T_CGrammar {
attach_T_CGrammar :: Identity (T_CGrammar_s2 )
}
newtype T_CGrammar_s2 = C_CGrammar_s2 {
inv_CGrammar_s2 :: (T_CGrammar_v1 )
}
data T_CGrammar_s3 = C_CGrammar_s3
type T_CGrammar_v1 = (T_CGrammar_vIn1 ) -> (T_CGrammar_vOut1 )
data T_CGrammar_vIn1 = T_CGrammar_vIn1
data T_CGrammar_vOut1 = T_CGrammar_vOut1 (PP_Doc)
{-# NOINLINE sem_CGrammar_CGrammar #-}
sem_CGrammar_CGrammar :: (TypeSyns) -> (Derivings) -> (Set NontermIdent) -> T_CNonterminals -> (PragmaMap) -> (ParamMap) -> (ContextMap) -> (QuantMap) -> (Map NontermIdent (Map ConstructorIdent (Set Identifier))) -> (Map NontermIdent (Map ConstructorIdent (Map Identifier (Identifier,[Identifier])))) -> (Bool) -> T_CGrammar
sem_CGrammar_CGrammar arg_typeSyns_ arg_derivings_ _ arg_nonts_ _ _ _ _ _ _ _ = T_CGrammar (return st2) where
{-# NOINLINE st2 #-}
st2 = let
v1 :: T_CGrammar_v1
v1 = \ (T_CGrammar_vIn1 ) -> ( let
_nontsX11 = Control.Monad.Identity.runIdentity (attach_T_CNonterminals (arg_nonts_))
(T_CNonterminals_vOut10 _nontsIpp _nontsIppL) = inv_CNonterminals_s11 _nontsX11 (T_CNonterminals_vIn10 )
_lhsOpp :: PP_Doc
_lhsOpp = rule0 _nontsIppL arg_derivings_ arg_typeSyns_
__result_ = T_CGrammar_vOut1 _lhsOpp
in __result_ )
in C_CGrammar_s2 v1
{-# INLINE rule0 #-}
{-# LINE 47 "./src-ag/CodeSyntaxDump.ag" #-}
rule0 = \ ((_nontsIppL) :: [PP_Doc]) derivings_ typeSyns_ ->
{-# LINE 47 "./src-ag/CodeSyntaxDump.ag" #-}
ppNestInfo ["CGrammar","CGrammar"] []
[ ppF "typeSyns" $ ppAssocL typeSyns_
, ppF "derivings" $ ppMap $ derivings_
, ppF "nonts" $ ppVList _nontsIppL
] []
{-# LINE 114 "dist/build/CodeSyntaxDump.hs"#-}
-- CInterface --------------------------------------------------
-- wrapper
data Inh_CInterface = Inh_CInterface { }
data Syn_CInterface = Syn_CInterface { pp_Syn_CInterface :: (PP_Doc) }
{-# INLINABLE wrap_CInterface #-}
wrap_CInterface :: T_CInterface -> Inh_CInterface -> (Syn_CInterface )
wrap_CInterface (T_CInterface act) (Inh_CInterface ) =
Control.Monad.Identity.runIdentity (
do sem <- act
let arg = T_CInterface_vIn4
(T_CInterface_vOut4 _lhsOpp) <- return (inv_CInterface_s5 sem arg)
return (Syn_CInterface _lhsOpp)
)
-- cata
{-# INLINE sem_CInterface #-}
sem_CInterface :: CInterface -> T_CInterface
sem_CInterface ( CInterface seg_ ) = sem_CInterface_CInterface ( sem_CSegments seg_ )
-- semantic domain
newtype T_CInterface = T_CInterface {
attach_T_CInterface :: Identity (T_CInterface_s5 )
}
newtype T_CInterface_s5 = C_CInterface_s5 {
inv_CInterface_s5 :: (T_CInterface_v4 )
}
data T_CInterface_s6 = C_CInterface_s6
type T_CInterface_v4 = (T_CInterface_vIn4 ) -> (T_CInterface_vOut4 )
data T_CInterface_vIn4 = T_CInterface_vIn4
data T_CInterface_vOut4 = T_CInterface_vOut4 (PP_Doc)
{-# NOINLINE sem_CInterface_CInterface #-}
sem_CInterface_CInterface :: T_CSegments -> T_CInterface
sem_CInterface_CInterface arg_seg_ = T_CInterface (return st5) where
{-# NOINLINE st5 #-}
st5 = let
v4 :: T_CInterface_v4
v4 = \ (T_CInterface_vIn4 ) -> ( let
_segX26 = Control.Monad.Identity.runIdentity (attach_T_CSegments (arg_seg_))
(T_CSegments_vOut25 _segIpp _segIppL) = inv_CSegments_s26 _segX26 (T_CSegments_vIn25 )
_lhsOpp :: PP_Doc
_lhsOpp = rule1 _segIppL
__result_ = T_CInterface_vOut4 _lhsOpp
in __result_ )
in C_CInterface_s5 v4
{-# INLINE rule1 #-}
{-# LINE 57 "./src-ag/CodeSyntaxDump.ag" #-}
rule1 = \ ((_segIppL) :: [PP_Doc]) ->
{-# LINE 57 "./src-ag/CodeSyntaxDump.ag" #-}
ppNestInfo ["CInterface","CInterface"] [] [ppF "seg" $ ppVList _segIppL] []
{-# LINE 165 "dist/build/CodeSyntaxDump.hs"#-}
-- CNonterminal ------------------------------------------------
-- wrapper
data Inh_CNonterminal = Inh_CNonterminal { }
data Syn_CNonterminal = Syn_CNonterminal { pp_Syn_CNonterminal :: (PP_Doc) }
{-# INLINABLE wrap_CNonterminal #-}
wrap_CNonterminal :: T_CNonterminal -> Inh_CNonterminal -> (Syn_CNonterminal )
wrap_CNonterminal (T_CNonterminal act) (Inh_CNonterminal ) =
Control.Monad.Identity.runIdentity (
do sem <- act
let arg = T_CNonterminal_vIn7
(T_CNonterminal_vOut7 _lhsOpp) <- return (inv_CNonterminal_s8 sem arg)
return (Syn_CNonterminal _lhsOpp)
)
-- cata
{-# INLINE sem_CNonterminal #-}
sem_CNonterminal :: CNonterminal -> T_CNonterminal
sem_CNonterminal ( CNonterminal nt_ params_ inh_ syn_ prods_ inter_ ) = sem_CNonterminal_CNonterminal nt_ params_ inh_ syn_ ( sem_CProductions prods_ ) ( sem_CInterface inter_ )
-- semantic domain
newtype T_CNonterminal = T_CNonterminal {
attach_T_CNonterminal :: Identity (T_CNonterminal_s8 )
}
newtype T_CNonterminal_s8 = C_CNonterminal_s8 {
inv_CNonterminal_s8 :: (T_CNonterminal_v7 )
}
data T_CNonterminal_s9 = C_CNonterminal_s9
type T_CNonterminal_v7 = (T_CNonterminal_vIn7 ) -> (T_CNonterminal_vOut7 )
data T_CNonterminal_vIn7 = T_CNonterminal_vIn7
data T_CNonterminal_vOut7 = T_CNonterminal_vOut7 (PP_Doc)
{-# NOINLINE sem_CNonterminal_CNonterminal #-}
sem_CNonterminal_CNonterminal :: (NontermIdent) -> ([Identifier]) -> (Attributes) -> (Attributes) -> T_CProductions -> T_CInterface -> T_CNonterminal
sem_CNonterminal_CNonterminal arg_nt_ arg_params_ arg_inh_ arg_syn_ arg_prods_ arg_inter_ = T_CNonterminal (return st8) where
{-# NOINLINE st8 #-}
st8 = let
v7 :: T_CNonterminal_v7
v7 = \ (T_CNonterminal_vIn7 ) -> ( let
_prodsX17 = Control.Monad.Identity.runIdentity (attach_T_CProductions (arg_prods_))
_interX5 = Control.Monad.Identity.runIdentity (attach_T_CInterface (arg_inter_))
(T_CProductions_vOut16 _prodsIpp _prodsIppL) = inv_CProductions_s17 _prodsX17 (T_CProductions_vIn16 )
(T_CInterface_vOut4 _interIpp) = inv_CInterface_s5 _interX5 (T_CInterface_vIn4 )
_lhsOpp :: PP_Doc
_lhsOpp = rule2 _interIpp _prodsIppL arg_inh_ arg_nt_ arg_params_ arg_syn_
__result_ = T_CNonterminal_vOut7 _lhsOpp
in __result_ )
in C_CNonterminal_s8 v7
{-# INLINE rule2 #-}
{-# LINE 54 "./src-ag/CodeSyntaxDump.ag" #-}
rule2 = \ ((_interIpp) :: PP_Doc) ((_prodsIppL) :: [PP_Doc]) inh_ nt_ params_ syn_ ->
{-# LINE 54 "./src-ag/CodeSyntaxDump.ag" #-}
ppNestInfo ["CNonterminal","CNonterminal"] (pp nt_ : map pp params_) [ppF "inh" $ ppMap inh_, ppF "syn" $ ppMap syn_, ppF "prods" $ ppVList _prodsIppL, ppF "inter" _interIpp] []
{-# LINE 218 "dist/build/CodeSyntaxDump.hs"#-}
-- CNonterminals -----------------------------------------------
-- wrapper
data Inh_CNonterminals = Inh_CNonterminals { }
data Syn_CNonterminals = Syn_CNonterminals { pp_Syn_CNonterminals :: (PP_Doc), ppL_Syn_CNonterminals :: ([PP_Doc]) }
{-# INLINABLE wrap_CNonterminals #-}
wrap_CNonterminals :: T_CNonterminals -> Inh_CNonterminals -> (Syn_CNonterminals )
wrap_CNonterminals (T_CNonterminals act) (Inh_CNonterminals ) =
Control.Monad.Identity.runIdentity (
do sem <- act
let arg = T_CNonterminals_vIn10
(T_CNonterminals_vOut10 _lhsOpp _lhsOppL) <- return (inv_CNonterminals_s11 sem arg)
return (Syn_CNonterminals _lhsOpp _lhsOppL)
)
-- cata
{-# NOINLINE sem_CNonterminals #-}
sem_CNonterminals :: CNonterminals -> T_CNonterminals
sem_CNonterminals list = Prelude.foldr sem_CNonterminals_Cons sem_CNonterminals_Nil (Prelude.map sem_CNonterminal list)
-- semantic domain
newtype T_CNonterminals = T_CNonterminals {
attach_T_CNonterminals :: Identity (T_CNonterminals_s11 )
}
newtype T_CNonterminals_s11 = C_CNonterminals_s11 {
inv_CNonterminals_s11 :: (T_CNonterminals_v10 )
}
data T_CNonterminals_s12 = C_CNonterminals_s12
type T_CNonterminals_v10 = (T_CNonterminals_vIn10 ) -> (T_CNonterminals_vOut10 )
data T_CNonterminals_vIn10 = T_CNonterminals_vIn10
data T_CNonterminals_vOut10 = T_CNonterminals_vOut10 (PP_Doc) ([PP_Doc])
{-# NOINLINE sem_CNonterminals_Cons #-}
sem_CNonterminals_Cons :: T_CNonterminal -> T_CNonterminals -> T_CNonterminals
sem_CNonterminals_Cons arg_hd_ arg_tl_ = T_CNonterminals (return st11) where
{-# NOINLINE st11 #-}
st11 = let
v10 :: T_CNonterminals_v10
v10 = \ (T_CNonterminals_vIn10 ) -> ( let
_hdX8 = Control.Monad.Identity.runIdentity (attach_T_CNonterminal (arg_hd_))
_tlX11 = Control.Monad.Identity.runIdentity (attach_T_CNonterminals (arg_tl_))
(T_CNonterminal_vOut7 _hdIpp) = inv_CNonterminal_s8 _hdX8 (T_CNonterminal_vIn7 )
(T_CNonterminals_vOut10 _tlIpp _tlIppL) = inv_CNonterminals_s11 _tlX11 (T_CNonterminals_vIn10 )
_lhsOppL :: [PP_Doc]
_lhsOppL = rule3 _hdIpp _tlIppL
_lhsOpp :: PP_Doc
_lhsOpp = rule4 _hdIpp _tlIpp
__result_ = T_CNonterminals_vOut10 _lhsOpp _lhsOppL
in __result_ )
in C_CNonterminals_s11 v10
{-# INLINE rule3 #-}
{-# LINE 102 "./src-ag/CodeSyntaxDump.ag" #-}
rule3 = \ ((_hdIpp) :: PP_Doc) ((_tlIppL) :: [PP_Doc]) ->
{-# LINE 102 "./src-ag/CodeSyntaxDump.ag" #-}
_hdIpp : _tlIppL
{-# LINE 273 "dist/build/CodeSyntaxDump.hs"#-}
{-# INLINE rule4 #-}
rule4 = \ ((_hdIpp) :: PP_Doc) ((_tlIpp) :: PP_Doc) ->
_hdIpp >-< _tlIpp
{-# NOINLINE sem_CNonterminals_Nil #-}
sem_CNonterminals_Nil :: T_CNonterminals
sem_CNonterminals_Nil = T_CNonterminals (return st11) where
{-# NOINLINE st11 #-}
st11 = let
v10 :: T_CNonterminals_v10
v10 = \ (T_CNonterminals_vIn10 ) -> ( let
_lhsOppL :: [PP_Doc]
_lhsOppL = rule5 ()
_lhsOpp :: PP_Doc
_lhsOpp = rule6 ()
__result_ = T_CNonterminals_vOut10 _lhsOpp _lhsOppL
in __result_ )
in C_CNonterminals_s11 v10
{-# INLINE rule5 #-}
{-# LINE 103 "./src-ag/CodeSyntaxDump.ag" #-}
rule5 = \ (_ :: ()) ->
{-# LINE 103 "./src-ag/CodeSyntaxDump.ag" #-}
[]
{-# LINE 296 "dist/build/CodeSyntaxDump.hs"#-}
{-# INLINE rule6 #-}
rule6 = \ (_ :: ()) ->
empty
-- CProduction -------------------------------------------------
-- wrapper
data Inh_CProduction = Inh_CProduction { }
data Syn_CProduction = Syn_CProduction { pp_Syn_CProduction :: (PP_Doc) }
{-# INLINABLE wrap_CProduction #-}
wrap_CProduction :: T_CProduction -> Inh_CProduction -> (Syn_CProduction )
wrap_CProduction (T_CProduction act) (Inh_CProduction ) =
Control.Monad.Identity.runIdentity (
do sem <- act
let arg = T_CProduction_vIn13
(T_CProduction_vOut13 _lhsOpp) <- return (inv_CProduction_s14 sem arg)
return (Syn_CProduction _lhsOpp)
)
-- cata
{-# INLINE sem_CProduction #-}
sem_CProduction :: CProduction -> T_CProduction
sem_CProduction ( CProduction con_ visits_ children_ terminals_ ) = sem_CProduction_CProduction con_ ( sem_CVisits visits_ ) children_ terminals_
-- semantic domain
newtype T_CProduction = T_CProduction {
attach_T_CProduction :: Identity (T_CProduction_s14 )
}
newtype T_CProduction_s14 = C_CProduction_s14 {
inv_CProduction_s14 :: (T_CProduction_v13 )
}
data T_CProduction_s15 = C_CProduction_s15
type T_CProduction_v13 = (T_CProduction_vIn13 ) -> (T_CProduction_vOut13 )
data T_CProduction_vIn13 = T_CProduction_vIn13
data T_CProduction_vOut13 = T_CProduction_vOut13 (PP_Doc)
{-# NOINLINE sem_CProduction_CProduction #-}
sem_CProduction_CProduction :: (ConstructorIdent) -> T_CVisits -> ([(Identifier,Type,ChildKind)]) -> ([Identifier]) -> T_CProduction
sem_CProduction_CProduction arg_con_ arg_visits_ arg_children_ arg_terminals_ = T_CProduction (return st14) where
{-# NOINLINE st14 #-}
st14 = let
v13 :: T_CProduction_v13
v13 = \ (T_CProduction_vIn13 ) -> ( let
_visitsX32 = Control.Monad.Identity.runIdentity (attach_T_CVisits (arg_visits_))
(T_CVisits_vOut31 _visitsIpp _visitsIppL) = inv_CVisits_s32 _visitsX32 (T_CVisits_vIn31 )
_lhsOpp :: PP_Doc
_lhsOpp = rule7 _visitsIppL arg_children_ arg_con_ arg_terminals_
__result_ = T_CProduction_vOut13 _lhsOpp
in __result_ )
in C_CProduction_s14 v13
{-# INLINE rule7 #-}
{-# LINE 63 "./src-ag/CodeSyntaxDump.ag" #-}
rule7 = \ ((_visitsIppL) :: [PP_Doc]) children_ con_ terminals_ ->
{-# LINE 63 "./src-ag/CodeSyntaxDump.ag" #-}
ppNestInfo ["CProduction","CProduction"] [pp con_] [ppF "visits" $ ppVList _visitsIppL, ppF "children" $ ppVList (map ppChild children_),ppF "terminals" $ ppVList (map ppShow terminals_)] []
{-# LINE 350 "dist/build/CodeSyntaxDump.hs"#-}
-- CProductions ------------------------------------------------
-- wrapper
data Inh_CProductions = Inh_CProductions { }
data Syn_CProductions = Syn_CProductions { pp_Syn_CProductions :: (PP_Doc), ppL_Syn_CProductions :: ([PP_Doc]) }
{-# INLINABLE wrap_CProductions #-}
wrap_CProductions :: T_CProductions -> Inh_CProductions -> (Syn_CProductions )
wrap_CProductions (T_CProductions act) (Inh_CProductions ) =
Control.Monad.Identity.runIdentity (
do sem <- act
let arg = T_CProductions_vIn16
(T_CProductions_vOut16 _lhsOpp _lhsOppL) <- return (inv_CProductions_s17 sem arg)
return (Syn_CProductions _lhsOpp _lhsOppL)
)
-- cata
{-# NOINLINE sem_CProductions #-}
sem_CProductions :: CProductions -> T_CProductions
sem_CProductions list = Prelude.foldr sem_CProductions_Cons sem_CProductions_Nil (Prelude.map sem_CProduction list)
-- semantic domain
newtype T_CProductions = T_CProductions {
attach_T_CProductions :: Identity (T_CProductions_s17 )
}
newtype T_CProductions_s17 = C_CProductions_s17 {
inv_CProductions_s17 :: (T_CProductions_v16 )
}
data T_CProductions_s18 = C_CProductions_s18
type T_CProductions_v16 = (T_CProductions_vIn16 ) -> (T_CProductions_vOut16 )
data T_CProductions_vIn16 = T_CProductions_vIn16
data T_CProductions_vOut16 = T_CProductions_vOut16 (PP_Doc) ([PP_Doc])
{-# NOINLINE sem_CProductions_Cons #-}
sem_CProductions_Cons :: T_CProduction -> T_CProductions -> T_CProductions
sem_CProductions_Cons arg_hd_ arg_tl_ = T_CProductions (return st17) where
{-# NOINLINE st17 #-}
st17 = let
v16 :: T_CProductions_v16
v16 = \ (T_CProductions_vIn16 ) -> ( let
_hdX14 = Control.Monad.Identity.runIdentity (attach_T_CProduction (arg_hd_))
_tlX17 = Control.Monad.Identity.runIdentity (attach_T_CProductions (arg_tl_))
(T_CProduction_vOut13 _hdIpp) = inv_CProduction_s14 _hdX14 (T_CProduction_vIn13 )
(T_CProductions_vOut16 _tlIpp _tlIppL) = inv_CProductions_s17 _tlX17 (T_CProductions_vIn16 )
_lhsOppL :: [PP_Doc]
_lhsOppL = rule8 _hdIpp _tlIppL
_lhsOpp :: PP_Doc
_lhsOpp = rule9 _hdIpp _tlIpp
__result_ = T_CProductions_vOut16 _lhsOpp _lhsOppL
in __result_ )
in C_CProductions_s17 v16
{-# INLINE rule8 #-}
{-# LINE 94 "./src-ag/CodeSyntaxDump.ag" #-}
rule8 = \ ((_hdIpp) :: PP_Doc) ((_tlIppL) :: [PP_Doc]) ->
{-# LINE 94 "./src-ag/CodeSyntaxDump.ag" #-}
_hdIpp : _tlIppL
{-# LINE 405 "dist/build/CodeSyntaxDump.hs"#-}
{-# INLINE rule9 #-}
rule9 = \ ((_hdIpp) :: PP_Doc) ((_tlIpp) :: PP_Doc) ->
_hdIpp >-< _tlIpp
{-# NOINLINE sem_CProductions_Nil #-}
sem_CProductions_Nil :: T_CProductions
sem_CProductions_Nil = T_CProductions (return st17) where
{-# NOINLINE st17 #-}
st17 = let
v16 :: T_CProductions_v16
v16 = \ (T_CProductions_vIn16 ) -> ( let
_lhsOppL :: [PP_Doc]
_lhsOppL = rule10 ()
_lhsOpp :: PP_Doc
_lhsOpp = rule11 ()
__result_ = T_CProductions_vOut16 _lhsOpp _lhsOppL
in __result_ )
in C_CProductions_s17 v16
{-# INLINE rule10 #-}
{-# LINE 95 "./src-ag/CodeSyntaxDump.ag" #-}
rule10 = \ (_ :: ()) ->
{-# LINE 95 "./src-ag/CodeSyntaxDump.ag" #-}
[]
{-# LINE 428 "dist/build/CodeSyntaxDump.hs"#-}
{-# INLINE rule11 #-}
rule11 = \ (_ :: ()) ->
empty
-- CRule -------------------------------------------------------
-- wrapper
data Inh_CRule = Inh_CRule { }
data Syn_CRule = Syn_CRule { pp_Syn_CRule :: (PP_Doc) }
{-# INLINABLE wrap_CRule #-}
wrap_CRule :: T_CRule -> Inh_CRule -> (Syn_CRule )
wrap_CRule (T_CRule act) (Inh_CRule ) =
Control.Monad.Identity.runIdentity (
do sem <- act
let arg = T_CRule_vIn19
(T_CRule_vOut19 _lhsOpp) <- return (inv_CRule_s20 sem arg)
return (Syn_CRule _lhsOpp)
)
-- cata
{-# NOINLINE sem_CRule #-}
sem_CRule :: CRule -> T_CRule
sem_CRule ( CRule name_ isIn_ hasCode_ nt_ con_ field_ childnt_ tp_ pattern_ rhs_ defines_ owrt_ origin_ uses_ explicit_ mbNamed_ ) = sem_CRule_CRule name_ isIn_ hasCode_ nt_ con_ field_ childnt_ tp_ ( sem_Pattern pattern_ ) rhs_ defines_ owrt_ origin_ uses_ explicit_ mbNamed_
sem_CRule ( CChildVisit name_ nt_ nr_ inh_ syn_ isLast_ ) = sem_CRule_CChildVisit name_ nt_ nr_ inh_ syn_ isLast_
-- semantic domain
newtype T_CRule = T_CRule {
attach_T_CRule :: Identity (T_CRule_s20 )
}
newtype T_CRule_s20 = C_CRule_s20 {
inv_CRule_s20 :: (T_CRule_v19 )
}
data T_CRule_s21 = C_CRule_s21
type T_CRule_v19 = (T_CRule_vIn19 ) -> (T_CRule_vOut19 )
data T_CRule_vIn19 = T_CRule_vIn19
data T_CRule_vOut19 = T_CRule_vOut19 (PP_Doc)
{-# NOINLINE sem_CRule_CRule #-}
sem_CRule_CRule :: (Identifier) -> (Bool) -> (Bool) -> (NontermIdent) -> (ConstructorIdent) -> (Identifier) -> (Maybe NontermIdent) -> (Maybe Type) -> T_Pattern -> ([String]) -> (Map Int (Identifier,Identifier,Maybe Type)) -> (Bool) -> (String) -> (Set (Identifier, Identifier)) -> (Bool) -> (Maybe Identifier) -> T_CRule
sem_CRule_CRule arg_name_ arg_isIn_ arg_hasCode_ arg_nt_ arg_con_ arg_field_ arg_childnt_ arg_tp_ arg_pattern_ arg_rhs_ arg_defines_ arg_owrt_ arg_origin_ _ _ _ = T_CRule (return st20) where
{-# NOINLINE st20 #-}
st20 = let
v19 :: T_CRule_v19
v19 = \ (T_CRule_vIn19 ) -> ( let
_patternX35 = Control.Monad.Identity.runIdentity (attach_T_Pattern (arg_pattern_))
(T_Pattern_vOut34 _patternIcopy _patternIpp) = inv_Pattern_s35 _patternX35 (T_Pattern_vIn34 )
_lhsOpp :: PP_Doc
_lhsOpp = rule12 _patternIpp arg_childnt_ arg_con_ arg_defines_ arg_field_ arg_hasCode_ arg_isIn_ arg_name_ arg_nt_ arg_origin_ arg_owrt_ arg_rhs_ arg_tp_
__result_ = T_CRule_vOut19 _lhsOpp
in __result_ )
in C_CRule_s20 v19
{-# INLINE rule12 #-}
{-# LINE 69 "./src-ag/CodeSyntaxDump.ag" #-}
rule12 = \ ((_patternIpp) :: PP_Doc) childnt_ con_ defines_ field_ hasCode_ isIn_ name_ nt_ origin_ owrt_ rhs_ tp_ ->
{-# LINE 69 "./src-ag/CodeSyntaxDump.ag" #-}
ppNestInfo ["CRule","CRule"] [pp name_] [ppF "isIn" $ ppBool isIn_, ppF "hasCode" $ ppBool hasCode_, ppF "nt" $ pp nt_, ppF "con" $ pp con_, ppF "field" $ pp field_, ppF "childnt" $ ppMaybeShow childnt_, ppF "tp" $ ppMaybeShow tp_, ppF "pattern" $ if isIn_ then pp "<no pat because In>" else _patternIpp, ppF "rhs" $ ppStrings rhs_, ppF "defines" $ ppVertexMap defines_, ppF "owrt" $ ppBool owrt_, ppF "origin" $ pp origin_] []
{-# LINE 483 "dist/build/CodeSyntaxDump.hs"#-}
{-# NOINLINE sem_CRule_CChildVisit #-}
sem_CRule_CChildVisit :: (Identifier) -> (NontermIdent) -> (Int) -> (Attributes) -> (Attributes) -> (Bool) -> T_CRule
sem_CRule_CChildVisit arg_name_ arg_nt_ arg_nr_ arg_inh_ arg_syn_ arg_isLast_ = T_CRule (return st20) where
{-# NOINLINE st20 #-}
st20 = let
v19 :: T_CRule_v19
v19 = \ (T_CRule_vIn19 ) -> ( let
_lhsOpp :: PP_Doc
_lhsOpp = rule13 arg_inh_ arg_isLast_ arg_name_ arg_nr_ arg_nt_ arg_syn_
__result_ = T_CRule_vOut19 _lhsOpp
in __result_ )
in C_CRule_s20 v19
{-# INLINE rule13 #-}
{-# LINE 70 "./src-ag/CodeSyntaxDump.ag" #-}
rule13 = \ inh_ isLast_ name_ nr_ nt_ syn_ ->
{-# LINE 70 "./src-ag/CodeSyntaxDump.ag" #-}
ppNestInfo ["CRule","CChildVisit"] [pp name_] [ppF "nt" $ pp nt_, ppF "nr" $ ppShow nr_, ppF "inh" $ ppMap inh_, ppF "syn" $ ppMap syn_, ppF "last" $ ppBool isLast_] []
{-# LINE 501 "dist/build/CodeSyntaxDump.hs"#-}
-- CSegment ----------------------------------------------------
-- wrapper
data Inh_CSegment = Inh_CSegment { }
data Syn_CSegment = Syn_CSegment { pp_Syn_CSegment :: (PP_Doc) }
{-# INLINABLE wrap_CSegment #-}
wrap_CSegment :: T_CSegment -> Inh_CSegment -> (Syn_CSegment )
wrap_CSegment (T_CSegment act) (Inh_CSegment ) =
Control.Monad.Identity.runIdentity (
do sem <- act
let arg = T_CSegment_vIn22
(T_CSegment_vOut22 _lhsOpp) <- return (inv_CSegment_s23 sem arg)
return (Syn_CSegment _lhsOpp)
)
-- cata
{-# INLINE sem_CSegment #-}
sem_CSegment :: CSegment -> T_CSegment
sem_CSegment ( CSegment inh_ syn_ ) = sem_CSegment_CSegment inh_ syn_
-- semantic domain
newtype T_CSegment = T_CSegment {
attach_T_CSegment :: Identity (T_CSegment_s23 )
}
newtype T_CSegment_s23 = C_CSegment_s23 {
inv_CSegment_s23 :: (T_CSegment_v22 )
}
data T_CSegment_s24 = C_CSegment_s24
type T_CSegment_v22 = (T_CSegment_vIn22 ) -> (T_CSegment_vOut22 )
data T_CSegment_vIn22 = T_CSegment_vIn22
data T_CSegment_vOut22 = T_CSegment_vOut22 (PP_Doc)
{-# NOINLINE sem_CSegment_CSegment #-}
sem_CSegment_CSegment :: (Attributes) -> (Attributes) -> T_CSegment
sem_CSegment_CSegment arg_inh_ arg_syn_ = T_CSegment (return st23) where
{-# NOINLINE st23 #-}
st23 = let
v22 :: T_CSegment_v22
v22 = \ (T_CSegment_vIn22 ) -> ( let
_lhsOpp :: PP_Doc
_lhsOpp = rule14 arg_inh_ arg_syn_
__result_ = T_CSegment_vOut22 _lhsOpp
in __result_ )
in C_CSegment_s23 v22
{-# INLINE rule14 #-}
{-# LINE 60 "./src-ag/CodeSyntaxDump.ag" #-}
rule14 = \ inh_ syn_ ->
{-# LINE 60 "./src-ag/CodeSyntaxDump.ag" #-}
ppNestInfo ["CSegment","CSegment"] [] [ppF "inh" $ ppMap inh_, ppF "syn" $ ppMap syn_] []
{-# LINE 550 "dist/build/CodeSyntaxDump.hs"#-}
-- CSegments ---------------------------------------------------
-- wrapper
data Inh_CSegments = Inh_CSegments { }
data Syn_CSegments = Syn_CSegments { pp_Syn_CSegments :: (PP_Doc), ppL_Syn_CSegments :: ([PP_Doc]) }
{-# INLINABLE wrap_CSegments #-}
wrap_CSegments :: T_CSegments -> Inh_CSegments -> (Syn_CSegments )
wrap_CSegments (T_CSegments act) (Inh_CSegments ) =
Control.Monad.Identity.runIdentity (
do sem <- act
let arg = T_CSegments_vIn25
(T_CSegments_vOut25 _lhsOpp _lhsOppL) <- return (inv_CSegments_s26 sem arg)
return (Syn_CSegments _lhsOpp _lhsOppL)
)
-- cata
{-# NOINLINE sem_CSegments #-}
sem_CSegments :: CSegments -> T_CSegments
sem_CSegments list = Prelude.foldr sem_CSegments_Cons sem_CSegments_Nil (Prelude.map sem_CSegment list)
-- semantic domain
newtype T_CSegments = T_CSegments {
attach_T_CSegments :: Identity (T_CSegments_s26 )
}
newtype T_CSegments_s26 = C_CSegments_s26 {
inv_CSegments_s26 :: (T_CSegments_v25 )
}
data T_CSegments_s27 = C_CSegments_s27
type T_CSegments_v25 = (T_CSegments_vIn25 ) -> (T_CSegments_vOut25 )
data T_CSegments_vIn25 = T_CSegments_vIn25
data T_CSegments_vOut25 = T_CSegments_vOut25 (PP_Doc) ([PP_Doc])
{-# NOINLINE sem_CSegments_Cons #-}
sem_CSegments_Cons :: T_CSegment -> T_CSegments -> T_CSegments
sem_CSegments_Cons arg_hd_ arg_tl_ = T_CSegments (return st26) where
{-# NOINLINE st26 #-}
st26 = let
v25 :: T_CSegments_v25
v25 = \ (T_CSegments_vIn25 ) -> ( let
_hdX23 = Control.Monad.Identity.runIdentity (attach_T_CSegment (arg_hd_))
_tlX26 = Control.Monad.Identity.runIdentity (attach_T_CSegments (arg_tl_))
(T_CSegment_vOut22 _hdIpp) = inv_CSegment_s23 _hdX23 (T_CSegment_vIn22 )
(T_CSegments_vOut25 _tlIpp _tlIppL) = inv_CSegments_s26 _tlX26 (T_CSegments_vIn25 )
_lhsOppL :: [PP_Doc]
_lhsOppL = rule15 _hdIpp _tlIppL
_lhsOpp :: PP_Doc
_lhsOpp = rule16 _hdIpp _tlIpp
__result_ = T_CSegments_vOut25 _lhsOpp _lhsOppL
in __result_ )
in C_CSegments_s26 v25
{-# INLINE rule15 #-}
{-# LINE 98 "./src-ag/CodeSyntaxDump.ag" #-}
rule15 = \ ((_hdIpp) :: PP_Doc) ((_tlIppL) :: [PP_Doc]) ->
{-# LINE 98 "./src-ag/CodeSyntaxDump.ag" #-}
_hdIpp : _tlIppL
{-# LINE 605 "dist/build/CodeSyntaxDump.hs"#-}
{-# INLINE rule16 #-}
rule16 = \ ((_hdIpp) :: PP_Doc) ((_tlIpp) :: PP_Doc) ->
_hdIpp >-< _tlIpp
{-# NOINLINE sem_CSegments_Nil #-}
sem_CSegments_Nil :: T_CSegments
sem_CSegments_Nil = T_CSegments (return st26) where
{-# NOINLINE st26 #-}
st26 = let
v25 :: T_CSegments_v25
v25 = \ (T_CSegments_vIn25 ) -> ( let
_lhsOppL :: [PP_Doc]
_lhsOppL = rule17 ()
_lhsOpp :: PP_Doc
_lhsOpp = rule18 ()
__result_ = T_CSegments_vOut25 _lhsOpp _lhsOppL
in __result_ )
in C_CSegments_s26 v25
{-# INLINE rule17 #-}
{-# LINE 99 "./src-ag/CodeSyntaxDump.ag" #-}
rule17 = \ (_ :: ()) ->
{-# LINE 99 "./src-ag/CodeSyntaxDump.ag" #-}
[]
{-# LINE 628 "dist/build/CodeSyntaxDump.hs"#-}
{-# INLINE rule18 #-}
rule18 = \ (_ :: ()) ->
empty
-- CVisit ------------------------------------------------------
-- wrapper
data Inh_CVisit = Inh_CVisit { }
data Syn_CVisit = Syn_CVisit { pp_Syn_CVisit :: (PP_Doc) }
{-# INLINABLE wrap_CVisit #-}
wrap_CVisit :: T_CVisit -> Inh_CVisit -> (Syn_CVisit )
wrap_CVisit (T_CVisit act) (Inh_CVisit ) =
Control.Monad.Identity.runIdentity (
do sem <- act
let arg = T_CVisit_vIn28
(T_CVisit_vOut28 _lhsOpp) <- return (inv_CVisit_s29 sem arg)
return (Syn_CVisit _lhsOpp)
)
-- cata
{-# INLINE sem_CVisit #-}
sem_CVisit :: CVisit -> T_CVisit
sem_CVisit ( CVisit inh_ syn_ vss_ intra_ ordered_ ) = sem_CVisit_CVisit inh_ syn_ ( sem_Sequence vss_ ) ( sem_Sequence intra_ ) ordered_
-- semantic domain
newtype T_CVisit = T_CVisit {
attach_T_CVisit :: Identity (T_CVisit_s29 )
}
newtype T_CVisit_s29 = C_CVisit_s29 {
inv_CVisit_s29 :: (T_CVisit_v28 )
}
data T_CVisit_s30 = C_CVisit_s30
type T_CVisit_v28 = (T_CVisit_vIn28 ) -> (T_CVisit_vOut28 )
data T_CVisit_vIn28 = T_CVisit_vIn28
data T_CVisit_vOut28 = T_CVisit_vOut28 (PP_Doc)
{-# NOINLINE sem_CVisit_CVisit #-}
sem_CVisit_CVisit :: (Attributes) -> (Attributes) -> T_Sequence -> T_Sequence -> (Bool) -> T_CVisit
sem_CVisit_CVisit arg_inh_ arg_syn_ arg_vss_ arg_intra_ arg_ordered_ = T_CVisit (return st29) where
{-# NOINLINE st29 #-}
st29 = let
v28 :: T_CVisit_v28
v28 = \ (T_CVisit_vIn28 ) -> ( let
_vssX41 = Control.Monad.Identity.runIdentity (attach_T_Sequence (arg_vss_))
_intraX41 = Control.Monad.Identity.runIdentity (attach_T_Sequence (arg_intra_))
(T_Sequence_vOut40 _vssIppL) = inv_Sequence_s41 _vssX41 (T_Sequence_vIn40 )
(T_Sequence_vOut40 _intraIppL) = inv_Sequence_s41 _intraX41 (T_Sequence_vIn40 )
_lhsOpp :: PP_Doc
_lhsOpp = rule19 _intraIppL _vssIppL arg_inh_ arg_ordered_ arg_syn_
__result_ = T_CVisit_vOut28 _lhsOpp
in __result_ )
in C_CVisit_s29 v28
{-# INLINE rule19 #-}
{-# LINE 66 "./src-ag/CodeSyntaxDump.ag" #-}
rule19 = \ ((_intraIppL) :: [PP_Doc]) ((_vssIppL) :: [PP_Doc]) inh_ ordered_ syn_ ->
{-# LINE 66 "./src-ag/CodeSyntaxDump.ag" #-}
ppNestInfo ["CVisit","CVisit"] [] [ppF "inh" $ ppMap inh_, ppF "syn" $ ppMap syn_, ppF "sequence" $ ppVList _vssIppL, ppF "intra" $ ppVList _intraIppL, ppF "ordered" $ ppBool ordered_] []
{-# LINE 684 "dist/build/CodeSyntaxDump.hs"#-}
-- CVisits -----------------------------------------------------
-- wrapper
data Inh_CVisits = Inh_CVisits { }
data Syn_CVisits = Syn_CVisits { pp_Syn_CVisits :: (PP_Doc), ppL_Syn_CVisits :: ([PP_Doc]) }
{-# INLINABLE wrap_CVisits #-}
wrap_CVisits :: T_CVisits -> Inh_CVisits -> (Syn_CVisits )
wrap_CVisits (T_CVisits act) (Inh_CVisits ) =
Control.Monad.Identity.runIdentity (
do sem <- act
let arg = T_CVisits_vIn31
(T_CVisits_vOut31 _lhsOpp _lhsOppL) <- return (inv_CVisits_s32 sem arg)
return (Syn_CVisits _lhsOpp _lhsOppL)
)
-- cata
{-# NOINLINE sem_CVisits #-}
sem_CVisits :: CVisits -> T_CVisits
sem_CVisits list = Prelude.foldr sem_CVisits_Cons sem_CVisits_Nil (Prelude.map sem_CVisit list)
-- semantic domain
newtype T_CVisits = T_CVisits {
attach_T_CVisits :: Identity (T_CVisits_s32 )
}
newtype T_CVisits_s32 = C_CVisits_s32 {
inv_CVisits_s32 :: (T_CVisits_v31 )
}
data T_CVisits_s33 = C_CVisits_s33
type T_CVisits_v31 = (T_CVisits_vIn31 ) -> (T_CVisits_vOut31 )
data T_CVisits_vIn31 = T_CVisits_vIn31
data T_CVisits_vOut31 = T_CVisits_vOut31 (PP_Doc) ([PP_Doc])
{-# NOINLINE sem_CVisits_Cons #-}
sem_CVisits_Cons :: T_CVisit -> T_CVisits -> T_CVisits
sem_CVisits_Cons arg_hd_ arg_tl_ = T_CVisits (return st32) where
{-# NOINLINE st32 #-}
st32 = let
v31 :: T_CVisits_v31
v31 = \ (T_CVisits_vIn31 ) -> ( let
_hdX29 = Control.Monad.Identity.runIdentity (attach_T_CVisit (arg_hd_))
_tlX32 = Control.Monad.Identity.runIdentity (attach_T_CVisits (arg_tl_))
(T_CVisit_vOut28 _hdIpp) = inv_CVisit_s29 _hdX29 (T_CVisit_vIn28 )
(T_CVisits_vOut31 _tlIpp _tlIppL) = inv_CVisits_s32 _tlX32 (T_CVisits_vIn31 )
_lhsOppL :: [PP_Doc]
_lhsOppL = rule20 _hdIpp _tlIppL
_lhsOpp :: PP_Doc
_lhsOpp = rule21 _hdIpp _tlIpp
__result_ = T_CVisits_vOut31 _lhsOpp _lhsOppL
in __result_ )
in C_CVisits_s32 v31
{-# INLINE rule20 #-}
{-# LINE 90 "./src-ag/CodeSyntaxDump.ag" #-}
rule20 = \ ((_hdIpp) :: PP_Doc) ((_tlIppL) :: [PP_Doc]) ->
{-# LINE 90 "./src-ag/CodeSyntaxDump.ag" #-}
_hdIpp : _tlIppL
{-# LINE 739 "dist/build/CodeSyntaxDump.hs"#-}
{-# INLINE rule21 #-}
rule21 = \ ((_hdIpp) :: PP_Doc) ((_tlIpp) :: PP_Doc) ->
_hdIpp >-< _tlIpp
{-# NOINLINE sem_CVisits_Nil #-}
sem_CVisits_Nil :: T_CVisits
sem_CVisits_Nil = T_CVisits (return st32) where
{-# NOINLINE st32 #-}
st32 = let
v31 :: T_CVisits_v31
v31 = \ (T_CVisits_vIn31 ) -> ( let
_lhsOppL :: [PP_Doc]
_lhsOppL = rule22 ()
_lhsOpp :: PP_Doc
_lhsOpp = rule23 ()
__result_ = T_CVisits_vOut31 _lhsOpp _lhsOppL
in __result_ )
in C_CVisits_s32 v31
{-# INLINE rule22 #-}
{-# LINE 91 "./src-ag/CodeSyntaxDump.ag" #-}
rule22 = \ (_ :: ()) ->
{-# LINE 91 "./src-ag/CodeSyntaxDump.ag" #-}
[]
{-# LINE 762 "dist/build/CodeSyntaxDump.hs"#-}
{-# INLINE rule23 #-}
rule23 = \ (_ :: ()) ->
empty
-- Pattern -----------------------------------------------------
-- wrapper
data Inh_Pattern = Inh_Pattern { }
data Syn_Pattern = Syn_Pattern { copy_Syn_Pattern :: (Pattern), pp_Syn_Pattern :: (PP_Doc) }
{-# INLINABLE wrap_Pattern #-}
wrap_Pattern :: T_Pattern -> Inh_Pattern -> (Syn_Pattern )
wrap_Pattern (T_Pattern act) (Inh_Pattern ) =
Control.Monad.Identity.runIdentity (
do sem <- act
let arg = T_Pattern_vIn34
(T_Pattern_vOut34 _lhsOcopy _lhsOpp) <- return (inv_Pattern_s35 sem arg)
return (Syn_Pattern _lhsOcopy _lhsOpp)
)
-- cata
{-# NOINLINE sem_Pattern #-}
sem_Pattern :: Pattern -> T_Pattern
sem_Pattern ( Constr name_ pats_ ) = sem_Pattern_Constr name_ ( sem_Patterns pats_ )
sem_Pattern ( Product pos_ pats_ ) = sem_Pattern_Product pos_ ( sem_Patterns pats_ )
sem_Pattern ( Alias field_ attr_ pat_ ) = sem_Pattern_Alias field_ attr_ ( sem_Pattern pat_ )
sem_Pattern ( Irrefutable pat_ ) = sem_Pattern_Irrefutable ( sem_Pattern pat_ )
sem_Pattern ( Underscore pos_ ) = sem_Pattern_Underscore pos_
-- semantic domain
newtype T_Pattern = T_Pattern {
attach_T_Pattern :: Identity (T_Pattern_s35 )
}
newtype T_Pattern_s35 = C_Pattern_s35 {
inv_Pattern_s35 :: (T_Pattern_v34 )
}
data T_Pattern_s36 = C_Pattern_s36
type T_Pattern_v34 = (T_Pattern_vIn34 ) -> (T_Pattern_vOut34 )
data T_Pattern_vIn34 = T_Pattern_vIn34
data T_Pattern_vOut34 = T_Pattern_vOut34 (Pattern) (PP_Doc)
{-# NOINLINE sem_Pattern_Constr #-}
sem_Pattern_Constr :: (ConstructorIdent) -> T_Patterns -> T_Pattern
sem_Pattern_Constr arg_name_ arg_pats_ = T_Pattern (return st35) where
{-# NOINLINE st35 #-}
st35 = let
v34 :: T_Pattern_v34
v34 = \ (T_Pattern_vIn34 ) -> ( let
_patsX38 = Control.Monad.Identity.runIdentity (attach_T_Patterns (arg_pats_))
(T_Patterns_vOut37 _patsIcopy _patsIpp _patsIppL) = inv_Patterns_s38 _patsX38 (T_Patterns_vIn37 )
_lhsOpp :: PP_Doc
_lhsOpp = rule24 _patsIppL arg_name_
_copy = rule25 _patsIcopy arg_name_
_lhsOcopy :: Pattern
_lhsOcopy = rule26 _copy
__result_ = T_Pattern_vOut34 _lhsOcopy _lhsOpp
in __result_ )
in C_Pattern_s35 v34
{-# INLINE rule24 #-}
{-# LINE 73 "./src-ag/CodeSyntaxDump.ag" #-}
rule24 = \ ((_patsIppL) :: [PP_Doc]) name_ ->
{-# LINE 73 "./src-ag/CodeSyntaxDump.ag" #-}
ppNestInfo ["Pattern","Constr"] [pp name_] [ppF "pats" $ ppVList _patsIppL] []
{-# LINE 823 "dist/build/CodeSyntaxDump.hs"#-}
{-# INLINE rule25 #-}
rule25 = \ ((_patsIcopy) :: Patterns) name_ ->
Constr name_ _patsIcopy
{-# INLINE rule26 #-}
rule26 = \ _copy ->
_copy
{-# NOINLINE sem_Pattern_Product #-}
sem_Pattern_Product :: (Pos) -> T_Patterns -> T_Pattern
sem_Pattern_Product arg_pos_ arg_pats_ = T_Pattern (return st35) where
{-# NOINLINE st35 #-}
st35 = let
v34 :: T_Pattern_v34
v34 = \ (T_Pattern_vIn34 ) -> ( let
_patsX38 = Control.Monad.Identity.runIdentity (attach_T_Patterns (arg_pats_))
(T_Patterns_vOut37 _patsIcopy _patsIpp _patsIppL) = inv_Patterns_s38 _patsX38 (T_Patterns_vIn37 )
_lhsOpp :: PP_Doc
_lhsOpp = rule27 _patsIppL arg_pos_
_copy = rule28 _patsIcopy arg_pos_
_lhsOcopy :: Pattern
_lhsOcopy = rule29 _copy
__result_ = T_Pattern_vOut34 _lhsOcopy _lhsOpp
in __result_ )
in C_Pattern_s35 v34
{-# INLINE rule27 #-}
{-# LINE 74 "./src-ag/CodeSyntaxDump.ag" #-}
rule27 = \ ((_patsIppL) :: [PP_Doc]) pos_ ->
{-# LINE 74 "./src-ag/CodeSyntaxDump.ag" #-}
ppNestInfo ["Pattern","Product"] [ppShow pos_] [ppF "pats" $ ppVList _patsIppL] []
{-# LINE 852 "dist/build/CodeSyntaxDump.hs"#-}
{-# INLINE rule28 #-}
rule28 = \ ((_patsIcopy) :: Patterns) pos_ ->
Product pos_ _patsIcopy
{-# INLINE rule29 #-}
rule29 = \ _copy ->
_copy
{-# NOINLINE sem_Pattern_Alias #-}
sem_Pattern_Alias :: (Identifier) -> (Identifier) -> T_Pattern -> T_Pattern
sem_Pattern_Alias arg_field_ arg_attr_ arg_pat_ = T_Pattern (return st35) where
{-# NOINLINE st35 #-}
st35 = let
v34 :: T_Pattern_v34
v34 = \ (T_Pattern_vIn34 ) -> ( let
_patX35 = Control.Monad.Identity.runIdentity (attach_T_Pattern (arg_pat_))
(T_Pattern_vOut34 _patIcopy _patIpp) = inv_Pattern_s35 _patX35 (T_Pattern_vIn34 )
_lhsOpp :: PP_Doc
_lhsOpp = rule30 _patIpp arg_attr_ arg_field_
_copy = rule31 _patIcopy arg_attr_ arg_field_
_lhsOcopy :: Pattern
_lhsOcopy = rule32 _copy
__result_ = T_Pattern_vOut34 _lhsOcopy _lhsOpp
in __result_ )
in C_Pattern_s35 v34
{-# INLINE rule30 #-}
{-# LINE 75 "./src-ag/CodeSyntaxDump.ag" #-}
rule30 = \ ((_patIpp) :: PP_Doc) attr_ field_ ->
{-# LINE 75 "./src-ag/CodeSyntaxDump.ag" #-}
ppNestInfo ["Pattern","Alias"] [pp field_, pp attr_] [ppF "pat" $ _patIpp] []
{-# LINE 881 "dist/build/CodeSyntaxDump.hs"#-}
{-# INLINE rule31 #-}
rule31 = \ ((_patIcopy) :: Pattern) attr_ field_ ->
Alias field_ attr_ _patIcopy
{-# INLINE rule32 #-}
rule32 = \ _copy ->
_copy
{-# NOINLINE sem_Pattern_Irrefutable #-}
sem_Pattern_Irrefutable :: T_Pattern -> T_Pattern
sem_Pattern_Irrefutable arg_pat_ = T_Pattern (return st35) where
{-# NOINLINE st35 #-}
st35 = let
v34 :: T_Pattern_v34
v34 = \ (T_Pattern_vIn34 ) -> ( let
_patX35 = Control.Monad.Identity.runIdentity (attach_T_Pattern (arg_pat_))
(T_Pattern_vOut34 _patIcopy _patIpp) = inv_Pattern_s35 _patX35 (T_Pattern_vIn34 )
_lhsOpp :: PP_Doc
_lhsOpp = rule33 _patIpp
_copy = rule34 _patIcopy
_lhsOcopy :: Pattern
_lhsOcopy = rule35 _copy
__result_ = T_Pattern_vOut34 _lhsOcopy _lhsOpp
in __result_ )
in C_Pattern_s35 v34
{-# INLINE rule33 #-}
rule33 = \ ((_patIpp) :: PP_Doc) ->
_patIpp
{-# INLINE rule34 #-}
rule34 = \ ((_patIcopy) :: Pattern) ->
Irrefutable _patIcopy
{-# INLINE rule35 #-}
rule35 = \ _copy ->
_copy
{-# NOINLINE sem_Pattern_Underscore #-}
sem_Pattern_Underscore :: (Pos) -> T_Pattern
sem_Pattern_Underscore arg_pos_ = T_Pattern (return st35) where
{-# NOINLINE st35 #-}
st35 = let
v34 :: T_Pattern_v34
v34 = \ (T_Pattern_vIn34 ) -> ( let
_lhsOpp :: PP_Doc
_lhsOpp = rule36 arg_pos_
_copy = rule37 arg_pos_
_lhsOcopy :: Pattern
_lhsOcopy = rule38 _copy
__result_ = T_Pattern_vOut34 _lhsOcopy _lhsOpp
in __result_ )
in C_Pattern_s35 v34
{-# INLINE rule36 #-}
{-# LINE 76 "./src-ag/CodeSyntaxDump.ag" #-}
rule36 = \ pos_ ->
{-# LINE 76 "./src-ag/CodeSyntaxDump.ag" #-}
ppNestInfo ["Pattern","Underscore"] [ppShow pos_] [] []
{-# LINE 934 "dist/build/CodeSyntaxDump.hs"#-}
{-# INLINE rule37 #-}
rule37 = \ pos_ ->
Underscore pos_
{-# INLINE rule38 #-}
rule38 = \ _copy ->
_copy
-- Patterns ----------------------------------------------------
-- wrapper
data Inh_Patterns = Inh_Patterns { }
data Syn_Patterns = Syn_Patterns { copy_Syn_Patterns :: (Patterns), pp_Syn_Patterns :: (PP_Doc), ppL_Syn_Patterns :: ([PP_Doc]) }
{-# INLINABLE wrap_Patterns #-}
wrap_Patterns :: T_Patterns -> Inh_Patterns -> (Syn_Patterns )
wrap_Patterns (T_Patterns act) (Inh_Patterns ) =
Control.Monad.Identity.runIdentity (
do sem <- act
let arg = T_Patterns_vIn37
(T_Patterns_vOut37 _lhsOcopy _lhsOpp _lhsOppL) <- return (inv_Patterns_s38 sem arg)
return (Syn_Patterns _lhsOcopy _lhsOpp _lhsOppL)
)
-- cata
{-# NOINLINE sem_Patterns #-}
sem_Patterns :: Patterns -> T_Patterns
sem_Patterns list = Prelude.foldr sem_Patterns_Cons sem_Patterns_Nil (Prelude.map sem_Pattern list)
-- semantic domain
newtype T_Patterns = T_Patterns {
attach_T_Patterns :: Identity (T_Patterns_s38 )
}
newtype T_Patterns_s38 = C_Patterns_s38 {
inv_Patterns_s38 :: (T_Patterns_v37 )
}
data T_Patterns_s39 = C_Patterns_s39
type T_Patterns_v37 = (T_Patterns_vIn37 ) -> (T_Patterns_vOut37 )
data T_Patterns_vIn37 = T_Patterns_vIn37
data T_Patterns_vOut37 = T_Patterns_vOut37 (Patterns) (PP_Doc) ([PP_Doc])
{-# NOINLINE sem_Patterns_Cons #-}
sem_Patterns_Cons :: T_Pattern -> T_Patterns -> T_Patterns
sem_Patterns_Cons arg_hd_ arg_tl_ = T_Patterns (return st38) where
{-# NOINLINE st38 #-}
st38 = let
v37 :: T_Patterns_v37
v37 = \ (T_Patterns_vIn37 ) -> ( let
_hdX35 = Control.Monad.Identity.runIdentity (attach_T_Pattern (arg_hd_))
_tlX38 = Control.Monad.Identity.runIdentity (attach_T_Patterns (arg_tl_))
(T_Pattern_vOut34 _hdIcopy _hdIpp) = inv_Pattern_s35 _hdX35 (T_Pattern_vIn34 )
(T_Patterns_vOut37 _tlIcopy _tlIpp _tlIppL) = inv_Patterns_s38 _tlX38 (T_Patterns_vIn37 )
_lhsOppL :: [PP_Doc]
_lhsOppL = rule39 _hdIpp _tlIppL
_lhsOpp :: PP_Doc
_lhsOpp = rule40 _hdIpp _tlIpp
_copy = rule41 _hdIcopy _tlIcopy
_lhsOcopy :: Patterns
_lhsOcopy = rule42 _copy
__result_ = T_Patterns_vOut37 _lhsOcopy _lhsOpp _lhsOppL
in __result_ )
in C_Patterns_s38 v37
{-# INLINE rule39 #-}
{-# LINE 82 "./src-ag/CodeSyntaxDump.ag" #-}
rule39 = \ ((_hdIpp) :: PP_Doc) ((_tlIppL) :: [PP_Doc]) ->
{-# LINE 82 "./src-ag/CodeSyntaxDump.ag" #-}
_hdIpp : _tlIppL
{-# LINE 998 "dist/build/CodeSyntaxDump.hs"#-}
{-# INLINE rule40 #-}
rule40 = \ ((_hdIpp) :: PP_Doc) ((_tlIpp) :: PP_Doc) ->
_hdIpp >-< _tlIpp
{-# INLINE rule41 #-}
rule41 = \ ((_hdIcopy) :: Pattern) ((_tlIcopy) :: Patterns) ->
(:) _hdIcopy _tlIcopy
{-# INLINE rule42 #-}
rule42 = \ _copy ->
_copy
{-# NOINLINE sem_Patterns_Nil #-}
sem_Patterns_Nil :: T_Patterns
sem_Patterns_Nil = T_Patterns (return st38) where
{-# NOINLINE st38 #-}
st38 = let
v37 :: T_Patterns_v37
v37 = \ (T_Patterns_vIn37 ) -> ( let
_lhsOppL :: [PP_Doc]
_lhsOppL = rule43 ()
_lhsOpp :: PP_Doc
_lhsOpp = rule44 ()
_copy = rule45 ()
_lhsOcopy :: Patterns
_lhsOcopy = rule46 _copy
__result_ = T_Patterns_vOut37 _lhsOcopy _lhsOpp _lhsOppL
in __result_ )
in C_Patterns_s38 v37
{-# INLINE rule43 #-}
{-# LINE 83 "./src-ag/CodeSyntaxDump.ag" #-}
rule43 = \ (_ :: ()) ->
{-# LINE 83 "./src-ag/CodeSyntaxDump.ag" #-}
[]
{-# LINE 1030 "dist/build/CodeSyntaxDump.hs"#-}
{-# INLINE rule44 #-}
rule44 = \ (_ :: ()) ->
empty
{-# INLINE rule45 #-}
rule45 = \ (_ :: ()) ->
[]
{-# INLINE rule46 #-}
rule46 = \ _copy ->
_copy
-- Sequence ----------------------------------------------------
-- wrapper
data Inh_Sequence = Inh_Sequence { }
data Syn_Sequence = Syn_Sequence { ppL_Syn_Sequence :: ([PP_Doc]) }
{-# INLINABLE wrap_Sequence #-}
wrap_Sequence :: T_Sequence -> Inh_Sequence -> (Syn_Sequence )
wrap_Sequence (T_Sequence act) (Inh_Sequence ) =
Control.Monad.Identity.runIdentity (
do sem <- act
let arg = T_Sequence_vIn40
(T_Sequence_vOut40 _lhsOppL) <- return (inv_Sequence_s41 sem arg)
return (Syn_Sequence _lhsOppL)
)
-- cata
{-# NOINLINE sem_Sequence #-}
sem_Sequence :: Sequence -> T_Sequence
sem_Sequence list = Prelude.foldr sem_Sequence_Cons sem_Sequence_Nil (Prelude.map sem_CRule list)
-- semantic domain
newtype T_Sequence = T_Sequence {
attach_T_Sequence :: Identity (T_Sequence_s41 )
}
newtype T_Sequence_s41 = C_Sequence_s41 {
inv_Sequence_s41 :: (T_Sequence_v40 )
}
data T_Sequence_s42 = C_Sequence_s42
type T_Sequence_v40 = (T_Sequence_vIn40 ) -> (T_Sequence_vOut40 )
data T_Sequence_vIn40 = T_Sequence_vIn40
data T_Sequence_vOut40 = T_Sequence_vOut40 ([PP_Doc])
{-# NOINLINE sem_Sequence_Cons #-}
sem_Sequence_Cons :: T_CRule -> T_Sequence -> T_Sequence
sem_Sequence_Cons arg_hd_ arg_tl_ = T_Sequence (return st41) where
{-# NOINLINE st41 #-}
st41 = let
v40 :: T_Sequence_v40
v40 = \ (T_Sequence_vIn40 ) -> ( let
_hdX20 = Control.Monad.Identity.runIdentity (attach_T_CRule (arg_hd_))
_tlX41 = Control.Monad.Identity.runIdentity (attach_T_Sequence (arg_tl_))
(T_CRule_vOut19 _hdIpp) = inv_CRule_s20 _hdX20 (T_CRule_vIn19 )
(T_Sequence_vOut40 _tlIppL) = inv_Sequence_s41 _tlX41 (T_Sequence_vIn40 )
_lhsOppL :: [PP_Doc]
_lhsOppL = rule47 _hdIpp _tlIppL
__result_ = T_Sequence_vOut40 _lhsOppL
in __result_ )
in C_Sequence_s41 v40
{-# INLINE rule47 #-}
{-# LINE 86 "./src-ag/CodeSyntaxDump.ag" #-}
rule47 = \ ((_hdIpp) :: PP_Doc) ((_tlIppL) :: [PP_Doc]) ->
{-# LINE 86 "./src-ag/CodeSyntaxDump.ag" #-}
_hdIpp : _tlIppL
{-# LINE 1092 "dist/build/CodeSyntaxDump.hs"#-}
{-# NOINLINE sem_Sequence_Nil #-}
sem_Sequence_Nil :: T_Sequence
sem_Sequence_Nil = T_Sequence (return st41) where
{-# NOINLINE st41 #-}
st41 = let
v40 :: T_Sequence_v40
v40 = \ (T_Sequence_vIn40 ) -> ( let
_lhsOppL :: [PP_Doc]
_lhsOppL = rule48 ()
__result_ = T_Sequence_vOut40 _lhsOppL
in __result_ )
in C_Sequence_s41 v40
{-# INLINE rule48 #-}
{-# LINE 87 "./src-ag/CodeSyntaxDump.ag" #-}
rule48 = \ (_ :: ()) ->
{-# LINE 87 "./src-ag/CodeSyntaxDump.ag" #-}
[]
{-# LINE 1110 "dist/build/CodeSyntaxDump.hs"#-}
|
norm2782/uuagc
|
src-generated/CodeSyntaxDump.hs
|
bsd-3-clause
| 53,365 | 14 | 22 | 16,287 | 10,656 | 5,865 | 4,791 | 847 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
module NXT.Parser.AttoParser
( parseFile
, pFullParser
)
where
import NXT.Types
import qualified NXT.Parser.AttoExpr as E
import GHC.Float
import Data.Attoparsec.Text
import Data.Char (isSpace, isAlpha, isAlphaNum)
import qualified Data.Text as T
import Data.Maybe
import Numeric (readHex)
import Control.Applicative
import Prelude hiding (takeWhile)
-- | Helpers
parseFile :: FilePath -> IO (Either String [Definition])
parseFile fname =
do inp <- readFile fname
return $ parseOnly pFullParser (T.pack inp)
-- | Program parser
pFullParser =
((stripSpace $ many1 pDef) <* endOfInput)
pDef =
pConst <|>
pLibDef <|>
pFun
pConst =
mk <$> ((string "const" *> space_) *> pName <* (char '=' <* optSpace_)) <*> (stripSpace pExpr <* pStmtEnd)
where
mk a b = PConst $ ConstDefinition (T.unpack a) b
pFun =
mk <$> ((string "function" *> space_) *> pName)
<*> tupleP pName
<*> (stripSpace $ (braced (char '{') (char '}') (many pStmt)))
<* optSpace_
where
mk name args body =
PFun $ FunDefinition (T.unpack name) "dynamic" (map (\x -> DeclVar "dynamic" (VarP $ T.unpack x)) args) $ concat body
pLibDef =
mk <$> ((string "libDef" *> space_) *> (pTy <* char ':'))
<*> pName
<*> tupleP pTy
<* pStmtEnd
where
mk extType name extArgTys =
PLib $ LibCallDefinition (T.unpack name) extType extArgTys
pTy =
const NXTString <$> string "string" <|>
const NXTBool <$> string "bool" <|>
const NXTInt <$> string "int" <|>
const NXTFloat <$> string "float" <|>
const NXTVoid <$> string "void"
pStmt = stripSpace pStmt'
pStmt' =
pDecl <|>
pDeclAndAssign <|>
pAssign <|>
pIf <|>
pWhile <|>
pReturn <|>
pEval
pDecl =
mk <$> ((string "var" *> space_) *> pName <* pStmtEnd)
where
mk a = [DeclVar "dynamic" (VarP $ T.unpack a)]
pDeclAndAssign =
mk <$> ((string "var" *> space_) *> pName <* (char '=' <* optSpace_)) <*> (stripSpace pExpr <* pStmtEnd)
where
mk a b = [ DeclVar "dynamic" (VarP $ T.unpack a)
, AssignVar (VarP $ T.unpack a) b
]
pAssign =
mk <$> (pName <* (char '=' <* optSpace_)) <*> (stripSpace pExpr <* pStmtEnd)
where
mk a b = [ AssignVar (VarP $ T.unpack a) b ]
pWhile =
mk <$> pCond "while"
where
mk (a, b) = [While a b]
pIf =
mk <$> pCond "if"
<*> many (pCond "else if")
<*> (option [] $ (stripSpace (string "else")) *> (stripSpace $ (braced (char '{') (char '}') (many pStmt))) <* optSpace_)
where
mk a b c = [mkIf a b $ concat c]
mkIf :: (T, [Stmt]) -> [(T, [Stmt])] -> [Stmt] -> Stmt
mkIf (cond, body) (x:xs) elseBody =
If cond body [(mkIf x xs elseBody)]
mkIf (cond, body) [] elseBody =
If cond body elseBody
pReturn =
mk <$> ((string "return" *> space_) *> pExpr <* pStmtEnd)
where
mk a = [FunReturn a]
pEval =
mk <$> pExpr <* pStmtEnd
where
mk a = [Eval a]
pCond :: T.Text -> Parser (T, [Stmt])
pCond condName =
mk <$> ((stripSpace $ string condName) *> (braced (char '(') (char ')') pExpr))
<*> (stripSpace $ (braced (char '{') (char '}') (many pStmt)))
<* optSpace_
where
mk a b = (a, concat b)
pExpr =
E.buildExpressionParser opTable pValExpr
pValExpr =
braced (char '(') (char ')') pExpr <|>
BoolLit <$> pBool <|>
(StrLit . T.unpack) <$> stringP <|>
mkLit <$> number <|>
pFunCall <|>
(VarP . T.unpack) <$> pName
where
mkLit n =
case n of
I int -> Lit $ fromIntegral int
D dbl -> Rat $ double2Float dbl
pFunCall =
fun <$> pName <*> tupleP pExpr
where
fun name args =
FunCall (T.unpack name) args
liftOp op x = BinOp op x Void
liftOp2 op x y = BinOp op x y
opTable = [ [ --prefix (string "not" *> space_) (liftOp BNot)
]
, [ binarySym "*" (liftOp2 BMul) E.AssocLeft
, binarySym "/" (liftOp2 BDiv) E.AssocLeft
]
, [ binarySym "+" (liftOp2 BAdd) E.AssocLeft
, binarySym "-" (liftOp2 BSub) E.AssocLeft
]
, [ binarySym "<" (liftOp2 BSt) E.AssocNone
, binarySym ">" (liftOp2 BLt) E.AssocNone
, binarySym "<=" (liftOp2 BSEq) E.AssocNone
, binarySym ">=" (liftOp2 BLEq) E.AssocNone
]
, [ binarySym "==" (liftOp2 BEq) E.AssocNone
, binarySym "!=" (liftOp2 BNEq) E.AssocNone
]
, [ binaryWord "and" (liftOp2 BAnd) E.AssocLeft
]
, [ binaryWord "or" (liftOp2 BOr) E.AssocLeft
]
]
where
binary op fun assoc = E.Infix (fun <$ op <* optSpace_) assoc
prefix op fun = E.Prefix (fun <$ op <* optSpace_)
binarySym sym = binary (stripSpace $ string sym)
binaryWord w = binary (between optSpace_ space_ $ string w)
pBool :: Parser Bool
pBool =
const True <$> string "true" <|>
const False <$> string "false"
stringP :: Parser T.Text
stringP = quotedString '"' <|> quotedString '\''
pStmtEnd = char ';' <* optSpace_
pName :: Parser T.Text
pName = stripSpace $ identP isAlpha isAlphaNum
stripSpace = between optSpace_ optSpace_
space_ = skipWhile1 isSpace
optSpace_ = skipWhile isSpace
between :: Parser a -> Parser b -> Parser c -> Parser c
between left right main = left *> main <* right
skipWhile1 pred = (() <$ takeWhile1 pred) <?> "skipWhile1"
identP :: (Char -> Bool) -> (Char -> Bool) -> Parser T.Text
identP first rest = T.cons <$> satisfy first <*> takeWhile rest
quotedString :: Char -> Parser T.Text
quotedString c = T.pack <$> between (char c) (char c) (many innerChar)
where innerChar = char '\\' *> (escapeSeq <|> unicodeSeq)
<|> satisfy (`notElem` [c,'\\'])
escapeSeq :: Parser Char
escapeSeq = choice (zipWith decode "bnfrt\\\"'" "\b\n\f\r\t\\\"'")
where decode c r = r <$ char c
unicodeSeq :: Parser Char
unicodeSeq = char 'u' *> (intToChar <$> decodeHexUnsafe <$> count 4 hexDigit)
where intToChar = toEnum . fromIntegral
decodeHexUnsafe :: String -> Integer
decodeHexUnsafe hex = (head $ map fst $ readHex hex)
hexDigitUpper = satisfy (inClass "0-9A-F")
hexDigit = satisfy (inClass "0-9a-fA-F")
braced :: Parser l -> Parser r -> Parser a -> Parser a
braced l r = between (l *> optSpace_) (optSpace_ *> r)
listLike :: Parser l -> Parser r -> Parser s -> Parser a -> Parser [a]
listLike l r sep inner = braced l r (sepBy inner (stripSpace sep))
tupleP :: Parser p -> Parser [p]
tupleP = listLike (char '(') (char ')') (char ',')
|
agrafix/legoDSL
|
NXT/Parser/AttoParser.hs
|
bsd-3-clause
| 6,722 | 0 | 18 | 1,857 | 2,585 | 1,317 | 1,268 | 165 | 2 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
module Main where
import qualified DB
import DB (DB)
import Data.Aeson (encode)
import qualified Data.ByteString.Lazy.Char8 as BL8
import Data.Swagger (info, title, version, Swagger)
import Network.Wai.Handler.Warp (run)
import Control.Lens
import OurPrelude
import Servant.Client
import Servant.Swagger
type Interface =
GET [Keyed Hello]
:<|> POST Hello (Keyed Hello)
:<|> Capture "id" Int :> (
GET (Maybe Hello)
:<|> PUT Hello OK
:<|> DELETE OK
)
ls :: DB -> Server (GET [Keyed Hello])
ls db = do
ss <- DB.ls db
return [Keyed i (Hello s) | (i, s) <- ss]
post :: DB -> Server (POST Hello (Keyed Hello))
post db (Hello s) = do
i <- DB.create s db
return (Keyed i (Hello s))
get :: Int -> DB -> Server (GET (Maybe Hello))
get hid db = do
sMaybe <- DB.read hid db
return (Hello <$> sMaybe)
put :: Int -> DB -> Server (PUT Hello OK)
put hid db (Hello s) = do
DB.update hid db s
return OK
delete :: Int -> DB -> Server (DELETE OK)
delete hid db = do
DB.delete hid db
return OK
proxy :: Proxy Interface
proxy = Proxy
swag :: Swagger
swag =
toSwagger proxy
& info . title .~ "A Collection of Hellos, Friendly and Unfriendly"
& info . version .~ "v1"
main :: IO ()
main = do
db <- DB.init
BL8.writeFile "swagger.json" (encode swag)
run 9000 (serve proxy
(ls db :<|> post db :<|> (\hid -> get hid db :<|> put hid db :<|> delete hid db)))
ls' :<|> post' :<|> rest' =
client proxy (BaseUrl Http "localhost" 9000)
get' :<|> put' :<|> delete' =
rest' 1
|
hlian/atypical
|
app/Main.hs
|
bsd-3-clause
| 1,784 | 0 | 16 | 454 | 688 | 347 | 341 | -1 | -1 |
module Simplifier where
import Syntax
import Substitution
-- Simplify PE result by inlining
simplify :: Expr -> FEnv -> (Expr, FEnv)
simplify e fs = simplify' e [] fs
simplify' :: Expr -> FEnv -> FEnv -> (Expr, FEnv)
simplify' e fs [] = (e,fs)
simplify' e fs1 (f@(s,(ss,e')):fs2)
= if count == 1
then let
e'' = inlineE e
fs1' = inlineFL fs1
fs2' = inlineFL fs2
in simplify' e'' fs1' fs2'
else simplify' e (fs1++[f]) fs2
where
-- Count the number of applications of a given function
count = countE e + countFL fs1 + countF f + countFL fs2
countE :: Expr -> Int
countE (Const _) = 0
countE (Var _) = 0
countE (Binary _ e1 e2) = countE e1 + countE e2
countE (IfZero e1 e2 e3) = countE e1 + countE e2 + countE e3
countE (Apply s' es') = (if s==s' then 1 else 0) + countEL es'
countEL :: [Expr] -> Int
countEL = sum . map countE
countF :: FDef -> Int
countF (_,(_,e)) = countE e
countFL :: [FDef] -> Int
countFL = sum . map countF
-- Inline the given function
inlineE :: Expr -> Expr
inlineE e@(Const _) = e
inlineE e@(Var _) = e
inlineE (Binary op e1 e2) = Binary op (inlineE e1) (inlineE e2)
inlineE (IfZero e1 e2 e3) = IfZero (inlineE e1) (inlineE e2) (inlineE e3)
inlineE (Apply s' es)
= if s==s'
then substitute (zip ss es) e'
else Apply s' (inlineEL es)
inlineEL :: [Expr] -> [Expr]
inlineEL = map inlineE
inlineF :: FDef -> FDef
inlineF (s,(ss',e)) = (s,(ss',inlineE e))
inlineFL :: [FDef] -> [FDef]
inlineFL = map inlineF
|
grammarware/slps
|
topics/partial-evaluation/simplepe/Simplifier.hs
|
bsd-3-clause
| 1,557 | 0 | 10 | 411 | 708 | 373 | 335 | 43 | 12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.