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 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.BigQueryDataTransfer.Projects.Locations.TransferConfigs.ScheduleRuns -- 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) -- -- Creates transfer runs for a time range [start_time, end_time]. For each -- date - or whatever granularity the data source supports - in the range, -- one transfer run is created. Note that runs are created per UTC time in -- the time range. DEPRECATED: use StartManualTransferRuns instead. -- -- /See:/ <https://cloud.google.com/bigquery-transfer/ BigQuery Data Transfer API Reference> for @bigquerydatatransfer.projects.locations.transferConfigs.scheduleRuns@. module Network.Google.Resource.BigQueryDataTransfer.Projects.Locations.TransferConfigs.ScheduleRuns ( -- * REST Resource ProjectsLocationsTransferConfigsScheduleRunsResource -- * Creating a Request , projectsLocationsTransferConfigsScheduleRuns , ProjectsLocationsTransferConfigsScheduleRuns -- * Request Lenses , pltcsrParent , pltcsrXgafv , pltcsrUploadProtocol , pltcsrAccessToken , pltcsrUploadType , pltcsrPayload , pltcsrCallback ) where import Network.Google.BigQueryDataTransfer.Types import Network.Google.Prelude -- | A resource alias for @bigquerydatatransfer.projects.locations.transferConfigs.scheduleRuns@ method which the -- 'ProjectsLocationsTransferConfigsScheduleRuns' request conforms to. type ProjectsLocationsTransferConfigsScheduleRunsResource = "v1" :> CaptureMode "parent" "scheduleRuns" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] ScheduleTransferRunsRequest :> Post '[JSON] ScheduleTransferRunsResponse -- | Creates transfer runs for a time range [start_time, end_time]. For each -- date - or whatever granularity the data source supports - in the range, -- one transfer run is created. Note that runs are created per UTC time in -- the time range. DEPRECATED: use StartManualTransferRuns instead. -- -- /See:/ 'projectsLocationsTransferConfigsScheduleRuns' smart constructor. data ProjectsLocationsTransferConfigsScheduleRuns = ProjectsLocationsTransferConfigsScheduleRuns' { _pltcsrParent :: !Text , _pltcsrXgafv :: !(Maybe Xgafv) , _pltcsrUploadProtocol :: !(Maybe Text) , _pltcsrAccessToken :: !(Maybe Text) , _pltcsrUploadType :: !(Maybe Text) , _pltcsrPayload :: !ScheduleTransferRunsRequest , _pltcsrCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsLocationsTransferConfigsScheduleRuns' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pltcsrParent' -- -- * 'pltcsrXgafv' -- -- * 'pltcsrUploadProtocol' -- -- * 'pltcsrAccessToken' -- -- * 'pltcsrUploadType' -- -- * 'pltcsrPayload' -- -- * 'pltcsrCallback' projectsLocationsTransferConfigsScheduleRuns :: Text -- ^ 'pltcsrParent' -> ScheduleTransferRunsRequest -- ^ 'pltcsrPayload' -> ProjectsLocationsTransferConfigsScheduleRuns projectsLocationsTransferConfigsScheduleRuns pPltcsrParent_ pPltcsrPayload_ = ProjectsLocationsTransferConfigsScheduleRuns' { _pltcsrParent = pPltcsrParent_ , _pltcsrXgafv = Nothing , _pltcsrUploadProtocol = Nothing , _pltcsrAccessToken = Nothing , _pltcsrUploadType = Nothing , _pltcsrPayload = pPltcsrPayload_ , _pltcsrCallback = Nothing } -- | Required. Transfer configuration name in the form: -- \`projects\/{project_id}\/transferConfigs\/{config_id}\` or -- \`projects\/{project_id}\/locations\/{location_id}\/transferConfigs\/{config_id}\`. pltcsrParent :: Lens' ProjectsLocationsTransferConfigsScheduleRuns Text pltcsrParent = lens _pltcsrParent (\ s a -> s{_pltcsrParent = a}) -- | V1 error format. pltcsrXgafv :: Lens' ProjectsLocationsTransferConfigsScheduleRuns (Maybe Xgafv) pltcsrXgafv = lens _pltcsrXgafv (\ s a -> s{_pltcsrXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pltcsrUploadProtocol :: Lens' ProjectsLocationsTransferConfigsScheduleRuns (Maybe Text) pltcsrUploadProtocol = lens _pltcsrUploadProtocol (\ s a -> s{_pltcsrUploadProtocol = a}) -- | OAuth access token. pltcsrAccessToken :: Lens' ProjectsLocationsTransferConfigsScheduleRuns (Maybe Text) pltcsrAccessToken = lens _pltcsrAccessToken (\ s a -> s{_pltcsrAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pltcsrUploadType :: Lens' ProjectsLocationsTransferConfigsScheduleRuns (Maybe Text) pltcsrUploadType = lens _pltcsrUploadType (\ s a -> s{_pltcsrUploadType = a}) -- | Multipart request metadata. pltcsrPayload :: Lens' ProjectsLocationsTransferConfigsScheduleRuns ScheduleTransferRunsRequest pltcsrPayload = lens _pltcsrPayload (\ s a -> s{_pltcsrPayload = a}) -- | JSONP pltcsrCallback :: Lens' ProjectsLocationsTransferConfigsScheduleRuns (Maybe Text) pltcsrCallback = lens _pltcsrCallback (\ s a -> s{_pltcsrCallback = a}) instance GoogleRequest ProjectsLocationsTransferConfigsScheduleRuns where type Rs ProjectsLocationsTransferConfigsScheduleRuns = ScheduleTransferRunsResponse type Scopes ProjectsLocationsTransferConfigsScheduleRuns = '["https://www.googleapis.com/auth/bigquery", "https://www.googleapis.com/auth/cloud-platform"] requestClient ProjectsLocationsTransferConfigsScheduleRuns'{..} = go _pltcsrParent _pltcsrXgafv _pltcsrUploadProtocol _pltcsrAccessToken _pltcsrUploadType _pltcsrCallback (Just AltJSON) _pltcsrPayload bigQueryDataTransferService where go = buildClient (Proxy :: Proxy ProjectsLocationsTransferConfigsScheduleRunsResource) mempty
brendanhay/gogol
gogol-bigquerydatatransfer/gen/Network/Google/Resource/BigQueryDataTransfer/Projects/Locations/TransferConfigs/ScheduleRuns.hs
mpl-2.0
6,915
0
16
1,399
789
464
325
123
1
#!/usr/bin/env stack {- stack --install-ghc runghc --package amqp --package bytestring --package text -} {-# LANGUAGE OverloadedStrings #-} import Network.AMQP import Control.Monad (forM_) import qualified Data.ByteString.Lazy.Char8 as BL import Data.Monoid ((<>)) import qualified Data.Text as DT import qualified Data.Text.Encoding as DT import System.Environment (getArgs) logsExchange = "direct_logs" main :: IO () main = do conn <- openConnection "127.0.0.1" "/" "guest" "guest" ch <- openChannel conn severities <- getArgs declareExchange ch newExchange {exchangeName = logsExchange, exchangeType = "direct", exchangeDurable = False} (q, _, _) <- declareQueue ch newQueue {queueName = "", queueAutoDelete = True, queueDurable = False} forM_ severities (bindQueue ch q logsExchange . DT.pack) BL.putStrLn " [*] Waiting for messages. To exit press CTRL+C" consumeMsgs ch q Ack deliveryHandler -- waits for keypresses getLine closeConnection conn deliveryHandler :: (Message, Envelope) -> IO () deliveryHandler (msg, metadata) = do BL.putStrLn $ " [x] " <> key <> ":" <> body BL.putStrLn " [x] Done" ackEnv metadata where body = msgBody msg key = BL.fromStrict . DT.encodeUtf8 $ envRoutingKey metadata
rabbitmq/rabbitmq-tutorials
haskell/receiveLogsDirect.hs
apache-2.0
1,522
0
11
484
343
184
159
32
1
-- Copyright 2014 Google Inc. All rights reserved. -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- http://www.apache.org/licenses/LICENSE-2.0 -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- Module takes a JSAST and gives each vertex a unique integer label. The label counter is simply -- threaded through the tree. Traversal is depth first. It's all fairly straight-forward. -- The methods in the pipeline are: -- ParseJS.parseTree - NEEDS PRETTY PRINT -- ParseJS.getJSASTWithSource - NEEDS PRETTY PRINT -- ResolveJSASTSourceFragments.jsastListWSMakeSourceFragments -- LabelJSAST.label -- DeclarationGraph.getDeclarationGraph - NEEDS PRETTY PRINT -- DeclarationGraph.graphGetAllRules (optional) - TYPES NEED PRETTY PRINT -- DeclarationGraph.cleanFunctionRules (optional) -- DeclarationGraph.cleanFunction (optional) module Main ( main ) where import DeclarationGraph import LabelJSAST import Language.JavaScript.Parser import ParseJS import PrettyPrint import ResolveSourceFragments import System.Environment import TypeRules -- TODO: Reverse these so that the earlier layers come first. -- TODO: Put these sections into functions. main :: IO () main = do (infile:[]) <- getArgs pr <- readFile infile putStrLn "" -- ***************** putStrLn "" putStrLn "Print the stripped parse tree" printParseTreeStripped $ jsnGetNode $ parseTree pr infile putStrLn "" putStrLn "Print the raw parse tree" putStrLn $ show $ parse pr infile -- ***************** -- PRETTY PRINTED -- Prints declared functions and function expressions, and the identifiers -- that are visible to each one. -- putStrLn "" -- putStrLn "Pretty print cleaned functions and function expressions, with identifiers" -- putStr "Top Level:" -- printCleanedElementList ((makeCleanedFunctions pr infile):[]) (makeIndent "") -- **PRETTY PRINTED** -- Prints the rules, indented base on their scope, with optional source code, and an optional -- list of the identifiers that are visible at that each scope. putStrLn "" putStrLn "Pretty print cleaned function rules with identifiers" putStr "Top Level:" printCleanedRulesList ((makeCleanedFunctionRules pr infile):[]) (makeIndent "") False True -- PRETTY PRINTED (could be improved with pretty printing for types) -- Print all the rules, optionally with source code. -- putStrLn "" -- putStrLn "Pretty print all the rules with code fragments" -- mapM_ (\r -> printRule r "" True) (makeAllRules pr infile) -- Print the raw declaration graph with rules. -- WARNING: Large and more-or-less illegible. -- putStrLn "" -- putStrLn "Print the declaration graph" -- putStrLn $ show $ makeDeclarationGraph pr infile -- PRETTY PRINTED -- Print the cleaned ATS. -- putStrLn "" -- putStrLn "Pretty print labelled JSAST without labels or source fragments" -- mapPrintASTChild (makeLabelledJSAST pr infile) (makeIndent "") False False -- PRETTY PRINTED -- Print the cleaned ATS with labels. -- putStrLn "" -- putStrLn "Pretty print labelled JSAST with labels" -- mapPrintASTChild (makeLabelledJSAST pr infile) (makeIndent "") False True -- PRETTY PRINTED -- Print the cleaned ATS with source. -- putStrLn "" -- putStrLn "Pretty print labelled JSAST with source fragments" -- mapPrintASTChild (makeLabelledJSAST pr infile) (makeIndent "") True False -- **PRETTY PRINTED** -- Print the cleaned ATS with labels and source. putStrLn "" putStrLn "Pretty print labelled JSAST with labels and source fragments" mapPrintASTChild (makeLabelledJSAST pr infile) (makeIndent "") True True -- **PRETTY PRINTED** -- Pretty print the JSASTWithSourceFragment with source fragments putStrLn "" putStrLn "Pretty print JSASTWithSourceFragment with source fragments" mapPrintASTWS (makeJSASTWithSourceFragments pr infile) (makeIndent "") True -- **PRETTY PRINTED** -- Pretty print the JSASTWithSourceFragment without source fragments putStrLn "" putStrLn "Pretty print JSASTWithSourceFragment without source fragments" mapPrintASTWS (makeJSASTWithSourceFragments pr infile) (makeIndent "") False -- Prints the first JSAST (pre-labels). -- putStrLn "" -- putStrLn "Print the the original JSAST" -- mapM_ print (makeJSAST pr infile) -- Rudimentary. Prints the parse tree using Language.JavaScript's showStripped function. Prints -- one top-level parse tree node per line. -- putStrLn "" -- putStrLn "Print the stripped parse tree" -- printParseTreeStripped $ jsnGetNode $ parseTree pr infile -- Print the raw parse tree. -- putStrLn "" -- putStrLn "Print the raw parse tree" -- putStrLn $ show $ parse pr infile -- TODO: Reverse these so that the earlier layers come first. makeCleanedFunctions :: String -> SourceFileName -> CleanedFunction makeCleanedFunctions input fileName = cleanFunction $ makeCleanedFunctionRules input fileName makeCleanedFunctionRules :: String -> SourceFileName -> CleanedFunctionRules makeCleanedFunctionRules input fileName = cleanFunctionRules $ makeDeclarationGraph input fileName makeAllRules :: String -> SourceFileName -> [Rule] makeAllRules input fileName = graphGetAllRules $ makeDeclarationGraph input fileName makeDeclarationGraph :: String -> SourceFileName -> FunctionRules makeDeclarationGraph input fileName = getDeclarationGraph (makeLabelledJSAST input fileName) (fileName, 1, 1, ((length $ lines input) + 1), 1) makeLabelledJSAST :: String -> SourceFileName -> [ASTChild] makeLabelledJSAST input fileName = label $ makeJSASTWithSourceFragments input fileName -- FIXME: Passing the file name here might mean that we don't need to thread it through the whole -- AST. makeJSASTWithSourceFragments :: String -> SourceFileName -> [JSASTWithSourceFragment] makeJSASTWithSourceFragments input fileName = jsastListWSMakeSourceFragments (makeJSAST input fileName) (SpanPoint fileName ((length $ lines input) + 1) 1) makeJSAST :: String -> SourceFileName -> ([JSASTWithSourceSpan], SourceFileName) makeJSAST input fileName = getJSASTWithSource (parseTree input fileName) fileName
rjwright/js-typeomatic
Main.hs
apache-2.0
6,429
8
12
991
707
387
320
53
1
-- Language extensions {{{ {-# LANGUAGE UnicodeSyntax #-} -- }}} Language extensions module Data.Quantum.Small.Operator.Qubit where -- Imports {{{ import Data.Bits (Bits()) import Data.Monoid (mappend) import Data.Word import Data.Quantum.Small.Operator -- }}} -- Types {{{ data Qubit = Qubit -- {{{ { qubitX :: {-# UNPACK #-} !Operator , qubitZ :: {-# UNPACK #-} !Operator } deriving (Eq,Ord,Show) -- }}} -- }}} -- Functions {{{ makeOperatorCommuteWithQubit :: Operator → Qubit → Operator -- {{{ makeOperatorCommuteWithQubit o (Qubit x z) = multiplyByIfAntiCommuteWith x z . multiplyByIfAntiCommuteWith z x $ o {-# INLINE makeOperatorCommuteWithQubit #-} -- }}} multiplyQubitByIfAntiCommuteWith :: Operator → Operator → Qubit → Qubit -- {{{ multiplyQubitByIfAntiCommuteWith multiplier commuter (Qubit x z) = Qubit (multiplyByIf (antiCommute commuter x) multiplier x) (multiplyByIf (antiCommute commuter z) multiplier z) {-# INLINE multiplyQubitByIfAntiCommuteWith #-} -- }}} qubitY (Qubit x z) = x `mappend` z {-# INLINE qubitY #-} -- }}} Functions
gcross/PauliQSC
Data/Quantum/Small/Operator/Qubit.hs
bsd-2-clause
1,127
0
9
212
251
145
106
26
1
{-# LANGUAGE DataKinds, EmptyDataDecls, TypeOperators, UndecidableInstances #-} module HaskHOL.Lib.IndDefs.Context ( IndDefsType , IndDefsThry , IndDefsCtxt , ctxtIndDefs ) where import HaskHOL.Core import HaskHOL.Lib.Theorems import HaskHOL.Lib.Theorems.Context import HaskHOL.Lib.IndDefs.Base -- New Theory Type and Constraint data IndDefsThry type instance IndDefsThry == IndDefsThry = 'True instance CtxtName IndDefsThry where ctxtName _ = "IndDefsCtxt" type instance PolyTheory IndDefsType b = IndDefsCtxt b type family IndDefsCtxt a :: Constraint where IndDefsCtxt a = (Typeable a, TheoremsCtxt a, IndDefsContext a ~ 'True) -- Assert Theory Hierarchy type IndDefsType = ExtThry IndDefsThry TheoremsType type family IndDefsContext a :: Bool where IndDefsContext UnsafeThry = 'True IndDefsContext BaseThry = 'False IndDefsContext (ExtThry a b) = IndDefsContext b || (a == IndDefsThry) ctxtIndDefs :: TheoryPath IndDefsType ctxtIndDefs = extendTheory ctxtTheorems $(thisModule') $ mapM_ addMonoThm [ thmMONO_AND, thmMONO_OR, thmMONO_IMP , thmMONO_NOT, thmMONO_EXISTS, thmMONO_FORALL ]
ecaustin/haskhol-deductive
src/HaskHOL/Lib/IndDefs/Context.hs
bsd-2-clause
1,162
1
8
207
260
150
110
-1
-1
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE GADTs #-} {-# OPTIONS_GHC -fno-warn-incomplete-patterns #-} {-# LANGUAGE CPP #-} #if __GLASGOW_HASKELL__ >= 702 && __GLASGOW_HASKELL__ <= 708 {-# LANGUAGE Trustworthy #-} #endif ----------------------------------------------------------------------------- -- | -- Module : Data.Profunctor.Collage -- Copyright : (C) 2011-2015 Edward Kmett, -- License : BSD-style (see the file LICENSE) -- -- Maintainer : Edward Kmett <[email protected]> -- Stability : provisional -- Portability : MPTCs -- ---------------------------------------------------------------------------- module Data.Profunctor.Collage ( Collage(..) ) where import Data.Semigroupoid import Data.Semigroupoid.Ob import Data.Profunctor -- | The cograph of a 'Profunctor'. data Collage k b a where L :: (b -> b') -> Collage k (Left b) (Left b') R :: (a -> a') -> Collage k (Right a) (Right a') C :: k b a -> Collage k (Left b) (Right a) instance Profunctor k => Semigroupoid (Collage k) where L f `o` L g = L (f . g) R f `o` R g = R (f . g) R f `o` C g = C (rmap f g) C f `o` L g = C (lmap g f) instance Profunctor k => Ob (Collage k) (Left a) where semiid = L semiid instance Profunctor k => Ob (Collage k) (Right a) where semiid = R semiid
ekmett/semigroupoid-extras
src/Data/Profunctor/Collage.hs
bsd-2-clause
1,431
0
9
272
378
204
174
26
0
{-# LANGUAGE DataKinds, EmptyDataDecls, TypeOperators, UndecidableInstances #-} module HaskHOL.Lib.IndTypesPre.Context ( IndTypesPreType , IndTypesPreThry , IndTypesPreCtxt , ctxtIndTypesPre ) where import HaskHOL.Core import HaskHOL.Deductive hiding (newDefinition, newSpecification) import HaskHOL.Lib.Recursion import HaskHOL.Lib.Nums import HaskHOL.Lib.Pair import HaskHOL.Lib.IndTypesPre.Base import HaskHOL.Lib.WF.Context data IndTypesPreThry type instance IndTypesPreThry == IndTypesPreThry = 'True instance CtxtName IndTypesPreThry where ctxtName _ = "IndTypesPreCtxt" type instance PolyTheory IndTypesPreType b = IndTypesPreCtxt b type family IndTypesPreCtxt a :: Constraint where IndTypesPreCtxt a = (Typeable a, WFCtxt a, IndTypesPreContext a ~ 'True) type IndTypesPreType = ExtThry IndTypesPreThry WFType type family IndTypesPreContext a :: Bool where IndTypesPreContext UnsafeThry = 'True IndTypesPreContext BaseThry = 'False IndTypesPreContext (ExtThry a b) = IndTypesPreContext b || (a == IndTypesPreThry) ctxtIndTypesPre :: TheoryPath IndTypesPreType ctxtIndTypesPre = extendTheory ctxtWF $(thisModule') $ do void $ newSpecification ["NUMFST", "NUMSND"] =<< ruleMATCH_MP thmINJ_INVERSE2 thmNUMPAIR_INJ void $ newSpecification ["NUMLEFT", "NUMRIGHT"] =<< ruleMATCH_MP thmINJ_INVERSE2 thmNUMSUM_INJ mapM_ newDefinition [ ("INJN", [txt| INJN (m:num) = \(n:num) (a:A). n = m |]) , ("INJA", [txt| INJA (a:A) = \(n:num) b. b = a |]) , ("INJF", [txt| INJF (f:num->(num->A->bool)) = \n. f (NUMFST n) (NUMSND n) |]) , ("INJP", [txt| INJP f1 f2:num->A->bool = \n a. if NUMLEFT n then f1 (NUMRIGHT n) a else f2 (NUMRIGHT n) a |]) , ("ZCONSTR", [txt| ZCONSTR c i r :num->A->bool = INJP (INJN (SUC c)) (INJP (INJA i) (INJF r)) |]) , ("ZBOT", [txt| ZBOT = INJP (INJN 0) (@z:num->A->bool. T) |]) ] (rep, _, _) <- newInductiveDefinition "ZRECSPACE" [txt| ZRECSPACE (ZBOT:num->A->bool) /\ (!c i r. (!n. ZRECSPACE (r n)) ==> ZRECSPACE (ZCONSTR c i r)) |] void $ newBasicTypeDefinition "recspace" "_mk_rec" "_dest_rec" =<< ruleCONJUNCT1 rep mapM_ newDefinition [ ("BOTTOM", [txt| BOTTOM = _mk_rec (ZBOT:num->A->bool) |]) , ("CONSTR", [txt| CONSTR c i r :(A)recspace = _mk_rec (ZCONSTR c i (\n. _dest_rec(r n))) |]) , ("FNIL", [txt| FNIL (n:num) = @x:A. T |]) ] void $ newRecursiveDefinition recursionNUM ("FCONS", [txt| (!a f. FCONS (a:A) f 0 = a) /\ (!a f n. FCONS (a:A) f (SUC n) = f n) |])
ecaustin/haskhol-math
src/HaskHOL/Lib/IndTypesPre/Context.hs
bsd-2-clause
2,938
1
11
878
512
308
204
-1
-1
{-# LANGUAGE ScopedTypeVariables #-} module WASH.Utility.Auxiliary where import Control.Exception import System.Directory import System.Environment import System.IO import System.IO.Error import System.Process (system) import WASH.Utility.FileNames import qualified WASH.Utility.Shell as Shell protectedGetEnv :: String -> String -> IO String protectedGetEnv var deflt = catch (getEnv var) (\ (e :: SomeException) -> return deflt) readFileNonExistent :: FilePath -> String -> IO String readFileNonExistent fileName def = do existent <- doesFileExist fileName if existent then readFile fileName else return def readFileStrictly :: FilePath -> IO String readFileStrictly filePath = do h <- openFile filePath ReadMode contents <- hGetContents h hClose (g contents h) return contents where g [] h = h g (_:rest) h = g rest h assertDirectoryExists :: FilePath -> IO () -> IO () assertDirectoryExists dirname existsAction = catch (createDirectory dirname) (\ (ioe :: IOException) -> if isAlreadyExistsError ioe then existsAction else if isDoesNotExistError ioe then do assertDirectoryExists (dropLastComponent dirname) (return ()) assertDirectoryExists dirname existsAction else do hPutStrLn stderr ("assertDirectoryExists " ++ show dirname) ioError ioe) writeDebugFile :: String -> String -> IO () writeDebugFile filename str = do writeFile filename str system ("chmod 666 " ++ Shell.quote filename) return () appendDebugFile :: String -> String -> IO () appendDebugFile filename str = do appendFile filename ('\n':str) system ("chmod 666 " ++ Shell.quote filename) return ()
nh2/WashNGo
WASH/Utility/Auxiliary.hs
bsd-3-clause
1,675
8
16
317
537
266
271
45
3
-- | This module exports the memory model and its instances. module Jat.PState.MemoryModel (module M) where import Jat.PState.MemoryModel.Data as M import Jat.PState.MemoryModel.Primitive as M import Jat.PState.MemoryModel.UnSharing as M {-import Jat.PState.MemoryModel.Sharing-} import Jat.PState.MemoryModel.PairSharing as M
ComputationWithBoundedResources/jat
src/Jat/PState/MemoryModel.hs
bsd-3-clause
329
0
4
36
51
39
12
5
0
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Lib ( mainEntry ) where import System.Environment import System.Exit import Text.Hamlet import Text.Blaze.Html.Renderer.String (renderHtml) import Text.Blaze.Html import Control.Monad.Reader (runReaderT) import Database (load, addMetric, clearFile, generateJson, MetricHistory) import Grep (identifierCount, findCount, findAllCount, saveCount) -- renderTemplate :: String -> String -> String -> String -- renderTemplate testVariable exit other = renderHtml ( $(shamletFile "mypage.hamlet") ) -- generateHtml = do -- exit <- generateJson "db.txt" "Identifier" -- writeFile "./report.html" $ renderTemplate "foobar" exit exit saveGrep :: IO Int -> String -> IO MetricHistory saveGrep results name = results >>= (\count -> runReaderT (addMetric name count) "db.txt" ) saveAllStats :: IO MetricHistory saveAllStats = saveGrep identifierCount "Identifier" `seq` saveGrep findCount "Find" `seq` saveGrep findAllCount "FindAll" `seq` saveGrep saveCount "Save" mainEntry :: IO () mainEntry = getArgs >>= parse parse :: [String] -> IO () parse ["-a"] = saveAllStats >> exit -- parse ["-s"] = generateHtml >> exit parse ["-c"] = runReaderT clearFile "db.txt" >> exit parse ["-h"] = usage >> exit parse ["-t"] = (identifierCount >>= (putStrLn . show)) >> exit parse _ = usage >> exit usage :: IO () usage = putStrLn "Usage: metrics \n [-h help]\n [-c clear database]\n [-s generate html file from database] \n [-a update database with todays metrics]\n" exit :: IO a exit = exitSuccess die :: IO a die = exitWith (ExitFailure 1)
steveshogren/project-metrics
src/Lib.hs
bsd-3-clause
1,631
0
10
264
384
215
169
38
1
{-# LANGUAGE OverloadedStrings, TemplateHaskell, QuasiQuotes, RecordWildCards #-} module Myo ( module Myo.Foreign.Types , module Myo.Foreign.Hub , module Myo.Foreign.String , errorKind , errorCString , getMacAddress , setLockingPolicy , vibrate , run ) where import qualified Language.C.Inline as C import Data.Word import Data.Monoid import Myo.Foreign.Types import Myo.Foreign.String import Myo.Foreign.Hub import Myo.Foreign.Hub.Types import Foreign.C.String import Foreign.ForeignPtr import Foreign.Storable import Foreign.Marshal.Alloc C.context (myoCtx <> hubCtx) C.include "libmyo.h" C.include "<string.h>" C.include "wrapper.h" ------------------------------------------------------------------------------- errorKind :: ErrorDetails -> IO Result errorKind ed = withForeignPtr ed $ \ed' -> do alloca $ \resPtr -> do [C.block| void { libmyo_result_t r = libmyo_error_kind($(libmyo_error_details_t ed')); memmove($(libmyo_result_t* resPtr) , &r , sizeof(libmyo_result_t) ); } |] peek resPtr ------------------------------------------------------------------------------- errorCString :: ErrorDetails -> IO CString errorCString ed = withForeignPtr ed $ \ed' -> do [C.exp| const char* { libmyo_error_cstring($(libmyo_error_details_t ed')) }|] ------------------------------------------------------------------------------- -- Set the locking policy for Myos connected to the hub. -- @returns libmyo_success if the locking policy is successfully set, otherwise -- - libmyo_error_invalid_argument if \a hub is NULL -- - libmyo_error if \a hub is not a valid hub -- libmyo_result_t libmyo_set_locking_policy(libmyo_hub_t hub, libmyo_locking_policy_t locking_policy, -- libmyo_error_details_t* out_error); setLockingPolicy :: MyoHub -> LockingPolicy -> ErrorDetails -> IO Result setLockingPolicy h lp ed = withForeignPtr h $ \h' -> withForeignPtr ed $ \ed' -> do alloca $ \lp' -> do poke lp' lp alloca $ \resPtr -> do [C.block| void { libmyo_result_t r = libmyo_set_locking_policy( $(libmyo_hub_t h') , *$(libmyo_locking_policy_t* lp') , &$(libmyo_error_details_t ed') ); memmove($(libmyo_result_t* resPtr) , &r , sizeof(libmyo_result_t) ); } |] peek resPtr -- | Retrieve the MAC address of a Myo. -- The MAC address is unique to the physical Myo, and is a 48-bit number. -- uint64_t libmyo_get_mac_address(libmyo_myo_t myo); getMacAddress :: MyoDevice -> IO Word64 getMacAddress md = withForeignPtr md $ \myo -> do [C.exp| uint64_t { libmyo_get_mac_address($(libmyo_myo_t myo))} |] -- | Vibrate the given myo. -- Can be called when a Myo is paired. -- @returns libmyo_success if the Myo successfully vibrated, otherwise -- - libmyo_error_invalid_argument if \a myo is NULL vibrate :: MyoDevice -> Vibration -> ErrorDetails -> IO Result vibrate device vib eDetails = withForeignPtr device $ \d -> withForeignPtr eDetails $ \ed -> do alloca $ \resPtr -> do alloca $ \vibPtr -> do poke vibPtr vib [C.block| void { libmyo_result_t r = libmyo_vibrate( $(libmyo_myo_t d) , *$(libmyo_vibration_type_t* vibPtr) , &$(libmyo_error_details_t ed) ); memmove($(libmyo_result_t* resPtr) , &r , sizeof(libmyo_result_t) ); } |] peek resPtr type Duration = Int -- | Process events and call the provided callback as they occur. -- Runs for up to approximately \a duration_ms milliseconds or until a called handler returns libmyo_handler_stop. -- @returns libmyo_success after a successful run, otherwise -- - libmyo_error_invalid_argument if \a hub is NULL -- - libmyo_error_invalid_argument if \a handler is NULL -- libmyo_result_t libmyo_run(libmyo_hub_t hub, unsigned int duration_ms, libmyo_handler_t handler, void* user_data, -- libmyo_error_details_t* out_error); run :: MyoHub -> Duration -> Handler -> UserData -> ErrorDetails -> IO Result run h dur_ms hdlr ud ed = do let dur = fromIntegral dur_ms withForeignPtr h $ \h' -> do withForeignPtr ed $ \ed' -> do withForeignPtr ud $ \ud' -> do alloca $ \resPtr -> do [C.block| void { libmyo_result_t r = libmyo_run( $(libmyo_hub_t h') , $(unsigned int dur) , $(libmyo_handler_t hdlr) , $(void * ud') , $(libmyo_error_details_t ed') ); memmove($(libmyo_result_t* resPtr) , &r , sizeof(libmyo_result_t) ); } |] peek resPtr
adinapoli/myo
src/Myo.hs
bsd-3-clause
5,174
0
23
1,565
655
357
298
68
1
{-# LANGUAGE OverloadedStrings #-} module Court.Result ( Results(..) , Result(..) , modifyGlobalResults , modifyLocalResults ) where import Control.Applicative import Data.Aeson hiding (Result) import qualified Data.ByteString.Lazy.Char8 as BSL import System.Directory import System.Exit import System.FilePath import Court.Job import Court.Options newtype Results = Results [Result] deriving (Show, Eq) instance FromJSON Results where parseJSON (Object v) = Results <$> v .: "results" parseJSON _ = fail "object expected" instance ToJSON Results where toJSON (Results results) = object [ "results" .= results ] data Result = Result { resultExitCode :: ExitCode , resultOutput :: String , resultPath :: FilePath } deriving (Show, Eq) instance FromJSON Result where parseJSON (Object v) = Result <$> (fmap read $ v .: "exit_code") <*> v .: "output" <*> v .: "path" parseJSON _ = fail "object expected" instance ToJSON Result where toJSON result = object [ "exit_code" .= show (resultExitCode result) , "output" .= resultOutput result , "path" .= resultPath result , "project_path" .= (snd . splitFileName .takeDirectory . resultPath $ result) , "succeed" .= (resultExitCode result == ExitSuccess) ] modifyGlobalResults :: Options -> (Results -> Results) -> IO () modifyGlobalResults opts f = do let path = optDirectory opts </> "results.json" modifyResults' path f modifyLocalResults :: Job -> (Results -> Results) -> IO () modifyLocalResults job f = do let path = jobProjectPath job </> "results.json" modifyResults' path f modifyResults' :: FilePath -> (Results -> Results) -> IO () modifyResults' path f = do check <- doesFileExist path results <- if check then do contents <- BSL.readFile path return $ either (const (Results [])) id $ eitherDecode contents else return $ Results [] BSL.writeFile path $! encode $ f results
thoferon/court
src/Court/Result.hs
bsd-3-clause
2,103
1
18
548
630
326
304
55
2
module Main(main) where import System.Environment import Proper.Lexer import Proper.Parser import Proper.Formula import System.IO import Proper.Utils main :: IO () main = do (fileName:rest) <- getArgs fHandle <- openFile fileName ReadMode thmString <- hGetContents fHandle let thm = processTheoremFile thmString case thm of Failed errMsg -> putStrLn errMsg Succeeded t -> do putStr $ show t putStrLn $ "\n\nis " ++ (show $ checkTheorem t) processTheoremFile thmFileContents = (toTokens thmFileContents >>= parseTheoremToks)
dillonhuff/Proper
src/Main.hs
bsd-3-clause
561
0
15
108
179
88
91
20
2
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.NV -- Copyright : (c) Sven Panne 2015 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -- A convenience module, combining all raw modules containing NV extensions. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.NV ( module Graphics.Rendering.OpenGL.Raw.NV.BindlessMultiDrawIndirectCount, module Graphics.Rendering.OpenGL.Raw.NV.BindlessMultiDrawIndirect, module Graphics.Rendering.OpenGL.Raw.NV.BindlessTexture, module Graphics.Rendering.OpenGL.Raw.NV.BlendEquationAdvancedCoherent, module Graphics.Rendering.OpenGL.Raw.NV.BlendEquationAdvanced, module Graphics.Rendering.OpenGL.Raw.NV.ComputeProgram5, module Graphics.Rendering.OpenGL.Raw.NV.ConditionalRender, module Graphics.Rendering.OpenGL.Raw.NV.ConservativeRaster, module Graphics.Rendering.OpenGL.Raw.NV.CopyDepthToColor, module Graphics.Rendering.OpenGL.Raw.NV.CopyImage, module Graphics.Rendering.OpenGL.Raw.NV.DeepTexture3D, module Graphics.Rendering.OpenGL.Raw.NV.DepthBufferFloat, module Graphics.Rendering.OpenGL.Raw.NV.DepthClamp, module Graphics.Rendering.OpenGL.Raw.NV.DrawTexture, module Graphics.Rendering.OpenGL.Raw.NV.Evaluators, module Graphics.Rendering.OpenGL.Raw.NV.ExplicitMultisample, module Graphics.Rendering.OpenGL.Raw.NV.Fence, module Graphics.Rendering.OpenGL.Raw.NV.FillRectangle, module Graphics.Rendering.OpenGL.Raw.NV.FloatBuffer, module Graphics.Rendering.OpenGL.Raw.NV.FogDistance, module Graphics.Rendering.OpenGL.Raw.NV.FragmentCoverageToColor, module Graphics.Rendering.OpenGL.Raw.NV.FragmentProgram2, module Graphics.Rendering.OpenGL.Raw.NV.FragmentProgram, module Graphics.Rendering.OpenGL.Raw.NV.FramebufferMixedSamples, module Graphics.Rendering.OpenGL.Raw.NV.FramebufferMultisampleCoverage, module Graphics.Rendering.OpenGL.Raw.NV.GeometryProgram4, module Graphics.Rendering.OpenGL.Raw.NV.GPUProgram4, module Graphics.Rendering.OpenGL.Raw.NV.GPUProgram5, module Graphics.Rendering.OpenGL.Raw.NV.GPUShader5, module Graphics.Rendering.OpenGL.Raw.NV.HalfFloat, module Graphics.Rendering.OpenGL.Raw.NV.InternalformatSampleQuery, module Graphics.Rendering.OpenGL.Raw.NV.LightMaxExponent, module Graphics.Rendering.OpenGL.Raw.NV.MultisampleCoverage, module Graphics.Rendering.OpenGL.Raw.NV.MultisampleFilterHint, module Graphics.Rendering.OpenGL.Raw.NV.OcclusionQuery, module Graphics.Rendering.OpenGL.Raw.NV.PackedDepthStencil, module Graphics.Rendering.OpenGL.Raw.NV.ParameterBufferObject, module Graphics.Rendering.OpenGL.Raw.NV.PathRenderingCompatibility, module Graphics.Rendering.OpenGL.Raw.NV.PathRenderingCore, module Graphics.Rendering.OpenGL.Raw.NV.PathRenderingSharedEdge, module Graphics.Rendering.OpenGL.Raw.NV.PixelDataRange, module Graphics.Rendering.OpenGL.Raw.NV.PointSprite, module Graphics.Rendering.OpenGL.Raw.NV.PresentVideo, module Graphics.Rendering.OpenGL.Raw.NV.PrimitiveRestart, module Graphics.Rendering.OpenGL.Raw.NV.RegisterCombiners2, module Graphics.Rendering.OpenGL.Raw.NV.RegisterCombiners, module Graphics.Rendering.OpenGL.Raw.NV.SampleLocations, module Graphics.Rendering.OpenGL.Raw.NV.ShaderBufferLoad, module Graphics.Rendering.OpenGL.Raw.NV.ShaderBufferStore, module Graphics.Rendering.OpenGL.Raw.NV.ShaderThreadGroup, module Graphics.Rendering.OpenGL.Raw.NV.TessellationProgram5, module Graphics.Rendering.OpenGL.Raw.NV.TexgenEmboss, module Graphics.Rendering.OpenGL.Raw.NV.TexgenReflection, module Graphics.Rendering.OpenGL.Raw.NV.TextureBarrier, module Graphics.Rendering.OpenGL.Raw.NV.TextureEnvCombine4, module Graphics.Rendering.OpenGL.Raw.NV.TextureExpandNormal, module Graphics.Rendering.OpenGL.Raw.NV.TextureMultisample, module Graphics.Rendering.OpenGL.Raw.NV.TextureRectangle, module Graphics.Rendering.OpenGL.Raw.NV.TextureShader2, module Graphics.Rendering.OpenGL.Raw.NV.TextureShader3, module Graphics.Rendering.OpenGL.Raw.NV.TextureShader, module Graphics.Rendering.OpenGL.Raw.NV.TransformFeedback2, module Graphics.Rendering.OpenGL.Raw.NV.TransformFeedback, module Graphics.Rendering.OpenGL.Raw.NV.UniformBufferUnifiedMemory, module Graphics.Rendering.OpenGL.Raw.NV.VDPAUInterop, module Graphics.Rendering.OpenGL.Raw.NV.VertexArrayRange2, module Graphics.Rendering.OpenGL.Raw.NV.VertexArrayRange, module Graphics.Rendering.OpenGL.Raw.NV.VertexAttribInteger64Bit, module Graphics.Rendering.OpenGL.Raw.NV.VertexBufferUnifiedMemory, module Graphics.Rendering.OpenGL.Raw.NV.VertexProgram2Option, module Graphics.Rendering.OpenGL.Raw.NV.VertexProgram3, module Graphics.Rendering.OpenGL.Raw.NV.VertexProgram4, module Graphics.Rendering.OpenGL.Raw.NV.VertexProgram, module Graphics.Rendering.OpenGL.Raw.NV.VideoCapture ) where import Graphics.Rendering.OpenGL.Raw.NV.BindlessMultiDrawIndirectCount import Graphics.Rendering.OpenGL.Raw.NV.BindlessMultiDrawIndirect import Graphics.Rendering.OpenGL.Raw.NV.BindlessTexture import Graphics.Rendering.OpenGL.Raw.NV.BlendEquationAdvancedCoherent import Graphics.Rendering.OpenGL.Raw.NV.BlendEquationAdvanced import Graphics.Rendering.OpenGL.Raw.NV.ComputeProgram5 import Graphics.Rendering.OpenGL.Raw.NV.ConditionalRender import Graphics.Rendering.OpenGL.Raw.NV.ConservativeRaster import Graphics.Rendering.OpenGL.Raw.NV.CopyDepthToColor import Graphics.Rendering.OpenGL.Raw.NV.CopyImage import Graphics.Rendering.OpenGL.Raw.NV.DeepTexture3D import Graphics.Rendering.OpenGL.Raw.NV.DepthBufferFloat import Graphics.Rendering.OpenGL.Raw.NV.DepthClamp import Graphics.Rendering.OpenGL.Raw.NV.DrawTexture import Graphics.Rendering.OpenGL.Raw.NV.Evaluators import Graphics.Rendering.OpenGL.Raw.NV.ExplicitMultisample import Graphics.Rendering.OpenGL.Raw.NV.Fence import Graphics.Rendering.OpenGL.Raw.NV.FillRectangle import Graphics.Rendering.OpenGL.Raw.NV.FloatBuffer import Graphics.Rendering.OpenGL.Raw.NV.FogDistance import Graphics.Rendering.OpenGL.Raw.NV.FragmentCoverageToColor import Graphics.Rendering.OpenGL.Raw.NV.FragmentProgram2 import Graphics.Rendering.OpenGL.Raw.NV.FragmentProgram import Graphics.Rendering.OpenGL.Raw.NV.FramebufferMixedSamples import Graphics.Rendering.OpenGL.Raw.NV.FramebufferMultisampleCoverage import Graphics.Rendering.OpenGL.Raw.NV.GeometryProgram4 import Graphics.Rendering.OpenGL.Raw.NV.GPUProgram4 import Graphics.Rendering.OpenGL.Raw.NV.GPUProgram5 import Graphics.Rendering.OpenGL.Raw.NV.GPUShader5 import Graphics.Rendering.OpenGL.Raw.NV.HalfFloat import Graphics.Rendering.OpenGL.Raw.NV.InternalformatSampleQuery import Graphics.Rendering.OpenGL.Raw.NV.LightMaxExponent import Graphics.Rendering.OpenGL.Raw.NV.MultisampleCoverage import Graphics.Rendering.OpenGL.Raw.NV.MultisampleFilterHint import Graphics.Rendering.OpenGL.Raw.NV.OcclusionQuery import Graphics.Rendering.OpenGL.Raw.NV.PackedDepthStencil import Graphics.Rendering.OpenGL.Raw.NV.ParameterBufferObject import Graphics.Rendering.OpenGL.Raw.NV.PathRenderingCompatibility import Graphics.Rendering.OpenGL.Raw.NV.PathRenderingCore import Graphics.Rendering.OpenGL.Raw.NV.PathRenderingSharedEdge import Graphics.Rendering.OpenGL.Raw.NV.PixelDataRange import Graphics.Rendering.OpenGL.Raw.NV.PointSprite import Graphics.Rendering.OpenGL.Raw.NV.PresentVideo import Graphics.Rendering.OpenGL.Raw.NV.PrimitiveRestart import Graphics.Rendering.OpenGL.Raw.NV.RegisterCombiners2 import Graphics.Rendering.OpenGL.Raw.NV.RegisterCombiners import Graphics.Rendering.OpenGL.Raw.NV.SampleLocations import Graphics.Rendering.OpenGL.Raw.NV.ShaderBufferLoad import Graphics.Rendering.OpenGL.Raw.NV.ShaderBufferStore import Graphics.Rendering.OpenGL.Raw.NV.ShaderThreadGroup import Graphics.Rendering.OpenGL.Raw.NV.TessellationProgram5 import Graphics.Rendering.OpenGL.Raw.NV.TexgenEmboss import Graphics.Rendering.OpenGL.Raw.NV.TexgenReflection import Graphics.Rendering.OpenGL.Raw.NV.TextureBarrier import Graphics.Rendering.OpenGL.Raw.NV.TextureEnvCombine4 import Graphics.Rendering.OpenGL.Raw.NV.TextureExpandNormal import Graphics.Rendering.OpenGL.Raw.NV.TextureMultisample import Graphics.Rendering.OpenGL.Raw.NV.TextureRectangle import Graphics.Rendering.OpenGL.Raw.NV.TextureShader2 import Graphics.Rendering.OpenGL.Raw.NV.TextureShader3 import Graphics.Rendering.OpenGL.Raw.NV.TextureShader import Graphics.Rendering.OpenGL.Raw.NV.TransformFeedback2 import Graphics.Rendering.OpenGL.Raw.NV.TransformFeedback import Graphics.Rendering.OpenGL.Raw.NV.UniformBufferUnifiedMemory import Graphics.Rendering.OpenGL.Raw.NV.VDPAUInterop import Graphics.Rendering.OpenGL.Raw.NV.VertexArrayRange2 import Graphics.Rendering.OpenGL.Raw.NV.VertexArrayRange import Graphics.Rendering.OpenGL.Raw.NV.VertexAttribInteger64Bit import Graphics.Rendering.OpenGL.Raw.NV.VertexBufferUnifiedMemory import Graphics.Rendering.OpenGL.Raw.NV.VertexProgram2Option import Graphics.Rendering.OpenGL.Raw.NV.VertexProgram3 import Graphics.Rendering.OpenGL.Raw.NV.VertexProgram4 import Graphics.Rendering.OpenGL.Raw.NV.VertexProgram import Graphics.Rendering.OpenGL.Raw.NV.VideoCapture
phaazon/OpenGLRaw
src/Graphics/Rendering/OpenGL/Raw/NV.hs
bsd-3-clause
9,275
0
5
518
1,430
1,131
299
149
0
{-# LANGUAGE FlexibleInstances, CPP #-} -- | Lua pretty-printer. module Language.Lua.PrettyPrinter ( pprint , renderPretty , displayS , displayIO , LPretty ) where #if __GLASGOW_HASKELL__ >= 710 import Prelude hiding (EQ, GT, LT, (<$>)) #else import Prelude hiding (EQ, GT, LT) #endif import Text.PrettyPrint.Leijen hiding ((<$>)) import Language.Lua.Syntax intercalate :: Doc -> [Doc] -> Doc intercalate s elems = sep (punctuate s elems) infixr 5 <$> (<$>) :: Doc -> Doc -> Doc x <$> y | isEmpty y = x | otherwise = x <> line <> y type Precedence = Int class LPretty a where pprint :: a -> Doc pprint = pprint' 0 pprint' :: Precedence -> a -> Doc pprint' _ = pprint instance LPretty [Char] where pprint = text instance LPretty Bool where pprint True = text "true" pprint False = text "false" instance LPretty Exp where pprint' _ Nil = text "nil" pprint' _ (Bool s) = pprint s pprint' _ (Number n) = text n pprint' _ (String s) = text s pprint' _ Vararg = text "..." pprint' _ (EFunDef f) = pprint f pprint' _ (PrefixExp pe) = pprint pe pprint' _ (TableConst t) = pprint t pprint' p (Binop op e1 e2) = ps (pprint' opPrecL e1 <+> pprint op <+> case e2 of Unop{} -> pprint e2 _ -> pprint' opPrecR e2) where (opPrecL, opPrecR) = getBinopPrec op ps = if min opPrecL opPrecR < p then parens else id -- We handle this as a special case: When we have a chain of negations, we -- should put a space between operators, otherwise we end up printing a -- comment. -- -- One another solution would be to always put a space after negation, but I -- like to put negation just before the expression, without any spaces. pprint' p (Unop Neg (Unop Neg e)) = ps (pprint Neg <+> pprint' opPrec (Unop Neg e)) where opPrec = getUnopPrec Neg ps = if opPrec < p then parens else id pprint' p (Unop op e) = ps (pprint op <> pprint' opPrec e) where opPrec = getUnopPrec op ps = if opPrec < p then parens else id instance LPretty Var where pprint (VarName n) = pprint n pprint (Select pe e) = pprint pe <> align (brackets (pprint e)) pprint (SelectName pe name) = pprint pe <//> (char '.' <> pprint name) instance LPretty Binop where pprint Add = char '+' pprint Sub = char '-' pprint Mul = char '*' pprint Div = char '/' pprint IDiv = text "//" pprint Exp = char '^' pprint Mod = char '%' pprint Concat = text ".." pprint LT = char '<' pprint LTE = text "<=" pprint GT = char '>' pprint GTE = text ">=" pprint EQ = text "==" pprint NEQ = text "~=" pprint And = text "and" pprint Or = text "or" pprint BAnd = char '&' pprint BOr = char '|' pprint BXor = char '~' pprint ShiftL = text "<<" pprint ShiftR = text ">>" instance LPretty Unop where pprint Neg = char '-' pprint Not = text "not " pprint Len = char '#' pprint Complement = char '~' getBinopPrec :: Binop -> (Precedence, Precedence) getBinopPrec op = case op of Add -> (10, 10) Sub -> (10, 10) Mul -> (11, 11) Div -> (11, 11) IDiv -> (11, 11) Exp -> (14, 13) Mod -> (11, 11) Concat -> (9, 8) ShiftL -> (7, 7) ShiftR -> (7, 7) BAnd -> (6, 6) BXor -> (5, 5) BOr -> (4, 4) LT -> (3, 3) LTE -> (3, 3) GT -> (3, 3) GTE -> (3, 3) EQ -> (3, 3) NEQ -> (3, 3) And -> (2, 2) Or -> (1, 1) getUnopPrec :: Unop -> Precedence getUnopPrec = const 12 instance LPretty PrefixExp where pprint (PEVar var) = pprint var pprint (PEFunCall funcall) = pprint funcall pprint (Paren e) = parens (pprint e) instance LPretty [TableField] where pprint fields = braces (align (fillSep (punctuate comma (map pprint fields)))) instance LPretty TableField where pprint (ExpField e1 e2) = brackets (pprint e1) <+> equals <+> pprint e2 pprint (NamedField name e) = pprint name <+> equals <+> pprint e pprint (Field e) = pprint e instance LPretty Block where pprint (Block stats ret) = case stats of [] -> ret' _ -> vsep (map pprint stats) <$> ret' where ret' = case ret of Nothing -> empty Just [fun@EFunDef{}] -> text "return" <+> pprint fun Just e -> nest 2 (text "return" </> intercalate comma (map (align . pprint) e)) instance LPretty FunName where pprint (FunName name s methods) = cat (punctuate dot (map pprint $ name:s)) <> method' where method' = case methods of Nothing -> empty Just m' -> char ':' <> pprint m' instance LPretty FunBody where pprint = pprintFunction Nothing pprintFunction :: Maybe Doc -> FunBody -> Doc pprintFunction funname (FunBody args vararg block) = group (nest 2 (header <$> body) <$> end) where header = case funname of Nothing -> text "function" <+> args' Just n -> text "function" <+> n <> args' vararg' = if vararg then ["..."] else [] args' = parens (align (cat (punctuate (comma <> space) (map pprint (args ++ vararg'))))) body = pprint block end = text "end" instance LPretty FunCall where pprint (NormalFunCall pe arg) = pprint pe <> pprint arg pprint (MethodCall pe method arg) = pprint pe <//> colon <> pprint method <> pprint arg instance LPretty FunArg where pprint (Args [fun@EFunDef{}]) = parens (pprint fun) pprint (Args exps) = parens (align (fillSep (punctuate comma (map (align . pprint) exps)))) pprint (TableArg t) = pprint t pprint (StringArg s) = text s instance LPretty Stat where pprint (Assign names vals) = intercalate comma (map pprint names) <+> equals <+> intercalate comma (map pprint vals) pprint (FunCall funcall) = pprint funcall pprint (Label name) = text "::" <> pprint name <> text "::" pprint Break = text "break" pprint (Goto name) = text "goto" <+> pprint name pprint (Do block) = group (nest 2 (text "do" <$> pprint block) <$> text "end") pprint (While guard e) = nest 2 (text "while" <+> pprint guard <+> text "do" <$> pprint e) <$> text "end" pprint (Repeat block guard) = nest 2 (text "repeat" <$> pprint block) </> nest 2 (text "until" </> pprint guard) pprint (If cases elsePart) = group (printIf cases elsePart) where printIf ((guard, block) : xs) e = nest 2 (text "if" <+> pprint guard <+> text "then" <$> pprint block) <$> printIf' xs e printIf [] _ = error $ "pprint: Trying to print invalid syntax:\n\t" ++ "if statement should have at least one case" printIf' [] Nothing = text "end" printIf' [] (Just b) = nest 2 (text "else" <$> pprint b) <$> text "end" printIf' ((guard, block) : xs) e = nest 2 (text "elseif" <+> pprint guard <+> text "then" <$> pprint block) <$> printIf' xs e pprint (ForRange name e1 e2 e3 block) = nest 2 (text "for" <+> pprint name <> equals <> pprint e1 <> comma <> pprint e2 <> e3' <+> text "do" <$> pprint block) <$> text "end" where e3' = case e3 of Nothing -> empty Just e -> comma <> pprint e pprint (ForIn names exps block) = nest 2 (text "for" <+> intercalate comma (map pprint names) <+> text "in" <+> intercalate comma (map pprint exps) <+> text "do" <$> pprint block) <$> text "end" pprint (FunAssign name body) = pprintFunction (Just (pprint name)) body pprint (LocalFunAssign name body) = text "local" <+> pprintFunction (Just (pprint name)) body pprint (LocalAssign names exps) = text "local" <+> intercalate comma (map pprint names) <+> exps' where exps' = case exps of Nothing -> empty Just es -> equals </> intercalate comma (map pprint es) pprint EmptyStat = text ";"
osa1/language-lua
src/Language/Lua/PrettyPrinter.hs
bsd-3-clause
8,603
0
18
2,912
3,109
1,544
1,565
197
21
module LexPassUtil where import Common import Control.Applicative import Control.Arrow import Control.Monad.State import Data.Binary import qualified Data.ByteString.Char8 as BSC import Data.Data import Data.Generics import HSH import Options import System.Directory import System.FilePath import System.IO import System.Process import Text.Parsec.Prim (Parsec) import qualified Data.Intercal as IC import Lang.Php.Ast import Util -- -- transf framework -- data Transf = Transf { transfName :: String, transfTypes :: [String], transfDoc :: String, transfArgs :: String, -- unused currently transfFunc :: [String] -> Options -> FilePath -> FilePath -> Int -> Int -> CanErrStrIO (Bool, [String])} data Transformed a = Transformed { infoLines :: [String], transfResult :: Maybe a} deriving (Show) instance Functor Transformed where fmap f t = t {transfResult = fmap f $ transfResult t} instance Applicative Transformed where pure x = Transformed {infoLines = [], transfResult = Just x} -- needed? (sensible?) or should we just have Pointed / use own pure f <*> t = Transformed { infoLines = infoLines f ++ infoLines t, transfResult = transfResult f <*> transfResult t} (-:-) :: String -> [String] -> (String, [String]) name -:- ftypes = (name, ftypes) (-?-) :: (String, [String]) -> String -> (String, [String], String) (name, ftypes) -?- doc = (name, ftypes, doc) (-=-) :: (String, [String], String) -> ([String] -> Options -> FilePath -> FilePath -> Int -> Int -> CanErrStrIO (Bool, [String])) -> Transf (name, ftypes, doc) -=- func = Transf { transfName = bareName, transfTypes = ftypes, transfDoc = doc, transfArgs = argInfo, transfFunc = func} where (bareName, argInfo) = break (== ' ') name -- todo: something more graceful here? argless :: (t -> t1 -> t2) -> [a] -> t -> t1 -> t2 argless f args dir subPath = if null args then f dir subPath else error "Expected no arguments." lexPass :: (Binary a, Parse a, Unparse a) => (a -> Transformed a) -> Options -> FilePath -> FilePath -> Int -> Int -> CanErrStrIO (Bool, [String]) lexPass transf opts codeDir subPath total cur = do liftIO . hPutStrLn stderr $ "Checking (" ++ show cur ++ "/" ++ show total ++ ") " ++ subPath ast <- liftIO $ parseAndCache (optCacheAsts opts) codeDir subPath case transf ast of Transformed {infoLines = infoLines, transfResult = Nothing} -> return (False, infoLines) Transformed {infoLines = infoLines, transfResult = Just ast'} -> liftIO $ do hPutStrLn stderr "- Saving" writeSrcFile (codeDir </> subPath) $ unparse ast' encodeFile (astPath codeDir subPath) ast' return (True, infoLines) -- -- basic transf-building tools -- transfNothing :: Transformed a transfNothing = Transformed {infoLines = [], transfResult = Nothing} {- lastIndent :: WS -> (WS, WS) lastIndent [] = ([], []) lastIndent ws = case wsTail of Tok "WHITESPACE" s -> (wsInit ++ wsTokLIfNotNull sMost, wsTokLIfNotNull sAfterLastLine) where (sMost, sAfterLastLine) = reversifyTup (span (/= '\n')) s wsTokLIfNotNull [] = [] wsTokLIfNotNull x = [wsTokOf x] _ -> (ws, []) where (wsTail:wsInitRev) = reverse ws wsInit = reverse wsInitRev lastLine :: WS -> WS lastLine ws = case lastIndent ws of (_, [Tok "WHITESPACE" s]) -> [wsTokOf $ '\n':s] _ -> [wsTokOf "\n"] wsSp :: [Tok] wsSp = [wsTokOf " "] -} modIntercal :: (a -> b -> a -> Transformed (IC.Intercal a b)) -> IC.Intercal a b -> Transformed (IC.Intercal a b) modIntercal f ical = case runState (IC.concatMapM f' ical) ([], False) of (res, (infoLines, True)) -> Transformed {infoLines = infoLines, transfResult = Just res} (_, (infoLines, False)) -> Transformed {infoLines = infoLines, transfResult = Nothing} where f' a1 b a2 = case f a1 b a2 of Transformed {infoLines = infoLines, transfResult = Just res} -> withState (\ (i, _) -> (i ++ infoLines, True)) $ return res Transformed {infoLines = infoLines, transfResult = Nothing} -> withState (first (++ infoLines)) . return . IC.Intercal a1 b $ IC.Interend a2 modMap :: (a -> Transformed a) -> [a] -> Transformed [a] modMap f xs = case runState (mapM f' xs) ([], False) of (res, (infoLines, True)) -> Transformed {infoLines = infoLines, transfResult = Just res} (_, (infoLines, False)) -> Transformed {infoLines = infoLines, transfResult = Nothing} where f' x = case f x of Transformed {infoLines = infoLines, transfResult = Just res} -> withState (\ (i, _) -> (i ++ infoLines, True)) $ return res Transformed {infoLines = infoLines, transfResult = Nothing} -> withState (first (++ infoLines)) $ return x transformerToState :: (a -> Transformed a) -> a -> State ([String], Bool) a transformerToState f x = case f x of Transformed {infoLines = infoLines, transfResult = Just res} -> withState (\ (i, _) -> (i ++ infoLines, True)) $ return res Transformed {infoLines = infoLines, transfResult = Nothing} -> withState (first (++ infoLines)) $ return x stateToTransformer :: (a -> State ([String], Bool) a) -> a -> Transformed a stateToTransformer f x = case runState (f x) ([], False) of (res, (infoLines, True)) -> Transformed {infoLines = infoLines, transfResult = Just res} (_, (infoLines, False)) -> Transformed {infoLines = infoLines, transfResult = Nothing} modAll :: (Typeable a, Data b) => (a -> Transformed a) -> b -> Transformed b modAll f = stateToTransformer (everywhereM (mkM $ transformerToState f)) -- -- behind-the-scenes/lower-level stuff -- (some of these might be removable after the 2.0 refactor) -- astPath :: FilePath -> FilePath -> FilePath astPath codeDir subPath = codeDir </> ".ast" </> subPath ++ ".ast" transfModsFile :: Parsec s (Bool, b) () transfModsFile = updateState ((,) True . snd) -- - When we read a source file it must be done strictly since we also -- overwrite the files in place when transforming. -- - Unfortunately there are PHP files that are not UTF8. For example -- WordPress uses a bare 0xA9 byte for "©". So we probably have to just -- work at the byte level, which may be best for performance anyway. -- - But all the parsing stuff uses String right now, so I'm hackily -- shoving byte streams into Strings for now. readSrcFile :: FilePath -> IO String readSrcFile f = BSC.unpack <$> BSC.readFile f writeSrcFile :: FilePath -> String -> IO () writeSrcFile f = BSC.writeFile f . BSC.pack -- combine these into AnAst? parseAndCache :: (Binary a, Parse a, Unparse a) => Bool -> FilePath -> FilePath -> IO a parseAndCache cacheAsts codeDir subPath = do let astFilename = astPath codeDir subPath regen = do hPutStrLn stderr "- Parsing" c <- readSrcFile $ codeDir </> subPath case runParser parse () subPath c of Left err -> error $ show err Right ast -> do createDirectoryIfMissing True $ takeDirectory astFilename encodeFile astFilename ast return ast if cacheAsts then doesFileExist astFilename >>= \ r -> if r then do mtimeAst <- getModificationTime astFilename mtimeFile <- getModificationTime (codeDir </> subPath) if mtimeFile > mtimeAst then regen else decodeFile astFilename else regen else do hPutStrLn stderr "- Parsing (always)" c <- readSrcFile $ codeDir </> subPath return $ case runParser parse () subPath c of Left err -> error $ show err Right ast -> ast -- -- eof --
facebookarchive/lex-pass
src/LexPassUtil.hs
bsd-3-clause
7,571
0
18
1,651
2,352
1,270
1,082
145
6
module Main where import Control.Applicative import Control.Monad import Test.DocTest import System.Directory import System.FilePath findHs :: FilePath -> IO [FilePath] findHs dir = do fs <- map (dir </>) <$> filter (`notElem` ["..","."]) <$> getDirectoryContents dir subDirs <- filterM doesDirectoryExist fs files1 <- filter ((`elem` [".hs", ".lhs"]) . takeExtension) <$> filterM doesFileExist fs files2 <- concat <$> mapM findHs subDirs return $ files1 ++ files2 main :: IO () main = do files <- findHs "Numeric" putStrLn $ "testing: " ++ unwords files doctest files
nushio3/binary-search
test/doctests.hs
bsd-3-clause
600
0
13
115
214
110
104
21
1
{- If we are presented with the first k terms of a sequence it is impossible to say with certainty the value of the next term, as there are infinitely many polynomial functions that can model the sequence. As an example, let us consider the sequence of cube numbers. This is defined by the generating function, un = n3: 1, 8, 27, 64, 125, 216, ... Suppose we were only given the first two terms of this sequence. Working on the principle that "simple is best" we should assume a linear relationship and predict the next term to be 15 (common difference 7). Even if we were presented with the first three terms, by the same principle of simplicity, a quadratic relationship should be assumed. We shall define OP(k, n) to be the nth term of the optimum polynomial generating function for the first k terms of a sequence. It should be clear that OP(k, n) will accurately generate the terms of the sequence for n ≤ k, and potentially the first incorrect term (FIT) will be OP(k, k+1); in which case we shall call it a bad OP (BOP). As a basis, if we were only given the first term of sequence, it would be most sensible to assume constancy; that is, for n ≥ 2, OP(1, n) = u1. Hence we obtain the following OPs for the cubic sequence: OP(1, n) = 1 1, 1, 1, 1, ... OP(2, n) = 7n−6 1, 8, 15, ... OP(3, n) = 6n2−11n+6 1, 8, 27, 58, ... OP(4, n) = n3 1, 8, 27, 64, 125, ... Clearly no BOPs exist for k ≥ 4. By considering the sum of FITs generated by the BOPs (indicated in red above), we obtain 1 + 15 + 58 = 74. Consider the following tenth degree polynomial generating function: un = 1 − n + n2 − n3 + n4 − n5 + n6 − n7 + n8 − n9 + n10 Find the sum of FITs for the BOPs. -} {- Notice: find the c_i (`c` for "coefficient") s.t. n=0: c_0 = 1 n=1: 2c_1 + c_0 = 8 1c_1 + c_0 = 1 n=2: 9c_2 + 3c_1 + c_0 = 27 4c_2 + 2c_1 + c_0 = 8 1c_2 + 1c_1 + c_0 = 1 n=3: 64c_3 + 16c_2 + 4c_1 + c_0 = 64 27c_3 + 9c_2 + 3c_1 + c_0 = 27 8c_3 + 4c_2 + 2c_1 + c_0 = 8 1c_3 + 1c_2 + 1c_1 + c_0 = 1 More generally, (watch out for off_by_one) [ (n+1)^n, ... (n+1)^0] [c_n] [t_n] ... ... = ... [ 1^n , ... 1^0 ] [c_1] [t_1] N C = T NC = T C = (N^-1)T N, T known -} {-# LANGUAGE ScopedTypeVariables #-} import qualified Zora.List as ZList import qualified Zora.Math as ZMath import qualified Data.Ord as Ord import qualified Data.Set as Set import qualified Data.List as List import qualified Data.MemoCombinators as Memo import Data.Maybe import Control.Applicative linear_system_of_degree :: Int -> [[Double]] linear_system_of_degree degree = map reverse $ [ [ fromIntegral (n^e) | e <- [0..degree]] | n <- [1..(degree + 1)] ] polynomial :: Double -> Double polynomial n = 1 - n^1 + n^2 - n^3 + n^4 - n^5 + n^6 - n^7 + n^8 - n^9 + n^10 ub :: Double ub = 10 poly_terms_seqs :: [[Double]] poly_terms_seqs = tail . List.inits . map polynomial $ [1..ub] -- Interpolated from Mathematica -- ZMath's is subject to rounding errors for large numbers. interpolated_polynomials :: [[Double]] interpolated_polynomials = [[1], [682, -681], [21461, -63701, 42241], [118008, -686587, 1234387, -665807], [210232, -1984312, 6671533, -9277213, 4379761], [159060, -2175668, 11535788, -29116967, 34305227, -14707439], [58542, -1070322, 8069182, -31492582, 65955241, -68962861, 27442801], [11165, -254078, 2524808, -13814218, 44083303, -80663539, 76941359, -28828799], [1111, -28831, 352528, -2514688, 11126621, -30669221, 50572225, -44806465, 15966721], [54, -1319, 18149, -157772, 902054, -3416929, 8409499, -12753575, 10628639, -3628799]] interpolated_polynomials' :: [[Double]] interpolated_polynomials' = (:) [1.0] $ map (\poly_terms_seq -> ZMath.solve_linear_system (linear_system_of_degree $ pred . length $ poly_terms_seq) poly_terms_seq) $ tail poly_terms_seqs eval_poly :: [Double] -> Double -> Double eval_poly coeffs n = sum . map (\(e, coeff) -> coeff * (n^e)) $ reverse . zip [0..] . reverse $ coeffs fits :: [Double] fits = map (\coeffs -> eval_poly coeffs (fromIntegral . succ . length $ coeffs)) interpolated_polynomials main :: IO () main = do putStrLn . show $ round . sum $ fits
bgwines/project-euler
src/solved/problem101.hs
bsd-3-clause
4,351
22
24
1,016
798
463
335
57
1
{-# LANGUAGE FlexibleContexts #-} import Plots import Plots.Axis import Plots.Types hiding (B) import Plots.Themes import Plots.Utils import Data.List import Diagrams.Prelude import Diagrams.Backend.Rasterific import Diagrams.Backend.CmdLine import Diagrams.Coordinates.Polar import Data.Array import Data.Monoid.Recommend import Dataset fillOpacity = barStyle . mapped . _opacity data1 = [2.3,5.6,7.4,4.3,6.3] grayScale = cycle [sRGB24 33 33 33 , sRGB24 77 77 77 , sRGB24 122 122 122 , sRGB24 163 163 163 , sRGB24 191 191 191 , sRGB24 227 227 227] myaxis :: Axis B Polar Double myaxis = polarAxis &~ do annularWedgePlotFrom' 9 7 xDir (1 @@ turn) $ do strokeArc .= True fillOpacity .= 0.9 plotColor .= sRGB24 227 227 227 annularWedgePlotFrom' 7 4.3 xDir (1 @@ turn) $ do strokeArc .= True fillOpacity .= 0.9 plotColor .= sRGB24 163 163 163 annularWedgePlotFrom' 4.3 3.1 xDir (1 @@ turn) $ do strokeArc .= True fillOpacity .= 0.9 plotColor .= sRGB24 77 77 77 annularWedgePlotFrom' 3.1 0.1 xDir (1 @@ turn) $ do strokeArc .= True fillOpacity .= 0.9 plotColor .= sRGB24 191 191 191 make :: Diagram B -> IO () make = renderRasterific "test.png" (mkWidth 1000) . frame 20 main :: IO () main = make $ renderAxis myaxis
bergey/plots
examples/rings.hs
bsd-3-clause
1,362
0
12
344
461
233
228
44
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE FlexibleInstances #-} module MVC.Event where import Control.Arrow ((+++)) import Data.Maybe (fromJust) import Data.Typeable ----------------------------------------------------------------------------- class (Typeable a, Show a) => Event a data SomeEvent = forall a. (Event a) => SomeEvent a type EitherSomeEvent = Either SomeEvent SomeEvent instance Show SomeEvent where show (SomeEvent x) = show x fromEvent :: Event a => SomeEvent -> Maybe a fromEvent (SomeEvent x) = cast x fromEvent' :: Event a => SomeEvent -> a fromEvent' = fromJust . fromEvent data Match m = forall a. (Event a, Monad m) => Match (a -> m ()) handleEvent :: [Match m] -> (SomeEvent -> m ()) -> SomeEvent -> m () handleEvent matches nomatch e = foldr check' (nomatch e) matches where check' (Match f) ms = case fromEvent e of Just e' -> f e' Nothing -> ms fromEitherSomeEvent :: (Event a, Event b) => Either SomeEvent SomeEvent -> Either a b fromEitherSomeEvent = (fromJust . fromEvent) +++ (fromJust . fromEvent) toEitherSomeEvent :: (Event a, Event b) => Either a b -> Either SomeEvent SomeEvent toEitherSomeEvent = SomeEvent +++ SomeEvent data Msg = Msg String deriving (Typeable) instance Show Msg where show (Msg x) = show x instance Event Msg instance Event String
cmahon/mvc-service
library/MVC/Event.hs
bsd-3-clause
1,383
0
10
256
484
251
233
-1
-1
{-# OPTIONS -fglasgow-exts -cpp #-} -- parser produced by Happy Version 1.13 {- % % (c) The GRASP/AQUA Project, Glasgow University, 1998 % % @(#) $Docid: Jun. 6th 2003 16:54 Sigbjorn Finne $ % @(#) $Contactid: [email protected] $ % A grammar for IDL, DCE / MS (IDL/ODL) style. Conflicts: - 1 reduce/reduce conflict due to `default' both being an attribute and a keyword. - 7 shift/reduce conflicts due to the overloading of `const' (t. qualifier and keyword.) ToDo: - fix above conflicts. -} module Parser ( parseIDL ) where import LexM import Lex import IDLToken import IDLSyn import IDLUtils ( mkFunId, mkMethodId, toCConvAttrib, mkGNUAttrib, toPackedAttrib, exprType ) import BasicTypes import Literal import System.IO ( hPutStrLn, stderr ) {- BEGIN_GHC_ONLY import GlaExts END_GHC_ONLY -} #if __GLASGOW_HASKELL__ >= 503 import GHC.Exts #else import GlaExts #endif data HappyAbsSyn = HappyTerminal IDLToken | HappyErrorToken Int | HappyAbsSyn4 (Either [Defn] [(Name, Bool, [Attribute])]) | HappyAbsSyn5 ([Defn]) | HappyAbsSyn6 ([(String, Bool, [Attribute])]) | HappyAbsSyn7 ((String, Bool, [Attribute] )) | HappyAbsSyn8 (String) | HappyAbsSyn9 (Defn) | HappyAbsSyn13 ([([Attribute], Type, Id)]) | HappyAbsSyn14 ([CoClassMember]) | HappyAbsSyn15 (CoClassMember) | HappyAbsSyn16 ([Attribute]) | HappyAbsSyn18 (Id) | HappyAbsSyn25 (Inherit) | HappyAbsSyn29 ([String]) | HappyAbsSyn30 (Type) | HappyAbsSyn34 (Expr) | HappyAbsSyn42 (BinaryOp) | HappyAbsSyn49 (UnaryOp) | HappyAbsSyn54 (Qualifier) | HappyAbsSyn62 (Either [Switch] [Member]) | HappyAbsSyn63 ([ Id ]) | HappyAbsSyn65 ((Id -> Id)) | HappyAbsSyn71 ([[Qualifier]]) | HappyAbsSyn72 ([ Qualifier ]) | HappyAbsSyn73 ([Member]) | HappyAbsSyn74 (Member) | HappyAbsSyn75 (Maybe Id) | HappyAbsSyn77 ([Switch]) | HappyAbsSyn78 (Switch) | HappyAbsSyn79 (Maybe SwitchArm) | HappyAbsSyn81 ([CaseLabel]) | HappyAbsSyn82 (CaseLabel) | HappyAbsSyn84 ([Expr]) | HappyAbsSyn87 ([(Id, [Attribute], Maybe Expr)]) | HappyAbsSyn88 ((Id, [Attribute], Maybe Expr)) | HappyAbsSyn90 ((Maybe Expr -> Type)) | HappyAbsSyn95 ([[Attribute]]) | HappyAbsSyn98 (Attribute) | HappyAbsSyn101 ([AttrParam]) | HappyAbsSyn103 (AttrParam) | HappyAbsSyn105 (Param) | HappyAbsSyn106 ([Param]) | HappyAbsSyn109 ([GNUAttrib]) | HappyAbsSyn111 (GNUAttrib) | HappyAbsSyn115 (()) type HappyReduction = Int# -> (IDLToken) -> HappyState (IDLToken) (HappyStk HappyAbsSyn -> LexM(HappyAbsSyn)) -> [HappyState (IDLToken) (HappyStk HappyAbsSyn -> LexM(HappyAbsSyn))] -> HappyStk HappyAbsSyn -> LexM(HappyAbsSyn) action_0, action_1, action_2, action_3, action_4, action_5, action_6, action_7, action_8, action_9, action_10, action_11, action_12, action_13, action_14, action_15, action_16, action_17, action_18, action_19, action_20, action_21, action_22, action_23, action_24, action_25, action_26, action_27, action_28, action_29, action_30, action_31, action_32, action_33, action_34, action_35, action_36, action_37, action_38, action_39, action_40, action_41, action_42, action_43, action_44, action_45, action_46, action_47, action_48, action_49, action_50, action_51, action_52, action_53, action_54, action_55, action_56, action_57, action_58, action_59, action_60, action_61, action_62, action_63, action_64, action_65, action_66, action_67, action_68, action_69, action_70, action_71, action_72, action_73, action_74, action_75, action_76, action_77, action_78, action_79, action_80, action_81, action_82, action_83, action_84, action_85, action_86, action_87, action_88, action_89, action_90, action_91, action_92, action_93, action_94, action_95, action_96, action_97, action_98, action_99, action_100, action_101, action_102, action_103, action_104, action_105, action_106, action_107, action_108, action_109, action_110, action_111, action_112, action_113, action_114, action_115, action_116, action_117, action_118, action_119, action_120, action_121, action_122, action_123, action_124, action_125, action_126, action_127, action_128, action_129, action_130, action_131, action_132, action_133, action_134, action_135, action_136, action_137, action_138, action_139, action_140, action_141, action_142, action_143, action_144, action_145, action_146, action_147, action_148, action_149, action_150, action_151, action_152, action_153, action_154, action_155, action_156, action_157, action_158, action_159, action_160, action_161, action_162, action_163, action_164, action_165, action_166, action_167, action_168, action_169, action_170, action_171, action_172, action_173, action_174, action_175, action_176, action_177, action_178, action_179, action_180, action_181, action_182, action_183, action_184, action_185, action_186, action_187, action_188, action_189, action_190, action_191, action_192, action_193, action_194, action_195, action_196, action_197, action_198, action_199, action_200, action_201, action_202, action_203, action_204, action_205, action_206, action_207, action_208, action_209, action_210, action_211, action_212, action_213, action_214, action_215, action_216, action_217, action_218, action_219, action_220, action_221, action_222, action_223, action_224, action_225, action_226, action_227, action_228, action_229, action_230, action_231, action_232, action_233, action_234, action_235, action_236, action_237, action_238, action_239, action_240, action_241, action_242, action_243, action_244, action_245, action_246, action_247, action_248, action_249, action_250, action_251, action_252, action_253, action_254, action_255, action_256, action_257, action_258, action_259, action_260, action_261, action_262, action_263, action_264, action_265, action_266, action_267, action_268, action_269, action_270, action_271, action_272, action_273, action_274, action_275, action_276, action_277, action_278, action_279, action_280, action_281, action_282, action_283, action_284, action_285, action_286, action_287, action_288, action_289, action_290, action_291, action_292, action_293, action_294, action_295, action_296, action_297, action_298, action_299, action_300, action_301, action_302, action_303, action_304, action_305, action_306, action_307, action_308, action_309, action_310, action_311, action_312, action_313, action_314, action_315, action_316, action_317, action_318, action_319, action_320, action_321, action_322, action_323, action_324, action_325, action_326, action_327, action_328, action_329, action_330, action_331, action_332, action_333, action_334, action_335, action_336, action_337, action_338, action_339, action_340, action_341, action_342, action_343, action_344, action_345, action_346, action_347, action_348, action_349, action_350, action_351, action_352, action_353, action_354, action_355, action_356, action_357, action_358, action_359, action_360, action_361, action_362, action_363, action_364, action_365, action_366, action_367, action_368, action_369, action_370, action_371, action_372, action_373, action_374, action_375, action_376, action_377, action_378, action_379, action_380, action_381, action_382, action_383, action_384, action_385, action_386, action_387, action_388, action_389, action_390, action_391, action_392, action_393, action_394, action_395, action_396, action_397, action_398, action_399, action_400, action_401, action_402, action_403, action_404, action_405, action_406, action_407, action_408, action_409, action_410, action_411, action_412, action_413, action_414, action_415, action_416, action_417, action_418, action_419, action_420, action_421, action_422, action_423, action_424, action_425, action_426, action_427, action_428, action_429, action_430, action_431, action_432, action_433, action_434, action_435, action_436, action_437, action_438, action_439, action_440, action_441, action_442, action_443, action_444, action_445, action_446, action_447, action_448, action_449, action_450, action_451, action_452, action_453, action_454, action_455, action_456, action_457, action_458, action_459, action_460, action_461, action_462, action_463, action_464, action_465, action_466, action_467, action_468, action_469, action_470, action_471, action_472, action_473, action_474, action_475, action_476, action_477, action_478, action_479, action_480, action_481, action_482, action_483, action_484, action_485, action_486, action_487, action_488, action_489, action_490, action_491, action_492, action_493, action_494, action_495, action_496, action_497, action_498, action_499, action_500, action_501, action_502, action_503, action_504, action_505, action_506, action_507, action_508, action_509, action_510, action_511, action_512, action_513, action_514, action_515, action_516, action_517, action_518, action_519, action_520, action_521, action_522, action_523, action_524, action_525, action_526, action_527, action_528, action_529, action_530, action_531, action_532, action_533, action_534, action_535, action_536, action_537, action_538, action_539, action_540, action_541, action_542, action_543, action_544, action_545, action_546, action_547, action_548, action_549, action_550, action_551, action_552, action_553, action_554, action_555, action_556, action_557, action_558, action_559, action_560, action_561, action_562, action_563, action_564, action_565, action_566, action_567, action_568, action_569, action_570, action_571, action_572, action_573, action_574, action_575, action_576, action_577, action_578, action_579, action_580, action_581, action_582, action_583, action_584, action_585, action_586, action_587, action_588, action_589, action_590, action_591, action_592, action_593, action_594, action_595, action_596, action_597 :: Int# -> HappyReduction happyReduce_1, happyReduce_2, happyReduce_3, happyReduce_4, happyReduce_5, happyReduce_6, happyReduce_7, happyReduce_8, happyReduce_9, happyReduce_10, happyReduce_11, happyReduce_12, happyReduce_13, happyReduce_14, happyReduce_15, happyReduce_16, happyReduce_17, happyReduce_18, happyReduce_19, happyReduce_20, happyReduce_21, happyReduce_22, happyReduce_23, happyReduce_24, happyReduce_25, happyReduce_26, happyReduce_27, happyReduce_28, happyReduce_29, happyReduce_30, happyReduce_31, happyReduce_32, happyReduce_33, happyReduce_34, happyReduce_35, happyReduce_36, happyReduce_37, happyReduce_38, happyReduce_39, happyReduce_40, happyReduce_41, happyReduce_42, happyReduce_43, happyReduce_44, happyReduce_45, happyReduce_46, happyReduce_47, happyReduce_48, happyReduce_49, happyReduce_50, happyReduce_51, happyReduce_52, happyReduce_53, happyReduce_54, happyReduce_55, happyReduce_56, happyReduce_57, happyReduce_58, happyReduce_59, happyReduce_60, happyReduce_61, happyReduce_62, happyReduce_63, happyReduce_64, happyReduce_65, happyReduce_66, happyReduce_67, happyReduce_68, happyReduce_69, happyReduce_70, happyReduce_71, happyReduce_72, happyReduce_73, happyReduce_74, happyReduce_75, happyReduce_76, happyReduce_77, happyReduce_78, happyReduce_79, happyReduce_80, happyReduce_81, happyReduce_82, happyReduce_83, happyReduce_84, happyReduce_85, happyReduce_86, happyReduce_87, happyReduce_88, happyReduce_89, happyReduce_90, happyReduce_91, happyReduce_92, happyReduce_93, happyReduce_94, happyReduce_95, happyReduce_96, happyReduce_97, happyReduce_98, happyReduce_99, happyReduce_100, happyReduce_101, happyReduce_102, happyReduce_103, happyReduce_104, happyReduce_105, happyReduce_106, happyReduce_107, happyReduce_108, happyReduce_109, happyReduce_110, happyReduce_111, happyReduce_112, happyReduce_113, happyReduce_114, happyReduce_115, happyReduce_116, happyReduce_117, happyReduce_118, happyReduce_119, happyReduce_120, happyReduce_121, happyReduce_122, happyReduce_123, happyReduce_124, happyReduce_125, happyReduce_126, happyReduce_127, happyReduce_128, happyReduce_129, happyReduce_130, happyReduce_131, happyReduce_132, happyReduce_133, happyReduce_134, happyReduce_135, happyReduce_136, happyReduce_137, happyReduce_138, happyReduce_139, happyReduce_140, happyReduce_141, happyReduce_142, happyReduce_143, happyReduce_144, happyReduce_145, happyReduce_146, happyReduce_147, happyReduce_148, happyReduce_149, happyReduce_150, happyReduce_151, happyReduce_152, happyReduce_153, happyReduce_154, happyReduce_155, happyReduce_156, happyReduce_157, happyReduce_158, happyReduce_159, happyReduce_160, happyReduce_161, happyReduce_162, happyReduce_163, happyReduce_164, happyReduce_165, happyReduce_166, happyReduce_167, happyReduce_168, happyReduce_169, happyReduce_170, happyReduce_171, happyReduce_172, happyReduce_173, happyReduce_174, happyReduce_175, happyReduce_176, happyReduce_177, happyReduce_178, happyReduce_179, happyReduce_180, happyReduce_181, happyReduce_182, happyReduce_183, happyReduce_184, happyReduce_185, happyReduce_186, happyReduce_187, happyReduce_188, happyReduce_189, happyReduce_190, happyReduce_191, happyReduce_192, happyReduce_193, happyReduce_194, happyReduce_195, happyReduce_196, happyReduce_197, happyReduce_198, happyReduce_199, happyReduce_200, happyReduce_201, happyReduce_202, happyReduce_203, happyReduce_204, happyReduce_205, happyReduce_206, happyReduce_207, happyReduce_208, happyReduce_209, happyReduce_210, happyReduce_211, happyReduce_212, happyReduce_213, happyReduce_214, happyReduce_215, happyReduce_216, happyReduce_217, happyReduce_218, happyReduce_219, happyReduce_220, happyReduce_221, happyReduce_222, happyReduce_223, happyReduce_224, happyReduce_225, happyReduce_226, happyReduce_227, happyReduce_228, happyReduce_229, happyReduce_230, happyReduce_231, happyReduce_232, happyReduce_233, happyReduce_234, happyReduce_235, happyReduce_236, happyReduce_237, happyReduce_238, happyReduce_239, happyReduce_240, happyReduce_241, happyReduce_242, happyReduce_243, happyReduce_244, happyReduce_245, happyReduce_246, happyReduce_247, happyReduce_248, happyReduce_249, happyReduce_250, happyReduce_251, happyReduce_252, happyReduce_253, happyReduce_254, happyReduce_255, happyReduce_256, happyReduce_257, happyReduce_258, happyReduce_259, happyReduce_260, happyReduce_261, happyReduce_262, happyReduce_263, happyReduce_264, happyReduce_265, happyReduce_266, happyReduce_267, happyReduce_268, happyReduce_269, happyReduce_270, happyReduce_271, happyReduce_272, happyReduce_273, happyReduce_274, happyReduce_275, happyReduce_276, happyReduce_277, happyReduce_278, happyReduce_279, happyReduce_280, happyReduce_281, happyReduce_282, happyReduce_283, happyReduce_284, happyReduce_285, happyReduce_286, happyReduce_287, happyReduce_288, happyReduce_289, happyReduce_290, happyReduce_291, happyReduce_292, happyReduce_293, happyReduce_294, happyReduce_295, happyReduce_296, happyReduce_297, happyReduce_298, happyReduce_299, happyReduce_300, happyReduce_301, happyReduce_302, happyReduce_303, happyReduce_304, happyReduce_305, happyReduce_306, happyReduce_307, happyReduce_308, happyReduce_309, happyReduce_310, happyReduce_311, happyReduce_312, happyReduce_313, happyReduce_314, happyReduce_315, happyReduce_316, happyReduce_317, happyReduce_318, happyReduce_319, happyReduce_320, happyReduce_321, happyReduce_322, happyReduce_323, happyReduce_324, happyReduce_325, happyReduce_326, happyReduce_327, happyReduce_328, happyReduce_329, happyReduce_330, happyReduce_331, happyReduce_332, happyReduce_333, happyReduce_334, happyReduce_335, happyReduce_336, happyReduce_337, happyReduce_338, happyReduce_339, happyReduce_340, happyReduce_341, happyReduce_342, happyReduce_343, happyReduce_344, happyReduce_345, happyReduce_346, happyReduce_347, happyReduce_348, happyReduce_349, happyReduce_350, happyReduce_351, happyReduce_352, happyReduce_353, happyReduce_354, happyReduce_355, happyReduce_356, happyReduce_357, happyReduce_358, happyReduce_359 :: HappyReduction action_0 (130#) = happyShift action_4 action_0 (4#) = happyGoto action_3 action_0 (5#) = happyGoto action_2 action_0 x = happyTcHack x happyReduce_3 action_1 (5#) = happyGoto action_2 action_1 x = happyTcHack x happyFail action_2 (1#) = happyShift action_36 action_2 (118#) = happyShift action_37 action_2 (119#) = happyShift action_38 action_2 (128#) = happyShift action_39 action_2 (144#) = happyReduce_344 action_2 (145#) = happyReduce_344 action_2 (146#) = happyShift action_40 action_2 (147#) = happyShift action_41 action_2 (148#) = happyShift action_42 action_2 (149#) = happyShift action_43 action_2 (150#) = happyShift action_44 action_2 (151#) = happyShift action_45 action_2 (152#) = happyShift action_46 action_2 (153#) = happyShift action_47 action_2 (154#) = happyShift action_48 action_2 (155#) = happyShift action_49 action_2 (156#) = happyShift action_50 action_2 (157#) = happyShift action_51 action_2 (158#) = happyShift action_52 action_2 (159#) = happyShift action_53 action_2 (163#) = happyShift action_54 action_2 (168#) = happyShift action_55 action_2 (171#) = happyShift action_56 action_2 (176#) = happyShift action_57 action_2 (177#) = happyShift action_58 action_2 (178#) = happyShift action_59 action_2 (179#) = happyShift action_60 action_2 (183#) = happyShift action_61 action_2 (184#) = happyShift action_62 action_2 (187#) = happyShift action_63 action_2 (188#) = happyShift action_64 action_2 (189#) = happyShift action_65 action_2 (190#) = happyShift action_66 action_2 (191#) = happyShift action_67 action_2 (192#) = happyShift action_68 action_2 (193#) = happyShift action_69 action_2 (194#) = happyShift action_70 action_2 (195#) = happyShift action_71 action_2 (196#) = happyShift action_72 action_2 (197#) = happyShift action_73 action_2 (199#) = happyReduce_1 action_2 (9#) = happyGoto action_6 action_2 (10#) = happyGoto action_7 action_2 (11#) = happyGoto action_8 action_2 (12#) = happyGoto action_9 action_2 (17#) = happyGoto action_10 action_2 (18#) = happyGoto action_11 action_2 (19#) = happyGoto action_12 action_2 (20#) = happyGoto action_13 action_2 (21#) = happyGoto action_14 action_2 (26#) = happyGoto action_15 action_2 (27#) = happyGoto action_16 action_2 (28#) = happyGoto action_17 action_2 (31#) = happyGoto action_18 action_2 (32#) = happyGoto action_19 action_2 (51#) = happyGoto action_20 action_2 (53#) = happyGoto action_21 action_2 (55#) = happyGoto action_22 action_2 (58#) = happyGoto action_23 action_2 (59#) = happyGoto action_24 action_2 (60#) = happyGoto action_25 action_2 (61#) = happyGoto action_26 action_2 (86#) = happyGoto action_27 action_2 (89#) = happyGoto action_28 action_2 (90#) = happyGoto action_29 action_2 (93#) = happyGoto action_30 action_2 (96#) = happyGoto action_31 action_2 (104#) = happyGoto action_32 action_2 (109#) = happyGoto action_33 action_2 (110#) = happyGoto action_34 action_2 (111#) = happyGoto action_35 action_2 x = happyTcHack x happyFail action_3 (199#) = happyAccept action_3 x = happyTcHack x happyFail action_4 (6#) = happyGoto action_5 action_4 x = happyTcHack x happyReduce_5 action_5 (146#) = happyShift action_175 action_5 (176#) = happyShift action_176 action_5 (7#) = happyGoto action_173 action_5 (8#) = happyGoto action_174 action_5 x = happyTcHack x happyReduce_2 action_6 x = happyTcHack x happyReduce_4 action_7 (1#) = happyShift action_166 action_7 (117#) = happyShift action_167 action_7 (115#) = happyGoto action_172 action_7 x = happyTcHack x happyFail action_8 x = happyTcHack x happyReduce_20 action_9 x = happyTcHack x happyReduce_24 action_10 x = happyTcHack x happyReduce_21 action_11 (122#) = happyReduce_60 action_11 (124#) = happyShift action_171 action_11 (25#) = happyGoto action_170 action_11 x = happyTcHack x happyReduce_41 action_12 (122#) = happyShift action_169 action_12 x = happyTcHack x happyFail action_13 (1#) = happyShift action_166 action_13 (117#) = happyShift action_167 action_13 (115#) = happyGoto action_168 action_13 x = happyTcHack x happyFail action_14 (1#) = happyShift action_166 action_14 (117#) = happyShift action_167 action_14 (115#) = happyGoto action_165 action_14 x = happyTcHack x happyFail action_15 (117#) = happyShift action_164 action_15 x = happyTcHack x happyFail action_16 x = happyTcHack x happyReduce_18 action_17 x = happyTcHack x happyReduce_16 action_18 (153#) = happyShift action_161 action_18 (154#) = happyShift action_162 action_18 (155#) = happyShift action_163 action_18 x = happyTcHack x happyReduce_99 action_19 x = happyTcHack x happyReduce_184 action_20 (117#) = happyShift action_160 action_20 x = happyTcHack x happyFail action_21 (168#) = happyShift action_159 action_21 x = happyTcHack x happyReduce_327 action_22 (128#) = happyShift action_157 action_22 (129#) = happyShift action_158 action_22 (54#) = happyGoto action_156 action_22 x = happyTcHack x happyReduce_176 action_23 x = happyTcHack x happyReduce_167 action_24 (120#) = happyReduce_198 action_24 (124#) = happyReduce_198 action_24 (128#) = happyReduce_198 action_24 (129#) = happyReduce_198 action_24 (146#) = happyReduce_198 action_24 (168#) = happyReduce_198 action_24 (172#) = happyReduce_198 action_24 (175#) = happyReduce_198 action_24 (176#) = happyReduce_198 action_24 (181#) = happyReduce_198 action_24 (193#) = happyReduce_198 action_24 x = happyTcHack x happyReduce_208 action_25 x = happyTcHack x happyReduce_210 action_26 x = happyTcHack x happyReduce_211 action_27 (120#) = happyReduce_199 action_27 (124#) = happyReduce_199 action_27 (128#) = happyReduce_199 action_27 (129#) = happyReduce_199 action_27 (146#) = happyReduce_199 action_27 (168#) = happyReduce_199 action_27 (172#) = happyReduce_199 action_27 (175#) = happyReduce_199 action_27 (176#) = happyReduce_199 action_27 (181#) = happyReduce_199 action_27 (193#) = happyReduce_199 action_27 x = happyTcHack x happyReduce_209 action_28 x = happyTcHack x happyReduce_328 action_29 (164#) = happyShift action_155 action_29 x = happyTcHack x happyReduce_295 action_30 x = happyTcHack x happyReduce_28 action_31 (1#) = happyShift action_36 action_31 (118#) = happyShift action_37 action_31 (119#) = happyShift action_38 action_31 (128#) = happyShift action_153 action_31 (146#) = happyShift action_40 action_31 (147#) = happyShift action_41 action_31 (148#) = happyShift action_42 action_31 (149#) = happyShift action_43 action_31 (150#) = happyShift action_44 action_31 (151#) = happyShift action_45 action_31 (152#) = happyShift action_46 action_31 (153#) = happyShift action_47 action_31 (154#) = happyShift action_48 action_31 (155#) = happyShift action_49 action_31 (156#) = happyShift action_50 action_31 (157#) = happyShift action_51 action_31 (158#) = happyShift action_52 action_31 (159#) = happyShift action_53 action_31 (163#) = happyShift action_54 action_31 (171#) = happyShift action_56 action_31 (176#) = happyShift action_57 action_31 (177#) = happyShift action_154 action_31 (178#) = happyShift action_59 action_31 (179#) = happyShift action_60 action_31 (183#) = happyShift action_61 action_31 (184#) = happyShift action_62 action_31 (197#) = happyShift action_73 action_31 (11#) = happyGoto action_151 action_31 (12#) = happyGoto action_9 action_31 (17#) = happyGoto action_10 action_31 (18#) = happyGoto action_11 action_31 (19#) = happyGoto action_12 action_31 (31#) = happyGoto action_18 action_31 (32#) = happyGoto action_19 action_31 (53#) = happyGoto action_21 action_31 (55#) = happyGoto action_22 action_31 (58#) = happyGoto action_152 action_31 (59#) = happyGoto action_24 action_31 (60#) = happyGoto action_25 action_31 (61#) = happyGoto action_26 action_31 (86#) = happyGoto action_27 action_31 (89#) = happyGoto action_28 action_31 (90#) = happyGoto action_29 action_31 (93#) = happyGoto action_30 action_31 (104#) = happyGoto action_32 action_31 x = happyTcHack x happyFail action_32 (120#) = happyShift action_148 action_32 (124#) = happyShift action_104 action_32 (146#) = happyShift action_105 action_32 (172#) = happyShift action_106 action_32 (175#) = happyShift action_149 action_32 (176#) = happyShift action_86 action_32 (181#) = happyShift action_150 action_32 (193#) = happyShift action_69 action_32 (64#) = happyGoto action_139 action_32 (65#) = happyGoto action_140 action_32 (66#) = happyGoto action_141 action_32 (67#) = happyGoto action_142 action_32 (68#) = happyGoto action_143 action_32 (69#) = happyGoto action_144 action_32 (70#) = happyGoto action_145 action_32 (71#) = happyGoto action_146 action_32 (110#) = happyGoto action_147 action_32 (111#) = happyGoto action_35 action_32 (114#) = happyGoto action_102 action_32 x = happyTcHack x happyFail action_33 (144#) = happyShift action_137 action_33 (145#) = happyShift action_138 action_33 x = happyTcHack x happyFail action_34 (193#) = happyShift action_69 action_34 (111#) = happyGoto action_136 action_34 x = happyTcHack x happyReduce_345 action_35 x = happyTcHack x happyReduce_346 action_36 x = happyTcHack x happyReduce_200 action_37 (176#) = happyShift action_86 action_37 (114#) = happyGoto action_135 action_37 x = happyTcHack x happyFail action_38 (146#) = happyShift action_133 action_38 (147#) = happyShift action_134 action_38 (176#) = happyShift action_86 action_38 (114#) = happyGoto action_132 action_38 x = happyTcHack x happyFail action_39 (1#) = happyShift action_122 action_39 (146#) = happyShift action_123 action_39 (147#) = happyShift action_124 action_39 (148#) = happyShift action_125 action_39 (149#) = happyShift action_43 action_39 (150#) = happyShift action_44 action_39 (151#) = happyShift action_45 action_39 (152#) = happyShift action_46 action_39 (153#) = happyShift action_47 action_39 (154#) = happyShift action_126 action_39 (155#) = happyShift action_127 action_39 (156#) = happyShift action_128 action_39 (157#) = happyShift action_129 action_39 (171#) = happyShift action_130 action_39 (176#) = happyShift action_131 action_39 (183#) = happyShift action_61 action_39 (184#) = happyShift action_62 action_39 (30#) = happyGoto action_118 action_39 (31#) = happyGoto action_119 action_39 (32#) = happyGoto action_120 action_39 (89#) = happyGoto action_121 action_39 (90#) = happyGoto action_29 action_39 x = happyTcHack x happyFail action_40 x = happyTcHack x happyReduce_195 action_41 x = happyTcHack x happyReduce_196 action_42 x = happyTcHack x happyReduce_181 action_43 x = happyTcHack x happyReduce_94 action_44 (150#) = happyShift action_117 action_44 x = happyTcHack x happyReduce_95 action_45 x = happyTcHack x happyReduce_97 action_46 x = happyTcHack x happyReduce_98 action_47 x = happyTcHack x happyReduce_101 action_48 (128#) = happyShift action_116 action_48 (146#) = happyShift action_111 action_48 (147#) = happyShift action_112 action_48 (148#) = happyShift action_113 action_48 (149#) = happyShift action_43 action_48 (150#) = happyShift action_44 action_48 (151#) = happyShift action_45 action_48 (152#) = happyShift action_46 action_48 (153#) = happyShift action_47 action_48 (156#) = happyShift action_114 action_48 (31#) = happyGoto action_107 action_48 (32#) = happyGoto action_108 action_48 (56#) = happyGoto action_115 action_48 x = happyTcHack x happyReduce_187 action_49 (128#) = happyShift action_110 action_49 (146#) = happyShift action_111 action_49 (147#) = happyShift action_112 action_49 (148#) = happyShift action_113 action_49 (149#) = happyShift action_43 action_49 (150#) = happyShift action_44 action_49 (151#) = happyShift action_45 action_49 (152#) = happyShift action_46 action_49 (153#) = happyShift action_47 action_49 (156#) = happyShift action_114 action_49 (31#) = happyGoto action_107 action_49 (32#) = happyGoto action_108 action_49 (56#) = happyGoto action_109 action_49 x = happyTcHack x happyReduce_186 action_50 x = happyTcHack x happyReduce_182 action_51 x = happyTcHack x happyReduce_183 action_52 (122#) = happyShift action_103 action_52 (124#) = happyShift action_104 action_52 (146#) = happyShift action_105 action_52 (172#) = happyShift action_106 action_52 (176#) = happyShift action_86 action_52 (67#) = happyGoto action_101 action_52 (114#) = happyGoto action_102 action_52 x = happyTcHack x happyFail action_53 (176#) = happyShift action_86 action_53 (75#) = happyGoto action_99 action_53 (114#) = happyGoto action_100 action_53 x = happyTcHack x happyReduce_257 action_54 (122#) = happyShift action_98 action_54 (176#) = happyShift action_86 action_54 (114#) = happyGoto action_97 action_54 x = happyTcHack x happyFail action_55 (169#) = happyShift action_94 action_55 (172#) = happyShift action_95 action_55 (176#) = happyShift action_86 action_55 (183#) = happyShift action_96 action_55 (97#) = happyGoto action_91 action_55 (98#) = happyGoto action_92 action_55 (114#) = happyGoto action_93 action_55 x = happyTcHack x happyFail action_56 x = happyTcHack x happyReduce_185 action_57 x = happyTcHack x happyReduce_194 action_58 (146#) = happyShift action_90 action_58 (176#) = happyShift action_86 action_58 (114#) = happyGoto action_89 action_58 x = happyTcHack x happyFail action_59 (146#) = happyShift action_88 action_59 (176#) = happyShift action_86 action_59 (114#) = happyGoto action_87 action_59 x = happyTcHack x happyFail action_60 (176#) = happyShift action_86 action_60 (114#) = happyGoto action_85 action_60 x = happyTcHack x happyFail action_61 x = happyTcHack x happyReduce_296 action_62 x = happyTcHack x happyReduce_297 action_63 (120#) = happyShift action_84 action_63 x = happyTcHack x happyFail action_64 (120#) = happyShift action_83 action_64 x = happyTcHack x happyFail action_65 x = happyTcHack x happyReduce_50 action_66 (120#) = happyShift action_82 action_66 x = happyTcHack x happyFail action_67 x = happyTcHack x happyReduce_66 action_68 x = happyTcHack x happyReduce_67 action_69 (120#) = happyShift action_81 action_69 x = happyTcHack x happyFail action_70 (174#) = happyShift action_80 action_70 (29#) = happyGoto action_79 action_70 x = happyTcHack x happyFail action_71 x = happyTcHack x happyReduce_65 action_72 (176#) = happyShift action_78 action_72 x = happyTcHack x happyFail action_73 (1#) = happyShift action_36 action_73 (146#) = happyShift action_40 action_73 (147#) = happyShift action_41 action_73 (148#) = happyShift action_42 action_73 (149#) = happyShift action_43 action_73 (150#) = happyShift action_44 action_73 (151#) = happyShift action_45 action_73 (152#) = happyShift action_46 action_73 (153#) = happyShift action_47 action_73 (154#) = happyShift action_48 action_73 (155#) = happyShift action_49 action_73 (156#) = happyShift action_50 action_73 (157#) = happyShift action_51 action_73 (158#) = happyShift action_52 action_73 (159#) = happyShift action_53 action_73 (163#) = happyShift action_54 action_73 (171#) = happyShift action_56 action_73 (176#) = happyShift action_57 action_73 (197#) = happyShift action_73 action_73 (31#) = happyGoto action_18 action_73 (32#) = happyGoto action_19 action_73 (55#) = happyGoto action_74 action_73 (57#) = happyGoto action_75 action_73 (59#) = happyGoto action_76 action_73 (60#) = happyGoto action_25 action_73 (61#) = happyGoto action_26 action_73 (86#) = happyGoto action_77 action_73 x = happyTcHack x happyFail action_74 x = happyTcHack x happyReduce_206 action_75 (121#) = happyShift action_274 action_75 (181#) = happyShift action_275 action_75 x = happyTcHack x happyFail action_76 x = happyTcHack x happyReduce_198 action_77 x = happyTcHack x happyReduce_199 action_78 (120#) = happyShift action_195 action_78 (141#) = happyShift action_196 action_78 (142#) = happyShift action_197 action_78 (170#) = happyShift action_198 action_78 (173#) = happyShift action_199 action_78 (174#) = happyShift action_200 action_78 (176#) = happyShift action_86 action_78 (180#) = happyShift action_201 action_78 (182#) = happyShift action_202 action_78 (34#) = happyGoto action_264 action_78 (35#) = happyGoto action_265 action_78 (36#) = happyGoto action_266 action_78 (37#) = happyGoto action_267 action_78 (38#) = happyGoto action_268 action_78 (39#) = happyGoto action_269 action_78 (40#) = happyGoto action_270 action_78 (41#) = happyGoto action_271 action_78 (43#) = happyGoto action_272 action_78 (44#) = happyGoto action_273 action_78 (45#) = happyGoto action_188 action_78 (46#) = happyGoto action_189 action_78 (47#) = happyGoto action_190 action_78 (48#) = happyGoto action_191 action_78 (49#) = happyGoto action_192 action_78 (50#) = happyGoto action_193 action_78 (114#) = happyGoto action_194 action_78 x = happyTcHack x happyFail action_79 x = happyTcHack x happyReduce_63 action_80 (125#) = happyShift action_263 action_80 x = happyTcHack x happyReduce_69 action_81 (120#) = happyShift action_262 action_81 x = happyTcHack x happyFail action_82 (174#) = happyShift action_261 action_82 x = happyTcHack x happyFail action_83 (174#) = happyShift action_260 action_83 x = happyTcHack x happyFail action_84 (174#) = happyShift action_259 action_84 x = happyTcHack x happyFail action_85 (122#) = happyShift action_258 action_85 x = happyTcHack x happyFail action_86 x = happyTcHack x happyReduce_355 action_87 (122#) = happyShift action_257 action_87 x = happyTcHack x happyFail action_88 (122#) = happyShift action_256 action_88 x = happyTcHack x happyFail action_89 (117#) = happyShift action_255 action_89 x = happyTcHack x happyReduce_46 action_90 x = happyTcHack x happyReduce_47 action_91 (125#) = happyShift action_254 action_91 (116#) = happyGoto action_253 action_91 x = happyTcHack x happyReduce_358 action_92 x = happyTcHack x happyReduce_307 action_93 (120#) = happyShift action_252 action_93 (101#) = happyGoto action_251 action_93 x = happyTcHack x happyReduce_316 action_94 x = happyTcHack x happyReduce_305 action_95 x = happyTcHack x happyReduce_311 action_96 x = happyTcHack x happyReduce_310 action_97 (122#) = happyShift action_250 action_97 x = happyTcHack x happyReduce_287 action_98 (168#) = happyShift action_55 action_98 (176#) = happyShift action_86 action_98 (87#) = happyGoto action_246 action_98 (88#) = happyGoto action_247 action_98 (96#) = happyGoto action_248 action_98 (114#) = happyGoto action_249 action_98 x = happyTcHack x happyFail action_99 (122#) = happyShift action_244 action_99 (160#) = happyShift action_245 action_99 x = happyTcHack x happyFail action_100 (122#) = happyReduce_258 action_100 (160#) = happyReduce_258 action_100 (193#) = happyShift action_69 action_100 (109#) = happyGoto action_243 action_100 (110#) = happyGoto action_34 action_100 (111#) = happyGoto action_35 action_100 x = happyTcHack x happyReduce_344 action_101 (122#) = happyShift action_242 action_101 x = happyTcHack x happyReduce_214 action_102 (124#) = happyShift action_241 action_102 x = happyTcHack x happyReduce_232 action_103 (168#) = happyShift action_55 action_103 (73#) = happyGoto action_238 action_103 (74#) = happyGoto action_239 action_103 (94#) = happyGoto action_240 action_103 (95#) = happyGoto action_219 action_103 (96#) = happyGoto action_220 action_103 x = happyTcHack x happyReduce_303 action_104 (173#) = happyShift action_237 action_104 x = happyTcHack x happyFail action_105 (124#) = happyShift action_236 action_105 x = happyTcHack x happyReduce_236 action_106 x = happyTcHack x happyReduce_237 action_107 (153#) = happyShift action_161 action_107 x = happyTcHack x happyReduce_99 action_108 x = happyTcHack x happyReduce_201 action_109 x = happyTcHack x happyReduce_188 action_110 (146#) = happyShift action_111 action_110 (147#) = happyShift action_112 action_110 (148#) = happyShift action_113 action_110 (149#) = happyShift action_43 action_110 (150#) = happyShift action_44 action_110 (151#) = happyShift action_45 action_110 (152#) = happyShift action_46 action_110 (153#) = happyShift action_47 action_110 (156#) = happyShift action_114 action_110 (31#) = happyGoto action_107 action_110 (32#) = happyGoto action_108 action_110 (56#) = happyGoto action_235 action_110 x = happyTcHack x happyFail action_111 x = happyTcHack x happyReduce_204 action_112 x = happyTcHack x happyReduce_205 action_113 x = happyTcHack x happyReduce_203 action_114 x = happyTcHack x happyReduce_202 action_115 x = happyTcHack x happyReduce_190 action_116 (146#) = happyShift action_111 action_116 (147#) = happyShift action_112 action_116 (148#) = happyShift action_113 action_116 (149#) = happyShift action_43 action_116 (150#) = happyShift action_44 action_116 (151#) = happyShift action_45 action_116 (152#) = happyShift action_46 action_116 (153#) = happyShift action_47 action_116 (156#) = happyShift action_114 action_116 (31#) = happyGoto action_107 action_116 (32#) = happyGoto action_108 action_116 (56#) = happyGoto action_234 action_116 x = happyTcHack x happyFail action_117 x = happyTcHack x happyReduce_96 action_118 (168#) = happyShift action_233 action_118 (176#) = happyShift action_86 action_118 (114#) = happyGoto action_232 action_118 x = happyTcHack x happyFail action_119 (153#) = happyShift action_161 action_119 (154#) = happyShift action_230 action_119 (155#) = happyShift action_231 action_119 x = happyTcHack x happyReduce_99 action_120 x = happyTcHack x happyReduce_71 action_121 x = happyTcHack x happyReduce_79 action_122 x = happyTcHack x happyReduce_93 action_123 (181#) = happyShift action_229 action_123 x = happyTcHack x happyReduce_90 action_124 x = happyTcHack x happyReduce_92 action_125 x = happyTcHack x happyReduce_74 action_126 (149#) = happyShift action_43 action_126 (150#) = happyShift action_44 action_126 (151#) = happyShift action_45 action_126 (152#) = happyShift action_46 action_126 (153#) = happyShift action_47 action_126 (156#) = happyShift action_228 action_126 (31#) = happyGoto action_107 action_126 (32#) = happyGoto action_227 action_126 x = happyTcHack x happyReduce_82 action_127 (149#) = happyShift action_43 action_127 (150#) = happyShift action_44 action_127 (151#) = happyShift action_45 action_127 (152#) = happyShift action_46 action_127 (153#) = happyShift action_47 action_127 (156#) = happyShift action_226 action_127 (31#) = happyGoto action_107 action_127 (32#) = happyGoto action_225 action_127 x = happyTcHack x happyReduce_81 action_128 (181#) = happyShift action_224 action_128 x = happyTcHack x happyReduce_72 action_129 (181#) = happyShift action_223 action_129 x = happyTcHack x happyReduce_73 action_130 (181#) = happyShift action_222 action_130 x = happyTcHack x happyReduce_75 action_131 x = happyTcHack x happyReduce_89 action_132 x = happyTcHack x happyReduce_43 action_133 x = happyTcHack x happyReduce_44 action_134 x = happyTcHack x happyReduce_45 action_135 (122#) = happyShift action_221 action_135 x = happyTcHack x happyReduce_22 action_136 x = happyTcHack x happyReduce_347 action_137 (168#) = happyShift action_55 action_137 (94#) = happyGoto action_218 action_137 (95#) = happyGoto action_219 action_137 (96#) = happyGoto action_220 action_137 x = happyTcHack x happyReduce_303 action_138 (193#) = happyShift action_69 action_138 (109#) = happyGoto action_217 action_138 (110#) = happyGoto action_34 action_138 (111#) = happyGoto action_35 action_138 x = happyTcHack x happyReduce_344 action_139 (193#) = happyShift action_69 action_139 (109#) = happyGoto action_216 action_139 (110#) = happyGoto action_34 action_139 (111#) = happyGoto action_35 action_139 x = happyTcHack x happyReduce_344 action_140 (120#) = happyShift action_148 action_140 (124#) = happyShift action_104 action_140 (146#) = happyShift action_105 action_140 (172#) = happyShift action_106 action_140 (176#) = happyShift action_86 action_140 (181#) = happyShift action_150 action_140 (66#) = happyGoto action_214 action_140 (67#) = happyGoto action_142 action_140 (68#) = happyGoto action_215 action_140 (69#) = happyGoto action_144 action_140 (70#) = happyGoto action_145 action_140 (71#) = happyGoto action_146 action_140 (114#) = happyGoto action_102 action_140 x = happyTcHack x happyFail action_141 (120#) = happyShift action_212 action_141 (168#) = happyShift action_213 action_141 x = happyTcHack x happyReduce_225 action_142 x = happyTcHack x happyReduce_228 action_143 x = happyTcHack x happyReduce_223 action_144 x = happyTcHack x happyReduce_231 action_145 x = happyTcHack x happyReduce_230 action_146 (120#) = happyShift action_148 action_146 (124#) = happyShift action_104 action_146 (146#) = happyShift action_105 action_146 (172#) = happyShift action_106 action_146 (175#) = happyShift action_211 action_146 (176#) = happyShift action_86 action_146 (193#) = happyShift action_69 action_146 (66#) = happyGoto action_209 action_146 (67#) = happyGoto action_142 action_146 (69#) = happyGoto action_144 action_146 (70#) = happyGoto action_145 action_146 (110#) = happyGoto action_210 action_146 (111#) = happyGoto action_35 action_146 (114#) = happyGoto action_102 action_146 x = happyTcHack x happyFail action_147 (193#) = happyShift action_69 action_147 (111#) = happyGoto action_136 action_147 x = happyTcHack x happyReduce_226 action_148 (120#) = happyShift action_148 action_148 (124#) = happyShift action_104 action_148 (146#) = happyShift action_105 action_148 (172#) = happyShift action_106 action_148 (175#) = happyShift action_149 action_148 (176#) = happyShift action_86 action_148 (181#) = happyShift action_150 action_148 (193#) = happyShift action_69 action_148 (64#) = happyGoto action_208 action_148 (65#) = happyGoto action_140 action_148 (66#) = happyGoto action_141 action_148 (67#) = happyGoto action_142 action_148 (68#) = happyGoto action_143 action_148 (69#) = happyGoto action_144 action_148 (70#) = happyGoto action_145 action_148 (71#) = happyGoto action_146 action_148 (110#) = happyGoto action_147 action_148 (111#) = happyGoto action_35 action_148 (114#) = happyGoto action_102 action_148 x = happyTcHack x happyFail action_149 x = happyTcHack x happyReduce_227 action_150 (128#) = happyShift action_157 action_150 (129#) = happyShift action_158 action_150 (181#) = happyShift action_150 action_150 (54#) = happyGoto action_205 action_150 (71#) = happyGoto action_206 action_150 (72#) = happyGoto action_207 action_150 x = happyTcHack x happyReduce_247 action_151 x = happyTcHack x happyReduce_19 action_152 x = happyTcHack x happyReduce_166 action_153 (1#) = happyShift action_122 action_153 (146#) = happyShift action_123 action_153 (147#) = happyShift action_124 action_153 (148#) = happyShift action_125 action_153 (149#) = happyShift action_43 action_153 (150#) = happyShift action_44 action_153 (151#) = happyShift action_45 action_153 (152#) = happyShift action_46 action_153 (153#) = happyShift action_47 action_153 (154#) = happyShift action_126 action_153 (155#) = happyShift action_127 action_153 (156#) = happyShift action_128 action_153 (157#) = happyShift action_129 action_153 (171#) = happyShift action_130 action_153 (176#) = happyShift action_131 action_153 (183#) = happyShift action_61 action_153 (184#) = happyShift action_62 action_153 (30#) = happyGoto action_204 action_153 (31#) = happyGoto action_119 action_153 (32#) = happyGoto action_120 action_153 (89#) = happyGoto action_121 action_153 (90#) = happyGoto action_29 action_153 x = happyTcHack x happyFail action_154 (146#) = happyShift action_90 action_154 (176#) = happyShift action_86 action_154 (114#) = happyGoto action_203 action_154 x = happyTcHack x happyFail action_155 (120#) = happyShift action_195 action_155 (141#) = happyShift action_196 action_155 (142#) = happyShift action_197 action_155 (170#) = happyShift action_198 action_155 (173#) = happyShift action_199 action_155 (174#) = happyShift action_200 action_155 (176#) = happyShift action_86 action_155 (180#) = happyShift action_201 action_155 (182#) = happyShift action_202 action_155 (44#) = happyGoto action_187 action_155 (45#) = happyGoto action_188 action_155 (46#) = happyGoto action_189 action_155 (47#) = happyGoto action_190 action_155 (48#) = happyGoto action_191 action_155 (49#) = happyGoto action_192 action_155 (50#) = happyGoto action_193 action_155 (114#) = happyGoto action_194 action_155 x = happyTcHack x happyFail action_156 x = happyTcHack x happyReduce_178 action_157 x = happyTcHack x happyReduce_179 action_158 x = happyTcHack x happyReduce_180 action_159 (169#) = happyShift action_186 action_159 x = happyTcHack x happyFail action_160 x = happyTcHack x happyReduce_11 action_161 x = happyTcHack x happyReduce_100 action_162 (153#) = happyShift action_185 action_162 x = happyTcHack x happyFail action_163 (153#) = happyShift action_184 action_163 x = happyTcHack x happyFail action_164 x = happyTcHack x happyReduce_17 action_165 x = happyTcHack x happyReduce_15 action_166 x = happyTcHack x happyReduce_356 action_167 x = happyTcHack x happyReduce_357 action_168 x = happyTcHack x happyReduce_14 action_169 (119#) = happyShift action_182 action_169 (186#) = happyShift action_183 action_169 x = happyTcHack x happyFail action_170 (122#) = happyShift action_181 action_170 x = happyTcHack x happyFail action_171 (146#) = happyShift action_180 action_171 (176#) = happyShift action_86 action_171 (114#) = happyGoto action_179 action_171 x = happyTcHack x happyFail action_172 x = happyTcHack x happyReduce_13 action_173 x = happyTcHack x happyReduce_6 action_174 (124#) = happyShift action_177 action_174 (130#) = happyShift action_178 action_174 x = happyTcHack x happyFail action_175 x = happyTcHack x happyReduce_10 action_176 x = happyTcHack x happyReduce_9 action_177 (168#) = happyShift action_55 action_177 (94#) = happyGoto action_391 action_177 (95#) = happyGoto action_219 action_177 (96#) = happyGoto action_220 action_177 x = happyTcHack x happyReduce_303 action_178 (168#) = happyShift action_55 action_178 (94#) = happyGoto action_390 action_178 (95#) = happyGoto action_219 action_178 (96#) = happyGoto action_220 action_178 x = happyTcHack x happyReduce_303 action_179 x = happyTcHack x happyReduce_62 action_180 x = happyTcHack x happyReduce_61 action_181 (22#) = happyGoto action_389 action_181 x = happyTcHack x happyReduce_51 action_182 (124#) = happyShift action_104 action_182 (146#) = happyShift action_105 action_182 (172#) = happyShift action_106 action_182 (176#) = happyShift action_86 action_182 (67#) = happyGoto action_388 action_182 (114#) = happyGoto action_102 action_182 x = happyTcHack x happyFail action_183 (124#) = happyShift action_387 action_183 x = happyTcHack x happyFail action_184 x = happyTcHack x happyReduce_192 action_185 x = happyTcHack x happyReduce_193 action_186 x = happyTcHack x happyReduce_177 action_187 (138#) = happyShift action_276 action_187 (166#) = happyShift action_386 action_187 x = happyTcHack x happyFail action_188 (180#) = happyShift action_384 action_188 (182#) = happyShift action_385 action_188 x = happyTcHack x happyReduce_143 action_189 (139#) = happyShift action_381 action_189 (140#) = happyShift action_382 action_189 (181#) = happyShift action_383 action_189 x = happyTcHack x happyReduce_145 action_190 x = happyTcHack x happyReduce_148 action_191 x = happyTcHack x happyReduce_152 action_192 (120#) = happyShift action_380 action_192 (173#) = happyShift action_199 action_192 (174#) = happyShift action_200 action_192 (176#) = happyShift action_86 action_192 (50#) = happyGoto action_379 action_192 (114#) = happyGoto action_194 action_192 x = happyTcHack x happyFail action_193 x = happyTcHack x happyReduce_154 action_194 x = happyTcHack x happyReduce_161 action_195 (1#) = happyShift action_369 action_195 (120#) = happyShift action_195 action_195 (141#) = happyShift action_196 action_195 (142#) = happyShift action_197 action_195 (146#) = happyShift action_370 action_195 (147#) = happyShift action_371 action_195 (148#) = happyShift action_372 action_195 (149#) = happyShift action_43 action_195 (150#) = happyShift action_44 action_195 (151#) = happyShift action_45 action_195 (152#) = happyShift action_46 action_195 (153#) = happyShift action_47 action_195 (154#) = happyShift action_373 action_195 (155#) = happyShift action_374 action_195 (156#) = happyShift action_375 action_195 (157#) = happyShift action_376 action_195 (170#) = happyShift action_198 action_195 (171#) = happyShift action_377 action_195 (173#) = happyShift action_199 action_195 (174#) = happyShift action_200 action_195 (176#) = happyShift action_378 action_195 (180#) = happyShift action_201 action_195 (182#) = happyShift action_202 action_195 (183#) = happyShift action_61 action_195 (184#) = happyShift action_62 action_195 (30#) = happyGoto action_363 action_195 (31#) = happyGoto action_364 action_195 (32#) = happyGoto action_365 action_195 (33#) = happyGoto action_366 action_195 (34#) = happyGoto action_367 action_195 (35#) = happyGoto action_265 action_195 (36#) = happyGoto action_266 action_195 (37#) = happyGoto action_267 action_195 (38#) = happyGoto action_268 action_195 (39#) = happyGoto action_269 action_195 (40#) = happyGoto action_270 action_195 (41#) = happyGoto action_271 action_195 (43#) = happyGoto action_272 action_195 (44#) = happyGoto action_273 action_195 (45#) = happyGoto action_188 action_195 (46#) = happyGoto action_189 action_195 (47#) = happyGoto action_190 action_195 (48#) = happyGoto action_191 action_195 (49#) = happyGoto action_192 action_195 (50#) = happyGoto action_193 action_195 (89#) = happyGoto action_368 action_195 (90#) = happyGoto action_29 action_195 (114#) = happyGoto action_194 action_195 x = happyTcHack x happyFail action_196 x = happyTcHack x happyReduce_159 action_197 x = happyTcHack x happyReduce_160 action_198 (120#) = happyShift action_362 action_198 x = happyTcHack x happyFail action_199 x = happyTcHack x happyReduce_162 action_200 x = happyTcHack x happyReduce_163 action_201 x = happyTcHack x happyReduce_158 action_202 x = happyTcHack x happyReduce_157 action_203 x = happyTcHack x happyReduce_46 action_204 (168#) = happyShift action_233 action_204 (176#) = happyShift action_86 action_204 (114#) = happyGoto action_361 action_204 x = happyTcHack x happyFail action_205 x = happyTcHack x happyReduce_251 action_206 x = happyTcHack x happyReduce_249 action_207 (128#) = happyShift action_157 action_207 (129#) = happyShift action_158 action_207 (181#) = happyShift action_150 action_207 (54#) = happyGoto action_359 action_207 (71#) = happyGoto action_360 action_207 x = happyTcHack x happyReduce_248 action_208 (121#) = happyShift action_358 action_208 x = happyTcHack x happyFail action_209 (120#) = happyShift action_212 action_209 (168#) = happyShift action_213 action_209 x = happyTcHack x happyReduce_238 action_210 (120#) = happyShift action_148 action_210 (124#) = happyShift action_104 action_210 (146#) = happyShift action_105 action_210 (172#) = happyShift action_106 action_210 (176#) = happyShift action_86 action_210 (193#) = happyShift action_69 action_210 (66#) = happyGoto action_357 action_210 (67#) = happyGoto action_142 action_210 (69#) = happyGoto action_144 action_210 (70#) = happyGoto action_145 action_210 (111#) = happyGoto action_136 action_210 (114#) = happyGoto action_102 action_210 x = happyTcHack x happyFail action_211 (120#) = happyShift action_148 action_211 (124#) = happyShift action_104 action_211 (146#) = happyShift action_105 action_211 (172#) = happyShift action_106 action_211 (176#) = happyShift action_86 action_211 (66#) = happyGoto action_356 action_211 (67#) = happyGoto action_142 action_211 (69#) = happyGoto action_144 action_211 (70#) = happyGoto action_145 action_211 (114#) = happyGoto action_102 action_211 x = happyTcHack x happyFail action_212 (121#) = happyShift action_354 action_212 (127#) = happyShift action_355 action_212 (168#) = happyShift action_55 action_212 (94#) = happyGoto action_351 action_212 (95#) = happyGoto action_219 action_212 (96#) = happyGoto action_220 action_212 (105#) = happyGoto action_352 action_212 (106#) = happyGoto action_353 action_212 x = happyTcHack x happyReduce_303 action_213 (120#) = happyShift action_195 action_213 (141#) = happyShift action_196 action_213 (142#) = happyShift action_197 action_213 (169#) = happyShift action_349 action_213 (170#) = happyShift action_198 action_213 (173#) = happyShift action_199 action_213 (174#) = happyShift action_200 action_213 (176#) = happyShift action_86 action_213 (180#) = happyShift action_201 action_213 (181#) = happyShift action_350 action_213 (182#) = happyShift action_202 action_213 (34#) = happyGoto action_347 action_213 (35#) = happyGoto action_265 action_213 (36#) = happyGoto action_266 action_213 (37#) = happyGoto action_267 action_213 (38#) = happyGoto action_268 action_213 (39#) = happyGoto action_269 action_213 (40#) = happyGoto action_270 action_213 (41#) = happyGoto action_271 action_213 (43#) = happyGoto action_272 action_213 (44#) = happyGoto action_273 action_213 (45#) = happyGoto action_188 action_213 (46#) = happyGoto action_189 action_213 (47#) = happyGoto action_190 action_213 (48#) = happyGoto action_191 action_213 (49#) = happyGoto action_192 action_213 (50#) = happyGoto action_348 action_213 (114#) = happyGoto action_194 action_213 x = happyTcHack x happyFail action_214 (120#) = happyShift action_212 action_214 (168#) = happyShift action_213 action_214 x = happyTcHack x happyReduce_224 action_215 x = happyTcHack x happyReduce_222 action_216 x = happyTcHack x happyReduce_301 action_217 (1#) = happyShift action_36 action_217 (128#) = happyShift action_157 action_217 (129#) = happyShift action_158 action_217 (146#) = happyShift action_40 action_217 (147#) = happyShift action_41 action_217 (148#) = happyShift action_42 action_217 (149#) = happyShift action_43 action_217 (150#) = happyShift action_44 action_217 (151#) = happyShift action_45 action_217 (152#) = happyShift action_46 action_217 (153#) = happyShift action_47 action_217 (154#) = happyShift action_48 action_217 (155#) = happyShift action_49 action_217 (156#) = happyShift action_50 action_217 (157#) = happyShift action_51 action_217 (158#) = happyShift action_52 action_217 (159#) = happyShift action_53 action_217 (163#) = happyShift action_54 action_217 (171#) = happyShift action_56 action_217 (176#) = happyShift action_57 action_217 (197#) = happyShift action_73 action_217 (31#) = happyGoto action_18 action_217 (32#) = happyGoto action_19 action_217 (52#) = happyGoto action_346 action_217 (54#) = happyGoto action_333 action_217 (55#) = happyGoto action_334 action_217 (59#) = happyGoto action_76 action_217 (60#) = happyGoto action_25 action_217 (61#) = happyGoto action_26 action_217 (86#) = happyGoto action_77 action_217 x = happyTcHack x happyFail action_218 (1#) = happyShift action_36 action_218 (128#) = happyShift action_157 action_218 (129#) = happyShift action_158 action_218 (146#) = happyShift action_40 action_218 (147#) = happyShift action_41 action_218 (148#) = happyShift action_42 action_218 (149#) = happyShift action_43 action_218 (150#) = happyShift action_44 action_218 (151#) = happyShift action_45 action_218 (152#) = happyShift action_46 action_218 (153#) = happyShift action_47 action_218 (154#) = happyShift action_48 action_218 (155#) = happyShift action_49 action_218 (156#) = happyShift action_50 action_218 (157#) = happyShift action_51 action_218 (158#) = happyShift action_52 action_218 (159#) = happyShift action_53 action_218 (163#) = happyShift action_54 action_218 (171#) = happyShift action_56 action_218 (176#) = happyShift action_57 action_218 (197#) = happyShift action_73 action_218 (31#) = happyGoto action_18 action_218 (32#) = happyGoto action_19 action_218 (52#) = happyGoto action_345 action_218 (54#) = happyGoto action_333 action_218 (55#) = happyGoto action_334 action_218 (59#) = happyGoto action_76 action_218 (60#) = happyGoto action_25 action_218 (61#) = happyGoto action_26 action_218 (86#) = happyGoto action_77 action_218 x = happyTcHack x happyFail action_219 x = happyTcHack x happyReduce_302 action_220 (168#) = happyShift action_55 action_220 (95#) = happyGoto action_344 action_220 (96#) = happyGoto action_220 action_220 x = happyTcHack x happyReduce_303 action_221 (5#) = happyGoto action_343 action_221 x = happyTcHack x happyReduce_3 action_222 x = happyTcHack x happyReduce_76 action_223 x = happyTcHack x happyReduce_78 action_224 x = happyTcHack x happyReduce_77 action_225 x = happyTcHack x happyReduce_84 action_226 x = happyTcHack x happyReduce_88 action_227 x = happyTcHack x happyReduce_83 action_228 x = happyTcHack x happyReduce_85 action_229 x = happyTcHack x happyReduce_91 action_230 (153#) = happyShift action_342 action_230 x = happyTcHack x happyFail action_231 (153#) = happyShift action_341 action_231 x = happyTcHack x happyFail action_232 (130#) = happyShift action_340 action_232 x = happyTcHack x happyFail action_233 (169#) = happyShift action_339 action_233 x = happyTcHack x happyFail action_234 x = happyTcHack x happyReduce_191 action_235 x = happyTcHack x happyReduce_189 action_236 (173#) = happyShift action_338 action_236 x = happyTcHack x happyFail action_237 x = happyTcHack x happyReduce_235 action_238 (123#) = happyShift action_337 action_238 (168#) = happyShift action_55 action_238 (74#) = happyGoto action_336 action_238 (94#) = happyGoto action_240 action_238 (95#) = happyGoto action_219 action_238 (96#) = happyGoto action_220 action_238 x = happyTcHack x happyReduce_303 action_239 (193#) = happyShift action_69 action_239 (109#) = happyGoto action_335 action_239 (110#) = happyGoto action_34 action_239 (111#) = happyGoto action_35 action_239 x = happyTcHack x happyReduce_344 action_240 (1#) = happyShift action_36 action_240 (128#) = happyShift action_157 action_240 (129#) = happyShift action_158 action_240 (146#) = happyShift action_40 action_240 (147#) = happyShift action_41 action_240 (148#) = happyShift action_42 action_240 (149#) = happyShift action_43 action_240 (150#) = happyShift action_44 action_240 (151#) = happyShift action_45 action_240 (152#) = happyShift action_46 action_240 (153#) = happyShift action_47 action_240 (154#) = happyShift action_48 action_240 (155#) = happyShift action_49 action_240 (156#) = happyShift action_50 action_240 (157#) = happyShift action_51 action_240 (158#) = happyShift action_52 action_240 (159#) = happyShift action_53 action_240 (163#) = happyShift action_54 action_240 (171#) = happyShift action_56 action_240 (176#) = happyShift action_57 action_240 (197#) = happyShift action_73 action_240 (31#) = happyGoto action_18 action_240 (32#) = happyGoto action_19 action_240 (52#) = happyGoto action_332 action_240 (54#) = happyGoto action_333 action_240 (55#) = happyGoto action_334 action_240 (59#) = happyGoto action_76 action_240 (60#) = happyGoto action_25 action_240 (61#) = happyGoto action_26 action_240 (86#) = happyGoto action_77 action_240 x = happyTcHack x happyFail action_241 (173#) = happyShift action_331 action_241 x = happyTcHack x happyFail action_242 (168#) = happyShift action_55 action_242 (73#) = happyGoto action_330 action_242 (74#) = happyGoto action_239 action_242 (94#) = happyGoto action_240 action_242 (95#) = happyGoto action_219 action_242 (96#) = happyGoto action_220 action_242 x = happyTcHack x happyReduce_303 action_243 x = happyTcHack x happyReduce_217 action_244 (161#) = happyShift action_327 action_244 (162#) = happyShift action_328 action_244 (168#) = happyShift action_329 action_244 (62#) = happyGoto action_321 action_244 (73#) = happyGoto action_322 action_244 (74#) = happyGoto action_239 action_244 (77#) = happyGoto action_323 action_244 (78#) = happyGoto action_324 action_244 (81#) = happyGoto action_325 action_244 (82#) = happyGoto action_326 action_244 (94#) = happyGoto action_240 action_244 (95#) = happyGoto action_219 action_244 (96#) = happyGoto action_220 action_244 x = happyTcHack x happyReduce_303 action_245 (120#) = happyShift action_320 action_245 x = happyTcHack x happyFail action_246 (125#) = happyShift action_319 action_246 (116#) = happyGoto action_318 action_246 x = happyTcHack x happyReduce_358 action_247 x = happyTcHack x happyReduce_288 action_248 (176#) = happyShift action_86 action_248 (114#) = happyGoto action_317 action_248 x = happyTcHack x happyFail action_249 (130#) = happyShift action_316 action_249 x = happyTcHack x happyReduce_290 action_250 (168#) = happyShift action_55 action_250 (176#) = happyShift action_86 action_250 (87#) = happyGoto action_315 action_250 (88#) = happyGoto action_247 action_250 (96#) = happyGoto action_248 action_250 (114#) = happyGoto action_249 action_250 x = happyTcHack x happyFail action_251 x = happyTcHack x happyReduce_309 action_252 (120#) = happyShift action_195 action_252 (122#) = happyShift action_310 action_252 (141#) = happyShift action_196 action_252 (142#) = happyShift action_197 action_252 (146#) = happyShift action_311 action_252 (154#) = happyShift action_312 action_252 (155#) = happyShift action_313 action_252 (170#) = happyShift action_198 action_252 (173#) = happyShift action_199 action_252 (174#) = happyShift action_200 action_252 (176#) = happyShift action_86 action_252 (180#) = happyShift action_201 action_252 (181#) = happyShift action_314 action_252 (182#) = happyShift action_202 action_252 (34#) = happyGoto action_307 action_252 (35#) = happyGoto action_265 action_252 (36#) = happyGoto action_266 action_252 (37#) = happyGoto action_267 action_252 (38#) = happyGoto action_268 action_252 (39#) = happyGoto action_269 action_252 (40#) = happyGoto action_270 action_252 (41#) = happyGoto action_271 action_252 (43#) = happyGoto action_272 action_252 (44#) = happyGoto action_273 action_252 (45#) = happyGoto action_188 action_252 (46#) = happyGoto action_189 action_252 (47#) = happyGoto action_190 action_252 (48#) = happyGoto action_191 action_252 (49#) = happyGoto action_192 action_252 (50#) = happyGoto action_193 action_252 (102#) = happyGoto action_308 action_252 (103#) = happyGoto action_309 action_252 (114#) = happyGoto action_194 action_252 x = happyTcHack x happyReduce_321 action_253 (169#) = happyShift action_306 action_253 x = happyTcHack x happyFail action_254 (172#) = happyShift action_95 action_254 (176#) = happyShift action_86 action_254 (183#) = happyShift action_96 action_254 (98#) = happyGoto action_305 action_254 (114#) = happyGoto action_93 action_254 x = happyTcHack x happyReduce_359 action_255 x = happyTcHack x happyReduce_12 action_256 (168#) = happyShift action_303 action_256 (14#) = happyGoto action_304 action_256 (15#) = happyGoto action_301 action_256 (16#) = happyGoto action_302 action_256 x = happyTcHack x happyReduce_39 action_257 (168#) = happyShift action_303 action_257 (14#) = happyGoto action_300 action_257 (15#) = happyGoto action_301 action_257 (16#) = happyGoto action_302 action_257 x = happyTcHack x happyReduce_39 action_258 (5#) = happyGoto action_299 action_258 x = happyTcHack x happyReduce_3 action_259 (121#) = happyShift action_298 action_259 x = happyTcHack x happyFail action_260 (121#) = happyShift action_297 action_260 x = happyTcHack x happyFail action_261 (121#) = happyShift action_296 action_261 x = happyTcHack x happyFail action_262 (146#) = happyShift action_293 action_262 (175#) = happyShift action_294 action_262 (176#) = happyShift action_295 action_262 (112#) = happyGoto action_291 action_262 (113#) = happyGoto action_292 action_262 x = happyTcHack x happyFail action_263 (174#) = happyShift action_80 action_263 (29#) = happyGoto action_290 action_263 x = happyTcHack x happyFail action_264 x = happyTcHack x happyReduce_68 action_265 (143#) = happyShift action_289 action_265 x = happyTcHack x happyReduce_121 action_266 (134#) = happyShift action_288 action_266 x = happyTcHack x happyReduce_122 action_267 (137#) = happyShift action_287 action_267 x = happyTcHack x happyReduce_124 action_268 (133#) = happyShift action_286 action_268 x = happyTcHack x happyReduce_126 action_269 (135#) = happyShift action_285 action_269 x = happyTcHack x happyReduce_128 action_270 (136#) = happyShift action_284 action_270 x = happyTcHack x happyReduce_130 action_271 (131#) = happyShift action_282 action_271 (132#) = happyShift action_283 action_271 (42#) = happyGoto action_281 action_271 x = happyTcHack x happyReduce_132 action_272 (164#) = happyShift action_277 action_272 (165#) = happyShift action_278 action_272 (166#) = happyShift action_279 action_272 (167#) = happyShift action_280 action_272 x = happyTcHack x happyReduce_134 action_273 (138#) = happyShift action_276 action_273 x = happyTcHack x happyReduce_138 action_274 x = happyTcHack x happyReduce_197 action_275 x = happyTcHack x happyReduce_207 action_276 (120#) = happyShift action_195 action_276 (141#) = happyShift action_196 action_276 (142#) = happyShift action_197 action_276 (170#) = happyShift action_198 action_276 (173#) = happyShift action_199 action_276 (174#) = happyShift action_200 action_276 (176#) = happyShift action_86 action_276 (180#) = happyShift action_201 action_276 (182#) = happyShift action_202 action_276 (45#) = happyGoto action_492 action_276 (46#) = happyGoto action_189 action_276 (47#) = happyGoto action_190 action_276 (48#) = happyGoto action_191 action_276 (49#) = happyGoto action_192 action_276 (50#) = happyGoto action_193 action_276 (114#) = happyGoto action_194 action_276 x = happyTcHack x happyFail action_277 (120#) = happyShift action_195 action_277 (141#) = happyShift action_196 action_277 (142#) = happyShift action_197 action_277 (170#) = happyShift action_198 action_277 (173#) = happyShift action_199 action_277 (174#) = happyShift action_200 action_277 (176#) = happyShift action_86 action_277 (180#) = happyShift action_201 action_277 (182#) = happyShift action_202 action_277 (44#) = happyGoto action_491 action_277 (45#) = happyGoto action_188 action_277 (46#) = happyGoto action_189 action_277 (47#) = happyGoto action_190 action_277 (48#) = happyGoto action_191 action_277 (49#) = happyGoto action_192 action_277 (50#) = happyGoto action_193 action_277 (114#) = happyGoto action_194 action_277 x = happyTcHack x happyFail action_278 (120#) = happyShift action_195 action_278 (141#) = happyShift action_196 action_278 (142#) = happyShift action_197 action_278 (170#) = happyShift action_198 action_278 (173#) = happyShift action_199 action_278 (174#) = happyShift action_200 action_278 (176#) = happyShift action_86 action_278 (180#) = happyShift action_201 action_278 (182#) = happyShift action_202 action_278 (44#) = happyGoto action_490 action_278 (45#) = happyGoto action_188 action_278 (46#) = happyGoto action_189 action_278 (47#) = happyGoto action_190 action_278 (48#) = happyGoto action_191 action_278 (49#) = happyGoto action_192 action_278 (50#) = happyGoto action_193 action_278 (114#) = happyGoto action_194 action_278 x = happyTcHack x happyFail action_279 (120#) = happyShift action_195 action_279 (141#) = happyShift action_196 action_279 (142#) = happyShift action_197 action_279 (170#) = happyShift action_198 action_279 (173#) = happyShift action_199 action_279 (174#) = happyShift action_200 action_279 (176#) = happyShift action_86 action_279 (180#) = happyShift action_201 action_279 (182#) = happyShift action_202 action_279 (44#) = happyGoto action_489 action_279 (45#) = happyGoto action_188 action_279 (46#) = happyGoto action_189 action_279 (47#) = happyGoto action_190 action_279 (48#) = happyGoto action_191 action_279 (49#) = happyGoto action_192 action_279 (50#) = happyGoto action_193 action_279 (114#) = happyGoto action_194 action_279 x = happyTcHack x happyFail action_280 (120#) = happyShift action_195 action_280 (141#) = happyShift action_196 action_280 (142#) = happyShift action_197 action_280 (170#) = happyShift action_198 action_280 (173#) = happyShift action_199 action_280 (174#) = happyShift action_200 action_280 (176#) = happyShift action_86 action_280 (180#) = happyShift action_201 action_280 (182#) = happyShift action_202 action_280 (44#) = happyGoto action_488 action_280 (45#) = happyGoto action_188 action_280 (46#) = happyGoto action_189 action_280 (47#) = happyGoto action_190 action_280 (48#) = happyGoto action_191 action_280 (49#) = happyGoto action_192 action_280 (50#) = happyGoto action_193 action_280 (114#) = happyGoto action_194 action_280 x = happyTcHack x happyFail action_281 (120#) = happyShift action_195 action_281 (141#) = happyShift action_196 action_281 (142#) = happyShift action_197 action_281 (170#) = happyShift action_198 action_281 (173#) = happyShift action_199 action_281 (174#) = happyShift action_200 action_281 (176#) = happyShift action_86 action_281 (180#) = happyShift action_201 action_281 (182#) = happyShift action_202 action_281 (43#) = happyGoto action_487 action_281 (44#) = happyGoto action_273 action_281 (45#) = happyGoto action_188 action_281 (46#) = happyGoto action_189 action_281 (47#) = happyGoto action_190 action_281 (48#) = happyGoto action_191 action_281 (49#) = happyGoto action_192 action_281 (50#) = happyGoto action_193 action_281 (114#) = happyGoto action_194 action_281 x = happyTcHack x happyFail action_282 x = happyTcHack x happyReduce_136 action_283 x = happyTcHack x happyReduce_137 action_284 (120#) = happyShift action_195 action_284 (141#) = happyShift action_196 action_284 (142#) = happyShift action_197 action_284 (170#) = happyShift action_198 action_284 (173#) = happyShift action_199 action_284 (174#) = happyShift action_200 action_284 (176#) = happyShift action_86 action_284 (180#) = happyShift action_201 action_284 (182#) = happyShift action_202 action_284 (41#) = happyGoto action_486 action_284 (43#) = happyGoto action_272 action_284 (44#) = happyGoto action_273 action_284 (45#) = happyGoto action_188 action_284 (46#) = happyGoto action_189 action_284 (47#) = happyGoto action_190 action_284 (48#) = happyGoto action_191 action_284 (49#) = happyGoto action_192 action_284 (50#) = happyGoto action_193 action_284 (114#) = happyGoto action_194 action_284 x = happyTcHack x happyFail action_285 (120#) = happyShift action_195 action_285 (141#) = happyShift action_196 action_285 (142#) = happyShift action_197 action_285 (170#) = happyShift action_198 action_285 (173#) = happyShift action_199 action_285 (174#) = happyShift action_200 action_285 (176#) = happyShift action_86 action_285 (180#) = happyShift action_201 action_285 (182#) = happyShift action_202 action_285 (40#) = happyGoto action_485 action_285 (41#) = happyGoto action_271 action_285 (43#) = happyGoto action_272 action_285 (44#) = happyGoto action_273 action_285 (45#) = happyGoto action_188 action_285 (46#) = happyGoto action_189 action_285 (47#) = happyGoto action_190 action_285 (48#) = happyGoto action_191 action_285 (49#) = happyGoto action_192 action_285 (50#) = happyGoto action_193 action_285 (114#) = happyGoto action_194 action_285 x = happyTcHack x happyFail action_286 (120#) = happyShift action_195 action_286 (141#) = happyShift action_196 action_286 (142#) = happyShift action_197 action_286 (170#) = happyShift action_198 action_286 (173#) = happyShift action_199 action_286 (174#) = happyShift action_200 action_286 (176#) = happyShift action_86 action_286 (180#) = happyShift action_201 action_286 (182#) = happyShift action_202 action_286 (39#) = happyGoto action_484 action_286 (40#) = happyGoto action_270 action_286 (41#) = happyGoto action_271 action_286 (43#) = happyGoto action_272 action_286 (44#) = happyGoto action_273 action_286 (45#) = happyGoto action_188 action_286 (46#) = happyGoto action_189 action_286 (47#) = happyGoto action_190 action_286 (48#) = happyGoto action_191 action_286 (49#) = happyGoto action_192 action_286 (50#) = happyGoto action_193 action_286 (114#) = happyGoto action_194 action_286 x = happyTcHack x happyFail action_287 (120#) = happyShift action_195 action_287 (141#) = happyShift action_196 action_287 (142#) = happyShift action_197 action_287 (170#) = happyShift action_198 action_287 (173#) = happyShift action_199 action_287 (174#) = happyShift action_200 action_287 (176#) = happyShift action_86 action_287 (180#) = happyShift action_201 action_287 (182#) = happyShift action_202 action_287 (38#) = happyGoto action_483 action_287 (39#) = happyGoto action_269 action_287 (40#) = happyGoto action_270 action_287 (41#) = happyGoto action_271 action_287 (43#) = happyGoto action_272 action_287 (44#) = happyGoto action_273 action_287 (45#) = happyGoto action_188 action_287 (46#) = happyGoto action_189 action_287 (47#) = happyGoto action_190 action_287 (48#) = happyGoto action_191 action_287 (49#) = happyGoto action_192 action_287 (50#) = happyGoto action_193 action_287 (114#) = happyGoto action_194 action_287 x = happyTcHack x happyFail action_288 (120#) = happyShift action_195 action_288 (141#) = happyShift action_196 action_288 (142#) = happyShift action_197 action_288 (170#) = happyShift action_198 action_288 (173#) = happyShift action_199 action_288 (174#) = happyShift action_200 action_288 (176#) = happyShift action_86 action_288 (180#) = happyShift action_201 action_288 (182#) = happyShift action_202 action_288 (37#) = happyGoto action_482 action_288 (38#) = happyGoto action_268 action_288 (39#) = happyGoto action_269 action_288 (40#) = happyGoto action_270 action_288 (41#) = happyGoto action_271 action_288 (43#) = happyGoto action_272 action_288 (44#) = happyGoto action_273 action_288 (45#) = happyGoto action_188 action_288 (46#) = happyGoto action_189 action_288 (47#) = happyGoto action_190 action_288 (48#) = happyGoto action_191 action_288 (49#) = happyGoto action_192 action_288 (50#) = happyGoto action_193 action_288 (114#) = happyGoto action_194 action_288 x = happyTcHack x happyFail action_289 (120#) = happyShift action_195 action_289 (141#) = happyShift action_196 action_289 (142#) = happyShift action_197 action_289 (170#) = happyShift action_198 action_289 (173#) = happyShift action_199 action_289 (174#) = happyShift action_200 action_289 (176#) = happyShift action_86 action_289 (180#) = happyShift action_201 action_289 (182#) = happyShift action_202 action_289 (34#) = happyGoto action_481 action_289 (35#) = happyGoto action_265 action_289 (36#) = happyGoto action_266 action_289 (37#) = happyGoto action_267 action_289 (38#) = happyGoto action_268 action_289 (39#) = happyGoto action_269 action_289 (40#) = happyGoto action_270 action_289 (41#) = happyGoto action_271 action_289 (43#) = happyGoto action_272 action_289 (44#) = happyGoto action_273 action_289 (45#) = happyGoto action_188 action_289 (46#) = happyGoto action_189 action_289 (47#) = happyGoto action_190 action_289 (48#) = happyGoto action_191 action_289 (49#) = happyGoto action_192 action_289 (50#) = happyGoto action_193 action_289 (114#) = happyGoto action_194 action_289 x = happyTcHack x happyFail action_290 x = happyTcHack x happyReduce_70 action_291 (121#) = happyShift action_480 action_291 x = happyTcHack x happyFail action_292 (120#) = happyShift action_479 action_292 x = happyTcHack x happyReduce_349 action_293 x = happyTcHack x happyReduce_354 action_294 x = happyTcHack x happyReduce_350 action_295 x = happyTcHack x happyReduce_353 action_296 x = happyTcHack x happyReduce_64 action_297 x = happyTcHack x happyReduce_49 action_298 x = happyTcHack x happyReduce_48 action_299 (1#) = happyShift action_36 action_299 (118#) = happyShift action_37 action_299 (119#) = happyShift action_38 action_299 (123#) = happyShift action_478 action_299 (128#) = happyShift action_39 action_299 (144#) = happyReduce_344 action_299 (145#) = happyReduce_344 action_299 (146#) = happyShift action_40 action_299 (147#) = happyShift action_41 action_299 (148#) = happyShift action_42 action_299 (149#) = happyShift action_43 action_299 (150#) = happyShift action_44 action_299 (151#) = happyShift action_45 action_299 (152#) = happyShift action_46 action_299 (153#) = happyShift action_47 action_299 (154#) = happyShift action_48 action_299 (155#) = happyShift action_49 action_299 (156#) = happyShift action_50 action_299 (157#) = happyShift action_51 action_299 (158#) = happyShift action_52 action_299 (159#) = happyShift action_53 action_299 (163#) = happyShift action_54 action_299 (168#) = happyShift action_55 action_299 (171#) = happyShift action_56 action_299 (176#) = happyShift action_57 action_299 (177#) = happyShift action_58 action_299 (178#) = happyShift action_59 action_299 (179#) = happyShift action_60 action_299 (183#) = happyShift action_61 action_299 (184#) = happyShift action_62 action_299 (187#) = happyShift action_63 action_299 (188#) = happyShift action_64 action_299 (189#) = happyShift action_65 action_299 (190#) = happyShift action_66 action_299 (191#) = happyShift action_67 action_299 (192#) = happyShift action_68 action_299 (193#) = happyShift action_69 action_299 (194#) = happyShift action_70 action_299 (195#) = happyShift action_71 action_299 (196#) = happyShift action_72 action_299 (197#) = happyShift action_73 action_299 (9#) = happyGoto action_6 action_299 (10#) = happyGoto action_7 action_299 (11#) = happyGoto action_8 action_299 (12#) = happyGoto action_9 action_299 (17#) = happyGoto action_10 action_299 (18#) = happyGoto action_11 action_299 (19#) = happyGoto action_12 action_299 (20#) = happyGoto action_13 action_299 (21#) = happyGoto action_14 action_299 (26#) = happyGoto action_15 action_299 (27#) = happyGoto action_16 action_299 (28#) = happyGoto action_17 action_299 (31#) = happyGoto action_18 action_299 (32#) = happyGoto action_19 action_299 (51#) = happyGoto action_20 action_299 (53#) = happyGoto action_21 action_299 (55#) = happyGoto action_22 action_299 (58#) = happyGoto action_23 action_299 (59#) = happyGoto action_24 action_299 (60#) = happyGoto action_25 action_299 (61#) = happyGoto action_26 action_299 (86#) = happyGoto action_27 action_299 (89#) = happyGoto action_28 action_299 (90#) = happyGoto action_29 action_299 (93#) = happyGoto action_30 action_299 (96#) = happyGoto action_31 action_299 (104#) = happyGoto action_32 action_299 (109#) = happyGoto action_33 action_299 (110#) = happyGoto action_34 action_299 (111#) = happyGoto action_35 action_299 x = happyTcHack x happyFail action_300 (117#) = happyShift action_477 action_300 x = happyTcHack x happyFail action_301 x = happyTcHack x happyReduce_33 action_302 (119#) = happyShift action_475 action_302 (177#) = happyShift action_476 action_302 x = happyTcHack x happyFail action_303 (162#) = happyShift action_474 action_303 (176#) = happyShift action_86 action_303 (99#) = happyGoto action_471 action_303 (100#) = happyGoto action_472 action_303 (114#) = happyGoto action_473 action_303 x = happyTcHack x happyFail action_304 (117#) = happyShift action_470 action_304 x = happyTcHack x happyFail action_305 x = happyTcHack x happyReduce_308 action_306 x = happyTcHack x happyReduce_306 action_307 x = happyTcHack x happyReduce_320 action_308 (121#) = happyShift action_468 action_308 (125#) = happyShift action_469 action_308 x = happyTcHack x happyFail action_309 x = happyTcHack x happyReduce_318 action_310 (173#) = happyShift action_467 action_310 x = happyTcHack x happyFail action_311 x = happyTcHack x happyReduce_322 action_312 (146#) = happyShift action_466 action_312 x = happyTcHack x happyFail action_313 (146#) = happyShift action_465 action_313 x = happyTcHack x happyFail action_314 (120#) = happyShift action_195 action_314 (122#) = happyShift action_310 action_314 (141#) = happyShift action_196 action_314 (142#) = happyShift action_197 action_314 (146#) = happyShift action_311 action_314 (154#) = happyShift action_312 action_314 (155#) = happyShift action_313 action_314 (170#) = happyShift action_198 action_314 (173#) = happyShift action_199 action_314 (174#) = happyShift action_200 action_314 (176#) = happyShift action_86 action_314 (180#) = happyShift action_201 action_314 (181#) = happyShift action_314 action_314 (182#) = happyShift action_202 action_314 (34#) = happyGoto action_307 action_314 (35#) = happyGoto action_265 action_314 (36#) = happyGoto action_266 action_314 (37#) = happyGoto action_267 action_314 (38#) = happyGoto action_268 action_314 (39#) = happyGoto action_269 action_314 (40#) = happyGoto action_270 action_314 (41#) = happyGoto action_271 action_314 (43#) = happyGoto action_272 action_314 (44#) = happyGoto action_273 action_314 (45#) = happyGoto action_188 action_314 (46#) = happyGoto action_189 action_314 (47#) = happyGoto action_190 action_314 (48#) = happyGoto action_191 action_314 (49#) = happyGoto action_192 action_314 (50#) = happyGoto action_193 action_314 (103#) = happyGoto action_464 action_314 (114#) = happyGoto action_194 action_314 x = happyTcHack x happyReduce_321 action_315 (125#) = happyShift action_319 action_315 (116#) = happyGoto action_463 action_315 x = happyTcHack x happyReduce_358 action_316 (120#) = happyShift action_195 action_316 (141#) = happyShift action_196 action_316 (142#) = happyShift action_197 action_316 (170#) = happyShift action_198 action_316 (173#) = happyShift action_199 action_316 (174#) = happyShift action_200 action_316 (176#) = happyShift action_86 action_316 (180#) = happyShift action_201 action_316 (182#) = happyShift action_202 action_316 (34#) = happyGoto action_462 action_316 (35#) = happyGoto action_265 action_316 (36#) = happyGoto action_266 action_316 (37#) = happyGoto action_267 action_316 (38#) = happyGoto action_268 action_316 (39#) = happyGoto action_269 action_316 (40#) = happyGoto action_270 action_316 (41#) = happyGoto action_271 action_316 (43#) = happyGoto action_272 action_316 (44#) = happyGoto action_273 action_316 (45#) = happyGoto action_188 action_316 (46#) = happyGoto action_189 action_316 (47#) = happyGoto action_190 action_316 (48#) = happyGoto action_191 action_316 (49#) = happyGoto action_192 action_316 (50#) = happyGoto action_193 action_316 (114#) = happyGoto action_194 action_316 x = happyTcHack x happyFail action_317 (130#) = happyShift action_461 action_317 x = happyTcHack x happyReduce_291 action_318 (123#) = happyShift action_460 action_318 x = happyTcHack x happyFail action_319 (168#) = happyShift action_55 action_319 (176#) = happyShift action_86 action_319 (88#) = happyGoto action_459 action_319 (96#) = happyGoto action_248 action_319 (114#) = happyGoto action_249 action_319 x = happyTcHack x happyReduce_359 action_320 (146#) = happyShift action_456 action_320 (149#) = happyShift action_43 action_320 (150#) = happyShift action_44 action_320 (151#) = happyShift action_45 action_320 (152#) = happyShift action_46 action_320 (153#) = happyShift action_47 action_320 (156#) = happyShift action_457 action_320 (158#) = happyShift action_52 action_320 (159#) = happyShift action_53 action_320 (163#) = happyShift action_54 action_320 (176#) = happyShift action_458 action_320 (31#) = happyGoto action_107 action_320 (32#) = happyGoto action_452 action_320 (59#) = happyGoto action_453 action_320 (60#) = happyGoto action_25 action_320 (61#) = happyGoto action_26 action_320 (76#) = happyGoto action_454 action_320 (86#) = happyGoto action_455 action_320 x = happyTcHack x happyFail action_321 (123#) = happyShift action_451 action_321 x = happyTcHack x happyFail action_322 (123#) = happyReduce_219 action_322 (168#) = happyShift action_55 action_322 (74#) = happyGoto action_336 action_322 (94#) = happyGoto action_240 action_322 (95#) = happyGoto action_219 action_322 (96#) = happyGoto action_220 action_322 x = happyTcHack x happyReduce_303 action_323 (161#) = happyShift action_327 action_323 (162#) = happyShift action_328 action_323 (168#) = happyShift action_450 action_323 (78#) = happyGoto action_449 action_323 (81#) = happyGoto action_325 action_323 (82#) = happyGoto action_326 action_323 x = happyTcHack x happyReduce_218 action_324 (117#) = happyShift action_448 action_324 x = happyTcHack x happyFail action_325 (117#) = happyReduce_272 action_325 (161#) = happyShift action_327 action_325 (162#) = happyShift action_328 action_325 (168#) = happyShift action_55 action_325 (80#) = happyGoto action_445 action_325 (82#) = happyGoto action_446 action_325 (94#) = happyGoto action_447 action_325 (95#) = happyGoto action_219 action_325 (96#) = happyGoto action_220 action_325 x = happyTcHack x happyReduce_303 action_326 x = happyTcHack x happyReduce_275 action_327 (120#) = happyShift action_195 action_327 (141#) = happyShift action_196 action_327 (142#) = happyShift action_197 action_327 (170#) = happyShift action_198 action_327 (173#) = happyShift action_199 action_327 (174#) = happyShift action_200 action_327 (176#) = happyShift action_86 action_327 (180#) = happyShift action_201 action_327 (182#) = happyShift action_202 action_327 (34#) = happyGoto action_444 action_327 (35#) = happyGoto action_265 action_327 (36#) = happyGoto action_266 action_327 (37#) = happyGoto action_267 action_327 (38#) = happyGoto action_268 action_327 (39#) = happyGoto action_269 action_327 (40#) = happyGoto action_270 action_327 (41#) = happyGoto action_271 action_327 (43#) = happyGoto action_272 action_327 (44#) = happyGoto action_273 action_327 (45#) = happyGoto action_188 action_327 (46#) = happyGoto action_189 action_327 (47#) = happyGoto action_190 action_327 (48#) = happyGoto action_191 action_327 (49#) = happyGoto action_192 action_327 (50#) = happyGoto action_193 action_327 (114#) = happyGoto action_194 action_327 x = happyTcHack x happyFail action_328 (124#) = happyShift action_443 action_328 x = happyTcHack x happyFail action_329 (161#) = happyShift action_441 action_329 (162#) = happyShift action_442 action_329 (169#) = happyShift action_94 action_329 (172#) = happyShift action_95 action_329 (176#) = happyShift action_86 action_329 (183#) = happyShift action_96 action_329 (83#) = happyGoto action_440 action_329 (97#) = happyGoto action_91 action_329 (98#) = happyGoto action_92 action_329 (114#) = happyGoto action_93 action_329 x = happyTcHack x happyFail action_330 (123#) = happyShift action_439 action_330 (168#) = happyShift action_55 action_330 (74#) = happyGoto action_336 action_330 (94#) = happyGoto action_240 action_330 (95#) = happyGoto action_219 action_330 (96#) = happyGoto action_220 action_330 x = happyTcHack x happyReduce_303 action_331 x = happyTcHack x happyReduce_233 action_332 (120#) = happyShift action_148 action_332 (124#) = happyShift action_104 action_332 (146#) = happyShift action_105 action_332 (168#) = happyShift action_428 action_332 (172#) = happyShift action_106 action_332 (175#) = happyShift action_149 action_332 (176#) = happyShift action_86 action_332 (181#) = happyShift action_150 action_332 (193#) = happyShift action_69 action_332 (63#) = happyGoto action_438 action_332 (64#) = happyGoto action_427 action_332 (65#) = happyGoto action_140 action_332 (66#) = happyGoto action_141 action_332 (67#) = happyGoto action_142 action_332 (68#) = happyGoto action_143 action_332 (69#) = happyGoto action_144 action_332 (70#) = happyGoto action_145 action_332 (71#) = happyGoto action_146 action_332 (110#) = happyGoto action_147 action_332 (111#) = happyGoto action_35 action_332 (114#) = happyGoto action_102 action_332 x = happyTcHack x happyReduce_256 action_333 (1#) = happyShift action_36 action_333 (128#) = happyShift action_157 action_333 (129#) = happyShift action_158 action_333 (146#) = happyShift action_40 action_333 (147#) = happyShift action_41 action_333 (148#) = happyShift action_42 action_333 (149#) = happyShift action_43 action_333 (150#) = happyShift action_44 action_333 (151#) = happyShift action_45 action_333 (152#) = happyShift action_46 action_333 (153#) = happyShift action_47 action_333 (154#) = happyShift action_48 action_333 (155#) = happyShift action_49 action_333 (156#) = happyShift action_50 action_333 (157#) = happyShift action_51 action_333 (158#) = happyShift action_52 action_333 (159#) = happyShift action_53 action_333 (163#) = happyShift action_54 action_333 (171#) = happyShift action_56 action_333 (176#) = happyShift action_57 action_333 (197#) = happyShift action_73 action_333 (31#) = happyGoto action_18 action_333 (32#) = happyGoto action_19 action_333 (52#) = happyGoto action_437 action_333 (54#) = happyGoto action_333 action_333 (55#) = happyGoto action_334 action_333 (59#) = happyGoto action_76 action_333 (60#) = happyGoto action_25 action_333 (61#) = happyGoto action_26 action_333 (86#) = happyGoto action_77 action_333 x = happyTcHack x happyFail action_334 (128#) = happyShift action_157 action_334 (129#) = happyShift action_158 action_334 (54#) = happyGoto action_436 action_334 x = happyTcHack x happyReduce_171 action_335 (117#) = happyShift action_435 action_335 x = happyTcHack x happyFail action_336 (193#) = happyShift action_69 action_336 (109#) = happyGoto action_434 action_336 (110#) = happyGoto action_34 action_336 (111#) = happyGoto action_35 action_336 x = happyTcHack x happyReduce_344 action_337 (193#) = happyShift action_69 action_337 (109#) = happyGoto action_433 action_337 (110#) = happyGoto action_34 action_337 (111#) = happyGoto action_35 action_337 x = happyTcHack x happyReduce_344 action_338 x = happyTcHack x happyReduce_234 action_339 x = happyTcHack x happyReduce_80 action_340 (120#) = happyShift action_195 action_340 (141#) = happyShift action_196 action_340 (142#) = happyShift action_197 action_340 (170#) = happyShift action_198 action_340 (173#) = happyShift action_199 action_340 (174#) = happyShift action_200 action_340 (176#) = happyShift action_86 action_340 (180#) = happyShift action_201 action_340 (182#) = happyShift action_202 action_340 (34#) = happyGoto action_432 action_340 (35#) = happyGoto action_265 action_340 (36#) = happyGoto action_266 action_340 (37#) = happyGoto action_267 action_340 (38#) = happyGoto action_268 action_340 (39#) = happyGoto action_269 action_340 (40#) = happyGoto action_270 action_340 (41#) = happyGoto action_271 action_340 (43#) = happyGoto action_272 action_340 (44#) = happyGoto action_273 action_340 (45#) = happyGoto action_188 action_340 (46#) = happyGoto action_189 action_340 (47#) = happyGoto action_190 action_340 (48#) = happyGoto action_191 action_340 (49#) = happyGoto action_192 action_340 (50#) = happyGoto action_193 action_340 (114#) = happyGoto action_194 action_340 x = happyTcHack x happyFail action_341 x = happyTcHack x happyReduce_86 action_342 x = happyTcHack x happyReduce_87 action_343 (1#) = happyShift action_431 action_343 (117#) = happyShift action_167 action_343 (118#) = happyShift action_37 action_343 (119#) = happyShift action_38 action_343 (128#) = happyShift action_39 action_343 (144#) = happyReduce_344 action_343 (145#) = happyReduce_344 action_343 (146#) = happyShift action_40 action_343 (147#) = happyShift action_41 action_343 (148#) = happyShift action_42 action_343 (149#) = happyShift action_43 action_343 (150#) = happyShift action_44 action_343 (151#) = happyShift action_45 action_343 (152#) = happyShift action_46 action_343 (153#) = happyShift action_47 action_343 (154#) = happyShift action_48 action_343 (155#) = happyShift action_49 action_343 (156#) = happyShift action_50 action_343 (157#) = happyShift action_51 action_343 (158#) = happyShift action_52 action_343 (159#) = happyShift action_53 action_343 (163#) = happyShift action_54 action_343 (168#) = happyShift action_55 action_343 (171#) = happyShift action_56 action_343 (176#) = happyShift action_57 action_343 (177#) = happyShift action_58 action_343 (178#) = happyShift action_59 action_343 (179#) = happyShift action_60 action_343 (183#) = happyShift action_61 action_343 (184#) = happyShift action_62 action_343 (187#) = happyShift action_63 action_343 (188#) = happyShift action_64 action_343 (189#) = happyShift action_65 action_343 (190#) = happyShift action_66 action_343 (191#) = happyShift action_67 action_343 (192#) = happyShift action_68 action_343 (193#) = happyShift action_69 action_343 (194#) = happyShift action_70 action_343 (195#) = happyShift action_71 action_343 (196#) = happyShift action_72 action_343 (197#) = happyShift action_73 action_343 (9#) = happyGoto action_6 action_343 (10#) = happyGoto action_7 action_343 (11#) = happyGoto action_8 action_343 (12#) = happyGoto action_9 action_343 (17#) = happyGoto action_10 action_343 (18#) = happyGoto action_11 action_343 (19#) = happyGoto action_12 action_343 (20#) = happyGoto action_13 action_343 (21#) = happyGoto action_14 action_343 (26#) = happyGoto action_15 action_343 (27#) = happyGoto action_16 action_343 (28#) = happyGoto action_17 action_343 (31#) = happyGoto action_18 action_343 (32#) = happyGoto action_19 action_343 (51#) = happyGoto action_20 action_343 (53#) = happyGoto action_21 action_343 (55#) = happyGoto action_22 action_343 (58#) = happyGoto action_23 action_343 (59#) = happyGoto action_24 action_343 (60#) = happyGoto action_25 action_343 (61#) = happyGoto action_26 action_343 (86#) = happyGoto action_27 action_343 (89#) = happyGoto action_28 action_343 (90#) = happyGoto action_29 action_343 (93#) = happyGoto action_30 action_343 (96#) = happyGoto action_31 action_343 (104#) = happyGoto action_32 action_343 (109#) = happyGoto action_33 action_343 (110#) = happyGoto action_34 action_343 (111#) = happyGoto action_35 action_343 (115#) = happyGoto action_430 action_343 x = happyTcHack x happyFail action_344 x = happyTcHack x happyReduce_304 action_345 (120#) = happyShift action_148 action_345 (124#) = happyShift action_104 action_345 (146#) = happyShift action_105 action_345 (168#) = happyShift action_428 action_345 (172#) = happyShift action_106 action_345 (175#) = happyShift action_149 action_345 (176#) = happyShift action_86 action_345 (181#) = happyShift action_150 action_345 (193#) = happyShift action_69 action_345 (63#) = happyGoto action_429 action_345 (64#) = happyGoto action_427 action_345 (65#) = happyGoto action_140 action_345 (66#) = happyGoto action_141 action_345 (67#) = happyGoto action_142 action_345 (68#) = happyGoto action_143 action_345 (69#) = happyGoto action_144 action_345 (70#) = happyGoto action_145 action_345 (71#) = happyGoto action_146 action_345 (110#) = happyGoto action_147 action_345 (111#) = happyGoto action_35 action_345 (114#) = happyGoto action_102 action_345 x = happyTcHack x happyFail action_346 (120#) = happyShift action_148 action_346 (124#) = happyShift action_104 action_346 (146#) = happyShift action_105 action_346 (168#) = happyShift action_428 action_346 (172#) = happyShift action_106 action_346 (175#) = happyShift action_149 action_346 (176#) = happyShift action_86 action_346 (181#) = happyShift action_150 action_346 (193#) = happyShift action_69 action_346 (63#) = happyGoto action_426 action_346 (64#) = happyGoto action_427 action_346 (65#) = happyGoto action_140 action_346 (66#) = happyGoto action_141 action_346 (67#) = happyGoto action_142 action_346 (68#) = happyGoto action_143 action_346 (69#) = happyGoto action_144 action_346 (70#) = happyGoto action_145 action_346 (71#) = happyGoto action_146 action_346 (110#) = happyGoto action_147 action_346 (111#) = happyGoto action_35 action_346 (114#) = happyGoto action_102 action_346 x = happyTcHack x happyFail action_347 (169#) = happyShift action_425 action_347 x = happyTcHack x happyFail action_348 (126#) = happyShift action_424 action_348 x = happyTcHack x happyReduce_154 action_349 x = happyTcHack x happyReduce_241 action_350 (169#) = happyShift action_423 action_350 x = happyTcHack x happyFail action_351 (1#) = happyShift action_36 action_351 (128#) = happyShift action_157 action_351 (129#) = happyShift action_158 action_351 (146#) = happyShift action_40 action_351 (147#) = happyShift action_41 action_351 (148#) = happyShift action_42 action_351 (149#) = happyShift action_43 action_351 (150#) = happyShift action_44 action_351 (151#) = happyShift action_45 action_351 (152#) = happyShift action_46 action_351 (153#) = happyShift action_47 action_351 (154#) = happyShift action_48 action_351 (155#) = happyShift action_49 action_351 (156#) = happyShift action_50 action_351 (157#) = happyShift action_51 action_351 (158#) = happyShift action_52 action_351 (159#) = happyShift action_53 action_351 (163#) = happyShift action_54 action_351 (171#) = happyShift action_56 action_351 (176#) = happyShift action_57 action_351 (197#) = happyShift action_73 action_351 (31#) = happyGoto action_18 action_351 (32#) = happyGoto action_19 action_351 (52#) = happyGoto action_422 action_351 (54#) = happyGoto action_333 action_351 (55#) = happyGoto action_334 action_351 (59#) = happyGoto action_76 action_351 (60#) = happyGoto action_25 action_351 (61#) = happyGoto action_26 action_351 (86#) = happyGoto action_77 action_351 x = happyTcHack x happyFail action_352 x = happyTcHack x happyReduce_333 action_353 (121#) = happyShift action_420 action_353 (125#) = happyShift action_421 action_353 x = happyTcHack x happyFail action_354 x = happyTcHack x happyReduce_246 action_355 x = happyTcHack x happyReduce_332 action_356 (120#) = happyShift action_212 action_356 (168#) = happyShift action_213 action_356 x = happyTcHack x happyReduce_239 action_357 (120#) = happyShift action_212 action_357 (168#) = happyShift action_213 action_357 x = happyTcHack x happyReduce_240 action_358 x = happyTcHack x happyReduce_229 action_359 x = happyTcHack x happyReduce_252 action_360 x = happyTcHack x happyReduce_250 action_361 (130#) = happyShift action_419 action_361 x = happyTcHack x happyFail action_362 (1#) = happyShift action_122 action_362 (146#) = happyShift action_123 action_362 (147#) = happyShift action_124 action_362 (148#) = happyShift action_125 action_362 (149#) = happyShift action_43 action_362 (150#) = happyShift action_44 action_362 (151#) = happyShift action_45 action_362 (152#) = happyShift action_46 action_362 (153#) = happyShift action_47 action_362 (154#) = happyShift action_126 action_362 (155#) = happyShift action_127 action_362 (156#) = happyShift action_128 action_362 (157#) = happyShift action_129 action_362 (171#) = happyShift action_130 action_362 (176#) = happyShift action_131 action_362 (183#) = happyShift action_61 action_362 (184#) = happyShift action_62 action_362 (30#) = happyGoto action_418 action_362 (31#) = happyGoto action_119 action_362 (32#) = happyGoto action_120 action_362 (89#) = happyGoto action_121 action_362 (90#) = happyGoto action_29 action_362 x = happyTcHack x happyFail action_363 (168#) = happyShift action_417 action_363 x = happyTcHack x happyFail action_364 (153#) = happyShift action_161 action_364 (154#) = happyShift action_415 action_364 (155#) = happyShift action_416 action_364 x = happyTcHack x happyReduce_99 action_365 (168#) = happyReduce_71 action_365 x = happyTcHack x happyReduce_102 action_366 (121#) = happyShift action_414 action_366 x = happyTcHack x happyFail action_367 (121#) = happyShift action_413 action_367 x = happyTcHack x happyFail action_368 (168#) = happyReduce_79 action_368 x = happyTcHack x happyReduce_107 action_369 (168#) = happyReduce_93 action_369 x = happyTcHack x happyReduce_120 action_370 (168#) = happyReduce_90 action_370 (181#) = happyShift action_229 action_370 x = happyTcHack x happyReduce_117 action_371 (168#) = happyReduce_92 action_371 x = happyTcHack x happyReduce_119 action_372 (168#) = happyReduce_74 action_372 x = happyTcHack x happyReduce_105 action_373 (149#) = happyShift action_43 action_373 (150#) = happyShift action_44 action_373 (151#) = happyShift action_45 action_373 (152#) = happyShift action_46 action_373 (153#) = happyShift action_47 action_373 (156#) = happyShift action_412 action_373 (168#) = happyReduce_82 action_373 (31#) = happyGoto action_107 action_373 (32#) = happyGoto action_411 action_373 x = happyTcHack x happyReduce_110 action_374 (149#) = happyShift action_43 action_374 (150#) = happyShift action_44 action_374 (151#) = happyShift action_45 action_374 (152#) = happyShift action_46 action_374 (153#) = happyShift action_47 action_374 (156#) = happyShift action_410 action_374 (168#) = happyReduce_81 action_374 (31#) = happyGoto action_107 action_374 (32#) = happyGoto action_409 action_374 x = happyTcHack x happyReduce_109 action_375 (168#) = happyReduce_72 action_375 (181#) = happyShift action_224 action_375 x = happyTcHack x happyReduce_103 action_376 (168#) = happyReduce_73 action_376 (181#) = happyShift action_223 action_376 x = happyTcHack x happyReduce_104 action_377 (168#) = happyReduce_75 action_377 (181#) = happyShift action_408 action_377 x = happyTcHack x happyReduce_106 action_378 (168#) = happyReduce_89 action_378 x = happyTcHack x happyReduce_355 action_379 x = happyTcHack x happyReduce_156 action_380 (120#) = happyShift action_195 action_380 (141#) = happyShift action_196 action_380 (142#) = happyShift action_197 action_380 (170#) = happyShift action_198 action_380 (173#) = happyShift action_199 action_380 (174#) = happyShift action_200 action_380 (176#) = happyShift action_86 action_380 (180#) = happyShift action_201 action_380 (182#) = happyShift action_202 action_380 (34#) = happyGoto action_367 action_380 (35#) = happyGoto action_265 action_380 (36#) = happyGoto action_266 action_380 (37#) = happyGoto action_267 action_380 (38#) = happyGoto action_268 action_380 (39#) = happyGoto action_269 action_380 (40#) = happyGoto action_270 action_380 (41#) = happyGoto action_271 action_380 (43#) = happyGoto action_272 action_380 (44#) = happyGoto action_273 action_380 (45#) = happyGoto action_188 action_380 (46#) = happyGoto action_189 action_380 (47#) = happyGoto action_190 action_380 (48#) = happyGoto action_191 action_380 (49#) = happyGoto action_192 action_380 (50#) = happyGoto action_193 action_380 (114#) = happyGoto action_194 action_380 x = happyTcHack x happyFail action_381 (120#) = happyShift action_195 action_381 (141#) = happyShift action_196 action_381 (142#) = happyShift action_197 action_381 (170#) = happyShift action_198 action_381 (173#) = happyShift action_199 action_381 (174#) = happyShift action_200 action_381 (176#) = happyShift action_86 action_381 (180#) = happyShift action_201 action_381 (182#) = happyShift action_202 action_381 (47#) = happyGoto action_407 action_381 (48#) = happyGoto action_191 action_381 (49#) = happyGoto action_192 action_381 (50#) = happyGoto action_193 action_381 (114#) = happyGoto action_194 action_381 x = happyTcHack x happyFail action_382 (120#) = happyShift action_195 action_382 (141#) = happyShift action_196 action_382 (142#) = happyShift action_197 action_382 (170#) = happyShift action_198 action_382 (173#) = happyShift action_199 action_382 (174#) = happyShift action_200 action_382 (176#) = happyShift action_86 action_382 (180#) = happyShift action_201 action_382 (182#) = happyShift action_202 action_382 (47#) = happyGoto action_406 action_382 (48#) = happyGoto action_191 action_382 (49#) = happyGoto action_192 action_382 (50#) = happyGoto action_193 action_382 (114#) = happyGoto action_194 action_382 x = happyTcHack x happyFail action_383 (120#) = happyShift action_195 action_383 (141#) = happyShift action_196 action_383 (142#) = happyShift action_197 action_383 (170#) = happyShift action_198 action_383 (173#) = happyShift action_199 action_383 (174#) = happyShift action_200 action_383 (176#) = happyShift action_86 action_383 (180#) = happyShift action_201 action_383 (182#) = happyShift action_202 action_383 (47#) = happyGoto action_405 action_383 (48#) = happyGoto action_191 action_383 (49#) = happyGoto action_192 action_383 (50#) = happyGoto action_193 action_383 (114#) = happyGoto action_194 action_383 x = happyTcHack x happyFail action_384 (120#) = happyShift action_195 action_384 (141#) = happyShift action_196 action_384 (142#) = happyShift action_197 action_384 (170#) = happyShift action_198 action_384 (173#) = happyShift action_199 action_384 (174#) = happyShift action_200 action_384 (176#) = happyShift action_86 action_384 (180#) = happyShift action_201 action_384 (182#) = happyShift action_202 action_384 (46#) = happyGoto action_404 action_384 (47#) = happyGoto action_190 action_384 (48#) = happyGoto action_191 action_384 (49#) = happyGoto action_192 action_384 (50#) = happyGoto action_193 action_384 (114#) = happyGoto action_194 action_384 x = happyTcHack x happyFail action_385 (120#) = happyShift action_195 action_385 (141#) = happyShift action_196 action_385 (142#) = happyShift action_197 action_385 (170#) = happyShift action_198 action_385 (173#) = happyShift action_199 action_385 (174#) = happyShift action_200 action_385 (176#) = happyShift action_86 action_385 (180#) = happyShift action_201 action_385 (182#) = happyShift action_202 action_385 (46#) = happyGoto action_403 action_385 (47#) = happyGoto action_190 action_385 (48#) = happyGoto action_191 action_385 (49#) = happyGoto action_192 action_385 (50#) = happyGoto action_193 action_385 (114#) = happyGoto action_194 action_385 x = happyTcHack x happyFail action_386 x = happyTcHack x happyReduce_294 action_387 (13#) = happyGoto action_402 action_387 x = happyTcHack x happyReduce_31 action_388 (117#) = happyShift action_401 action_388 x = happyTcHack x happyFail action_389 (1#) = happyShift action_36 action_389 (123#) = happyShift action_400 action_389 (128#) = happyShift action_39 action_389 (144#) = happyReduce_344 action_389 (145#) = happyReduce_344 action_389 (146#) = happyShift action_40 action_389 (147#) = happyShift action_41 action_389 (148#) = happyShift action_42 action_389 (149#) = happyShift action_43 action_389 (150#) = happyShift action_44 action_389 (151#) = happyShift action_45 action_389 (152#) = happyShift action_46 action_389 (153#) = happyShift action_47 action_389 (154#) = happyShift action_48 action_389 (155#) = happyShift action_49 action_389 (156#) = happyShift action_50 action_389 (157#) = happyShift action_51 action_389 (158#) = happyShift action_52 action_389 (159#) = happyShift action_53 action_389 (163#) = happyShift action_54 action_389 (168#) = happyShift action_55 action_389 (171#) = happyShift action_56 action_389 (176#) = happyShift action_57 action_389 (183#) = happyShift action_61 action_389 (184#) = happyShift action_62 action_389 (187#) = happyShift action_63 action_389 (188#) = happyShift action_64 action_389 (189#) = happyShift action_65 action_389 (190#) = happyShift action_66 action_389 (193#) = happyShift action_69 action_389 (194#) = happyShift action_70 action_389 (197#) = happyShift action_73 action_389 (20#) = happyGoto action_392 action_389 (21#) = happyGoto action_393 action_389 (23#) = happyGoto action_394 action_389 (24#) = happyGoto action_395 action_389 (26#) = happyGoto action_396 action_389 (31#) = happyGoto action_18 action_389 (32#) = happyGoto action_19 action_389 (51#) = happyGoto action_397 action_389 (53#) = happyGoto action_21 action_389 (55#) = happyGoto action_22 action_389 (58#) = happyGoto action_23 action_389 (59#) = happyGoto action_24 action_389 (60#) = happyGoto action_25 action_389 (61#) = happyGoto action_26 action_389 (86#) = happyGoto action_27 action_389 (89#) = happyGoto action_28 action_389 (90#) = happyGoto action_29 action_389 (93#) = happyGoto action_398 action_389 (96#) = happyGoto action_399 action_389 (104#) = happyGoto action_32 action_389 (109#) = happyGoto action_33 action_389 (110#) = happyGoto action_34 action_389 (111#) = happyGoto action_35 action_389 x = happyTcHack x happyFail action_390 x = happyTcHack x happyReduce_8 action_391 x = happyTcHack x happyReduce_7 action_392 (1#) = happyShift action_166 action_392 (117#) = happyShift action_167 action_392 (115#) = happyGoto action_546 action_392 x = happyTcHack x happyFail action_393 (1#) = happyShift action_166 action_393 (117#) = happyShift action_167 action_393 (115#) = happyGoto action_545 action_393 x = happyTcHack x happyFail action_394 x = happyTcHack x happyReduce_52 action_395 (117#) = happyShift action_544 action_395 x = happyTcHack x happyFail action_396 (117#) = happyShift action_543 action_396 x = happyTcHack x happyFail action_397 (117#) = happyShift action_542 action_397 x = happyTcHack x happyFail action_398 x = happyTcHack x happyReduce_59 action_399 (1#) = happyShift action_36 action_399 (128#) = happyShift action_153 action_399 (146#) = happyShift action_40 action_399 (147#) = happyShift action_41 action_399 (148#) = happyShift action_42 action_399 (149#) = happyShift action_43 action_399 (150#) = happyShift action_44 action_399 (151#) = happyShift action_45 action_399 (152#) = happyShift action_46 action_399 (153#) = happyShift action_47 action_399 (154#) = happyShift action_48 action_399 (155#) = happyShift action_49 action_399 (156#) = happyShift action_50 action_399 (157#) = happyShift action_51 action_399 (158#) = happyShift action_52 action_399 (159#) = happyShift action_53 action_399 (163#) = happyShift action_54 action_399 (171#) = happyShift action_56 action_399 (176#) = happyShift action_57 action_399 (183#) = happyShift action_61 action_399 (184#) = happyShift action_62 action_399 (197#) = happyShift action_73 action_399 (31#) = happyGoto action_18 action_399 (32#) = happyGoto action_19 action_399 (53#) = happyGoto action_21 action_399 (55#) = happyGoto action_22 action_399 (58#) = happyGoto action_152 action_399 (59#) = happyGoto action_24 action_399 (60#) = happyGoto action_25 action_399 (61#) = happyGoto action_26 action_399 (86#) = happyGoto action_27 action_399 (89#) = happyGoto action_28 action_399 (90#) = happyGoto action_29 action_399 (93#) = happyGoto action_541 action_399 (104#) = happyGoto action_32 action_399 x = happyTcHack x happyFail action_400 x = happyTcHack x happyReduce_42 action_401 (123#) = happyShift action_540 action_401 x = happyTcHack x happyFail action_402 (168#) = happyShift action_55 action_402 (185#) = happyShift action_539 action_402 (94#) = happyGoto action_538 action_402 (95#) = happyGoto action_219 action_402 (96#) = happyGoto action_220 action_402 x = happyTcHack x happyReduce_303 action_403 (139#) = happyShift action_381 action_403 (140#) = happyShift action_382 action_403 (181#) = happyShift action_383 action_403 x = happyTcHack x happyReduce_147 action_404 (139#) = happyShift action_381 action_404 (140#) = happyShift action_382 action_404 (181#) = happyShift action_383 action_404 x = happyTcHack x happyReduce_146 action_405 x = happyTcHack x happyReduce_149 action_406 x = happyTcHack x happyReduce_151 action_407 x = happyTcHack x happyReduce_150 action_408 (168#) = happyReduce_76 action_408 x = happyTcHack x happyReduce_118 action_409 (168#) = happyReduce_84 action_409 x = happyTcHack x happyReduce_112 action_410 (168#) = happyReduce_88 action_410 x = happyTcHack x happyReduce_116 action_411 (168#) = happyReduce_83 action_411 x = happyTcHack x happyReduce_111 action_412 (168#) = happyReduce_85 action_412 x = happyTcHack x happyReduce_115 action_413 x = happyTcHack x happyReduce_164 action_414 (120#) = happyShift action_195 action_414 (141#) = happyShift action_196 action_414 (142#) = happyShift action_197 action_414 (170#) = happyShift action_198 action_414 (173#) = happyShift action_199 action_414 (174#) = happyShift action_200 action_414 (176#) = happyShift action_86 action_414 (180#) = happyShift action_201 action_414 (182#) = happyShift action_202 action_414 (47#) = happyGoto action_537 action_414 (48#) = happyGoto action_191 action_414 (49#) = happyGoto action_192 action_414 (50#) = happyGoto action_193 action_414 (114#) = happyGoto action_194 action_414 x = happyTcHack x happyFail action_415 (153#) = happyShift action_536 action_415 x = happyTcHack x happyFail action_416 (153#) = happyShift action_535 action_416 x = happyTcHack x happyFail action_417 (169#) = happyShift action_534 action_417 x = happyTcHack x happyFail action_418 (121#) = happyShift action_533 action_418 (168#) = happyShift action_233 action_418 x = happyTcHack x happyFail action_419 (120#) = happyShift action_195 action_419 (141#) = happyShift action_196 action_419 (142#) = happyShift action_197 action_419 (170#) = happyShift action_198 action_419 (173#) = happyShift action_199 action_419 (174#) = happyShift action_200 action_419 (176#) = happyShift action_86 action_419 (180#) = happyShift action_201 action_419 (182#) = happyShift action_202 action_419 (34#) = happyGoto action_532 action_419 (35#) = happyGoto action_265 action_419 (36#) = happyGoto action_266 action_419 (37#) = happyGoto action_267 action_419 (38#) = happyGoto action_268 action_419 (39#) = happyGoto action_269 action_419 (40#) = happyGoto action_270 action_419 (41#) = happyGoto action_271 action_419 (43#) = happyGoto action_272 action_419 (44#) = happyGoto action_273 action_419 (45#) = happyGoto action_188 action_419 (46#) = happyGoto action_189 action_419 (47#) = happyGoto action_190 action_419 (48#) = happyGoto action_191 action_419 (49#) = happyGoto action_192 action_419 (50#) = happyGoto action_193 action_419 (114#) = happyGoto action_194 action_419 x = happyTcHack x happyFail action_420 x = happyTcHack x happyReduce_245 action_421 (127#) = happyShift action_355 action_421 (168#) = happyShift action_55 action_421 (94#) = happyGoto action_351 action_421 (95#) = happyGoto action_219 action_421 (96#) = happyGoto action_220 action_421 (105#) = happyGoto action_531 action_421 x = happyTcHack x happyReduce_303 action_422 (120#) = happyShift action_530 action_422 (124#) = happyShift action_104 action_422 (146#) = happyShift action_105 action_422 (168#) = happyShift action_428 action_422 (172#) = happyShift action_106 action_422 (175#) = happyShift action_149 action_422 (176#) = happyShift action_86 action_422 (181#) = happyShift action_150 action_422 (193#) = happyShift action_69 action_422 (64#) = happyGoto action_525 action_422 (65#) = happyGoto action_526 action_422 (66#) = happyGoto action_141 action_422 (67#) = happyGoto action_142 action_422 (68#) = happyGoto action_143 action_422 (69#) = happyGoto action_144 action_422 (70#) = happyGoto action_145 action_422 (71#) = happyGoto action_527 action_422 (107#) = happyGoto action_528 action_422 (108#) = happyGoto action_529 action_422 (110#) = happyGoto action_147 action_422 (111#) = happyGoto action_35 action_422 (114#) = happyGoto action_102 action_422 x = happyTcHack x happyReduce_329 action_423 x = happyTcHack x happyReduce_242 action_424 (126#) = happyShift action_524 action_424 x = happyTcHack x happyFail action_425 x = happyTcHack x happyReduce_243 action_426 (125#) = happyShift action_517 action_426 (193#) = happyShift action_69 action_426 (109#) = happyGoto action_523 action_426 (110#) = happyGoto action_34 action_426 (111#) = happyGoto action_35 action_426 x = happyTcHack x happyReduce_344 action_427 x = happyTcHack x happyReduce_220 action_428 (120#) = happyShift action_195 action_428 (141#) = happyShift action_196 action_428 (142#) = happyShift action_197 action_428 (169#) = happyShift action_522 action_428 (170#) = happyShift action_198 action_428 (173#) = happyShift action_199 action_428 (174#) = happyShift action_200 action_428 (176#) = happyShift action_86 action_428 (180#) = happyShift action_201 action_428 (182#) = happyShift action_202 action_428 (34#) = happyGoto action_521 action_428 (35#) = happyGoto action_265 action_428 (36#) = happyGoto action_266 action_428 (37#) = happyGoto action_267 action_428 (38#) = happyGoto action_268 action_428 (39#) = happyGoto action_269 action_428 (40#) = happyGoto action_270 action_428 (41#) = happyGoto action_271 action_428 (43#) = happyGoto action_272 action_428 (44#) = happyGoto action_273 action_428 (45#) = happyGoto action_188 action_428 (46#) = happyGoto action_189 action_428 (47#) = happyGoto action_190 action_428 (48#) = happyGoto action_191 action_428 (49#) = happyGoto action_192 action_428 (50#) = happyGoto action_193 action_428 (114#) = happyGoto action_194 action_428 x = happyTcHack x happyFail action_429 (125#) = happyShift action_517 action_429 (193#) = happyShift action_69 action_429 (109#) = happyGoto action_520 action_429 (110#) = happyGoto action_34 action_429 (111#) = happyGoto action_35 action_429 x = happyTcHack x happyReduce_344 action_430 (123#) = happyShift action_519 action_430 x = happyTcHack x happyFail action_431 (123#) = happyReduce_356 action_431 x = happyTcHack x happyReduce_200 action_432 x = happyTcHack x happyReduce_169 action_433 x = happyTcHack x happyReduce_213 action_434 (117#) = happyShift action_518 action_434 x = happyTcHack x happyFail action_435 x = happyTcHack x happyReduce_253 action_436 x = happyTcHack x happyReduce_174 action_437 (168#) = happyShift action_428 action_437 x = happyTcHack x happyReduce_175 action_438 (125#) = happyShift action_517 action_438 x = happyTcHack x happyReduce_255 action_439 (193#) = happyShift action_69 action_439 (109#) = happyGoto action_516 action_439 (110#) = happyGoto action_34 action_439 (111#) = happyGoto action_35 action_439 x = happyTcHack x happyReduce_344 action_440 (169#) = happyShift action_515 action_440 x = happyTcHack x happyFail action_441 (120#) = happyShift action_514 action_441 x = happyTcHack x happyFail action_442 x = happyTcHack x happyReduce_280 action_443 x = happyTcHack x happyReduce_278 action_444 (124#) = happyShift action_513 action_444 x = happyTcHack x happyFail action_445 x = happyTcHack x happyReduce_267 action_446 x = happyTcHack x happyReduce_276 action_447 (1#) = happyShift action_36 action_447 (128#) = happyShift action_157 action_447 (129#) = happyShift action_158 action_447 (146#) = happyShift action_40 action_447 (147#) = happyShift action_41 action_447 (148#) = happyShift action_42 action_447 (149#) = happyShift action_43 action_447 (150#) = happyShift action_44 action_447 (151#) = happyShift action_45 action_447 (152#) = happyShift action_46 action_447 (153#) = happyShift action_47 action_447 (154#) = happyShift action_48 action_447 (155#) = happyShift action_49 action_447 (156#) = happyShift action_50 action_447 (157#) = happyShift action_51 action_447 (158#) = happyShift action_52 action_447 (159#) = happyShift action_53 action_447 (163#) = happyShift action_54 action_447 (171#) = happyShift action_56 action_447 (176#) = happyShift action_57 action_447 (197#) = happyShift action_73 action_447 (31#) = happyGoto action_18 action_447 (32#) = happyGoto action_19 action_447 (52#) = happyGoto action_512 action_447 (54#) = happyGoto action_333 action_447 (55#) = happyGoto action_334 action_447 (59#) = happyGoto action_76 action_447 (60#) = happyGoto action_25 action_447 (61#) = happyGoto action_26 action_447 (86#) = happyGoto action_77 action_447 x = happyTcHack x happyFail action_448 x = happyTcHack x happyReduce_265 action_449 (117#) = happyShift action_511 action_449 x = happyTcHack x happyFail action_450 (161#) = happyShift action_441 action_450 (162#) = happyShift action_442 action_450 (83#) = happyGoto action_440 action_450 x = happyTcHack x happyFail action_451 (193#) = happyShift action_69 action_451 (109#) = happyGoto action_510 action_451 (110#) = happyGoto action_34 action_451 (111#) = happyGoto action_35 action_451 x = happyTcHack x happyReduce_344 action_452 x = happyTcHack x happyReduce_259 action_453 x = happyTcHack x happyReduce_262 action_454 (176#) = happyShift action_86 action_454 (114#) = happyGoto action_509 action_454 x = happyTcHack x happyFail action_455 x = happyTcHack x happyReduce_261 action_456 x = happyTcHack x happyReduce_264 action_457 x = happyTcHack x happyReduce_260 action_458 x = happyTcHack x happyReduce_263 action_459 x = happyTcHack x happyReduce_289 action_460 x = happyTcHack x happyReduce_285 action_461 (120#) = happyShift action_195 action_461 (141#) = happyShift action_196 action_461 (142#) = happyShift action_197 action_461 (170#) = happyShift action_198 action_461 (173#) = happyShift action_199 action_461 (174#) = happyShift action_200 action_461 (176#) = happyShift action_86 action_461 (180#) = happyShift action_201 action_461 (182#) = happyShift action_202 action_461 (34#) = happyGoto action_508 action_461 (35#) = happyGoto action_265 action_461 (36#) = happyGoto action_266 action_461 (37#) = happyGoto action_267 action_461 (38#) = happyGoto action_268 action_461 (39#) = happyGoto action_269 action_461 (40#) = happyGoto action_270 action_461 (41#) = happyGoto action_271 action_461 (43#) = happyGoto action_272 action_461 (44#) = happyGoto action_273 action_461 (45#) = happyGoto action_188 action_461 (46#) = happyGoto action_189 action_461 (47#) = happyGoto action_190 action_461 (48#) = happyGoto action_191 action_461 (49#) = happyGoto action_192 action_461 (50#) = happyGoto action_193 action_461 (114#) = happyGoto action_194 action_461 x = happyTcHack x happyFail action_462 x = happyTcHack x happyReduce_292 action_463 (123#) = happyShift action_507 action_463 x = happyTcHack x happyFail action_464 x = happyTcHack x happyReduce_326 action_465 x = happyTcHack x happyReduce_324 action_466 x = happyTcHack x happyReduce_323 action_467 (123#) = happyShift action_506 action_467 x = happyTcHack x happyFail action_468 x = happyTcHack x happyReduce_317 action_469 (120#) = happyShift action_195 action_469 (122#) = happyShift action_310 action_469 (141#) = happyShift action_196 action_469 (142#) = happyShift action_197 action_469 (146#) = happyShift action_311 action_469 (154#) = happyShift action_312 action_469 (155#) = happyShift action_313 action_469 (170#) = happyShift action_198 action_469 (173#) = happyShift action_199 action_469 (174#) = happyShift action_200 action_469 (176#) = happyShift action_86 action_469 (180#) = happyShift action_201 action_469 (181#) = happyShift action_314 action_469 (182#) = happyShift action_202 action_469 (34#) = happyGoto action_307 action_469 (35#) = happyGoto action_265 action_469 (36#) = happyGoto action_266 action_469 (37#) = happyGoto action_267 action_469 (38#) = happyGoto action_268 action_469 (39#) = happyGoto action_269 action_469 (40#) = happyGoto action_270 action_469 (41#) = happyGoto action_271 action_469 (43#) = happyGoto action_272 action_469 (44#) = happyGoto action_273 action_469 (45#) = happyGoto action_188 action_469 (46#) = happyGoto action_189 action_469 (47#) = happyGoto action_190 action_469 (48#) = happyGoto action_191 action_469 (49#) = happyGoto action_192 action_469 (50#) = happyGoto action_193 action_469 (103#) = happyGoto action_505 action_469 (114#) = happyGoto action_194 action_469 x = happyTcHack x happyReduce_321 action_470 (123#) = happyShift action_504 action_470 (168#) = happyShift action_303 action_470 (15#) = happyGoto action_496 action_470 (16#) = happyGoto action_302 action_470 x = happyTcHack x happyReduce_39 action_471 (125#) = happyShift action_502 action_471 (169#) = happyShift action_503 action_471 x = happyTcHack x happyFail action_472 x = happyTcHack x happyReduce_312 action_473 x = happyTcHack x happyReduce_314 action_474 x = happyTcHack x happyReduce_315 action_475 (146#) = happyShift action_501 action_475 (176#) = happyShift action_86 action_475 (114#) = happyGoto action_500 action_475 x = happyTcHack x happyFail action_476 (146#) = happyShift action_499 action_476 (176#) = happyShift action_86 action_476 (114#) = happyGoto action_498 action_476 x = happyTcHack x happyFail action_477 (123#) = happyShift action_497 action_477 (168#) = happyShift action_303 action_477 (15#) = happyGoto action_496 action_477 (16#) = happyGoto action_302 action_477 x = happyTcHack x happyReduce_39 action_478 x = happyTcHack x happyReduce_27 action_479 (176#) = happyShift action_495 action_479 x = happyTcHack x happyFail action_480 (121#) = happyShift action_494 action_480 x = happyTcHack x happyFail action_481 (124#) = happyShift action_493 action_481 x = happyTcHack x happyFail action_482 (137#) = happyShift action_287 action_482 x = happyTcHack x happyReduce_125 action_483 (133#) = happyShift action_286 action_483 x = happyTcHack x happyReduce_127 action_484 (135#) = happyShift action_285 action_484 x = happyTcHack x happyReduce_129 action_485 (136#) = happyShift action_284 action_485 x = happyTcHack x happyReduce_131 action_486 (131#) = happyShift action_282 action_486 (132#) = happyShift action_283 action_486 (42#) = happyGoto action_281 action_486 x = happyTcHack x happyReduce_133 action_487 (164#) = happyShift action_277 action_487 (165#) = happyShift action_278 action_487 (166#) = happyShift action_279 action_487 (167#) = happyShift action_280 action_487 x = happyTcHack x happyReduce_135 action_488 (138#) = happyShift action_276 action_488 x = happyTcHack x happyReduce_141 action_489 (138#) = happyShift action_276 action_489 x = happyTcHack x happyReduce_142 action_490 (138#) = happyShift action_276 action_490 x = happyTcHack x happyReduce_140 action_491 (138#) = happyShift action_276 action_491 x = happyTcHack x happyReduce_139 action_492 (180#) = happyShift action_384 action_492 (182#) = happyShift action_385 action_492 x = happyTcHack x happyReduce_144 action_493 (120#) = happyShift action_195 action_493 (141#) = happyShift action_196 action_493 (142#) = happyShift action_197 action_493 (170#) = happyShift action_198 action_493 (173#) = happyShift action_199 action_493 (174#) = happyShift action_200 action_493 (176#) = happyShift action_86 action_493 (180#) = happyShift action_201 action_493 (182#) = happyShift action_202 action_493 (36#) = happyGoto action_568 action_493 (37#) = happyGoto action_267 action_493 (38#) = happyGoto action_268 action_493 (39#) = happyGoto action_269 action_493 (40#) = happyGoto action_270 action_493 (41#) = happyGoto action_271 action_493 (43#) = happyGoto action_272 action_493 (44#) = happyGoto action_273 action_493 (45#) = happyGoto action_188 action_493 (46#) = happyGoto action_189 action_493 (47#) = happyGoto action_190 action_493 (48#) = happyGoto action_191 action_493 (49#) = happyGoto action_192 action_493 (50#) = happyGoto action_193 action_493 (114#) = happyGoto action_194 action_493 x = happyTcHack x happyFail action_494 x = happyTcHack x happyReduce_348 action_495 (121#) = happyShift action_566 action_495 (125#) = happyShift action_567 action_495 x = happyTcHack x happyFail action_496 x = happyTcHack x happyReduce_34 action_497 x = happyTcHack x happyReduce_25 action_498 x = happyTcHack x happyReduce_38 action_499 x = happyTcHack x happyReduce_36 action_500 x = happyTcHack x happyReduce_37 action_501 x = happyTcHack x happyReduce_35 action_502 (162#) = happyShift action_474 action_502 (176#) = happyShift action_86 action_502 (100#) = happyGoto action_565 action_502 (114#) = happyGoto action_473 action_502 x = happyTcHack x happyFail action_503 x = happyTcHack x happyReduce_40 action_504 x = happyTcHack x happyReduce_26 action_505 x = happyTcHack x happyReduce_319 action_506 x = happyTcHack x happyReduce_325 action_507 x = happyTcHack x happyReduce_286 action_508 x = happyTcHack x happyReduce_293 action_509 (121#) = happyShift action_564 action_509 x = happyTcHack x happyFail action_510 x = happyTcHack x happyReduce_216 action_511 x = happyTcHack x happyReduce_266 action_512 (120#) = happyShift action_148 action_512 (124#) = happyShift action_104 action_512 (146#) = happyShift action_105 action_512 (168#) = happyShift action_428 action_512 (172#) = happyShift action_106 action_512 (175#) = happyShift action_149 action_512 (176#) = happyShift action_86 action_512 (181#) = happyShift action_150 action_512 (193#) = happyShift action_69 action_512 (64#) = happyGoto action_563 action_512 (65#) = happyGoto action_140 action_512 (66#) = happyGoto action_141 action_512 (67#) = happyGoto action_142 action_512 (68#) = happyGoto action_143 action_512 (69#) = happyGoto action_144 action_512 (70#) = happyGoto action_145 action_512 (71#) = happyGoto action_146 action_512 (110#) = happyGoto action_147 action_512 (111#) = happyGoto action_35 action_512 (114#) = happyGoto action_102 action_512 x = happyTcHack x happyReduce_274 action_513 x = happyTcHack x happyReduce_277 action_514 (120#) = happyShift action_195 action_514 (141#) = happyShift action_196 action_514 (142#) = happyShift action_197 action_514 (170#) = happyShift action_198 action_514 (173#) = happyShift action_199 action_514 (174#) = happyShift action_200 action_514 (176#) = happyShift action_86 action_514 (180#) = happyShift action_201 action_514 (182#) = happyShift action_202 action_514 (34#) = happyGoto action_561 action_514 (35#) = happyGoto action_265 action_514 (36#) = happyGoto action_266 action_514 (37#) = happyGoto action_267 action_514 (38#) = happyGoto action_268 action_514 (39#) = happyGoto action_269 action_514 (40#) = happyGoto action_270 action_514 (41#) = happyGoto action_271 action_514 (43#) = happyGoto action_272 action_514 (44#) = happyGoto action_273 action_514 (45#) = happyGoto action_188 action_514 (46#) = happyGoto action_189 action_514 (47#) = happyGoto action_190 action_514 (48#) = happyGoto action_191 action_514 (49#) = happyGoto action_192 action_514 (50#) = happyGoto action_193 action_514 (84#) = happyGoto action_562 action_514 (114#) = happyGoto action_194 action_514 x = happyTcHack x happyFail action_515 (1#) = happyShift action_36 action_515 (117#) = happyReduce_269 action_515 (128#) = happyShift action_157 action_515 (129#) = happyShift action_158 action_515 (146#) = happyShift action_40 action_515 (147#) = happyShift action_41 action_515 (148#) = happyShift action_42 action_515 (149#) = happyShift action_43 action_515 (150#) = happyShift action_44 action_515 (151#) = happyShift action_45 action_515 (152#) = happyShift action_46 action_515 (153#) = happyShift action_47 action_515 (154#) = happyShift action_48 action_515 (155#) = happyShift action_49 action_515 (156#) = happyShift action_50 action_515 (157#) = happyShift action_51 action_515 (158#) = happyShift action_52 action_515 (159#) = happyShift action_53 action_515 (163#) = happyShift action_54 action_515 (171#) = happyShift action_56 action_515 (176#) = happyShift action_57 action_515 (197#) = happyShift action_73 action_515 (31#) = happyGoto action_18 action_515 (32#) = happyGoto action_19 action_515 (52#) = happyGoto action_559 action_515 (54#) = happyGoto action_333 action_515 (55#) = happyGoto action_334 action_515 (59#) = happyGoto action_76 action_515 (60#) = happyGoto action_25 action_515 (61#) = happyGoto action_26 action_515 (79#) = happyGoto action_560 action_515 (86#) = happyGoto action_77 action_515 x = happyTcHack x happyFail action_516 x = happyTcHack x happyReduce_212 action_517 (120#) = happyShift action_148 action_517 (124#) = happyShift action_104 action_517 (146#) = happyShift action_105 action_517 (172#) = happyShift action_106 action_517 (175#) = happyShift action_149 action_517 (176#) = happyShift action_86 action_517 (181#) = happyShift action_150 action_517 (193#) = happyShift action_69 action_517 (64#) = happyGoto action_558 action_517 (65#) = happyGoto action_140 action_517 (66#) = happyGoto action_141 action_517 (67#) = happyGoto action_142 action_517 (68#) = happyGoto action_143 action_517 (69#) = happyGoto action_144 action_517 (70#) = happyGoto action_145 action_517 (71#) = happyGoto action_146 action_517 (110#) = happyGoto action_147 action_517 (111#) = happyGoto action_35 action_517 (114#) = happyGoto action_102 action_517 x = happyTcHack x happyFail action_518 x = happyTcHack x happyReduce_254 action_519 x = happyTcHack x happyReduce_23 action_520 x = happyTcHack x happyReduce_165 action_521 (169#) = happyShift action_557 action_521 x = happyTcHack x happyFail action_522 x = happyTcHack x happyReduce_172 action_523 x = happyTcHack x happyReduce_170 action_524 (120#) = happyShift action_380 action_524 (173#) = happyShift action_199 action_524 (174#) = happyShift action_200 action_524 (176#) = happyShift action_86 action_524 (50#) = happyGoto action_556 action_524 (114#) = happyGoto action_194 action_524 x = happyTcHack x happyFail action_525 x = happyTcHack x happyReduce_330 action_526 (120#) = happyShift action_530 action_526 (124#) = happyShift action_104 action_526 (146#) = happyShift action_105 action_526 (172#) = happyShift action_106 action_526 (175#) = happyShift action_149 action_526 (176#) = happyShift action_86 action_526 (181#) = happyShift action_150 action_526 (193#) = happyShift action_69 action_526 (65#) = happyGoto action_554 action_526 (66#) = happyGoto action_214 action_526 (67#) = happyGoto action_142 action_526 (68#) = happyGoto action_215 action_526 (69#) = happyGoto action_144 action_526 (70#) = happyGoto action_145 action_526 (71#) = happyGoto action_527 action_526 (107#) = happyGoto action_555 action_526 (108#) = happyGoto action_529 action_526 (110#) = happyGoto action_147 action_526 (111#) = happyGoto action_35 action_526 (114#) = happyGoto action_102 action_526 x = happyTcHack x happyFail action_527 (120#) = happyShift action_530 action_527 (124#) = happyShift action_104 action_527 (146#) = happyShift action_105 action_527 (172#) = happyShift action_106 action_527 (175#) = happyShift action_211 action_527 (176#) = happyShift action_86 action_527 (193#) = happyShift action_69 action_527 (66#) = happyGoto action_209 action_527 (67#) = happyGoto action_142 action_527 (69#) = happyGoto action_144 action_527 (70#) = happyGoto action_145 action_527 (108#) = happyGoto action_553 action_527 (110#) = happyGoto action_210 action_527 (111#) = happyGoto action_35 action_527 (114#) = happyGoto action_102 action_527 x = happyTcHack x happyReduce_335 action_528 x = happyTcHack x happyReduce_331 action_529 (120#) = happyShift action_552 action_529 x = happyTcHack x happyReduce_337 action_530 (120#) = happyShift action_530 action_530 (121#) = happyShift action_551 action_530 (124#) = happyShift action_104 action_530 (127#) = happyShift action_355 action_530 (146#) = happyShift action_105 action_530 (168#) = happyShift action_55 action_530 (172#) = happyShift action_106 action_530 (175#) = happyShift action_149 action_530 (176#) = happyShift action_86 action_530 (181#) = happyShift action_150 action_530 (193#) = happyShift action_69 action_530 (64#) = happyGoto action_208 action_530 (65#) = happyGoto action_526 action_530 (66#) = happyGoto action_141 action_530 (67#) = happyGoto action_142 action_530 (68#) = happyGoto action_143 action_530 (69#) = happyGoto action_144 action_530 (70#) = happyGoto action_145 action_530 (71#) = happyGoto action_527 action_530 (94#) = happyGoto action_351 action_530 (95#) = happyGoto action_219 action_530 (96#) = happyGoto action_220 action_530 (105#) = happyGoto action_352 action_530 (106#) = happyGoto action_549 action_530 (107#) = happyGoto action_550 action_530 (108#) = happyGoto action_529 action_530 (110#) = happyGoto action_147 action_530 (111#) = happyGoto action_35 action_530 (114#) = happyGoto action_102 action_530 x = happyTcHack x happyReduce_303 action_531 x = happyTcHack x happyReduce_334 action_532 x = happyTcHack x happyReduce_168 action_533 x = happyTcHack x happyReduce_155 action_534 (168#) = happyReduce_80 action_534 x = happyTcHack x happyReduce_108 action_535 (168#) = happyReduce_86 action_535 x = happyTcHack x happyReduce_114 action_536 (168#) = happyReduce_87 action_536 x = happyTcHack x happyReduce_113 action_537 x = happyTcHack x happyReduce_153 action_538 (1#) = happyShift action_36 action_538 (128#) = happyShift action_157 action_538 (129#) = happyShift action_158 action_538 (146#) = happyShift action_40 action_538 (147#) = happyShift action_41 action_538 (148#) = happyShift action_42 action_538 (149#) = happyShift action_43 action_538 (150#) = happyShift action_44 action_538 (151#) = happyShift action_45 action_538 (152#) = happyShift action_46 action_538 (153#) = happyShift action_47 action_538 (154#) = happyShift action_48 action_538 (155#) = happyShift action_49 action_538 (156#) = happyShift action_50 action_538 (157#) = happyShift action_51 action_538 (158#) = happyShift action_52 action_538 (159#) = happyShift action_53 action_538 (163#) = happyShift action_54 action_538 (171#) = happyShift action_56 action_538 (176#) = happyShift action_57 action_538 (197#) = happyShift action_73 action_538 (31#) = happyGoto action_18 action_538 (32#) = happyGoto action_19 action_538 (52#) = happyGoto action_548 action_538 (54#) = happyGoto action_333 action_538 (55#) = happyGoto action_334 action_538 (59#) = happyGoto action_76 action_538 (60#) = happyGoto action_25 action_538 (61#) = happyGoto action_26 action_538 (86#) = happyGoto action_77 action_538 x = happyTcHack x happyFail action_539 (124#) = happyShift action_547 action_539 x = happyTcHack x happyFail action_540 x = happyTcHack x happyReduce_30 action_541 x = happyTcHack x happyReduce_58 action_542 x = happyTcHack x happyReduce_54 action_543 x = happyTcHack x happyReduce_57 action_544 x = happyTcHack x happyReduce_53 action_545 x = happyTcHack x happyReduce_56 action_546 x = happyTcHack x happyReduce_55 action_547 (91#) = happyGoto action_583 action_547 x = happyTcHack x happyReduce_298 action_548 (120#) = happyShift action_148 action_548 (124#) = happyShift action_104 action_548 (146#) = happyShift action_105 action_548 (168#) = happyShift action_428 action_548 (172#) = happyShift action_106 action_548 (175#) = happyShift action_149 action_548 (176#) = happyShift action_86 action_548 (181#) = happyShift action_150 action_548 (193#) = happyShift action_69 action_548 (64#) = happyGoto action_582 action_548 (65#) = happyGoto action_140 action_548 (66#) = happyGoto action_141 action_548 (67#) = happyGoto action_142 action_548 (68#) = happyGoto action_143 action_548 (69#) = happyGoto action_144 action_548 (70#) = happyGoto action_145 action_548 (71#) = happyGoto action_146 action_548 (110#) = happyGoto action_147 action_548 (111#) = happyGoto action_35 action_548 (114#) = happyGoto action_102 action_548 x = happyTcHack x happyFail action_549 (121#) = happyShift action_581 action_549 (125#) = happyShift action_421 action_549 x = happyTcHack x happyFail action_550 (121#) = happyShift action_580 action_550 x = happyTcHack x happyFail action_551 x = happyTcHack x happyReduce_340 action_552 (121#) = happyShift action_579 action_552 (127#) = happyShift action_355 action_552 (168#) = happyShift action_55 action_552 (94#) = happyGoto action_351 action_552 (95#) = happyGoto action_219 action_552 (96#) = happyGoto action_220 action_552 (105#) = happyGoto action_352 action_552 (106#) = happyGoto action_578 action_552 x = happyTcHack x happyReduce_303 action_553 (120#) = happyShift action_552 action_553 x = happyTcHack x happyReduce_338 action_554 (120#) = happyShift action_577 action_554 (175#) = happyShift action_149 action_554 (181#) = happyShift action_150 action_554 (193#) = happyShift action_69 action_554 (65#) = happyGoto action_554 action_554 (71#) = happyGoto action_576 action_554 (107#) = happyGoto action_555 action_554 (108#) = happyGoto action_529 action_554 (110#) = happyGoto action_147 action_554 (111#) = happyGoto action_35 action_554 x = happyTcHack x happyFail action_555 x = happyTcHack x happyReduce_336 action_556 (169#) = happyShift action_575 action_556 x = happyTcHack x happyFail action_557 x = happyTcHack x happyReduce_173 action_558 x = happyTcHack x happyReduce_221 action_559 (120#) = happyShift action_148 action_559 (124#) = happyShift action_104 action_559 (146#) = happyShift action_105 action_559 (168#) = happyShift action_428 action_559 (172#) = happyShift action_106 action_559 (175#) = happyShift action_149 action_559 (176#) = happyShift action_86 action_559 (181#) = happyShift action_150 action_559 (193#) = happyShift action_69 action_559 (64#) = happyGoto action_574 action_559 (65#) = happyGoto action_140 action_559 (66#) = happyGoto action_141 action_559 (67#) = happyGoto action_142 action_559 (68#) = happyGoto action_143 action_559 (69#) = happyGoto action_144 action_559 (70#) = happyGoto action_145 action_559 (71#) = happyGoto action_146 action_559 (110#) = happyGoto action_147 action_559 (111#) = happyGoto action_35 action_559 (114#) = happyGoto action_102 action_559 x = happyTcHack x happyReduce_271 action_560 x = happyTcHack x happyReduce_268 action_561 x = happyTcHack x happyReduce_281 action_562 (121#) = happyShift action_572 action_562 (125#) = happyShift action_573 action_562 x = happyTcHack x happyFail action_563 x = happyTcHack x happyReduce_273 action_564 (176#) = happyShift action_86 action_564 (75#) = happyGoto action_570 action_564 (114#) = happyGoto action_571 action_564 x = happyTcHack x happyReduce_257 action_565 x = happyTcHack x happyReduce_313 action_566 x = happyTcHack x happyReduce_351 action_567 (120#) = happyShift action_195 action_567 (141#) = happyShift action_196 action_567 (142#) = happyShift action_197 action_567 (170#) = happyShift action_198 action_567 (173#) = happyShift action_199 action_567 (174#) = happyShift action_200 action_567 (176#) = happyShift action_86 action_567 (180#) = happyShift action_201 action_567 (182#) = happyShift action_202 action_567 (34#) = happyGoto action_561 action_567 (35#) = happyGoto action_265 action_567 (36#) = happyGoto action_266 action_567 (37#) = happyGoto action_267 action_567 (38#) = happyGoto action_268 action_567 (39#) = happyGoto action_269 action_567 (40#) = happyGoto action_270 action_567 (41#) = happyGoto action_271 action_567 (43#) = happyGoto action_272 action_567 (44#) = happyGoto action_273 action_567 (45#) = happyGoto action_188 action_567 (46#) = happyGoto action_189 action_567 (47#) = happyGoto action_190 action_567 (48#) = happyGoto action_191 action_567 (49#) = happyGoto action_192 action_567 (50#) = happyGoto action_193 action_567 (84#) = happyGoto action_569 action_567 (114#) = happyGoto action_194 action_567 x = happyTcHack x happyFail action_568 (134#) = happyShift action_288 action_568 x = happyTcHack x happyReduce_123 action_569 (121#) = happyShift action_591 action_569 (125#) = happyShift action_573 action_569 x = happyTcHack x happyFail action_570 (122#) = happyShift action_590 action_570 x = happyTcHack x happyFail action_571 x = happyTcHack x happyReduce_258 action_572 x = happyTcHack x happyReduce_279 action_573 (120#) = happyShift action_195 action_573 (141#) = happyShift action_196 action_573 (142#) = happyShift action_197 action_573 (170#) = happyShift action_198 action_573 (173#) = happyShift action_199 action_573 (174#) = happyShift action_200 action_573 (176#) = happyShift action_86 action_573 (180#) = happyShift action_201 action_573 (182#) = happyShift action_202 action_573 (34#) = happyGoto action_589 action_573 (35#) = happyGoto action_265 action_573 (36#) = happyGoto action_266 action_573 (37#) = happyGoto action_267 action_573 (38#) = happyGoto action_268 action_573 (39#) = happyGoto action_269 action_573 (40#) = happyGoto action_270 action_573 (41#) = happyGoto action_271 action_573 (43#) = happyGoto action_272 action_573 (44#) = happyGoto action_273 action_573 (45#) = happyGoto action_188 action_573 (46#) = happyGoto action_189 action_573 (47#) = happyGoto action_190 action_573 (48#) = happyGoto action_191 action_573 (49#) = happyGoto action_192 action_573 (50#) = happyGoto action_193 action_573 (114#) = happyGoto action_194 action_573 x = happyTcHack x happyFail action_574 x = happyTcHack x happyReduce_270 action_575 x = happyTcHack x happyReduce_244 action_576 (120#) = happyShift action_577 action_576 (108#) = happyGoto action_553 action_576 x = happyTcHack x happyReduce_335 action_577 (120#) = happyShift action_577 action_577 (121#) = happyShift action_551 action_577 (127#) = happyShift action_355 action_577 (168#) = happyShift action_55 action_577 (175#) = happyShift action_149 action_577 (181#) = happyShift action_150 action_577 (193#) = happyShift action_69 action_577 (65#) = happyGoto action_554 action_577 (71#) = happyGoto action_576 action_577 (94#) = happyGoto action_351 action_577 (95#) = happyGoto action_219 action_577 (96#) = happyGoto action_220 action_577 (105#) = happyGoto action_352 action_577 (106#) = happyGoto action_549 action_577 (107#) = happyGoto action_550 action_577 (108#) = happyGoto action_529 action_577 (110#) = happyGoto action_147 action_577 (111#) = happyGoto action_35 action_577 x = happyTcHack x happyReduce_303 action_578 (121#) = happyShift action_588 action_578 (125#) = happyShift action_421 action_578 x = happyTcHack x happyFail action_579 x = happyTcHack x happyReduce_342 action_580 x = happyTcHack x happyReduce_339 action_581 x = happyTcHack x happyReduce_341 action_582 (117#) = happyShift action_587 action_582 x = happyTcHack x happyFail action_583 (123#) = happyShift action_586 action_583 (168#) = happyShift action_55 action_583 (92#) = happyGoto action_584 action_583 (94#) = happyGoto action_585 action_583 (95#) = happyGoto action_219 action_583 (96#) = happyGoto action_220 action_583 x = happyTcHack x happyReduce_303 action_584 (117#) = happyShift action_594 action_584 x = happyTcHack x happyFail action_585 (1#) = happyShift action_36 action_585 (146#) = happyShift action_40 action_585 (147#) = happyShift action_41 action_585 (148#) = happyShift action_42 action_585 (149#) = happyShift action_43 action_585 (150#) = happyShift action_44 action_585 (151#) = happyShift action_45 action_585 (152#) = happyShift action_46 action_585 (153#) = happyShift action_47 action_585 (154#) = happyShift action_48 action_585 (155#) = happyShift action_49 action_585 (156#) = happyShift action_50 action_585 (157#) = happyShift action_51 action_585 (158#) = happyShift action_52 action_585 (159#) = happyShift action_53 action_585 (163#) = happyShift action_54 action_585 (171#) = happyShift action_56 action_585 (176#) = happyShift action_57 action_585 (183#) = happyShift action_61 action_585 (184#) = happyShift action_62 action_585 (197#) = happyShift action_73 action_585 (31#) = happyGoto action_18 action_585 (32#) = happyGoto action_19 action_585 (53#) = happyGoto action_21 action_585 (55#) = happyGoto action_22 action_585 (59#) = happyGoto action_76 action_585 (60#) = happyGoto action_25 action_585 (61#) = happyGoto action_26 action_585 (86#) = happyGoto action_77 action_585 (89#) = happyGoto action_28 action_585 (90#) = happyGoto action_29 action_585 (104#) = happyGoto action_593 action_585 x = happyTcHack x happyFail action_586 x = happyTcHack x happyReduce_29 action_587 x = happyTcHack x happyReduce_32 action_588 x = happyTcHack x happyReduce_343 action_589 x = happyTcHack x happyReduce_282 action_590 (161#) = happyShift action_327 action_590 (162#) = happyShift action_328 action_590 (168#) = happyShift action_450 action_590 (77#) = happyGoto action_592 action_590 (78#) = happyGoto action_324 action_590 (81#) = happyGoto action_325 action_590 (82#) = happyGoto action_326 action_590 x = happyTcHack x happyFail action_591 x = happyTcHack x happyReduce_352 action_592 (123#) = happyShift action_596 action_592 (161#) = happyShift action_327 action_592 (162#) = happyShift action_328 action_592 (168#) = happyShift action_450 action_592 (78#) = happyGoto action_449 action_592 (81#) = happyGoto action_325 action_592 (82#) = happyGoto action_326 action_592 x = happyTcHack x happyFail action_593 (120#) = happyShift action_148 action_593 (124#) = happyShift action_104 action_593 (146#) = happyShift action_105 action_593 (172#) = happyShift action_106 action_593 (175#) = happyShift action_149 action_593 (176#) = happyShift action_86 action_593 (181#) = happyShift action_150 action_593 (193#) = happyShift action_69 action_593 (64#) = happyGoto action_595 action_593 (65#) = happyGoto action_140 action_593 (66#) = happyGoto action_141 action_593 (67#) = happyGoto action_142 action_593 (68#) = happyGoto action_143 action_593 (69#) = happyGoto action_144 action_593 (70#) = happyGoto action_145 action_593 (71#) = happyGoto action_146 action_593 (110#) = happyGoto action_147 action_593 (111#) = happyGoto action_35 action_593 (114#) = happyGoto action_102 action_593 x = happyTcHack x happyFail action_594 x = happyTcHack x happyReduce_299 action_595 (193#) = happyShift action_69 action_595 (109#) = happyGoto action_597 action_595 (110#) = happyGoto action_34 action_595 (111#) = happyGoto action_35 action_595 x = happyTcHack x happyReduce_344 action_596 x = happyTcHack x happyReduce_215 action_597 x = happyTcHack x happyReduce_300 happyReduce_1 = happySpecReduce_1 4# happyReduction_1 happyReduction_1 (HappyAbsSyn5 happy_var_1) = HappyAbsSyn4 (Left (reverse happy_var_1) ) happyReduction_1 _ = notHappyAtAll happyReduce_2 = happySpecReduce_2 4# happyReduction_2 happyReduction_2 (HappyAbsSyn6 happy_var_2) _ = HappyAbsSyn4 (Right (reverse happy_var_2) ) happyReduction_2 _ _ = notHappyAtAll happyReduce_3 = happySpecReduce_0 5# happyReduction_3 happyReduction_3 = HappyAbsSyn5 ([] ) happyReduce_4 = happySpecReduce_2 5# happyReduction_4 happyReduction_4 (HappyAbsSyn9 happy_var_2) (HappyAbsSyn5 happy_var_1) = HappyAbsSyn5 (happy_var_2 : happy_var_1 ) happyReduction_4 _ _ = notHappyAtAll happyReduce_5 = happySpecReduce_0 6# happyReduction_5 happyReduction_5 = HappyAbsSyn6 ([] ) happyReduce_6 = happySpecReduce_2 6# happyReduction_6 happyReduction_6 (HappyAbsSyn7 happy_var_2) (HappyAbsSyn6 happy_var_1) = HappyAbsSyn6 (happy_var_2 : happy_var_1 ) happyReduction_6 _ _ = notHappyAtAll happyReduce_7 = happySpecReduce_3 7# happyReduction_7 happyReduction_7 (HappyAbsSyn16 happy_var_3) _ (HappyAbsSyn8 happy_var_1) = HappyAbsSyn7 ((happy_var_1, True, happy_var_3) ) happyReduction_7 _ _ _ = notHappyAtAll happyReduce_8 = happySpecReduce_3 7# happyReduction_8 happyReduction_8 (HappyAbsSyn16 happy_var_3) _ (HappyAbsSyn8 happy_var_1) = HappyAbsSyn7 ((happy_var_1, False, happy_var_3) ) happyReduction_8 _ _ _ = notHappyAtAll happyReduce_9 = happySpecReduce_1 8# happyReduction_9 happyReduction_9 (HappyTerminal (T_id happy_var_1)) = HappyAbsSyn8 (happy_var_1 ) happyReduction_9 _ = notHappyAtAll happyReduce_10 = happySpecReduce_1 8# happyReduction_10 happyReduction_10 (HappyTerminal (T_type happy_var_1)) = HappyAbsSyn8 (happy_var_1 ) happyReduction_10 _ = notHappyAtAll happyReduce_11 = happySpecReduce_2 9# happyReduction_11 happyReduction_11 _ (HappyAbsSyn9 happy_var_1) = HappyAbsSyn9 (happy_var_1 ) happyReduction_11 _ _ = notHappyAtAll happyReduce_12 = happyMonadReduce 3# 9# happyReduction_12 happyReduction_12 (_ `HappyStk` (HappyAbsSyn18 happy_var_2) `HappyStk` _ `HappyStk` happyRest) = happyThen ( let (Id i) = happy_var_2 in addIfaceTypedef i >>= \ v -> return (Forward v) ) (\r -> happyReturn (HappyAbsSyn9 r)) happyReduce_13 = happySpecReduce_2 9# happyReduction_13 happyReduction_13 _ (HappyAbsSyn9 happy_var_1) = HappyAbsSyn9 (happy_var_1 ) happyReduction_13 _ _ = notHappyAtAll happyReduce_14 = happySpecReduce_2 9# happyReduction_14 happyReduction_14 _ (HappyAbsSyn9 happy_var_1) = HappyAbsSyn9 (happy_var_1 ) happyReduction_14 _ _ = notHappyAtAll happyReduce_15 = happySpecReduce_2 9# happyReduction_15 happyReduction_15 _ (HappyAbsSyn9 happy_var_1) = HappyAbsSyn9 (happy_var_1 ) happyReduction_15 _ _ = notHappyAtAll happyReduce_16 = happySpecReduce_1 9# happyReduction_16 happyReduction_16 (HappyAbsSyn9 happy_var_1) = HappyAbsSyn9 (happy_var_1 ) happyReduction_16 _ = notHappyAtAll happyReduce_17 = happySpecReduce_2 9# happyReduction_17 happyReduction_17 _ (HappyAbsSyn9 happy_var_1) = HappyAbsSyn9 (happy_var_1 ) happyReduction_17 _ _ = notHappyAtAll happyReduce_18 = happySpecReduce_1 9# happyReduction_18 happyReduction_18 (HappyAbsSyn9 happy_var_1) = HappyAbsSyn9 (happy_var_1 ) happyReduction_18 _ = notHappyAtAll happyReduce_19 = happySpecReduce_2 10# happyReduction_19 happyReduction_19 (HappyAbsSyn9 happy_var_2) (HappyAbsSyn16 happy_var_1) = HappyAbsSyn9 (Attributed happy_var_1 happy_var_2 ) happyReduction_19 _ _ = notHappyAtAll happyReduce_20 = happySpecReduce_1 10# happyReduction_20 happyReduction_20 (HappyAbsSyn9 happy_var_1) = HappyAbsSyn9 (happy_var_1 ) happyReduction_20 _ = notHappyAtAll happyReduce_21 = happySpecReduce_1 11# happyReduction_21 happyReduction_21 (HappyAbsSyn9 happy_var_1) = HappyAbsSyn9 (happy_var_1 ) happyReduction_21 _ = notHappyAtAll happyReduce_22 = happySpecReduce_2 11# happyReduction_22 happyReduction_22 (HappyAbsSyn18 happy_var_2) _ = HappyAbsSyn9 (Forward happy_var_2 ) happyReduction_22 _ _ = notHappyAtAll happyReduce_23 = happyReduce 6# 11# happyReduction_23 happyReduction_23 (_ `HappyStk` _ `HappyStk` (HappyAbsSyn5 happy_var_4) `HappyStk` _ `HappyStk` (HappyAbsSyn18 happy_var_2) `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn9 (Module happy_var_2 (reverse happy_var_4) ) `HappyStk` happyRest happyReduce_24 = happySpecReduce_1 11# happyReduction_24 happyReduction_24 (HappyAbsSyn9 happy_var_1) = HappyAbsSyn9 (happy_var_1 ) happyReduction_24 _ = notHappyAtAll happyReduce_25 = happyMonadReduce 6# 11# happyReduction_25 happyReduction_25 (_ `HappyStk` _ `HappyStk` (HappyAbsSyn14 happy_var_4) `HappyStk` _ `HappyStk` (HappyAbsSyn18 happy_var_2) `HappyStk` _ `HappyStk` happyRest) = happyThen ( let (Id i) = happy_var_2 in addIfaceTypedef i >>= \ v -> return (CoClass v (reverse happy_var_4)) ) (\r -> happyReturn (HappyAbsSyn9 r)) happyReduce_26 = happyReduce 6# 11# happyReduction_26 happyReduction_26 (_ `HappyStk` _ `HappyStk` (HappyAbsSyn14 happy_var_4) `HappyStk` _ `HappyStk` (HappyTerminal (T_type happy_var_2)) `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn9 (CoClass (Id happy_var_2) (reverse happy_var_4) ) `HappyStk` happyRest happyReduce_27 = happyReduce 5# 11# happyReduction_27 happyReduction_27 (_ `HappyStk` (HappyAbsSyn5 happy_var_4) `HappyStk` _ `HappyStk` (HappyAbsSyn18 happy_var_2) `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn9 (Library happy_var_2 (reverse happy_var_4) ) `HappyStk` happyRest happyReduce_28 = happySpecReduce_1 11# happyReduction_28 happyReduction_28 (HappyAbsSyn9 happy_var_1) = HappyAbsSyn9 (happy_var_1 ) happyReduction_28 _ = notHappyAtAll happyReduce_29 = happyMonadReduce 9# 12# happyReduction_29 happyReduction_29 (_ `HappyStk` (HappyAbsSyn5 happy_var_8) `HappyStk` _ `HappyStk` _ `HappyStk` (HappyAbsSyn13 happy_var_5) `HappyStk` _ `HappyStk` _ `HappyStk` _ `HappyStk` (HappyAbsSyn18 happy_var_1) `HappyStk` happyRest) = happyThen ( let (Id i) = happy_var_1 in addIfaceTypedef i >>= \ v -> return (DispInterface v happy_var_5 (reverse happy_var_8)) ) (\r -> happyReturn (HappyAbsSyn9 r)) happyReduce_30 = happyMonadReduce 6# 12# happyReduction_30 happyReduction_30 (_ `HappyStk` _ `HappyStk` (HappyAbsSyn18 happy_var_4) `HappyStk` _ `HappyStk` _ `HappyStk` (HappyAbsSyn18 happy_var_1) `HappyStk` happyRest) = happyThen ( let (Id i) = happy_var_1 in addIfaceTypedef i >>= \ v -> return (DispInterfaceDecl v happy_var_4) ) (\r -> happyReturn (HappyAbsSyn9 r)) happyReduce_31 = happySpecReduce_0 13# happyReduction_31 happyReduction_31 = HappyAbsSyn13 ([] ) happyReduce_32 = happyReduce 5# 13# happyReduction_32 happyReduction_32 (_ `HappyStk` (HappyAbsSyn18 happy_var_4) `HappyStk` (HappyAbsSyn30 happy_var_3) `HappyStk` (HappyAbsSyn16 happy_var_2) `HappyStk` (HappyAbsSyn13 happy_var_1) `HappyStk` happyRest) = HappyAbsSyn13 ((happy_var_2,happy_var_3,happy_var_4):happy_var_1 ) `HappyStk` happyRest happyReduce_33 = happySpecReduce_1 14# happyReduction_33 happyReduction_33 (HappyAbsSyn15 happy_var_1) = HappyAbsSyn14 ([happy_var_1] ) happyReduction_33 _ = notHappyAtAll happyReduce_34 = happySpecReduce_3 14# happyReduction_34 happyReduction_34 (HappyAbsSyn15 happy_var_3) _ (HappyAbsSyn14 happy_var_1) = HappyAbsSyn14 (happy_var_3 : happy_var_1 ) happyReduction_34 _ _ _ = notHappyAtAll happyReduce_35 = happySpecReduce_3 15# happyReduction_35 happyReduction_35 (HappyTerminal (T_type happy_var_3)) _ (HappyAbsSyn16 happy_var_1) = HappyAbsSyn15 ((True, Id happy_var_3, happy_var_1) ) happyReduction_35 _ _ _ = notHappyAtAll happyReduce_36 = happySpecReduce_3 15# happyReduction_36 happyReduction_36 (HappyTerminal (T_type happy_var_3)) _ (HappyAbsSyn16 happy_var_1) = HappyAbsSyn15 ((False, Id happy_var_3, happy_var_1) ) happyReduction_36 _ _ _ = notHappyAtAll happyReduce_37 = happySpecReduce_3 15# happyReduction_37 happyReduction_37 (HappyAbsSyn18 happy_var_3) _ (HappyAbsSyn16 happy_var_1) = HappyAbsSyn15 ((True, happy_var_3, happy_var_1) ) happyReduction_37 _ _ _ = notHappyAtAll happyReduce_38 = happySpecReduce_3 15# happyReduction_38 happyReduction_38 (HappyAbsSyn18 happy_var_3) _ (HappyAbsSyn16 happy_var_1) = HappyAbsSyn15 ((False, happy_var_3, happy_var_1) ) happyReduction_38 _ _ _ = notHappyAtAll happyReduce_39 = happySpecReduce_0 16# happyReduction_39 happyReduction_39 = HappyAbsSyn16 ([] ) happyReduce_40 = happySpecReduce_3 16# happyReduction_40 happyReduction_40 _ (HappyAbsSyn16 happy_var_2) _ = HappyAbsSyn16 (happy_var_2 ) happyReduction_40 _ _ _ = notHappyAtAll happyReduce_41 = happySpecReduce_1 17# happyReduction_41 happyReduction_41 (HappyAbsSyn18 happy_var_1) = HappyAbsSyn9 (Forward happy_var_1 ) happyReduction_41 _ = notHappyAtAll happyReduce_42 = happyReduce 5# 17# happyReduction_42 happyReduction_42 (_ `HappyStk` (HappyAbsSyn5 happy_var_4) `HappyStk` _ `HappyStk` (HappyAbsSyn25 happy_var_2) `HappyStk` (HappyAbsSyn18 happy_var_1) `HappyStk` happyRest) = HappyAbsSyn9 (Interface happy_var_1 happy_var_2 (reverse happy_var_4) ) `HappyStk` happyRest happyReduce_43 = happyMonadReduce 2# 18# happyReduction_43 happyReduction_43 ((HappyAbsSyn18 happy_var_2) `HappyStk` _ `HappyStk` happyRest) = happyThen ( let (Id i) = happy_var_2 in addIfaceTypedef i >>= return ) (\r -> happyReturn (HappyAbsSyn18 r)) happyReduce_44 = happySpecReduce_2 18# happyReduction_44 happyReduction_44 (HappyTerminal (T_type happy_var_2)) _ = HappyAbsSyn18 ((Id happy_var_2) ) happyReduction_44 _ _ = notHappyAtAll happyReduce_45 = happySpecReduce_2 18# happyReduction_45 happyReduction_45 _ _ = HappyAbsSyn18 ((Id "Object") ) happyReduce_46 = happyMonadReduce 2# 19# happyReduction_46 happyReduction_46 ((HappyAbsSyn18 happy_var_2) `HappyStk` _ `HappyStk` happyRest) = happyThen ( let (Id i) = happy_var_2 in addIfaceTypedef i >>= return ) (\r -> happyReturn (HappyAbsSyn18 r)) happyReduce_47 = happySpecReduce_2 19# happyReduction_47 happyReduction_47 (HappyTerminal (T_type happy_var_2)) _ = HappyAbsSyn18 ((Id happy_var_2) ) happyReduction_47 _ _ = notHappyAtAll happyReduce_48 = happyReduce 4# 20# happyReduction_48 happyReduction_48 (_ `HappyStk` (HappyTerminal (T_string_lit happy_var_3)) `HappyStk` _ `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn9 (CppQuote happy_var_3 ) `HappyStk` happyRest happyReduce_49 = happyReduce 4# 21# happyReduction_49 happyReduction_49 (_ `HappyStk` (HappyTerminal (T_string_lit happy_var_3)) `HappyStk` _ `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn9 (HsQuote happy_var_3 ) `HappyStk` happyRest happyReduce_50 = happySpecReduce_1 21# happyReduction_50 happyReduction_50 (HappyTerminal (T_include happy_var_1)) = HappyAbsSyn9 (CInclude happy_var_1 ) happyReduction_50 _ = notHappyAtAll happyReduce_51 = happySpecReduce_0 22# happyReduction_51 happyReduction_51 = HappyAbsSyn5 ([] ) happyReduce_52 = happySpecReduce_2 22# happyReduction_52 happyReduction_52 (HappyAbsSyn9 happy_var_2) (HappyAbsSyn5 happy_var_1) = HappyAbsSyn5 (happy_var_2 : happy_var_1 ) happyReduction_52 _ _ = notHappyAtAll happyReduce_53 = happySpecReduce_2 23# happyReduction_53 happyReduction_53 _ (HappyAbsSyn9 happy_var_1) = HappyAbsSyn9 (happy_var_1 ) happyReduction_53 _ _ = notHappyAtAll happyReduce_54 = happySpecReduce_2 23# happyReduction_54 happyReduction_54 _ (HappyAbsSyn9 happy_var_1) = HappyAbsSyn9 (happy_var_1 ) happyReduction_54 _ _ = notHappyAtAll happyReduce_55 = happySpecReduce_2 23# happyReduction_55 happyReduction_55 _ (HappyAbsSyn9 happy_var_1) = HappyAbsSyn9 (happy_var_1 ) happyReduction_55 _ _ = notHappyAtAll happyReduce_56 = happySpecReduce_2 23# happyReduction_56 happyReduction_56 _ (HappyAbsSyn9 happy_var_1) = HappyAbsSyn9 (happy_var_1 ) happyReduction_56 _ _ = notHappyAtAll happyReduce_57 = happySpecReduce_2 23# happyReduction_57 happyReduction_57 _ (HappyAbsSyn9 happy_var_1) = HappyAbsSyn9 (happy_var_1 ) happyReduction_57 _ _ = notHappyAtAll happyReduce_58 = happySpecReduce_2 24# happyReduction_58 happyReduction_58 (HappyAbsSyn9 happy_var_2) (HappyAbsSyn16 happy_var_1) = HappyAbsSyn9 (Attributed happy_var_1 happy_var_2 ) happyReduction_58 _ _ = notHappyAtAll happyReduce_59 = happySpecReduce_1 24# happyReduction_59 happyReduction_59 (HappyAbsSyn9 happy_var_1) = HappyAbsSyn9 (happy_var_1 ) happyReduction_59 _ = notHappyAtAll happyReduce_60 = happySpecReduce_0 25# happyReduction_60 happyReduction_60 = HappyAbsSyn25 ([] ) happyReduce_61 = happySpecReduce_2 25# happyReduction_61 happyReduction_61 (HappyTerminal (T_type happy_var_2)) _ = HappyAbsSyn25 ([ happy_var_2 ] ) happyReduction_61 _ _ = notHappyAtAll happyReduce_62 = happySpecReduce_2 25# happyReduction_62 happyReduction_62 (HappyAbsSyn18 happy_var_2) _ = HappyAbsSyn25 (let (Id i) = happy_var_2 in [ i ] ) happyReduction_62 _ _ = notHappyAtAll happyReduce_63 = happyMonadReduce 2# 26# happyReduction_63 happyReduction_63 ((HappyAbsSyn29 happy_var_2) `HappyStk` _ `HappyStk` happyRest) = happyThen ( slurpImports (parseIDL >>= \ (Left y) -> return y) happy_var_2 ) (\r -> happyReturn (HappyAbsSyn9 r)) happyReduce_64 = happyMonadReduce 4# 26# happyReduction_64 happyReduction_64 (_ `HappyStk` (HappyTerminal (T_string_lit happy_var_3)) `HappyStk` _ `HappyStk` _ `HappyStk` happyRest) = happyThen ( handleImportLib (parseIDL >>= \ (Left y) -> return y) happy_var_3 ) (\r -> happyReturn (HappyAbsSyn9 r)) happyReduce_65 = happySpecReduce_1 27# happyReduction_65 happyReduction_65 (HappyTerminal (T_pragma happy_var_1)) = HappyAbsSyn9 (Pragma happy_var_1 ) happyReduction_65 _ = notHappyAtAll happyReduce_66 = happySpecReduce_1 27# happyReduction_66 happyReduction_66 (HappyTerminal (T_include_start happy_var_1)) = HappyAbsSyn9 (IncludeStart happy_var_1 ) happyReduction_66 _ = notHappyAtAll happyReduce_67 = happySpecReduce_1 27# happyReduction_67 happyReduction_67 _ = HappyAbsSyn9 (IncludeEnd ) happyReduce_68 = happySpecReduce_3 28# happyReduction_68 happyReduction_68 (HappyAbsSyn34 happy_var_3) (HappyTerminal (T_id happy_var_2)) _ = HappyAbsSyn9 (Constant (Id happy_var_2) [] (exprType (TyInteger Natural) happy_var_3) happy_var_3 ) happyReduction_68 _ _ _ = notHappyAtAll happyReduce_69 = happySpecReduce_1 29# happyReduction_69 happyReduction_69 (HappyTerminal (T_string_lit happy_var_1)) = HappyAbsSyn29 ([ happy_var_1 ] ) happyReduction_69 _ = notHappyAtAll happyReduce_70 = happySpecReduce_3 29# happyReduction_70 happyReduction_70 (HappyAbsSyn29 happy_var_3) _ (HappyTerminal (T_string_lit happy_var_1)) = HappyAbsSyn29 ((happy_var_1 : happy_var_3) ) happyReduction_70 _ _ _ = notHappyAtAll happyReduce_71 = happySpecReduce_1 30# happyReduction_71 happyReduction_71 (HappyAbsSyn30 happy_var_1) = HappyAbsSyn30 (happy_var_1 ) happyReduction_71 _ = notHappyAtAll happyReduce_72 = happySpecReduce_1 30# happyReduction_72 happyReduction_72 _ = HappyAbsSyn30 (TyChar ) happyReduce_73 = happySpecReduce_1 30# happyReduction_73 happyReduction_73 _ = HappyAbsSyn30 (TyWChar ) happyReduce_74 = happySpecReduce_1 30# happyReduction_74 happyReduction_74 (HappyTerminal (T_float happy_var_1)) = HappyAbsSyn30 (TyFloat happy_var_1 ) happyReduction_74 _ = notHappyAtAll happyReduce_75 = happySpecReduce_1 30# happyReduction_75 happyReduction_75 _ = HappyAbsSyn30 (TyVoid ) happyReduce_76 = happySpecReduce_2 30# happyReduction_76 happyReduction_76 _ _ = HappyAbsSyn30 (TyPointer TyVoid ) happyReduce_77 = happySpecReduce_2 30# happyReduction_77 happyReduction_77 _ _ = HappyAbsSyn30 (TyString Nothing ) happyReduce_78 = happySpecReduce_2 30# happyReduction_78 happyReduction_78 _ _ = HappyAbsSyn30 (TyWString Nothing ) happyReduce_79 = happySpecReduce_1 30# happyReduction_79 happyReduction_79 (HappyAbsSyn30 happy_var_1) = HappyAbsSyn30 (happy_var_1 ) happyReduction_79 _ = notHappyAtAll happyReduce_80 = happySpecReduce_3 30# happyReduction_80 happyReduction_80 _ _ (HappyAbsSyn30 happy_var_1) = HappyAbsSyn30 (TyArray happy_var_1 [] ) happyReduction_80 _ _ _ = notHappyAtAll happyReduce_81 = happySpecReduce_1 30# happyReduction_81 happyReduction_81 _ = HappyAbsSyn30 (TySigned True ) happyReduce_82 = happySpecReduce_1 30# happyReduction_82 happyReduction_82 _ = HappyAbsSyn30 (TySigned False ) happyReduce_83 = happySpecReduce_2 30# happyReduction_83 happyReduction_83 (HappyAbsSyn30 happy_var_2) _ = HappyAbsSyn30 (TyApply (TySigned False) happy_var_2 ) happyReduction_83 _ _ = notHappyAtAll happyReduce_84 = happySpecReduce_2 30# happyReduction_84 happyReduction_84 (HappyAbsSyn30 happy_var_2) _ = HappyAbsSyn30 (TyApply (TySigned True) happy_var_2 ) happyReduction_84 _ _ = notHappyAtAll happyReduce_85 = happySpecReduce_2 30# happyReduction_85 happyReduction_85 _ _ = HappyAbsSyn30 (TyApply (TySigned False) TyChar ) happyReduce_86 = happySpecReduce_3 30# happyReduction_86 happyReduction_86 _ _ (HappyAbsSyn30 happy_var_1) = HappyAbsSyn30 (TyApply (TySigned True) happy_var_1 ) happyReduction_86 _ _ _ = notHappyAtAll happyReduce_87 = happySpecReduce_3 30# happyReduction_87 happyReduction_87 _ _ (HappyAbsSyn30 happy_var_1) = HappyAbsSyn30 (TyApply (TySigned False) happy_var_1 ) happyReduction_87 _ _ _ = notHappyAtAll happyReduce_88 = happySpecReduce_2 30# happyReduction_88 happyReduction_88 _ _ = HappyAbsSyn30 (TyApply (TySigned True) TyChar ) happyReduce_89 = happySpecReduce_1 30# happyReduction_89 happyReduction_89 (HappyTerminal (T_id happy_var_1)) = HappyAbsSyn30 (TyName happy_var_1 Nothing ) happyReduction_89 _ = notHappyAtAll happyReduce_90 = happySpecReduce_1 30# happyReduction_90 happyReduction_90 (HappyTerminal (T_type happy_var_1)) = HappyAbsSyn30 (TyName happy_var_1 Nothing ) happyReduction_90 _ = notHappyAtAll happyReduce_91 = happySpecReduce_2 30# happyReduction_91 happyReduction_91 _ (HappyTerminal (T_type happy_var_1)) = HappyAbsSyn30 (TyPointer (TyName happy_var_1 Nothing) ) happyReduction_91 _ _ = notHappyAtAll happyReduce_92 = happySpecReduce_1 30# happyReduction_92 happyReduction_92 (HappyTerminal (T_idl_type happy_var_1)) = HappyAbsSyn30 (happy_var_1 ) happyReduction_92 _ = notHappyAtAll happyReduce_93 = happyMonadReduce 1# 30# happyReduction_93 happyReduction_93 (_ `HappyStk` happyRest) = happyThen ( dumpErrMsg >> return TyVoid ) (\r -> happyReturn (HappyAbsSyn30 r)) happyReduce_94 = happySpecReduce_1 31# happyReduction_94 happyReduction_94 _ = HappyAbsSyn30 (TyInteger Short ) happyReduce_95 = happySpecReduce_1 31# happyReduction_95 happyReduction_95 _ = HappyAbsSyn30 (TyInteger Long ) happyReduce_96 = happySpecReduce_2 31# happyReduction_96 happyReduction_96 _ _ = HappyAbsSyn30 (TyInteger LongLong ) happyReduce_97 = happySpecReduce_1 31# happyReduction_97 happyReduction_97 _ = HappyAbsSyn30 (TyInteger LongLong ) happyReduce_98 = happySpecReduce_1 31# happyReduction_98 happyReduction_98 _ = HappyAbsSyn30 (TyApply (TySigned False) (TyInteger LongLong) ) happyReduce_99 = happySpecReduce_1 32# happyReduction_99 happyReduction_99 (HappyAbsSyn30 happy_var_1) = HappyAbsSyn30 (happy_var_1 ) happyReduction_99 _ = notHappyAtAll happyReduce_100 = happySpecReduce_2 32# happyReduction_100 happyReduction_100 _ (HappyAbsSyn30 happy_var_1) = HappyAbsSyn30 (happy_var_1 ) happyReduction_100 _ _ = notHappyAtAll happyReduce_101 = happySpecReduce_1 32# happyReduction_101 happyReduction_101 _ = HappyAbsSyn30 (TyInteger Natural ) happyReduce_102 = happySpecReduce_1 33# happyReduction_102 happyReduction_102 (HappyAbsSyn30 happy_var_1) = HappyAbsSyn30 (happy_var_1 ) happyReduction_102 _ = notHappyAtAll happyReduce_103 = happySpecReduce_1 33# happyReduction_103 happyReduction_103 _ = HappyAbsSyn30 (TyChar ) happyReduce_104 = happySpecReduce_1 33# happyReduction_104 happyReduction_104 _ = HappyAbsSyn30 (TyWChar ) happyReduce_105 = happySpecReduce_1 33# happyReduction_105 happyReduction_105 (HappyTerminal (T_float happy_var_1)) = HappyAbsSyn30 (TyFloat happy_var_1 ) happyReduction_105 _ = notHappyAtAll happyReduce_106 = happySpecReduce_1 33# happyReduction_106 happyReduction_106 _ = HappyAbsSyn30 (TyVoid ) happyReduce_107 = happySpecReduce_1 33# happyReduction_107 happyReduction_107 (HappyAbsSyn30 happy_var_1) = HappyAbsSyn30 (happy_var_1 ) happyReduction_107 _ = notHappyAtAll happyReduce_108 = happySpecReduce_3 33# happyReduction_108 happyReduction_108 _ _ (HappyAbsSyn30 happy_var_1) = HappyAbsSyn30 (TyArray happy_var_1 [] ) happyReduction_108 _ _ _ = notHappyAtAll happyReduce_109 = happySpecReduce_1 33# happyReduction_109 happyReduction_109 _ = HappyAbsSyn30 (TySigned True ) happyReduce_110 = happySpecReduce_1 33# happyReduction_110 happyReduction_110 _ = HappyAbsSyn30 (TySigned False ) happyReduce_111 = happySpecReduce_2 33# happyReduction_111 happyReduction_111 (HappyAbsSyn30 happy_var_2) _ = HappyAbsSyn30 (TyApply (TySigned False) happy_var_2 ) happyReduction_111 _ _ = notHappyAtAll happyReduce_112 = happySpecReduce_2 33# happyReduction_112 happyReduction_112 (HappyAbsSyn30 happy_var_2) _ = HappyAbsSyn30 (TyApply (TySigned True) happy_var_2 ) happyReduction_112 _ _ = notHappyAtAll happyReduce_113 = happySpecReduce_3 33# happyReduction_113 happyReduction_113 _ _ (HappyAbsSyn30 happy_var_1) = HappyAbsSyn30 (TyApply (TySigned False) happy_var_1 ) happyReduction_113 _ _ _ = notHappyAtAll happyReduce_114 = happySpecReduce_3 33# happyReduction_114 happyReduction_114 _ _ (HappyAbsSyn30 happy_var_1) = HappyAbsSyn30 (TyApply (TySigned True) happy_var_1 ) happyReduction_114 _ _ _ = notHappyAtAll happyReduce_115 = happySpecReduce_2 33# happyReduction_115 happyReduction_115 _ _ = HappyAbsSyn30 (TyApply (TySigned False) TyChar ) happyReduce_116 = happySpecReduce_2 33# happyReduction_116 happyReduction_116 _ _ = HappyAbsSyn30 (TyApply (TySigned True) TyChar ) happyReduce_117 = happySpecReduce_1 33# happyReduction_117 happyReduction_117 (HappyTerminal (T_type happy_var_1)) = HappyAbsSyn30 (TyName happy_var_1 Nothing ) happyReduction_117 _ = notHappyAtAll happyReduce_118 = happySpecReduce_2 33# happyReduction_118 happyReduction_118 _ _ = HappyAbsSyn30 (TyPointer TyVoid ) happyReduce_119 = happySpecReduce_1 33# happyReduction_119 happyReduction_119 (HappyTerminal (T_idl_type happy_var_1)) = HappyAbsSyn30 (happy_var_1 ) happyReduction_119 _ = notHappyAtAll happyReduce_120 = happyMonadReduce 1# 33# happyReduction_120 happyReduction_120 (_ `HappyStk` happyRest) = happyThen ( dumpErrMsg >> return TyVoid ) (\r -> happyReturn (HappyAbsSyn30 r)) happyReduce_121 = happySpecReduce_1 34# happyReduction_121 happyReduction_121 (HappyAbsSyn34 happy_var_1) = HappyAbsSyn34 (happy_var_1 ) happyReduction_121 _ = notHappyAtAll happyReduce_122 = happySpecReduce_1 35# happyReduction_122 happyReduction_122 (HappyAbsSyn34 happy_var_1) = HappyAbsSyn34 (happy_var_1 ) happyReduction_122 _ = notHappyAtAll happyReduce_123 = happyReduce 5# 35# happyReduction_123 happyReduction_123 ((HappyAbsSyn34 happy_var_5) `HappyStk` _ `HappyStk` (HappyAbsSyn34 happy_var_3) `HappyStk` _ `HappyStk` (HappyAbsSyn34 happy_var_1) `HappyStk` happyRest) = HappyAbsSyn34 (Cond happy_var_1 happy_var_3 happy_var_5 ) `HappyStk` happyRest happyReduce_124 = happySpecReduce_1 36# happyReduction_124 happyReduction_124 (HappyAbsSyn34 happy_var_1) = HappyAbsSyn34 (happy_var_1 ) happyReduction_124 _ = notHappyAtAll happyReduce_125 = happySpecReduce_3 36# happyReduction_125 happyReduction_125 (HappyAbsSyn34 happy_var_3) _ (HappyAbsSyn34 happy_var_1) = HappyAbsSyn34 (Binary LogOr happy_var_1 happy_var_3 ) happyReduction_125 _ _ _ = notHappyAtAll happyReduce_126 = happySpecReduce_1 37# happyReduction_126 happyReduction_126 (HappyAbsSyn34 happy_var_1) = HappyAbsSyn34 (happy_var_1 ) happyReduction_126 _ = notHappyAtAll happyReduce_127 = happySpecReduce_3 37# happyReduction_127 happyReduction_127 (HappyAbsSyn34 happy_var_3) _ (HappyAbsSyn34 happy_var_1) = HappyAbsSyn34 (Binary LogAnd happy_var_1 happy_var_3 ) happyReduction_127 _ _ _ = notHappyAtAll happyReduce_128 = happySpecReduce_1 38# happyReduction_128 happyReduction_128 (HappyAbsSyn34 happy_var_1) = HappyAbsSyn34 (happy_var_1 ) happyReduction_128 _ = notHappyAtAll happyReduce_129 = happySpecReduce_3 38# happyReduction_129 happyReduction_129 (HappyAbsSyn34 happy_var_3) _ (HappyAbsSyn34 happy_var_1) = HappyAbsSyn34 (Binary Or happy_var_1 happy_var_3 ) happyReduction_129 _ _ _ = notHappyAtAll happyReduce_130 = happySpecReduce_1 39# happyReduction_130 happyReduction_130 (HappyAbsSyn34 happy_var_1) = HappyAbsSyn34 (happy_var_1 ) happyReduction_130 _ = notHappyAtAll happyReduce_131 = happySpecReduce_3 39# happyReduction_131 happyReduction_131 (HappyAbsSyn34 happy_var_3) _ (HappyAbsSyn34 happy_var_1) = HappyAbsSyn34 (Binary Xor happy_var_1 happy_var_3 ) happyReduction_131 _ _ _ = notHappyAtAll happyReduce_132 = happySpecReduce_1 40# happyReduction_132 happyReduction_132 (HappyAbsSyn34 happy_var_1) = HappyAbsSyn34 (happy_var_1 ) happyReduction_132 _ = notHappyAtAll happyReduce_133 = happySpecReduce_3 40# happyReduction_133 happyReduction_133 (HappyAbsSyn34 happy_var_3) _ (HappyAbsSyn34 happy_var_1) = HappyAbsSyn34 (Binary And happy_var_1 happy_var_3 ) happyReduction_133 _ _ _ = notHappyAtAll happyReduce_134 = happySpecReduce_1 41# happyReduction_134 happyReduction_134 (HappyAbsSyn34 happy_var_1) = HappyAbsSyn34 (happy_var_1 ) happyReduction_134 _ = notHappyAtAll happyReduce_135 = happySpecReduce_3 41# happyReduction_135 happyReduction_135 (HappyAbsSyn34 happy_var_3) _ (HappyAbsSyn34 happy_var_1) = HappyAbsSyn34 (Binary Eq happy_var_1 happy_var_3 ) happyReduction_135 _ _ _ = notHappyAtAll happyReduce_136 = happySpecReduce_1 42# happyReduction_136 happyReduction_136 _ = HappyAbsSyn42 (Eq ) happyReduce_137 = happySpecReduce_1 42# happyReduction_137 happyReduction_137 _ = HappyAbsSyn42 (Ne ) happyReduce_138 = happySpecReduce_1 43# happyReduction_138 happyReduction_138 (HappyAbsSyn34 happy_var_1) = HappyAbsSyn34 (happy_var_1 ) happyReduction_138 _ = notHappyAtAll happyReduce_139 = happySpecReduce_3 43# happyReduction_139 happyReduction_139 (HappyAbsSyn34 happy_var_3) _ (HappyAbsSyn34 happy_var_1) = HappyAbsSyn34 (Binary Lt happy_var_1 happy_var_3 ) happyReduction_139 _ _ _ = notHappyAtAll happyReduce_140 = happySpecReduce_3 43# happyReduction_140 happyReduction_140 (HappyAbsSyn34 happy_var_3) _ (HappyAbsSyn34 happy_var_1) = HappyAbsSyn34 (Binary Le happy_var_1 happy_var_3 ) happyReduction_140 _ _ _ = notHappyAtAll happyReduce_141 = happySpecReduce_3 43# happyReduction_141 happyReduction_141 (HappyAbsSyn34 happy_var_3) _ (HappyAbsSyn34 happy_var_1) = HappyAbsSyn34 (Binary Ge happy_var_1 happy_var_3 ) happyReduction_141 _ _ _ = notHappyAtAll happyReduce_142 = happySpecReduce_3 43# happyReduction_142 happyReduction_142 (HappyAbsSyn34 happy_var_3) _ (HappyAbsSyn34 happy_var_1) = HappyAbsSyn34 (Binary Gt happy_var_1 happy_var_3 ) happyReduction_142 _ _ _ = notHappyAtAll happyReduce_143 = happySpecReduce_1 44# happyReduction_143 happyReduction_143 (HappyAbsSyn34 happy_var_1) = HappyAbsSyn34 (happy_var_1 ) happyReduction_143 _ = notHappyAtAll happyReduce_144 = happySpecReduce_3 44# happyReduction_144 happyReduction_144 (HappyAbsSyn34 happy_var_3) (HappyTerminal (T_shift happy_var_2)) (HappyAbsSyn34 happy_var_1) = HappyAbsSyn34 (Binary (Shift happy_var_2) happy_var_1 happy_var_3 ) happyReduction_144 _ _ _ = notHappyAtAll happyReduce_145 = happySpecReduce_1 45# happyReduction_145 happyReduction_145 (HappyAbsSyn34 happy_var_1) = HappyAbsSyn34 (happy_var_1 ) happyReduction_145 _ = notHappyAtAll happyReduce_146 = happySpecReduce_3 45# happyReduction_146 happyReduction_146 (HappyAbsSyn34 happy_var_3) _ (HappyAbsSyn34 happy_var_1) = HappyAbsSyn34 (Binary Add happy_var_1 happy_var_3 ) happyReduction_146 _ _ _ = notHappyAtAll happyReduce_147 = happySpecReduce_3 45# happyReduction_147 happyReduction_147 (HappyAbsSyn34 happy_var_3) _ (HappyAbsSyn34 happy_var_1) = HappyAbsSyn34 (Binary Sub happy_var_1 happy_var_3 ) happyReduction_147 _ _ _ = notHappyAtAll happyReduce_148 = happySpecReduce_1 46# happyReduction_148 happyReduction_148 (HappyAbsSyn34 happy_var_1) = HappyAbsSyn34 (happy_var_1 ) happyReduction_148 _ = notHappyAtAll happyReduce_149 = happySpecReduce_3 46# happyReduction_149 happyReduction_149 (HappyAbsSyn34 happy_var_3) _ (HappyAbsSyn34 happy_var_1) = HappyAbsSyn34 (Binary Mul happy_var_1 happy_var_3 ) happyReduction_149 _ _ _ = notHappyAtAll happyReduce_150 = happySpecReduce_3 46# happyReduction_150 happyReduction_150 (HappyAbsSyn34 happy_var_3) _ (HappyAbsSyn34 happy_var_1) = HappyAbsSyn34 (Binary Div happy_var_1 happy_var_3 ) happyReduction_150 _ _ _ = notHappyAtAll happyReduce_151 = happySpecReduce_3 46# happyReduction_151 happyReduction_151 (HappyAbsSyn34 happy_var_3) _ (HappyAbsSyn34 happy_var_1) = HappyAbsSyn34 (Binary Mod happy_var_1 happy_var_3 ) happyReduction_151 _ _ _ = notHappyAtAll happyReduce_152 = happySpecReduce_1 47# happyReduction_152 happyReduction_152 (HappyAbsSyn34 happy_var_1) = HappyAbsSyn34 (happy_var_1 ) happyReduction_152 _ = notHappyAtAll happyReduce_153 = happyReduce 4# 47# happyReduction_153 happyReduction_153 ((HappyAbsSyn34 happy_var_4) `HappyStk` _ `HappyStk` (HappyAbsSyn30 happy_var_2) `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn34 (Cast happy_var_2 happy_var_4 ) `HappyStk` happyRest happyReduce_154 = happySpecReduce_1 48# happyReduction_154 happyReduction_154 (HappyAbsSyn34 happy_var_1) = HappyAbsSyn34 (happy_var_1 ) happyReduction_154 _ = notHappyAtAll happyReduce_155 = happyReduce 4# 48# happyReduction_155 happyReduction_155 (_ `HappyStk` (HappyAbsSyn30 happy_var_3) `HappyStk` _ `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn34 (Sizeof happy_var_3 ) `HappyStk` happyRest happyReduce_156 = happySpecReduce_2 48# happyReduction_156 happyReduction_156 (HappyAbsSyn34 happy_var_2) (HappyAbsSyn49 happy_var_1) = HappyAbsSyn34 (Unary happy_var_1 happy_var_2 ) happyReduction_156 _ _ = notHappyAtAll happyReduce_157 = happySpecReduce_1 49# happyReduction_157 happyReduction_157 _ = HappyAbsSyn49 (Minus ) happyReduce_158 = happySpecReduce_1 49# happyReduction_158 happyReduction_158 _ = HappyAbsSyn49 (Plus ) happyReduce_159 = happySpecReduce_1 49# happyReduction_159 happyReduction_159 _ = HappyAbsSyn49 (Not ) happyReduce_160 = happySpecReduce_1 49# happyReduction_160 happyReduction_160 _ = HappyAbsSyn49 (Negate ) happyReduce_161 = happySpecReduce_1 50# happyReduction_161 happyReduction_161 (HappyAbsSyn18 happy_var_1) = HappyAbsSyn34 (let (Id i) = happy_var_1 in Var i ) happyReduction_161 _ = notHappyAtAll happyReduce_162 = happySpecReduce_1 50# happyReduction_162 happyReduction_162 (HappyTerminal (T_literal happy_var_1)) = HappyAbsSyn34 (Lit happy_var_1 ) happyReduction_162 _ = notHappyAtAll happyReduce_163 = happySpecReduce_1 50# happyReduction_163 happyReduction_163 (HappyTerminal (T_string_lit happy_var_1)) = HappyAbsSyn34 (Lit (StringLit happy_var_1) ) happyReduction_163 _ = notHappyAtAll happyReduce_164 = happySpecReduce_3 50# happyReduction_164 happyReduction_164 _ (HappyAbsSyn34 happy_var_2) _ = HappyAbsSyn34 (happy_var_2 ) happyReduction_164 _ _ _ = notHappyAtAll happyReduce_165 = happyMonadReduce 6# 51# happyReduction_165 happyReduction_165 (_ `HappyStk` (HappyAbsSyn63 happy_var_5) `HappyStk` (HappyAbsSyn30 happy_var_4) `HappyStk` (HappyAbsSyn16 happy_var_3) `HappyStk` _ `HappyStk` _ `HappyStk` happyRest) = happyThen ( let decls = reverse happy_var_5 in addTypes decls >> return (Typedef happy_var_4 happy_var_3 decls) ) (\r -> happyReturn (HappyAbsSyn9 r)) happyReduce_166 = happySpecReduce_2 51# happyReduction_166 happyReduction_166 (HappyAbsSyn30 happy_var_2) (HappyAbsSyn16 happy_var_1) = HappyAbsSyn9 (Attributed happy_var_1 (TypeDecl happy_var_2) ) happyReduction_166 _ _ = notHappyAtAll happyReduce_167 = happySpecReduce_1 51# happyReduction_167 happyReduction_167 (HappyAbsSyn30 happy_var_1) = HappyAbsSyn9 (TypeDecl happy_var_1 ) happyReduction_167 _ = notHappyAtAll happyReduce_168 = happyReduce 6# 51# happyReduction_168 happyReduction_168 ((HappyAbsSyn34 happy_var_6) `HappyStk` _ `HappyStk` (HappyAbsSyn18 happy_var_4) `HappyStk` (HappyAbsSyn30 happy_var_3) `HappyStk` _ `HappyStk` (HappyAbsSyn16 happy_var_1) `HappyStk` happyRest) = HappyAbsSyn9 (Constant happy_var_4 happy_var_1 happy_var_3 happy_var_6 ) `HappyStk` happyRest happyReduce_169 = happyReduce 5# 51# happyReduction_169 happyReduction_169 ((HappyAbsSyn34 happy_var_5) `HappyStk` _ `HappyStk` (HappyAbsSyn18 happy_var_3) `HappyStk` (HappyAbsSyn30 happy_var_2) `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn9 (Constant happy_var_3 [] happy_var_2 happy_var_5 ) `HappyStk` happyRest happyReduce_170 = happyMonadReduce 6# 51# happyReduction_170 happyReduction_170 (_ `HappyStk` (HappyAbsSyn63 happy_var_5) `HappyStk` (HappyAbsSyn30 happy_var_4) `HappyStk` _ `HappyStk` _ `HappyStk` _ `HappyStk` happyRest) = happyThen ( let decls = reverse happy_var_5 in addTypes decls >> return (ExternDecl happy_var_4 decls) ) (\r -> happyReturn (HappyAbsSyn9 r)) happyReduce_171 = happySpecReduce_1 52# happyReduction_171 happyReduction_171 (HappyAbsSyn30 happy_var_1) = HappyAbsSyn30 (happy_var_1 ) happyReduction_171 _ = notHappyAtAll happyReduce_172 = happySpecReduce_3 52# happyReduction_172 happyReduction_172 _ _ (HappyAbsSyn30 happy_var_1) = HappyAbsSyn30 (TyArray happy_var_1 [] ) happyReduction_172 _ _ _ = notHappyAtAll happyReduce_173 = happyReduce 4# 52# happyReduction_173 happyReduction_173 (_ `HappyStk` (HappyAbsSyn34 happy_var_3) `HappyStk` _ `HappyStk` (HappyAbsSyn30 happy_var_1) `HappyStk` happyRest) = HappyAbsSyn30 (TyArray happy_var_1 [happy_var_3] ) `HappyStk` happyRest happyReduce_174 = happySpecReduce_2 52# happyReduction_174 happyReduction_174 (HappyAbsSyn54 happy_var_2) (HappyAbsSyn30 happy_var_1) = HappyAbsSyn30 (TyApply (TyQualifier happy_var_2) happy_var_1 ) happyReduction_174 _ _ = notHappyAtAll happyReduce_175 = happySpecReduce_2 52# happyReduction_175 happyReduction_175 (HappyAbsSyn30 happy_var_2) (HappyAbsSyn54 happy_var_1) = HappyAbsSyn30 (TyApply (TyQualifier happy_var_1) happy_var_2 ) happyReduction_175 _ _ = notHappyAtAll happyReduce_176 = happySpecReduce_1 53# happyReduction_176 happyReduction_176 (HappyAbsSyn30 happy_var_1) = HappyAbsSyn30 (happy_var_1 ) happyReduction_176 _ = notHappyAtAll happyReduce_177 = happySpecReduce_3 53# happyReduction_177 happyReduction_177 _ _ (HappyAbsSyn30 happy_var_1) = HappyAbsSyn30 (TyArray happy_var_1 [] ) happyReduction_177 _ _ _ = notHappyAtAll happyReduce_178 = happySpecReduce_2 53# happyReduction_178 happyReduction_178 (HappyAbsSyn54 happy_var_2) (HappyAbsSyn30 happy_var_1) = HappyAbsSyn30 (TyApply (TyQualifier happy_var_2) happy_var_1 ) happyReduction_178 _ _ = notHappyAtAll happyReduce_179 = happySpecReduce_1 54# happyReduction_179 happyReduction_179 _ = HappyAbsSyn54 (Const ) happyReduce_180 = happySpecReduce_1 54# happyReduction_180 happyReduction_180 _ = HappyAbsSyn54 (Volatile ) happyReduce_181 = happySpecReduce_1 55# happyReduction_181 happyReduction_181 (HappyTerminal (T_float happy_var_1)) = HappyAbsSyn30 (TyFloat happy_var_1 ) happyReduction_181 _ = notHappyAtAll happyReduce_182 = happySpecReduce_1 55# happyReduction_182 happyReduction_182 _ = HappyAbsSyn30 (TyChar ) happyReduce_183 = happySpecReduce_1 55# happyReduction_183 happyReduction_183 _ = HappyAbsSyn30 (TyWChar ) happyReduce_184 = happySpecReduce_1 55# happyReduction_184 happyReduction_184 (HappyAbsSyn30 happy_var_1) = HappyAbsSyn30 (happy_var_1 ) happyReduction_184 _ = notHappyAtAll happyReduce_185 = happySpecReduce_1 55# happyReduction_185 happyReduction_185 _ = HappyAbsSyn30 (TyVoid ) happyReduce_186 = happySpecReduce_1 55# happyReduction_186 happyReduction_186 _ = HappyAbsSyn30 (TySigned True ) happyReduce_187 = happySpecReduce_1 55# happyReduction_187 happyReduction_187 _ = HappyAbsSyn30 (TySigned False ) happyReduce_188 = happySpecReduce_2 55# happyReduction_188 happyReduction_188 (HappyAbsSyn30 happy_var_2) _ = HappyAbsSyn30 (TyApply (TySigned True) happy_var_2 ) happyReduction_188 _ _ = notHappyAtAll happyReduce_189 = happySpecReduce_3 55# happyReduction_189 happyReduction_189 (HappyAbsSyn30 happy_var_3) _ _ = HappyAbsSyn30 (TyApply (TySigned True) happy_var_3 ) happyReduction_189 _ _ _ = notHappyAtAll happyReduce_190 = happySpecReduce_2 55# happyReduction_190 happyReduction_190 (HappyAbsSyn30 happy_var_2) _ = HappyAbsSyn30 (TyApply (TySigned False) happy_var_2 ) happyReduction_190 _ _ = notHappyAtAll happyReduce_191 = happySpecReduce_3 55# happyReduction_191 happyReduction_191 (HappyAbsSyn30 happy_var_3) _ _ = HappyAbsSyn30 (TyApply (TySigned False) happy_var_3 ) happyReduction_191 _ _ _ = notHappyAtAll happyReduce_192 = happySpecReduce_3 55# happyReduction_192 happyReduction_192 _ _ (HappyAbsSyn30 happy_var_1) = HappyAbsSyn30 (TyApply (TySigned True) happy_var_1 ) happyReduction_192 _ _ _ = notHappyAtAll happyReduce_193 = happySpecReduce_3 55# happyReduction_193 happyReduction_193 _ _ (HappyAbsSyn30 happy_var_1) = HappyAbsSyn30 (TyApply (TySigned False) happy_var_1 ) happyReduction_193 _ _ _ = notHappyAtAll happyReduce_194 = happySpecReduce_1 55# happyReduction_194 happyReduction_194 (HappyTerminal (T_id happy_var_1)) = HappyAbsSyn30 (TyName happy_var_1 Nothing ) happyReduction_194 _ = notHappyAtAll happyReduce_195 = happySpecReduce_1 55# happyReduction_195 happyReduction_195 (HappyTerminal (T_type happy_var_1)) = HappyAbsSyn30 (TyName happy_var_1 Nothing ) happyReduction_195 _ = notHappyAtAll happyReduce_196 = happySpecReduce_1 55# happyReduction_196 happyReduction_196 (HappyTerminal (T_idl_type happy_var_1)) = HappyAbsSyn30 (happy_var_1 ) happyReduction_196 _ = notHappyAtAll happyReduce_197 = happySpecReduce_3 55# happyReduction_197 happyReduction_197 _ (HappyAbsSyn30 happy_var_2) _ = HappyAbsSyn30 (TySafeArray happy_var_2 ) happyReduction_197 _ _ _ = notHappyAtAll happyReduce_198 = happySpecReduce_1 55# happyReduction_198 happyReduction_198 (HappyAbsSyn30 happy_var_1) = HappyAbsSyn30 (happy_var_1 ) happyReduction_198 _ = notHappyAtAll happyReduce_199 = happySpecReduce_1 55# happyReduction_199 happyReduction_199 (HappyAbsSyn30 happy_var_1) = HappyAbsSyn30 (happy_var_1 ) happyReduction_199 _ = notHappyAtAll happyReduce_200 = happyMonadReduce 1# 55# happyReduction_200 happyReduction_200 (_ `HappyStk` happyRest) = happyThen ( dumpErrMsg >> return TyVoid ) (\r -> happyReturn (HappyAbsSyn30 r)) happyReduce_201 = happySpecReduce_1 56# happyReduction_201 happyReduction_201 (HappyAbsSyn30 happy_var_1) = HappyAbsSyn30 (happy_var_1 ) happyReduction_201 _ = notHappyAtAll happyReduce_202 = happySpecReduce_1 56# happyReduction_202 happyReduction_202 _ = HappyAbsSyn30 (TyChar ) happyReduce_203 = happySpecReduce_1 56# happyReduction_203 happyReduction_203 (HappyTerminal (T_float happy_var_1)) = HappyAbsSyn30 (TyFloat happy_var_1 ) happyReduction_203 _ = notHappyAtAll happyReduce_204 = happySpecReduce_1 56# happyReduction_204 happyReduction_204 (HappyTerminal (T_type happy_var_1)) = HappyAbsSyn30 (TyName happy_var_1 Nothing ) happyReduction_204 _ = notHappyAtAll happyReduce_205 = happySpecReduce_1 56# happyReduction_205 happyReduction_205 (HappyTerminal (T_idl_type happy_var_1)) = HappyAbsSyn30 (happy_var_1 ) happyReduction_205 _ = notHappyAtAll happyReduce_206 = happySpecReduce_1 57# happyReduction_206 happyReduction_206 (HappyAbsSyn30 happy_var_1) = HappyAbsSyn30 (happy_var_1 ) happyReduction_206 _ = notHappyAtAll happyReduce_207 = happySpecReduce_2 57# happyReduction_207 happyReduction_207 _ (HappyAbsSyn30 happy_var_1) = HappyAbsSyn30 (TyPointer happy_var_1 ) happyReduction_207 _ _ = notHappyAtAll happyReduce_208 = happySpecReduce_1 58# happyReduction_208 happyReduction_208 (HappyAbsSyn30 happy_var_1) = HappyAbsSyn30 (happy_var_1 ) happyReduction_208 _ = notHappyAtAll happyReduce_209 = happySpecReduce_1 58# happyReduction_209 happyReduction_209 (HappyAbsSyn30 happy_var_1) = HappyAbsSyn30 (happy_var_1 ) happyReduction_209 _ = notHappyAtAll happyReduce_210 = happySpecReduce_1 59# happyReduction_210 happyReduction_210 (HappyAbsSyn30 happy_var_1) = HappyAbsSyn30 (happy_var_1 ) happyReduction_210 _ = notHappyAtAll happyReduce_211 = happySpecReduce_1 59# happyReduction_211 happyReduction_211 (HappyAbsSyn30 happy_var_1) = HappyAbsSyn30 (happy_var_1 ) happyReduction_211 _ = notHappyAtAll happyReduce_212 = happyReduce 6# 60# happyReduction_212 happyReduction_212 ((HappyAbsSyn109 happy_var_6) `HappyStk` _ `HappyStk` (HappyAbsSyn73 happy_var_4) `HappyStk` _ `HappyStk` (HappyAbsSyn18 happy_var_2) `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn30 (TyStruct (Just happy_var_2) (reverse happy_var_4) (toPackedAttrib happy_var_6) ) `HappyStk` happyRest happyReduce_213 = happyReduce 5# 60# happyReduction_213 happyReduction_213 ((HappyAbsSyn109 happy_var_5) `HappyStk` _ `HappyStk` (HappyAbsSyn73 happy_var_3) `HappyStk` _ `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn30 (TyStruct Nothing (reverse happy_var_3) (toPackedAttrib happy_var_5) ) `HappyStk` happyRest happyReduce_214 = happySpecReduce_2 60# happyReduction_214 happyReduction_214 (HappyAbsSyn18 happy_var_2) _ = HappyAbsSyn30 (TyStruct (Just happy_var_2) [] Nothing ) happyReduction_214 _ _ = notHappyAtAll happyReduce_215 = happyReduce 11# 61# happyReduction_215 happyReduction_215 (_ `HappyStk` (HappyAbsSyn77 happy_var_10) `HappyStk` _ `HappyStk` (HappyAbsSyn75 happy_var_8) `HappyStk` _ `HappyStk` (HappyAbsSyn18 happy_var_6) `HappyStk` (HappyAbsSyn30 happy_var_5) `HappyStk` _ `HappyStk` _ `HappyStk` (HappyAbsSyn75 happy_var_2) `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn30 (TyUnion happy_var_2 happy_var_5 happy_var_6 happy_var_8 (reverse happy_var_10) ) `HappyStk` happyRest happyReduce_216 = happyReduce 6# 61# happyReduction_216 happyReduction_216 ((HappyAbsSyn109 happy_var_6) `HappyStk` _ `HappyStk` (HappyAbsSyn62 happy_var_4) `HappyStk` _ `HappyStk` (HappyAbsSyn75 happy_var_2) `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn30 (case happy_var_4 of { Left sw -> TyUnionNon happy_var_2 (reverse sw) ; Right mem -> TyCUnion happy_var_2 (reverse mem) (toPackedAttrib happy_var_6) } ) `HappyStk` happyRest happyReduce_217 = happySpecReduce_3 61# happyReduction_217 happyReduction_217 (HappyAbsSyn109 happy_var_3) (HappyAbsSyn18 happy_var_2) _ = HappyAbsSyn30 (TyCUnion (Just happy_var_2) [] (toPackedAttrib happy_var_3) ) happyReduction_217 _ _ _ = notHappyAtAll happyReduce_218 = happySpecReduce_1 62# happyReduction_218 happyReduction_218 (HappyAbsSyn77 happy_var_1) = HappyAbsSyn62 (Left happy_var_1 ) happyReduction_218 _ = notHappyAtAll happyReduce_219 = happySpecReduce_1 62# happyReduction_219 happyReduction_219 (HappyAbsSyn73 happy_var_1) = HappyAbsSyn62 (Right happy_var_1 ) happyReduction_219 _ = notHappyAtAll happyReduce_220 = happySpecReduce_1 63# happyReduction_220 happyReduction_220 (HappyAbsSyn18 happy_var_1) = HappyAbsSyn63 ([ happy_var_1 ] ) happyReduction_220 _ = notHappyAtAll happyReduce_221 = happySpecReduce_3 63# happyReduction_221 happyReduction_221 (HappyAbsSyn18 happy_var_3) _ (HappyAbsSyn63 happy_var_1) = HappyAbsSyn63 (happy_var_3 : happy_var_1 ) happyReduction_221 _ _ _ = notHappyAtAll happyReduce_222 = happySpecReduce_2 64# happyReduction_222 happyReduction_222 (HappyAbsSyn18 happy_var_2) (HappyAbsSyn65 happy_var_1) = HappyAbsSyn18 (happy_var_1 happy_var_2 ) happyReduction_222 _ _ = notHappyAtAll happyReduce_223 = happySpecReduce_1 64# happyReduction_223 happyReduction_223 (HappyAbsSyn18 happy_var_1) = HappyAbsSyn18 (happy_var_1 ) happyReduction_223 _ = notHappyAtAll happyReduce_224 = happySpecReduce_2 64# happyReduction_224 happyReduction_224 (HappyAbsSyn18 happy_var_2) (HappyAbsSyn65 happy_var_1) = HappyAbsSyn18 (happy_var_1 happy_var_2 ) happyReduction_224 _ _ = notHappyAtAll happyReduce_225 = happySpecReduce_1 64# happyReduction_225 happyReduction_225 (HappyAbsSyn18 happy_var_1) = HappyAbsSyn18 (happy_var_1 ) happyReduction_225 _ = notHappyAtAll happyReduce_226 = happySpecReduce_1 65# happyReduction_226 happyReduction_226 (HappyAbsSyn109 happy_var_1) = HappyAbsSyn65 (toCConvAttrib happy_var_1 ) happyReduction_226 _ = notHappyAtAll happyReduce_227 = happySpecReduce_1 65# happyReduction_227 happyReduction_227 (HappyTerminal (T_callconv happy_var_1)) = HappyAbsSyn65 (CConvId happy_var_1 ) happyReduction_227 _ = notHappyAtAll happyReduce_228 = happySpecReduce_1 66# happyReduction_228 happyReduction_228 (HappyAbsSyn18 happy_var_1) = HappyAbsSyn18 (happy_var_1 ) happyReduction_228 _ = notHappyAtAll happyReduce_229 = happySpecReduce_3 66# happyReduction_229 happyReduction_229 _ (HappyAbsSyn18 happy_var_2) _ = HappyAbsSyn18 (happy_var_2 ) happyReduction_229 _ _ _ = notHappyAtAll happyReduce_230 = happySpecReduce_1 66# happyReduction_230 happyReduction_230 (HappyAbsSyn18 happy_var_1) = HappyAbsSyn18 (happy_var_1 ) happyReduction_230 _ = notHappyAtAll happyReduce_231 = happySpecReduce_1 66# happyReduction_231 happyReduction_231 (HappyAbsSyn18 happy_var_1) = HappyAbsSyn18 (happy_var_1 ) happyReduction_231 _ = notHappyAtAll happyReduce_232 = happySpecReduce_1 67# happyReduction_232 happyReduction_232 (HappyAbsSyn18 happy_var_1) = HappyAbsSyn18 (happy_var_1 ) happyReduction_232 _ = notHappyAtAll happyReduce_233 = happySpecReduce_3 67# happyReduction_233 happyReduction_233 (HappyTerminal (T_literal happy_var_3)) _ (HappyAbsSyn18 happy_var_1) = HappyAbsSyn18 ((let { (Id nm) = happy_var_1 ; x = mkBitField nm happy_var_3 } in BitFieldId x happy_var_1) ) happyReduction_233 _ _ _ = notHappyAtAll happyReduce_234 = happySpecReduce_3 67# happyReduction_234 happyReduction_234 (HappyTerminal (T_literal happy_var_3)) _ (HappyTerminal (T_type happy_var_1)) = HappyAbsSyn18 ((let x = mkBitField happy_var_1 happy_var_3 in BitFieldId x (Id happy_var_1)) ) happyReduction_234 _ _ _ = notHappyAtAll happyReduce_235 = happySpecReduce_2 67# happyReduction_235 happyReduction_235 (HappyTerminal (T_literal happy_var_2)) _ = HappyAbsSyn18 ((let x = mkBitField "" happy_var_2 in BitFieldId x (Id "")) ) happyReduction_235 _ _ = notHappyAtAll happyReduce_236 = happySpecReduce_1 67# happyReduction_236 happyReduction_236 (HappyTerminal (T_type happy_var_1)) = HappyAbsSyn18 ((Id happy_var_1) ) happyReduction_236 _ = notHappyAtAll happyReduce_237 = happySpecReduce_1 67# happyReduction_237 happyReduction_237 (HappyTerminal (T_mode happy_var_1)) = HappyAbsSyn18 ((if happy_var_1 == In then Id "in" else Id "out") ) happyReduction_237 _ = notHappyAtAll happyReduce_238 = happySpecReduce_2 68# happyReduction_238 happyReduction_238 (HappyAbsSyn18 happy_var_2) (HappyAbsSyn71 happy_var_1) = HappyAbsSyn18 (Pointed happy_var_1 happy_var_2 ) happyReduction_238 _ _ = notHappyAtAll happyReduce_239 = happySpecReduce_3 68# happyReduction_239 happyReduction_239 (HappyAbsSyn18 happy_var_3) (HappyTerminal (T_callconv happy_var_2)) (HappyAbsSyn71 happy_var_1) = HappyAbsSyn18 (Pointed happy_var_1 (CConvId happy_var_2 happy_var_3) ) happyReduction_239 _ _ _ = notHappyAtAll happyReduce_240 = happySpecReduce_3 68# happyReduction_240 happyReduction_240 (HappyAbsSyn18 happy_var_3) (HappyAbsSyn109 happy_var_2) (HappyAbsSyn71 happy_var_1) = HappyAbsSyn18 (Pointed happy_var_1 (toCConvAttrib happy_var_2 happy_var_3) ) happyReduction_240 _ _ _ = notHappyAtAll happyReduce_241 = happySpecReduce_3 69# happyReduction_241 happyReduction_241 _ _ (HappyAbsSyn18 happy_var_1) = HappyAbsSyn18 (ArrayId happy_var_1 [] ) happyReduction_241 _ _ _ = notHappyAtAll happyReduce_242 = happyReduce 4# 69# happyReduction_242 happyReduction_242 (_ `HappyStk` _ `HappyStk` _ `HappyStk` (HappyAbsSyn18 happy_var_1) `HappyStk` happyRest) = HappyAbsSyn18 (ArrayId happy_var_1 [] ) `HappyStk` happyRest happyReduce_243 = happyReduce 4# 69# happyReduction_243 happyReduction_243 (_ `HappyStk` (HappyAbsSyn34 happy_var_3) `HappyStk` _ `HappyStk` (HappyAbsSyn18 happy_var_1) `HappyStk` happyRest) = HappyAbsSyn18 (ArrayId happy_var_1 [happy_var_3] ) `HappyStk` happyRest happyReduce_244 = happyReduce 7# 69# happyReduction_244 happyReduction_244 (_ `HappyStk` (HappyAbsSyn34 happy_var_6) `HappyStk` _ `HappyStk` _ `HappyStk` (HappyAbsSyn34 happy_var_3) `HappyStk` _ `HappyStk` (HappyAbsSyn18 happy_var_1) `HappyStk` happyRest) = HappyAbsSyn18 (ArrayId happy_var_1 [happy_var_3,happy_var_6] ) `HappyStk` happyRest happyReduce_245 = happyReduce 4# 70# happyReduction_245 happyReduction_245 (_ `HappyStk` (HappyAbsSyn106 happy_var_3) `HappyStk` _ `HappyStk` (HappyAbsSyn18 happy_var_1) `HappyStk` happyRest) = HappyAbsSyn18 (mkFunId happy_var_1 (reverse happy_var_3) ) `HappyStk` happyRest happyReduce_246 = happySpecReduce_3 70# happyReduction_246 happyReduction_246 _ _ (HappyAbsSyn18 happy_var_1) = HappyAbsSyn18 (mkFunId happy_var_1 [] ) happyReduction_246 _ _ _ = notHappyAtAll happyReduce_247 = happySpecReduce_1 71# happyReduction_247 happyReduction_247 _ = HappyAbsSyn71 ([[]] ) happyReduce_248 = happySpecReduce_2 71# happyReduction_248 happyReduction_248 (HappyAbsSyn72 happy_var_2) _ = HappyAbsSyn71 ([happy_var_2] ) happyReduction_248 _ _ = notHappyAtAll happyReduce_249 = happySpecReduce_2 71# happyReduction_249 happyReduction_249 (HappyAbsSyn71 happy_var_2) _ = HappyAbsSyn71 ([] : happy_var_2 ) happyReduction_249 _ _ = notHappyAtAll happyReduce_250 = happySpecReduce_3 71# happyReduction_250 happyReduction_250 (HappyAbsSyn71 happy_var_3) (HappyAbsSyn72 happy_var_2) _ = HappyAbsSyn71 (happy_var_2 : happy_var_3 ) happyReduction_250 _ _ _ = notHappyAtAll happyReduce_251 = happySpecReduce_1 72# happyReduction_251 happyReduction_251 (HappyAbsSyn54 happy_var_1) = HappyAbsSyn72 ([happy_var_1] ) happyReduction_251 _ = notHappyAtAll happyReduce_252 = happySpecReduce_2 72# happyReduction_252 happyReduction_252 (HappyAbsSyn54 happy_var_2) (HappyAbsSyn72 happy_var_1) = HappyAbsSyn72 (happy_var_2 : happy_var_1 ) happyReduction_252 _ _ = notHappyAtAll happyReduce_253 = happySpecReduce_3 73# happyReduction_253 happyReduction_253 _ _ (HappyAbsSyn74 happy_var_1) = HappyAbsSyn73 ([ happy_var_1 ] ) happyReduction_253 _ _ _ = notHappyAtAll happyReduce_254 = happyReduce 4# 73# happyReduction_254 happyReduction_254 (_ `HappyStk` _ `HappyStk` (HappyAbsSyn74 happy_var_2) `HappyStk` (HappyAbsSyn73 happy_var_1) `HappyStk` happyRest) = HappyAbsSyn73 (happy_var_2 : happy_var_1 ) `HappyStk` happyRest happyReduce_255 = happySpecReduce_3 74# happyReduction_255 happyReduction_255 (HappyAbsSyn63 happy_var_3) (HappyAbsSyn30 happy_var_2) (HappyAbsSyn16 happy_var_1) = HappyAbsSyn74 ((happy_var_2, happy_var_1, reverse happy_var_3) ) happyReduction_255 _ _ _ = notHappyAtAll happyReduce_256 = happySpecReduce_2 74# happyReduction_256 happyReduction_256 (HappyAbsSyn30 happy_var_2) (HappyAbsSyn16 happy_var_1) = HappyAbsSyn74 ((happy_var_2, happy_var_1, []) ) happyReduction_256 _ _ = notHappyAtAll happyReduce_257 = happySpecReduce_0 75# happyReduction_257 happyReduction_257 = HappyAbsSyn75 (Nothing ) happyReduce_258 = happySpecReduce_1 75# happyReduction_258 happyReduction_258 (HappyAbsSyn18 happy_var_1) = HappyAbsSyn75 (Just happy_var_1 ) happyReduction_258 _ = notHappyAtAll happyReduce_259 = happySpecReduce_1 76# happyReduction_259 happyReduction_259 (HappyAbsSyn30 happy_var_1) = HappyAbsSyn30 (happy_var_1 ) happyReduction_259 _ = notHappyAtAll happyReduce_260 = happySpecReduce_1 76# happyReduction_260 happyReduction_260 _ = HappyAbsSyn30 (TyChar ) happyReduce_261 = happySpecReduce_1 76# happyReduction_261 happyReduction_261 (HappyAbsSyn30 happy_var_1) = HappyAbsSyn30 (happy_var_1 ) happyReduction_261 _ = notHappyAtAll happyReduce_262 = happySpecReduce_1 76# happyReduction_262 happyReduction_262 (HappyAbsSyn30 happy_var_1) = HappyAbsSyn30 (happy_var_1 ) happyReduction_262 _ = notHappyAtAll happyReduce_263 = happySpecReduce_1 76# happyReduction_263 happyReduction_263 (HappyTerminal (T_id happy_var_1)) = HappyAbsSyn30 (TyName happy_var_1 Nothing ) happyReduction_263 _ = notHappyAtAll happyReduce_264 = happySpecReduce_1 76# happyReduction_264 happyReduction_264 (HappyTerminal (T_type happy_var_1)) = HappyAbsSyn30 (TyName happy_var_1 Nothing ) happyReduction_264 _ = notHappyAtAll happyReduce_265 = happySpecReduce_2 77# happyReduction_265 happyReduction_265 _ (HappyAbsSyn78 happy_var_1) = HappyAbsSyn77 ([ happy_var_1 ] ) happyReduction_265 _ _ = notHappyAtAll happyReduce_266 = happySpecReduce_3 77# happyReduction_266 happyReduction_266 _ (HappyAbsSyn78 happy_var_2) (HappyAbsSyn77 happy_var_1) = HappyAbsSyn77 (happy_var_2 : happy_var_1 ) happyReduction_266 _ _ _ = notHappyAtAll happyReduce_267 = happySpecReduce_2 78# happyReduction_267 happyReduction_267 (HappyAbsSyn79 happy_var_2) (HappyAbsSyn81 happy_var_1) = HappyAbsSyn78 (Switch happy_var_1 happy_var_2 ) happyReduction_267 _ _ = notHappyAtAll happyReduce_268 = happyReduce 4# 78# happyReduction_268 happyReduction_268 ((HappyAbsSyn79 happy_var_4) `HappyStk` _ `HappyStk` (HappyAbsSyn82 happy_var_2) `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn78 (Switch [happy_var_2] happy_var_4 ) `HappyStk` happyRest happyReduce_269 = happySpecReduce_0 79# happyReduction_269 happyReduction_269 = HappyAbsSyn79 (Nothing ) happyReduce_270 = happySpecReduce_2 79# happyReduction_270 happyReduction_270 (HappyAbsSyn18 happy_var_2) (HappyAbsSyn30 happy_var_1) = HappyAbsSyn79 (Just (Param happy_var_2 happy_var_1 []) ) happyReduction_270 _ _ = notHappyAtAll happyReduce_271 = happySpecReduce_1 79# happyReduction_271 happyReduction_271 (HappyAbsSyn30 happy_var_1) = HappyAbsSyn79 (Just (Param (Id "") happy_var_1 []) ) happyReduction_271 _ = notHappyAtAll happyReduce_272 = happySpecReduce_0 80# happyReduction_272 happyReduction_272 = HappyAbsSyn79 (Nothing ) happyReduce_273 = happySpecReduce_3 80# happyReduction_273 happyReduction_273 (HappyAbsSyn18 happy_var_3) (HappyAbsSyn30 happy_var_2) (HappyAbsSyn16 happy_var_1) = HappyAbsSyn79 (Just (Param happy_var_3 happy_var_2 happy_var_1) ) happyReduction_273 _ _ _ = notHappyAtAll happyReduce_274 = happySpecReduce_2 80# happyReduction_274 happyReduction_274 (HappyAbsSyn30 happy_var_2) (HappyAbsSyn16 happy_var_1) = HappyAbsSyn79 (Just (Param (Id "") happy_var_2 happy_var_1) ) happyReduction_274 _ _ = notHappyAtAll happyReduce_275 = happySpecReduce_1 81# happyReduction_275 happyReduction_275 (HappyAbsSyn82 happy_var_1) = HappyAbsSyn81 ([ happy_var_1 ] ) happyReduction_275 _ = notHappyAtAll happyReduce_276 = happySpecReduce_2 81# happyReduction_276 happyReduction_276 (HappyAbsSyn82 happy_var_2) (HappyAbsSyn81 happy_var_1) = HappyAbsSyn81 (happy_var_2 : happy_var_1 ) happyReduction_276 _ _ = notHappyAtAll happyReduce_277 = happySpecReduce_3 82# happyReduction_277 happyReduction_277 _ (HappyAbsSyn34 happy_var_2) _ = HappyAbsSyn82 (Case [happy_var_2] ) happyReduction_277 _ _ _ = notHappyAtAll happyReduce_278 = happySpecReduce_2 82# happyReduction_278 happyReduction_278 _ _ = HappyAbsSyn82 (Default ) happyReduce_279 = happyReduce 4# 83# happyReduction_279 happyReduction_279 (_ `HappyStk` (HappyAbsSyn84 happy_var_3) `HappyStk` _ `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn82 (Case (reverse happy_var_3) ) `HappyStk` happyRest happyReduce_280 = happySpecReduce_1 83# happyReduction_280 happyReduction_280 _ = HappyAbsSyn82 (Default ) happyReduce_281 = happySpecReduce_1 84# happyReduction_281 happyReduction_281 (HappyAbsSyn34 happy_var_1) = HappyAbsSyn84 ([ happy_var_1 ] ) happyReduction_281 _ = notHappyAtAll happyReduce_282 = happySpecReduce_3 84# happyReduction_282 happyReduction_282 (HappyAbsSyn34 happy_var_3) _ (HappyAbsSyn84 happy_var_1) = HappyAbsSyn84 (happy_var_3 : happy_var_1 ) happyReduction_282 _ _ _ = notHappyAtAll happyReduce_283 = happySpecReduce_0 85# happyReduction_283 happyReduction_283 = HappyAbsSyn84 ([] ) happyReduce_284 = happySpecReduce_1 85# happyReduction_284 happyReduction_284 (HappyAbsSyn84 happy_var_1) = HappyAbsSyn84 (happy_var_1 ) happyReduction_284 _ = notHappyAtAll happyReduce_285 = happyReduce 5# 86# happyReduction_285 happyReduction_285 (_ `HappyStk` _ `HappyStk` (HappyAbsSyn87 happy_var_3) `HappyStk` _ `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn30 (TyEnum Nothing (reverse happy_var_3) ) `HappyStk` happyRest happyReduce_286 = happyReduce 6# 86# happyReduction_286 happyReduction_286 (_ `HappyStk` _ `HappyStk` (HappyAbsSyn87 happy_var_4) `HappyStk` _ `HappyStk` (HappyAbsSyn18 happy_var_2) `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn30 (TyEnum (Just happy_var_2) (reverse happy_var_4) ) `HappyStk` happyRest happyReduce_287 = happySpecReduce_2 86# happyReduction_287 happyReduction_287 (HappyAbsSyn18 happy_var_2) _ = HappyAbsSyn30 (TyEnum (Just happy_var_2) [] ) happyReduction_287 _ _ = notHappyAtAll happyReduce_288 = happySpecReduce_1 87# happyReduction_288 happyReduction_288 (HappyAbsSyn88 happy_var_1) = HappyAbsSyn87 ([ happy_var_1 ] ) happyReduction_288 _ = notHappyAtAll happyReduce_289 = happySpecReduce_3 87# happyReduction_289 happyReduction_289 (HappyAbsSyn88 happy_var_3) _ (HappyAbsSyn87 happy_var_1) = HappyAbsSyn87 (happy_var_3 : happy_var_1 ) happyReduction_289 _ _ _ = notHappyAtAll happyReduce_290 = happySpecReduce_1 88# happyReduction_290 happyReduction_290 (HappyAbsSyn18 happy_var_1) = HappyAbsSyn88 ((happy_var_1, [], Nothing) ) happyReduction_290 _ = notHappyAtAll happyReduce_291 = happySpecReduce_2 88# happyReduction_291 happyReduction_291 (HappyAbsSyn18 happy_var_2) (HappyAbsSyn16 happy_var_1) = HappyAbsSyn88 ((happy_var_2, happy_var_1, Nothing) ) happyReduction_291 _ _ = notHappyAtAll happyReduce_292 = happySpecReduce_3 88# happyReduction_292 happyReduction_292 (HappyAbsSyn34 happy_var_3) _ (HappyAbsSyn18 happy_var_1) = HappyAbsSyn88 ((happy_var_1, [], Just happy_var_3) ) happyReduction_292 _ _ _ = notHappyAtAll happyReduce_293 = happyReduce 4# 88# happyReduction_293 happyReduction_293 ((HappyAbsSyn34 happy_var_4) `HappyStk` _ `HappyStk` (HappyAbsSyn18 happy_var_2) `HappyStk` (HappyAbsSyn16 happy_var_1) `HappyStk` happyRest) = HappyAbsSyn88 ((happy_var_2, happy_var_1, Just happy_var_4) ) `HappyStk` happyRest happyReduce_294 = happyReduce 4# 89# happyReduction_294 happyReduction_294 (_ `HappyStk` (HappyAbsSyn34 happy_var_3) `HappyStk` _ `HappyStk` (HappyAbsSyn90 happy_var_1) `HappyStk` happyRest) = HappyAbsSyn30 (happy_var_1 (Just happy_var_3) ) `HappyStk` happyRest happyReduce_295 = happySpecReduce_1 89# happyReduction_295 happyReduction_295 (HappyAbsSyn90 happy_var_1) = HappyAbsSyn30 (happy_var_1 Nothing ) happyReduction_295 _ = notHappyAtAll happyReduce_296 = happySpecReduce_1 90# happyReduction_296 happyReduction_296 _ = HappyAbsSyn90 (TyString ) happyReduce_297 = happySpecReduce_1 90# happyReduction_297 happyReduction_297 _ = HappyAbsSyn90 (TyWString ) happyReduce_298 = happySpecReduce_0 91# happyReduction_298 happyReduction_298 = HappyAbsSyn5 ([] ) happyReduce_299 = happySpecReduce_3 91# happyReduction_299 happyReduction_299 _ (HappyAbsSyn9 happy_var_2) (HappyAbsSyn5 happy_var_1) = HappyAbsSyn5 (happy_var_2 : happy_var_1 ) happyReduction_299 _ _ _ = notHappyAtAll happyReduce_300 = happyReduce 4# 92# happyReduction_300 happyReduction_300 (_ `HappyStk` (HappyAbsSyn18 happy_var_3) `HappyStk` (HappyAbsSyn30 happy_var_2) `HappyStk` (HappyAbsSyn16 happy_var_1) `HappyStk` happyRest) = HappyAbsSyn9 (let m_id = mkMethodId happy_var_3 in (Attributed happy_var_1 (Operation m_id happy_var_2 Nothing Nothing)) ) `HappyStk` happyRest happyReduce_301 = happySpecReduce_3 93# happyReduction_301 happyReduction_301 _ (HappyAbsSyn18 happy_var_2) (HappyAbsSyn30 happy_var_1) = HappyAbsSyn9 (let m_id = mkMethodId happy_var_2 in (Operation m_id happy_var_1 Nothing Nothing) ) happyReduction_301 _ _ _ = notHappyAtAll happyReduce_302 = happySpecReduce_1 94# happyReduction_302 happyReduction_302 (HappyAbsSyn95 happy_var_1) = HappyAbsSyn16 (concat happy_var_1 ) happyReduction_302 _ = notHappyAtAll happyReduce_303 = happySpecReduce_0 95# happyReduction_303 happyReduction_303 = HappyAbsSyn95 ([] ) happyReduce_304 = happySpecReduce_2 95# happyReduction_304 happyReduction_304 (HappyAbsSyn95 happy_var_2) (HappyAbsSyn16 happy_var_1) = HappyAbsSyn95 (happy_var_1 : happy_var_2 ) happyReduction_304 _ _ = notHappyAtAll happyReduce_305 = happySpecReduce_2 96# happyReduction_305 happyReduction_305 _ _ = HappyAbsSyn16 ([] ) happyReduce_306 = happyReduce 4# 96# happyReduction_306 happyReduction_306 (_ `HappyStk` _ `HappyStk` (HappyAbsSyn16 happy_var_2) `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn16 ((reverse happy_var_2) ) `HappyStk` happyRest happyReduce_307 = happySpecReduce_1 97# happyReduction_307 happyReduction_307 (HappyAbsSyn98 happy_var_1) = HappyAbsSyn16 ([ happy_var_1 ] ) happyReduction_307 _ = notHappyAtAll happyReduce_308 = happySpecReduce_3 97# happyReduction_308 happyReduction_308 (HappyAbsSyn98 happy_var_3) _ (HappyAbsSyn16 happy_var_1) = HappyAbsSyn16 (happy_var_3 : happy_var_1 ) happyReduction_308 _ _ _ = notHappyAtAll happyReduce_309 = happySpecReduce_2 98# happyReduction_309 happyReduction_309 (HappyAbsSyn101 happy_var_2) (HappyAbsSyn18 happy_var_1) = HappyAbsSyn98 (Attrib happy_var_1 happy_var_2 ) happyReduction_309 _ _ = notHappyAtAll happyReduce_310 = happySpecReduce_1 98# happyReduction_310 happyReduction_310 _ = HappyAbsSyn98 (Attrib (Id "string") [] ) happyReduce_311 = happySpecReduce_1 98# happyReduction_311 happyReduction_311 (HappyTerminal (T_mode happy_var_1)) = HappyAbsSyn98 (Mode happy_var_1 ) happyReduction_311 _ = notHappyAtAll happyReduce_312 = happySpecReduce_1 99# happyReduction_312 happyReduction_312 (HappyAbsSyn98 happy_var_1) = HappyAbsSyn16 ([ happy_var_1 ] ) happyReduction_312 _ = notHappyAtAll happyReduce_313 = happySpecReduce_3 99# happyReduction_313 happyReduction_313 (HappyAbsSyn98 happy_var_3) _ (HappyAbsSyn16 happy_var_1) = HappyAbsSyn16 (happy_var_3 : happy_var_1 ) happyReduction_313 _ _ _ = notHappyAtAll happyReduce_314 = happySpecReduce_1 100# happyReduction_314 happyReduction_314 (HappyAbsSyn18 happy_var_1) = HappyAbsSyn98 (Attrib happy_var_1 [] ) happyReduction_314 _ = notHappyAtAll happyReduce_315 = happySpecReduce_1 100# happyReduction_315 happyReduction_315 _ = HappyAbsSyn98 (Attrib (Id "default") [] ) happyReduce_316 = happySpecReduce_0 101# happyReduction_316 happyReduction_316 = HappyAbsSyn101 ([] ) happyReduce_317 = happySpecReduce_3 101# happyReduction_317 happyReduction_317 _ (HappyAbsSyn101 happy_var_2) _ = HappyAbsSyn101 ((reverse happy_var_2) ) happyReduction_317 _ _ _ = notHappyAtAll happyReduce_318 = happySpecReduce_1 102# happyReduction_318 happyReduction_318 (HappyAbsSyn103 happy_var_1) = HappyAbsSyn101 ([happy_var_1] ) happyReduction_318 _ = notHappyAtAll happyReduce_319 = happySpecReduce_3 102# happyReduction_319 happyReduction_319 (HappyAbsSyn103 happy_var_3) _ (HappyAbsSyn101 happy_var_1) = HappyAbsSyn101 (happy_var_3:happy_var_1 ) happyReduction_319 _ _ _ = notHappyAtAll happyReduce_320 = happySpecReduce_1 103# happyReduction_320 happyReduction_320 (HappyAbsSyn34 happy_var_1) = HappyAbsSyn103 ((AttrExpr happy_var_1) ) happyReduction_320 _ = notHappyAtAll happyReduce_321 = happySpecReduce_0 103# happyReduction_321 happyReduction_321 = HappyAbsSyn103 (EmptyAttr ) happyReduce_322 = happySpecReduce_1 103# happyReduction_322 happyReduction_322 (HappyTerminal (T_type happy_var_1)) = HappyAbsSyn103 ((AttrLit (TypeConst happy_var_1)) ) happyReduction_322 _ = notHappyAtAll happyReduce_323 = happySpecReduce_2 103# happyReduction_323 happyReduction_323 (HappyTerminal (T_type happy_var_2)) _ = HappyAbsSyn103 ((AttrLit (TypeConst ("unsigned " ++ happy_var_2))) ) happyReduction_323 _ _ = notHappyAtAll happyReduce_324 = happySpecReduce_2 103# happyReduction_324 happyReduction_324 (HappyTerminal (T_type happy_var_2)) _ = HappyAbsSyn103 ((AttrLit (TypeConst ("signed " ++ happy_var_2))) ) happyReduction_324 _ _ = notHappyAtAll happyReduce_325 = happySpecReduce_3 103# happyReduction_325 happyReduction_325 _ (HappyTerminal (T_literal happy_var_2)) _ = HappyAbsSyn103 (AttrLit happy_var_2 ) happyReduction_325 _ _ _ = notHappyAtAll happyReduce_326 = happySpecReduce_2 103# happyReduction_326 happyReduction_326 (HappyAbsSyn103 happy_var_2) _ = HappyAbsSyn103 ((AttrPtr happy_var_2) ) happyReduction_326 _ _ = notHappyAtAll happyReduce_327 = happySpecReduce_1 104# happyReduction_327 happyReduction_327 (HappyAbsSyn30 happy_var_1) = HappyAbsSyn30 (happy_var_1 ) happyReduction_327 _ = notHappyAtAll happyReduce_328 = happySpecReduce_1 104# happyReduction_328 happyReduction_328 (HappyAbsSyn30 happy_var_1) = HappyAbsSyn30 (happy_var_1 ) happyReduction_328 _ = notHappyAtAll happyReduce_329 = happySpecReduce_2 105# happyReduction_329 happyReduction_329 (HappyAbsSyn30 happy_var_2) (HappyAbsSyn16 happy_var_1) = HappyAbsSyn105 (Param (Id "") happy_var_2 happy_var_1 ) happyReduction_329 _ _ = notHappyAtAll happyReduce_330 = happySpecReduce_3 105# happyReduction_330 happyReduction_330 (HappyAbsSyn18 happy_var_3) (HappyAbsSyn30 happy_var_2) (HappyAbsSyn16 happy_var_1) = HappyAbsSyn105 (Param happy_var_3 happy_var_2 happy_var_1 ) happyReduction_330 _ _ _ = notHappyAtAll happyReduce_331 = happySpecReduce_3 105# happyReduction_331 happyReduction_331 (HappyAbsSyn18 happy_var_3) (HappyAbsSyn30 happy_var_2) (HappyAbsSyn16 happy_var_1) = HappyAbsSyn105 (Param happy_var_3 happy_var_2 happy_var_1 ) happyReduction_331 _ _ _ = notHappyAtAll happyReduce_332 = happySpecReduce_1 105# happyReduction_332 happyReduction_332 _ = HappyAbsSyn105 (Param (Id "vararg") TyVoid [] ) happyReduce_333 = happySpecReduce_1 106# happyReduction_333 happyReduction_333 (HappyAbsSyn105 happy_var_1) = HappyAbsSyn106 ([happy_var_1] ) happyReduction_333 _ = notHappyAtAll happyReduce_334 = happySpecReduce_3 106# happyReduction_334 happyReduction_334 (HappyAbsSyn105 happy_var_3) _ (HappyAbsSyn106 happy_var_1) = HappyAbsSyn106 (happy_var_3 : happy_var_1 ) happyReduction_334 _ _ _ = notHappyAtAll happyReduce_335 = happySpecReduce_1 107# happyReduction_335 happyReduction_335 (HappyAbsSyn71 happy_var_1) = HappyAbsSyn18 (Pointed happy_var_1 (Id "") ) happyReduction_335 _ = notHappyAtAll happyReduce_336 = happySpecReduce_2 107# happyReduction_336 happyReduction_336 (HappyAbsSyn18 happy_var_2) (HappyAbsSyn65 happy_var_1) = HappyAbsSyn18 (happy_var_1 happy_var_2 ) happyReduction_336 _ _ = notHappyAtAll happyReduce_337 = happySpecReduce_1 107# happyReduction_337 happyReduction_337 (HappyAbsSyn18 happy_var_1) = HappyAbsSyn18 (happy_var_1 ) happyReduction_337 _ = notHappyAtAll happyReduce_338 = happySpecReduce_2 107# happyReduction_338 happyReduction_338 (HappyAbsSyn18 happy_var_2) (HappyAbsSyn71 happy_var_1) = HappyAbsSyn18 (Pointed happy_var_1 happy_var_2 ) happyReduction_338 _ _ = notHappyAtAll happyReduce_339 = happySpecReduce_3 108# happyReduction_339 happyReduction_339 _ (HappyAbsSyn18 happy_var_2) _ = HappyAbsSyn18 (happy_var_2 ) happyReduction_339 _ _ _ = notHappyAtAll happyReduce_340 = happySpecReduce_2 108# happyReduction_340 happyReduction_340 _ _ = HappyAbsSyn18 (FunId (Id "") Nothing [] ) happyReduce_341 = happySpecReduce_3 108# happyReduction_341 happyReduction_341 _ (HappyAbsSyn106 happy_var_2) _ = HappyAbsSyn18 (FunId (Id "") Nothing happy_var_2 ) happyReduction_341 _ _ _ = notHappyAtAll happyReduce_342 = happySpecReduce_3 108# happyReduction_342 happyReduction_342 _ _ (HappyAbsSyn18 happy_var_1) = HappyAbsSyn18 (FunId happy_var_1 Nothing [] ) happyReduction_342 _ _ _ = notHappyAtAll happyReduce_343 = happyReduce 4# 108# happyReduction_343 happyReduction_343 (_ `HappyStk` (HappyAbsSyn106 happy_var_3) `HappyStk` _ `HappyStk` (HappyAbsSyn18 happy_var_1) `HappyStk` happyRest) = HappyAbsSyn18 (FunId happy_var_1 Nothing happy_var_3 ) `HappyStk` happyRest happyReduce_344 = happySpecReduce_0 109# happyReduction_344 happyReduction_344 = HappyAbsSyn109 ([] ) happyReduce_345 = happySpecReduce_1 109# happyReduction_345 happyReduction_345 (HappyAbsSyn109 happy_var_1) = HappyAbsSyn109 ((reverse happy_var_1) ) happyReduction_345 _ = notHappyAtAll happyReduce_346 = happySpecReduce_1 110# happyReduction_346 happyReduction_346 (HappyAbsSyn111 happy_var_1) = HappyAbsSyn109 ([happy_var_1] ) happyReduction_346 _ = notHappyAtAll happyReduce_347 = happySpecReduce_2 110# happyReduction_347 happyReduction_347 (HappyAbsSyn111 happy_var_2) (HappyAbsSyn109 happy_var_1) = HappyAbsSyn109 ((happy_var_2:happy_var_1) ) happyReduction_347 _ _ = notHappyAtAll happyReduce_348 = happyReduce 6# 111# happyReduction_348 happyReduction_348 (_ `HappyStk` _ `HappyStk` (HappyAbsSyn111 happy_var_4) `HappyStk` _ `HappyStk` _ `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn111 (happy_var_4 ) `HappyStk` happyRest happyReduce_349 = happySpecReduce_1 112# happyReduction_349 happyReduction_349 (HappyAbsSyn8 happy_var_1) = HappyAbsSyn111 (mkGNUAttrib happy_var_1 [] ) happyReduction_349 _ = notHappyAtAll happyReduce_350 = happySpecReduce_1 112# happyReduction_350 happyReduction_350 (HappyTerminal (T_callconv happy_var_1)) = HappyAbsSyn111 (CConv happy_var_1 ) happyReduction_350 _ = notHappyAtAll happyReduce_351 = happyReduce 4# 112# happyReduction_351 happyReduction_351 (_ `HappyStk` (HappyTerminal (T_id happy_var_3)) `HappyStk` _ `HappyStk` (HappyAbsSyn8 happy_var_1) `HappyStk` happyRest) = HappyAbsSyn111 (mkGNUAttrib happy_var_1 [Var happy_var_3] ) `HappyStk` happyRest happyReduce_352 = happyReduce 6# 112# happyReduction_352 happyReduction_352 (_ `HappyStk` (HappyAbsSyn84 happy_var_5) `HappyStk` _ `HappyStk` (HappyTerminal (T_id happy_var_3)) `HappyStk` _ `HappyStk` (HappyAbsSyn8 happy_var_1) `HappyStk` happyRest) = HappyAbsSyn111 (mkGNUAttrib happy_var_1 (Var happy_var_3:happy_var_5) ) `HappyStk` happyRest happyReduce_353 = happySpecReduce_1 113# happyReduction_353 happyReduction_353 (HappyTerminal (T_id happy_var_1)) = HappyAbsSyn8 (happy_var_1 ) happyReduction_353 _ = notHappyAtAll happyReduce_354 = happySpecReduce_1 113# happyReduction_354 happyReduction_354 (HappyTerminal (T_type happy_var_1)) = HappyAbsSyn8 (happy_var_1 ) happyReduction_354 _ = notHappyAtAll happyReduce_355 = happySpecReduce_1 114# happyReduction_355 happyReduction_355 (HappyTerminal (T_id happy_var_1)) = HappyAbsSyn18 ((Id happy_var_1) ) happyReduction_355 _ = notHappyAtAll happyReduce_356 = happySpecReduce_1 115# happyReduction_356 happyReduction_356 _ = HappyAbsSyn115 (() ) happyReduce_357 = happySpecReduce_1 115# happyReduction_357 happyReduction_357 _ = HappyAbsSyn115 (() ) happyReduce_358 = happySpecReduce_0 116# happyReduction_358 happyReduction_358 = HappyAbsSyn115 (() ) happyReduce_359 = happySpecReduce_1 116# happyReduction_359 happyReduction_359 _ = HappyAbsSyn115 (() ) happyNewToken :: (Int# -> HappyReduction) -> [HappyState IDLToken (HappyStk HappyAbsSyn -> LexM HappyAbsSyn)] -> HappyStk HappyAbsSyn -> LexM HappyAbsSyn happyNewToken action sts stk = lexIDL(\tk -> let cont :: Int# -> LexM HappyAbsSyn cont i = action i i tk (HappyState action) sts stk in case tk of { T_eof -> action 199# 199# (error "reading EOF!") (HappyState action) sts stk; T_semi -> cont 117#; T_module -> cont 118#; T_interface -> cont 119#; T_oparen -> cont 120#; T_cparen -> cont 121#; T_ocurly -> cont 122#; T_ccurly -> cont 123#; T_colon -> cont 124#; T_comma -> cont 125#; T_dot -> cont 126#; T_dotdotdot -> cont 127#; T_const -> cont 128#; T_volatile -> cont 129#; T_equal -> cont 130#; T_eqeq -> cont 131#; T_neq -> cont 132#; T_or -> cont 133#; T_rel_or -> cont 134#; T_xor -> cont 135#; T_and -> cont 136#; T_rel_and -> cont 137#; T_shift happy_dollar_dollar -> cont 138#; T_div -> cont 139#; T_mod -> cont 140#; T_not -> cont 141#; T_negate -> cont 142#; T_question -> cont 143#; T_typedef -> cont 144#; T_extern -> cont 145#; T_type happy_dollar_dollar -> cont 146#; T_idl_type happy_dollar_dollar -> cont 147#; T_float happy_dollar_dollar -> cont 148#; (T_int Short) -> cont 149#; (T_int Long) -> cont 150#; (T_int LongLong) -> cont 151#; (T_uint LongLong) -> cont 152#; (T_int Natural) -> cont 153#; T_unsigned -> cont 154#; T_signed -> cont 155#; T_char -> cont 156#; T_wchar -> cont 157#; T_struct -> cont 158#; T_union -> cont 159#; T_switch -> cont 160#; T_case -> cont 161#; T_default -> cont 162#; T_enum -> cont 163#; T_lt -> cont 164#; T_le -> cont 165#; T_gt -> cont 166#; T_ge -> cont 167#; T_osquare -> cont 168#; T_csquare -> cont 169#; T_sizeof -> cont 170#; T_void -> cont 171#; T_mode happy_dollar_dollar -> cont 172#; T_literal happy_dollar_dollar -> cont 173#; T_string_lit happy_dollar_dollar -> cont 174#; T_callconv happy_dollar_dollar -> cont 175#; T_id happy_dollar_dollar -> cont 176#; T_dispinterface -> cont 177#; T_coclass -> cont 178#; T_library -> cont 179#; T_plus -> cont 180#; T_times -> cont 181#; T_minus -> cont 182#; T_string -> cont 183#; T_wstring -> cont 184#; T_methods -> cont 185#; T_properties -> cont 186#; T_cpp_quote -> cont 187#; T_hs_quote -> cont 188#; T_include happy_dollar_dollar -> cont 189#; T_importlib -> cont 190#; T_include_start happy_dollar_dollar -> cont 191#; T_include_end -> cont 192#; T_gnu_attribute -> cont 193#; T_import -> cont 194#; T_pragma happy_dollar_dollar -> cont 195#; T_hdefine -> cont 196#; T_safearray -> cont 197#; T_unknown happy_dollar_dollar -> cont 198#; _ -> happyError }) happyThen :: LexM a -> (a -> LexM b) -> LexM b happyThen = (thenLexM) happyReturn :: a -> LexM a happyReturn = (returnLexM) happyThen1 = happyThen happyReturn1 = happyReturn parseIDL = happyThen (happyParse action_0) (\x -> case x of {HappyAbsSyn4 z -> happyReturn z; _other -> notHappyAtAll }) happySeq = happyDontSeq addTypes :: [Id] -> LexM () addTypes ids = do sequence (map addTypedef ls) return () where ls = map getName ids getName (Id s) = s getName (ArrayId i _) = getName i getName (Pointed _ i) = getName i getName (CConvId _ i) = getName i getName (FunId i _ _) = getName i addIfaceTypedef :: String -> LexM Id addIfaceTypedef nm = addTypedef nm >> return (Id nm) mkBitField :: String -> Literal -> Int mkBitField nm l = case l of IntegerLit (ILit _ i) -> fromInteger i _ -> error ("bitfield " ++ show nm ++ " not an int.") warningMsg :: String -> LexM () warningMsg msg = do l <- getSrcLoc ioToLexM (hPutStrLn stderr (show l ++ ": warning: "++msg)) dumpErrMsg :: LexM () dumpErrMsg = do l <- getSrcLoc str <- getStream ioToLexM (ioError (userError (show l ++ ": Parse error on input: " ++ takeWhile (/='\n') str))) happyError :: LexM a happyError = do l <- getSrcLoc str <- getStream ioToLexM (ioError (userError (show l ++ ": Parse error: " ++ takeWhile (/='\n') str))) {-# LINE 1 "GenericTemplate.hs" #-} -- Id: GenericTemplate.hs,v 1.24 2003/06/03 09:41:51 ross Exp {-# LINE 27 "GenericTemplate.hs" #-} infixr 9 `HappyStk` data HappyStk a = HappyStk a (HappyStk a) ----------------------------------------------------------------------------- -- starting the parse happyParse start_state = happyNewToken start_state notHappyAtAll notHappyAtAll ----------------------------------------------------------------------------- -- Accepting the parse happyAccept j tk st sts (HappyStk ans _) = (happyTcHack j ) (happyReturn1 ans) ----------------------------------------------------------------------------- -- Arrays only: do the next action {-# LINE 150 "GenericTemplate.hs" #-} ----------------------------------------------------------------------------- -- HappyState data type (not arrays) newtype HappyState b c = HappyState (Int# -> -- token number Int# -> -- token number (yes, again) b -> -- token semantic value HappyState b c -> -- current state [HappyState b c] -> -- state stack c) ----------------------------------------------------------------------------- -- Shifting a token happyShift new_state 1# tk st sts stk@(x `HappyStk` _) = let i = (case x of { HappyErrorToken (I# (i)) -> i }) in -- trace "shifting the error token" $ new_state i i tk (HappyState (new_state)) ((st):(sts)) (stk) happyShift new_state i tk st sts stk = happyNewToken new_state ((st):(sts)) ((HappyTerminal (tk))`HappyStk`stk) -- happyReduce is specialised for the common cases. happySpecReduce_0 i fn 1# tk st sts stk = happyFail 1# tk st sts stk happySpecReduce_0 nt fn j tk st@((HappyState (action))) sts stk = action nt j tk st ((st):(sts)) (fn `HappyStk` stk) happySpecReduce_1 i fn 1# tk st sts stk = happyFail 1# tk st sts stk happySpecReduce_1 nt fn j tk _ sts@(((st@(HappyState (action))):(_))) (v1`HappyStk`stk') = let r = fn v1 in happySeq r (action nt j tk st sts (r `HappyStk` stk')) happySpecReduce_2 i fn 1# tk st sts stk = happyFail 1# tk st sts stk happySpecReduce_2 nt fn j tk _ ((_):(sts@(((st@(HappyState (action))):(_))))) (v1`HappyStk`v2`HappyStk`stk') = let r = fn v1 v2 in happySeq r (action nt j tk st sts (r `HappyStk` stk')) happySpecReduce_3 i fn 1# tk st sts stk = happyFail 1# tk st sts stk happySpecReduce_3 nt fn j tk _ ((_):(((_):(sts@(((st@(HappyState (action))):(_))))))) (v1`HappyStk`v2`HappyStk`v3`HappyStk`stk') = let r = fn v1 v2 v3 in happySeq r (action nt j tk st sts (r `HappyStk` stk')) happyReduce k i fn 1# tk st sts stk = happyFail 1# tk st sts stk happyReduce k nt fn j tk st sts stk = case happyDrop (k -# (1# :: Int#)) sts of sts1@(((st1@(HappyState (action))):(_))) -> let r = fn stk in -- it doesn't hurt to always seq here... happyDoSeq r (action nt j tk st1 sts1 r) happyMonadReduce k nt fn 1# tk st sts stk = happyFail 1# tk st sts stk happyMonadReduce k nt fn j tk st sts stk = happyThen1 (fn stk) (\r -> action nt j tk st1 sts1 (r `HappyStk` drop_stk)) where sts1@(((st1@(HappyState (action))):(_))) = happyDrop k ((st):(sts)) drop_stk = happyDropStk k stk happyDrop 0# l = l happyDrop n ((_):(t)) = happyDrop (n -# (1# :: Int#)) t happyDropStk 0# l = l happyDropStk n (x `HappyStk` xs) = happyDropStk (n -# (1#::Int#)) xs ----------------------------------------------------------------------------- -- Moving to a new state after a reduction happyGoto action j tk st = action j j tk (HappyState action) ----------------------------------------------------------------------------- -- Error recovery (1# is the error token) -- parse error if we are in recovery and we fail again happyFail 1# tk old_st _ stk = -- trace "failing" $ happyError {- We don't need state discarding for our restricted implementation of "error". In fact, it can cause some bogus parses, so I've disabled it for now --SDM -- discard a state happyFail 1# tk old_st (((HappyState (action))):(sts)) (saved_tok `HappyStk` _ `HappyStk` stk) = -- trace ("discarding state, depth " ++ show (length stk)) $ action 1# 1# tk (HappyState (action)) sts ((saved_tok`HappyStk`stk)) -} -- Enter error recovery: generate an error token, -- save the old token and carry on. happyFail i tk (HappyState (action)) sts stk = -- trace "entering error recovery" $ action 1# 1# tk (HappyState (action)) sts ( (HappyErrorToken (I# (i))) `HappyStk` stk) -- Internal happy errors: notHappyAtAll = error "Internal Happy error\n" ----------------------------------------------------------------------------- -- Hack to get the typechecker to accept our action functions happyTcHack :: Int# -> a -> a happyTcHack x y = y {-# INLINE happyTcHack #-} ----------------------------------------------------------------------------- -- Seq-ing. If the --strict flag is given, then Happy emits -- happySeq = happyDoSeq -- otherwise it emits -- happySeq = happyDontSeq happyDoSeq, happyDontSeq :: a -> b -> b happyDoSeq a b = a `seq` b happyDontSeq a b = b ----------------------------------------------------------------------------- -- Don't inline any functions from the template. GHC has a nasty habit -- of deciding to inline happyGoto everywhere, which increases the size of -- the generated parser quite a bit. {-# NOINLINE happyShift #-} {-# NOINLINE happySpecReduce_0 #-} {-# NOINLINE happySpecReduce_1 #-} {-# NOINLINE happySpecReduce_2 #-} {-# NOINLINE happySpecReduce_3 #-} {-# NOINLINE happyReduce #-} {-# NOINLINE happyMonadReduce #-} {-# NOINLINE happyGoto #-} {-# NOINLINE happyFail #-} -- end of Happy Template.
HJvT/hdirect
src/Parser.hs
bsd-3-clause
246,856
0
20
46,870
68,537
35,330
33,207
-1
-1
module Main where import Control.Applicative ((*>)) import Data.Char import Data.Functor.Identity import Numeric import System.Environment import Text.Parsec import Text.Parsec.String import qualified Data.Map as Map startState :: (Integer, Map.Map String Integer) startState = (0, Map.empty) type ParserState = (Integer, Map.Map String Integer) pMain :: ParsecT String ParserState Identity ([Instruction], ParserState) pMain = do instr <- asmFile eof st <- getState return (instr, st) asmFile :: ParsecT String ParserState Identity [Instruction] asmFile = instr `endBy` (optional comment *> eol) instr = blankLine <|> regInstr <|> ldImmInstr <|> ldStInstr <|> branchInstr <|> nop <|> halt <|> asmLabel comment = do skipMany (char ' ') char ';' skipMany (noneOf "\n") return () data Instruction = RegInstr String Operand Operand | LdImmInstr Integer | Label | BranchInstr String Integer | Nop | Halt | BlankLine deriving (Eq, Show) data Operand = Reg Char Integer | Imm Integer deriving (Eq, Show) regOrImm :: String -> Operand regOrImm x = case x of '#':t -> Imm $ read t v:vs -> Reg v (read vs) opcode = choice . map (try . string) $ ["addi", "fadd", "add", "sub", "fsub", "cmp", "mul", "fmul", "mac", "msc", "mad", "msd", "and", "nand", "or", "nor", "xor", "mov", "mvn", "i2f", "f2i"] ldStOpcode = choice . map (try . string) $ ["lda", "ldb", "ldc", "stb"] branchOpcode = choice . map (try . string) $ ["beq", "bne", "blt", "bgt", "jmp"] putLabel :: String -> ParserState -> ParserState putLabel k (n, m) = (n, Map.insert k n m) bumpInstrCount :: ParserState -> ParserState bumpInstrCount (n, r) = (n+1, r) blankLine = do lookAhead (char '\n') return BlankLine halt = do try (string "halt") modifyState bumpInstrCount return Halt nop = do try (string "nop") modifyState bumpInstrCount return Nop branchSymbol = char '@' <|> char '=' branchInstr = do op <- try branchOpcode skipMany (char ' ') c <- branchSymbol modifyState bumpInstrCount case c of '@' -> do label <- (many (noneOf "\n")) (_, m) <- getState case (Map.lookup label m) of Just x -> return (BranchInstr op x) Nothing -> fail "Invalid branch target" '=' -> (many1 digit >>= \x -> return $ BranchInstr op $ read x) _ -> fail "Invalid branch" asmLabel = do labelName <- try (many (noneOf ":\n")) char ':' modifyState (putLabel labelName) return Label regInstr = do op <- opcode skipMany (char ' ') reg1 <- (many (noneOf ", "))  char ',' skipMany (char ' ') reg2 <- (many (noneOf " ]\n;")) modifyState bumpInstrCount return $ RegInstr op (regOrImm reg1) (regOrImm reg2) ldImmInstr = do try (string "ldi") skipMany (char ' ') char '#' imm <- many digit modifyState bumpInstrCount return $ LdImmInstr $ read imm brackets :: ParsecT String u Identity a -> ParsecT String u Identity a brackets = between (char '[') (char ']') ldStInstr = do op <- ldStOpcode skipMany (char ' ') reg1 <- (many (noneOf ","))  char ',' skipMany (char ' ') reg2 <- brackets (many (noneOf "]")) modifyState bumpInstrCount return $ RegInstr op (regOrImm reg1) (regOrImm reg2) eol = try (string "\n\r") <|> try (string "\r\n") <|> string "\n" <|> string "\r" <?> "end of line" firstSixBits :: String -> String firstSixBits "add" = "000000" firstSixBits "addi" = "000001" firstSixBits "fadd" = "000010" firstSixBits "sub" = "000100" firstSixBits "fsub" = "000101" firstSixBits "cmp" = "000110" firstSixBits "mul" = "001000" firstSixBits "fmul" = "001001" firstSixBits "mac" = "001010" firstSixBits "msc" = "001011" firstSixBits "mad" = "001110" firstSixBits "msd" = "001111" firstSixBits "and" = "010000" firstSixBits "nand" = "010001" firstSixBits "or" = "010100" firstSixBits "nor" = "010101" firstSixBits "xor" = "010110" firstSixBits "mov" = "011000" firstSixBits "mvn" = "011001" firstSixBits "i2f" = "011010" firstSixBits "f2i" = "011011" firstSixBits "lda" = "011100" firstSixBits "ldb" = "011101" firstSixBits "ldc" = "011110" firstSixBits "stb" = "011111" loadImmGroup = "10" branchGroup = "11" bin x = showIntAtBase 2 intToDigit x "" binary `ofSize` n = replicate (n - (length binary)) '0' ++ binary fixedSizeBinary n x = bin x `ofSize` n translate :: Instruction -> String translate (RegInstr op r1@(Reg _ n1) r2) = firstSixBits op ++ firstOp ++ secondOp where firstOp = fixedSizeBinary 5 n1 secondOp = case r2 of (Reg b2 n2) -> fixedSizeBinary 5 n2 (Imm n2) -> fixedSizeBinary 5 n2 translate (LdImmInstr imm) = loadImmGroup ++ fixedSizeBinary 14 imm translate Label = "" translate BlankLine = "" translate (BranchInstr op adr) = branchGroup ++ flags ++ jumpAdr where flags = case op of "beq" -> "1000" "ble" -> "1001" "blt" -> "0001" "jmp" -> "0000" jumpAdr = fixedSizeBinary 10 adr translate Nop = replicate 16 '0' -- Note: Shifting is redefined to be halt translate Halt = "0011" ++ fixedSizeBinary 12 0 parseFile p fname = do input <- readFile fname return $ runParser p startState fname input main = do args <- getArgs results <- parseFile pMain $ head args case results of Left err -> print err Right (instrs, (count, labelMap)) -> do putStrLn $ "Instructions assembled: " ++ show count putStrLn $ concat $ map translate instrs
terjr/hassembler
hassembler.hs
bsd-3-clause
5,839
2
17
1,576
2,008
1,009
999
188
5
module CalculatorKata.Day6 (calculate) where calculate :: String -> Double calculate src = calculate' src "" where calculate' :: String -> String -> Double calculate' "" num = read num calculate' (c:src) num | c == '+' = read num + calculate' src "" | c == '-' = read num - calculate' src "" | c == '*' = read num * calculate' src "" | c == '/' = read num / calculate' src "" | otherwise = calculate' src (num ++ [c])
Alex-Diez/haskell-tdd-kata
old-katas/src/CalculatorKata/Day6.hs
bsd-3-clause
555
0
11
221
199
95
104
11
2
----------------------------------------------------------------------------- -- | -- Module : XMonad.Actions.WindowNames -- Copyright : (c) 2015 Phil Lindberg <[email protected]> -- License : BSD3-style (see LICENSE) -- -- Maintainer : Phil Lindberg <[email protected]> -- Stability : experimental -- Portability : unportable -- -- A library to automatically put named windows into the DynamicLog. It -- provides a modification of 'XMonad.Hooks.DynamicLog.dynamicLogWithPP' and -- some helper functions. -- ----------------------------------------------------------------------------- module XMonad.Actions.WindowNames ( -- * Usage -- $usage -- * Modified dynamic log functions dynamicLogStringMap , dynamicLogWithPPMap -- * Helper functions , evalLookup , filterShortNames -- * Stack and StackSet functions , getTagStack , getWindowNames , integrateM -- * Pretty-printer functions , pprWindowSetMap -- * To Do -- $todo ) where import Codec.Binary.UTF8.String (encodeString) import Control.Monad (mapM, MonadPlus(mplus)) import Data.List (intercalate) import Data.Maybe (listToMaybe, catMaybes, fromMaybe, isJust) import XMonad import XMonad.Hooks.DynamicLog (PP(..)) import XMonad.Hooks.UrgencyHook (readUrgents) import XMonad.Util.NamedWindows (getName) import XMonad.Util.WorkspaceCompare (WorkspaceSort) import qualified Data.Map as M import qualified XMonad.StackSet as W -- $usage -- You can add this to your @~\/.xmonad\/xmonad.hs@: -- -- > import Data.List (isSuffixOf) -- > import System.IO -- > import WindowNames -- > import XMonad -- > import XMonad.Hooks.DynamicLog -- > import XMonad.Util.Run(spawnPipe) -- -- A simple example is a follows (the example uses xmobar but feel free to -- substitute dzen or anything else): -- -- > myShortNames :: [(String -> Bool, String -> String)] -- > myShortNames = [ (("Pentadactyl" `isSuffixOf`), const "ff" ) -- > , ((=="Library"), const "ffdl") -- > , (const True, take 4 ) -- catch all -- > ] -- > -- > main = do -- > h <- spawnPipe "xmobar -options -foo -bar" -- > xmonad $ myXmonadConfig h -- > -- > myXmonadConfig h = defaultConfig { -- > ... -- > logHook = dynamicLogWithPPMap (getWindowNames (foc . filt) filt filt) xmobarPP { ppOutput = hPutStrLn h } -- > ... -- > } -- > where foc = wrap "<fn=1>" "</fn>" -- xmobar font 1 (additionalFonts!!0) -- > filt = filterShortNames myShortNames -- -- This works nicely with named tmux sessions or screens. You can use it in -- conjunction with other dynamicLog string modifiers. -- $todo -- * Incorporate with 'XMonad.Actions.TagWindows' -- * Efficiency (ExtensionClass?) -- * Make sure it works with the newest XMonad -- | Helper function used by 'filterShortNames' which run the first function in -- the tuple on the value. If it evalutes to true, the output of the second -- function if returned. evalLookup :: MonadPlus m => a -> [(a -> Bool, a -> b)] -> m b evalLookup n ((f,g):xs) | f n = return (g n) `mplus` evalLookup n xs | otherwise = evalLookup n xs -- | Example filter short name function. filterShortNames :: [(String -> Bool, String -> String)] -> String -> String filterShortNames filterList s = fromMaybe "" $ evalLookup s filterList -- | Get a Map of window tag to strings in the format "wsId:w1,w2,...,wN" where -- w1,...,wn represent the names of windows according to -- 'XMonad.Util.NamedWindows.getName' after being run through the respective -- focus, up, and down functions getWindowNames :: (String -> String) -- ^ Function to apply to the focused window's name. -> (String -> String) -- ^ Function to apply to the up windows' names. -> (String -> String) -- ^ Function to apply to the down windows' names. -> W.StackSet WorkspaceId l Window sid sd -- ^ Stack set -> X (M.Map WorkspaceId String) getWindowNames f u d w = fmap M.fromList $ mapM returnNameStr $ getTagStack w where joinWinNames x _ = fmap (((x ++ ":") ++) . intercalate "," . filter (not . null)) . integrateM (nameFunc f) (nameFunc u) (nameFunc d) returnNameStr (x, y) = maybe (return x) (joinWinNames x y) y >>= \z -> return (x, z) nameFunc f = fmap (f . show) . getName -- | Run a monadic function on 'XMonad.StackSet.Stack' components. integrateM :: Monad m => (a -> m b) -- ^ Monadic function to run on focused components. -> (a -> m b) -- ^ Monadic function to run on up components. -> (a -> m b) -- ^ Monadic function to run on down components. -> W.Stack a -- ^ Current StackSet -> m [b] integrateM f u d (W.Stack x l r) = do r2 <- mapM u r x2 <- f x l2 <- mapM d l return $ reverse l2 ++ x2 : r2 -- | Get a list of tag and maybe Stack. getTagStack :: W.StackSet t l a sid sd -> [(t, Maybe (W.Stack a))] getTagStack w = [ (i, a) | W.Workspace i _ a <- (W.workspace . W.current) w : map W.workspace (W.visible w) ++ W.hidden w ] -- | Modified 'XMonad.Hooks.DynamicLog.dynamicLogWithPP' which takes an -- additional WindowSet to Map of WorkspaceId to String. dynamicLogWithPPMap :: (WindowSet -> X (M.Map WorkspaceId String)) -> PP -> X () dynamicLogWithPPMap wsIdMap pp = dynamicLogStringMap wsIdMap pp >>= io . ppOutput pp -- | Modifed 'XMonad.Hooks.DynamicLog.dynamicLogString' which takes an -- additional WindowSet to Map of WorkspaceId to String. dynamicLogStringMap :: (WindowSet -> X (M.Map WorkspaceId String)) -> PP -> X String dynamicLogStringMap wsIdMap pp = do winset <- gets windowset urgents <- readUrgents sort' <- ppSort pp -- layout description let ld = description . W.layout . W.workspace . W.current $ winset -- workspace list ws <- pprWindowSetMap wsIdMap sort' urgents pp winset -- window title wt <- maybe (return "") (fmap show . getName) . W.peek $ winset -- run extra loggers, ignoring any that generate errors. extras <- mapM (`catchX` return Nothing) $ ppExtras pp return $ encodeString . sepBy (ppSep pp) . ppOrder pp $ [ ws , ppLayout pp ld , ppTitle pp $ ppTitleSanitize pp wt ] ++ catMaybes extras -- | Format the workspace information pprWindowSetMap :: (WindowSet -> X (M.Map WorkspaceId String)) -- ^ Map of WorkspaceId to a string to be displayed. -> WorkspaceSort -- ^ A workspace sorting function -> [Window] -- ^ A list of urgent windows -> PP -- ^ pretty-printer format -> WindowSet -- ^ current WindowSet -> X String pprWindowSetMap wsIdFunc sort' urgents pp s = do wsIdMap <- wsIdFunc s return $ sepBy (ppWsSep pp) . map (fmt wsIdMap) . sort' $ map W.workspace (W.current s : W.visible s) ++ W.hidden s where this = W.currentTag s visibles = map (W.tag . W.workspace) (W.visible s) fmt wsIdMap w = printer pp (fromMaybe "" $ M.lookup (W.tag w) wsIdMap) where printer | any (\x -> maybe False (== W.tag w) (W.findTag x s)) urgents = ppUrgent | W.tag w == this = ppCurrent | W.tag w `elem` visibles = ppVisible | isJust (W.stack w) = ppHidden | otherwise = ppHiddenNoWindows -- | Output a list of strings, ignoring empty ones and separating the -- rest with the given separator. sepBy :: String -- ^ separator -> [String] -- ^ fields to output -> String sepBy sep = intercalate sep . filter (not . null)
plindbe2/xmonad-windownames
src/XMonad/Actions/WindowNames.hs
bsd-3-clause
8,274
0
18
2,484
1,634
875
759
85
1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeSynonymInstances #-} -- | Models for <http://vk.com/dev/audio.get Audio API> module VK.API.Models.Audio where import Data.Aeson import Data.Aeson.Casing import qualified Data.Text as T import Data.Time.Clock.POSIX (POSIXTime) import GHC.Generics (Generic) import Network.API.Builder import VK.API.CommonTypes import VK.API.Models.Types import VK.Internal.Orphans () data AudioUser = AudioUser { audiouserId :: !Int , audiouserPhoto :: T.Text , audiouserName :: T.Text , audiouserNameGen :: T.Text } deriving (Show, Generic) instance FromJSON AudioUser where parseJSON = genericParseJSON $ aesonPrefix snakeCase data Audio = Audio { audioId :: !Int -- ^ идентификатор аудиозаписи. , audioOwnerId :: !OwnerId -- ^ идентификатор владельца аудиозаписи. , audioArtist :: !T.Text -- ^ текст описания аудиозаписи. , audioTitle :: !T.Text -- ^ название аудиозаписи. , audioDuration :: !Int -- ^ длительность ролика в секундах. , audioDate :: !POSIXTime -- ^ дата создания аудиозаписи в формате unixtime. , audioUrl :: T.Text , audioGenreId :: !(Maybe AudioGenre) , audioAlbumId :: !(Maybe Int) , audioLyricsId :: !(Maybe Int) -- ^ идентификатор текста аудиозаписи (если доступно). , audioUser :: !(Maybe AudioUser) } deriving (Show, Generic) instance FromJSON Audio where parseJSON = genericParseJSON $ aesonPrefix snakeCase instance Receivable Audio where receive = useFromJSON data Lyrics = Lyrics { lyricsLyricsId :: Int , lyricsText :: T.Text } deriving (Show, Generic) instance FromJSON Lyrics where parseJSON = genericParseJSON $ aesonPrefix snakeCase instance Receivable Lyrics where receive = useFromJSON data UploadServer = UploadServer {uploadserverUploadUrl :: !T.Text} deriving (Show, Generic) instance FromJSON UploadServer where parseJSON = genericParseJSON $ aesonPrefix snakeCase instance Receivable UploadServer where receive = useFromJSON data SavedAudio = SavedAudio { savedaudioId :: !Int -- ^ идентификатор аудиозаписи. , savedaudioOwnerId :: !OwnerId -- ^ идентификатор владельца аудиозаписи. , savedaudioArtist :: !T.Text -- ^ текст описания аудиозаписи. , savedaudioTitle :: !T.Text -- ^ название аудиозаписи. , savedaudioUrl :: T.Text } deriving (Show, Generic) instance FromJSON SavedAudio where parseJSON = genericParseJSON $ aesonPrefix snakeCase instance Receivable SavedAudio where receive = useFromJSON --- newtype AudioEditResponse = AudioEditResponse { audioeditResponse :: Int } deriving (Show, Generic) instance FromJSON AudioEditResponse where parseJSON = genericParseJSON $ aesonPrefix snakeCase instance Receivable AudioEditResponse where receive = useFromJSON data AudioSaveResponse = AudioSaveResponse { audiosaveUploadUrl :: !T.Text , audiosaveVid :: !Int , audiosaveOwnerId :: !OwnerId , audiosaveName :: !T.Text , audiosaveDescription :: !T.Text , audiosaveAccessKey :: !T.Text } deriving (Show, Generic) instance FromJSON AudioSaveResponse where parseJSON = genericParseJSON $ aesonPrefix snakeCase instance Receivable AudioSaveResponse where receive = useFromJSON data Comment = Comment { commentId :: !Int , commentFromId :: !Int , commentDate :: !POSIXTime , commentText :: !T.Text , commentLikes :: !Likes , commentRealOffset :: !(Maybe Int) , commentProfiles :: !(Maybe [User]) , commentGroups :: !(Maybe [Group]) } deriving (Show, Generic) instance FromJSON Comment where parseJSON = genericParseJSON $ aesonPrefix snakeCase instance Receivable Comment where receive = useFromJSON data Tag = Tag { tagUserId :: Int , tagTagId :: Int , tagPlacerId :: Int , tagTaggedName :: T.Text , tagDate :: POSIXTime , tagViewed :: Int } deriving (Show, Generic) instance FromJSON Tag where parseJSON = genericParseJSON $ aesonPrefix snakeCase instance Receivable Tag where receive = useFromJSON data NewTag = NewTag { newtagTagId :: Int , newtagPlacerId :: Int , newtagCreated :: POSIXTime } deriving (Show, Generic) instance FromJSON NewTag where parseJSON = genericParseJSON $ aesonPrefix snakeCase instance Receivable NewTag where receive = useFromJSON data BroadcastListResult = BroadcastListUser User | BroadcastListGroup Group deriving Show instance FromJSON BroadcastListResult where parseJSON v@(Object o ) = o .:? "type" .!= ("group"::String) >>= parser where parser "profile" = BroadcastListUser <$> parseJSON v parser _ = BroadcastListGroup <$> parseJSON v parseJSON _ = mempty instance Receivable BroadcastListResult where receive = useFromJSON data AlbumResponse = AlbumResponse { albumrespAlbumId :: !Int } deriving (Show, Generic) instance FromJSON AlbumResponse where parseJSON = genericParseJSON $ aesonPrefix snakeCase
eryx67/vk-api
src/VK/API/Models/Audio.hs
bsd-3-clause
5,973
0
12
1,638
1,162
655
507
197
0
module User where import Data.Aeson import Test.QuickCheck data User = User { name :: String , email :: String , password :: String , status :: Status } data Status = Enabled | Disabled -- Exercise 1 - Implement instance of Show for User -- class Show a where -- show :: a -> String -- Exercise 2 - Implement instance of ToJSON for User -- class ToJSON a where -- toJSON :: a -> Value -- Exercise 3 - Implement instance of FromJSON for User -- class FromJSON a where -- parseJSON :: Value -> Data.Aeson.Types.Internal.Parser a -- Exercise 4 - Implement instance of Arbitrary for User -- class Arbitrary a where -- arbitrary :: Gen a
whitehead1415/typeclasses-mob
app/User.hs
bsd-3-clause
723
0
8
208
69
48
21
8
0
module Main where import FJ import Reduction import Control.Applicative import System.Environment main :: IO () main = do args <- getArgs let originalFile = args !! 0 modifiedFile = args !! 1 fromClass = args !! 2 fromMethod = args !! 3 toClass = args !! 4 toMethod = args !! 5 original <- parse <$> readFile originalFile modified <- parse <$> readFile modifiedFile case (,) <$> original <*> modified of Right (originalProgram, modifiedProgram) -> case checkMethodExtraction originalProgram modifiedProgram fromClass fromMethod toClass toMethod of Nothing -> putStrLn "refactoring verified successfully" Just (actual, expected) -> do putStrLn $ "actual: " ++ show actual putStrLn $ "expected: " ++ show expected Left err -> print err
ademinn/RefactoringVerification
src/verifier/Main.hs
bsd-3-clause
897
0
16
277
242
121
121
24
3
module RunLength (decode, encode) where import Data.List.Split (keepDelimsR, split, whenElt, dropFinalBlank) import Data.List (group) import Data.Char (isDigit) encode :: String -> String encode = concatMap compact . group where compact l = lengthString (length l) ++ [head l] lengthString n = if n > 1 then show n else "" decode :: String -> String decode = concatMap expand . splitCodes where splitCodes = split . dropFinalBlank . keepDelimsR . whenElt $ not . isDigit expand code = replicate (count code) (last code) count code = max 1 (read $ '0' : init code)
Bugfry/exercises
exercism/haskell/run-length-encoding/src/RunLength.hs
mit
627
0
11
157
225
120
105
20
2
module PityTheBool where import Data.Int -- 1. Given the datatype -- data BigSmall = -- Big Bool -- | Small Bool -- deriving (Eq, Show) -- What is the cardinality of the datatype? -- True + False | True + False -- 2 + 2 = 4 -- 2. Given the datatype data NumberOrBool = Numba Int8 | BoolyBool Bool deriving (Eq, Show) -- let myNumba = Numba (-128) myNumba = Numba (-127) -- What is the cardinality of NumberOrBool? -- Int8 + Bool -- |-128| + 1 + 127 + Bool -- 256 + 2 -- 258 -- What happens when you create a Numba with a -- numeric literal larger than 127? -- *PityTheBool> let myNumba = Numba (-128) -- <interactive>:74:23: warning: [-Woverflowed-literals] -- Literal 128 is out of the Int8 range -128..127 -- If you are trying to write a large negative literal, use NegativeLiterals
brodyberg/Notes
ProjectRosalind.hsproj/LearnHaskell/lib/HaskellBook/PityTheBoolChapter11.hs
mit
822
0
7
185
68
48
20
7
1
{- | Module : ./Common/RunParsers.hs Description : test some parsers (and printers) Copyright : (c) Christian Maeder and Uni Bremen 2002-2003 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : portable test some parsers (and printers) -} module Common.RunParsers (exec, StringParser, toStringParser, fromAParser) where import Common.AnalyseAnnos (addGlobalAnnos) import Common.AnnoParser import Common.AnnoState import Common.DocUtils import Common.GlobalAnnotations import Common.Lexer (parseString) import Common.Parsec ((<<)) import Common.Result import Common.IO import System.Environment import Text.ParserCombinators.Parsec import Text.ParserCombinators.Parsec.Pos type StringParser = GlobalAnnos -> AParser () String fromAParser :: Pretty a => AParser () a -> StringParser fromAParser p ga = fmap (flip (showGlobalDoc ga) "") p toStringParser :: Pretty a => (GlobalAnnos -> AParser () a) -> StringParser toStringParser p ga = fmap (flip (showGlobalDoc ga) "") $ p ga exec :: [(String, StringParser)] -> [(String, StringParser)] -> IO () exec lps fps = do l <- getArgs setStdEnc Utf8 case l of [] -> parseSpec emptyGlobalAnnos . snd $ head fps opt : tl -> do let lps' = filter (\ (s, _) -> s == opt) lps fps' = filter (\ (s, _) -> s == opt) fps ga <- case tl of [] -> return emptyGlobalAnnos annoFile : _ -> do str <- readFile annoFile maybe (error "run parser") return $ maybeResult $ addGlobalAnnos emptyGlobalAnnos $ parseString annotations str -- should not fail but may return empty annos case (lps', fps') of ([], []) -> do putStrLn ("unknown option: " ++ opt) p <- getProgName putStrLn $ "Usage: " ++ p ++ " [OPTIONS] <Annotations> < infile" putStrLn "where OPTIONS is one of:" putStrLn $ unwords $ map fst lps ++ map fst fps ([], (_, hd) : _) -> parseSpec ga hd ((_, hd) : _, _) -> checkLines ga hd checkLines :: GlobalAnnos -> StringParser -> IO () checkLines ga p = getContents >>= putStr . unlines . scanLines ga p 1 . lines scanLines :: GlobalAnnos -> StringParser -> Line -> [String] -> [String] scanLines ga p n inp = case inp of [] -> [] x : l -> parseLine ga p x n : scanLines ga p (n + 1) l parseLine :: GlobalAnnos -> StringParser -> String -> Line -> String parseLine ga p line n = let pos = setSourceLine (initialPos "") n parser = do setPosition pos i <- p ga eof return i in showParse $ runParser parser (emptyAnnos ()) "" line parseSpec :: GlobalAnnos -> StringParser -> IO () parseSpec ga p = getContents >>= putStrLn . showParse . runParser (p ga << eof) (emptyAnnos ()) "" showParse :: Either ParseError String -> String showParse e = case e of Left err -> "parse error at " ++ showErr err ++ "\n" Right x -> x
spechub/Hets
Common/RunParsers.hs
gpl-2.0
2,973
0
23
720
993
503
490
67
5
-- | String formatting helpers, starting to get a bit out of control. module Hledger.Utils.String ( -- * misc lowercase, uppercase, underline, stripbrackets, unbracket, -- quoting quoteIfNeeded, singleQuoteIfNeeded, -- quotechars, -- whitespacechars, escapeQuotes, words', unwords', stripAnsi, -- * single-line layout strip, lstrip, rstrip, chomp, elideLeft, elideRight, formatString, -- * multi-line layout concatTopPadded, concatBottomPadded, concatOneLine, vConcatLeftAligned, vConcatRightAligned, padtop, padbottom, padleft, padright, cliptopleft, fitto, -- * wide-character-aware layout charWidth, strWidth, takeWidth, fitString, fitStringMulti, padLeftWide, padRightWide ) where import Data.Char import Data.List import Text.Megaparsec.Compat import Text.Printf (printf) import Hledger.Utils.Parse import Hledger.Utils.Regex lowercase, uppercase :: String -> String lowercase = map toLower uppercase = map toUpper -- | Remove leading and trailing whitespace. strip :: String -> String strip = lstrip . rstrip -- | Remove leading whitespace. lstrip :: String -> String lstrip = dropWhile isSpace -- | Remove trailing whitespace. rstrip :: String -> String rstrip = reverse . lstrip . reverse -- | Remove trailing newlines/carriage returns. chomp :: String -> String chomp = reverse . dropWhile (`elem` "\r\n") . reverse stripbrackets :: String -> String stripbrackets = dropWhile (`elem` "([") . reverse . dropWhile (`elem` "])") . reverse :: String -> String elideLeft :: Int -> String -> String elideLeft width s = if length s > width then ".." ++ reverse (take (width - 2) $ reverse s) else s elideRight :: Int -> String -> String elideRight width s = if length s > width then take (width - 2) s ++ ".." else s -- | Clip and pad a string to a minimum & maximum width, and/or left/right justify it. -- Works on multi-line strings too (but will rewrite non-unix line endings). formatString :: Bool -> Maybe Int -> Maybe Int -> String -> String formatString leftJustified minwidth maxwidth s = intercalate "\n" $ map (printf fmt) $ lines s where justify = if leftJustified then "-" else "" minwidth' = maybe "" show minwidth maxwidth' = maybe "" (("."++).show) maxwidth fmt = "%" ++ justify ++ minwidth' ++ maxwidth' ++ "s" underline :: String -> String underline s = s' ++ replicate (length s) '-' ++ "\n" where s' | last s == '\n' = s | otherwise = s ++ "\n" -- | Double-quote this string if it contains whitespace, single quotes -- or double-quotes, escaping the quotes as needed. quoteIfNeeded :: String -> String quoteIfNeeded s | any (`elem` s) (quotechars++whitespacechars) = "\"" ++ escapeDoubleQuotes s ++ "\"" | otherwise = s -- | Single-quote this string if it contains whitespace or double-quotes. -- No good for strings containing single quotes. singleQuoteIfNeeded :: String -> String singleQuoteIfNeeded s | any (`elem` s) whitespacechars = "'"++s++"'" | otherwise = s quotechars, whitespacechars :: [Char] quotechars = "'\"" whitespacechars = " \t\n\r" escapeDoubleQuotes :: String -> String escapeDoubleQuotes = regexReplace "\"" "\"" escapeQuotes :: String -> String escapeQuotes = regexReplace "([\"'])" "\\1" -- | Quote-aware version of words - don't split on spaces which are inside quotes. -- NB correctly handles "a'b" but not "''a''". Can raise an error if parsing fails. words' :: String -> [String] words' "" = [] words' s = map stripquotes $ fromparse $ parsewithString p s where p = do ss <- (singleQuotedPattern <|> doubleQuotedPattern <|> pattern) `sepBy` some spacenonewline -- eof return ss pattern = many (noneOf whitespacechars) singleQuotedPattern = between (char '\'') (char '\'') (many $ noneOf "'") doubleQuotedPattern = between (char '"') (char '"') (many $ noneOf "\"") -- | Quote-aware version of unwords - single-quote strings which contain whitespace unwords' :: [String] -> String unwords' = unwords . map quoteIfNeeded -- | Strip one matching pair of single or double quotes on the ends of a string. stripquotes :: String -> String stripquotes s = if isSingleQuoted s || isDoubleQuoted s then init $ tail s else s isSingleQuoted s@(_:_:_) = head s == '\'' && last s == '\'' isSingleQuoted _ = False isDoubleQuoted s@(_:_:_) = head s == '"' && last s == '"' isDoubleQuoted _ = False unbracket :: String -> String unbracket s | (head s == '[' && last s == ']') || (head s == '(' && last s == ')') = init $ tail s | otherwise = s -- | Join several multi-line strings as side-by-side rectangular strings of the same height, top-padded. -- Treats wide characters as double width. concatTopPadded :: [String] -> String concatTopPadded strs = intercalate "\n" $ map concat $ transpose padded where lss = map lines strs h = maximum $ map length lss ypad ls = replicate (difforzero h (length ls)) "" ++ ls xpad ls = map (padLeftWide w) ls where w | null ls = 0 | otherwise = maximum $ map strWidth ls padded = map (xpad . ypad) lss -- | Join several multi-line strings as side-by-side rectangular strings of the same height, bottom-padded. -- Treats wide characters as double width. concatBottomPadded :: [String] -> String concatBottomPadded strs = intercalate "\n" $ map concat $ transpose padded where lss = map lines strs h = maximum $ map length lss ypad ls = ls ++ replicate (difforzero h (length ls)) "" xpad ls = map (padRightWide w) ls where w | null ls = 0 | otherwise = maximum $ map strWidth ls padded = map (xpad . ypad) lss -- | Join multi-line strings horizontally, after compressing each of -- them to a single line with a comma and space between each original line. concatOneLine :: [String] -> String concatOneLine strs = concat $ map ((intercalate ", ").lines) strs -- | Join strings vertically, left-aligned and right-padded. vConcatLeftAligned :: [String] -> String vConcatLeftAligned ss = intercalate "\n" $ map showfixedwidth ss where showfixedwidth = printf (printf "%%-%ds" width) width = maximum $ map length ss -- | Join strings vertically, right-aligned and left-padded. vConcatRightAligned :: [String] -> String vConcatRightAligned ss = intercalate "\n" $ map showfixedwidth ss where showfixedwidth = printf (printf "%%%ds" width) width = maximum $ map length ss -- | Convert a multi-line string to a rectangular string top-padded to the specified height. padtop :: Int -> String -> String padtop h s = intercalate "\n" xpadded where ls = lines s sh = length ls sw | null ls = 0 | otherwise = maximum $ map length ls ypadded = replicate (difforzero h sh) "" ++ ls xpadded = map (padleft sw) ypadded -- | Convert a multi-line string to a rectangular string bottom-padded to the specified height. padbottom :: Int -> String -> String padbottom h s = intercalate "\n" xpadded where ls = lines s sh = length ls sw | null ls = 0 | otherwise = maximum $ map length ls ypadded = ls ++ replicate (difforzero h sh) "" xpadded = map (padleft sw) ypadded difforzero :: (Num a, Ord a) => a -> a -> a difforzero a b = maximum [(a - b), 0] -- | Convert a multi-line string to a rectangular string left-padded to the specified width. -- Treats wide characters as double width. padleft :: Int -> String -> String padleft w "" = concat $ replicate w " " padleft w s = intercalate "\n" $ map (printf (printf "%%%ds" w)) $ lines s -- | Convert a multi-line string to a rectangular string right-padded to the specified width. -- Treats wide characters as double width. padright :: Int -> String -> String padright w "" = concat $ replicate w " " padright w s = intercalate "\n" $ map (printf (printf "%%-%ds" w)) $ lines s -- | Clip a multi-line string to the specified width and height from the top left. cliptopleft :: Int -> Int -> String -> String cliptopleft w h = intercalate "\n" . take h . map (take w) . lines -- | Clip and pad a multi-line string to fill the specified width and height. fitto :: Int -> Int -> String -> String fitto w h s = intercalate "\n" $ take h $ rows ++ repeat blankline where rows = map (fit w) $ lines s fit w = take w . (++ repeat ' ') blankline = replicate w ' ' -- Functions below treat wide (eg CJK) characters as double-width. -- | General-purpose wide-char-aware single-line string layout function. -- It can left- or right-pad a short string to a minimum width. -- It can left- or right-clip a long string to a maximum width, optionally inserting an ellipsis (the third argument). -- It clips and pads on the right when the fourth argument is true, otherwise on the left. -- It treats wide characters as double width. fitString :: Maybe Int -> Maybe Int -> Bool -> Bool -> String -> String fitString mminwidth mmaxwidth ellipsify rightside s = (clip . pad) s where clip :: String -> String clip s = case mmaxwidth of Just w | strWidth s > w -> case rightside of True -> takeWidth (w - length ellipsis) s ++ ellipsis False -> ellipsis ++ reverse (takeWidth (w - length ellipsis) $ reverse s) | otherwise -> s where ellipsis = if ellipsify then ".." else "" Nothing -> s pad :: String -> String pad s = case mminwidth of Just w | sw < w -> case rightside of True -> s ++ replicate (w - sw) ' ' False -> replicate (w - sw) ' ' ++ s | otherwise -> s Nothing -> s where sw = strWidth s -- | A version of fitString that works on multi-line strings, -- separate for now to avoid breakage. -- This will rewrite any line endings to unix newlines. fitStringMulti :: Maybe Int -> Maybe Int -> Bool -> Bool -> String -> String fitStringMulti mminwidth mmaxwidth ellipsify rightside s = (intercalate "\n" . map (fitString mminwidth mmaxwidth ellipsify rightside) . lines) s -- | Left-pad a string to the specified width. -- Treats wide characters as double width. -- Works on multi-line strings too (but will rewrite non-unix line endings). padLeftWide :: Int -> String -> String padLeftWide w "" = replicate w ' ' padLeftWide w s = intercalate "\n" $ map (fitString (Just w) Nothing False False) $ lines s -- XXX not yet replaceable by -- padLeftWide w = fitStringMulti (Just w) Nothing False False -- | Right-pad a string to the specified width. -- Treats wide characters as double width. -- Works on multi-line strings too (but will rewrite non-unix line endings). padRightWide :: Int -> String -> String padRightWide w "" = replicate w ' ' padRightWide w s = intercalate "\n" $ map (fitString (Just w) Nothing False True) $ lines s -- XXX not yet replaceable by -- padRightWide w = fitStringMulti (Just w) Nothing False True -- | Double-width-character-aware string truncation. Take as many -- characters as possible from a string without exceeding the -- specified width. Eg takeWidth 3 "りんご" = "り". takeWidth :: Int -> String -> String takeWidth _ "" = "" takeWidth 0 _ = "" takeWidth w (c:cs) | cw <= w = c:takeWidth (w-cw) cs | otherwise = "" where cw = charWidth c -- from Pandoc (copyright John MacFarlane, GPL) -- see also http://unicode.org/reports/tr11/#Description -- | Calculate the render width of a string, considering -- wide characters (counted as double width), ANSI escape codes -- (not counted), and line breaks (in a multi-line string, the longest -- line determines the width). strWidth :: String -> Int strWidth "" = 0 strWidth s = maximum $ map (foldr (\a b -> charWidth a + b) 0) $ lines s' where s' = stripAnsi s stripAnsi :: String -> String stripAnsi = regexReplace "\ESC\\[([0-9]+;)*([0-9]+)?[ABCDHJKfmsu]" "" -- | Get the designated render width of a character: 0 for a combining -- character, 1 for a regular character, 2 for a wide character. -- (Wide characters are rendered as exactly double width in apps and -- fonts that support it.) (From Pandoc.) charWidth :: Char -> Int charWidth c = case c of _ | c < '\x0300' -> 1 | c >= '\x0300' && c <= '\x036F' -> 0 -- combining | c >= '\x0370' && c <= '\x10FC' -> 1 | c >= '\x1100' && c <= '\x115F' -> 2 | c >= '\x1160' && c <= '\x11A2' -> 1 | c >= '\x11A3' && c <= '\x11A7' -> 2 | c >= '\x11A8' && c <= '\x11F9' -> 1 | c >= '\x11FA' && c <= '\x11FF' -> 2 | c >= '\x1200' && c <= '\x2328' -> 1 | c >= '\x2329' && c <= '\x232A' -> 2 | c >= '\x232B' && c <= '\x2E31' -> 1 | c >= '\x2E80' && c <= '\x303E' -> 2 | c == '\x303F' -> 1 | c >= '\x3041' && c <= '\x3247' -> 2 | c >= '\x3248' && c <= '\x324F' -> 1 -- ambiguous | c >= '\x3250' && c <= '\x4DBF' -> 2 | c >= '\x4DC0' && c <= '\x4DFF' -> 1 | c >= '\x4E00' && c <= '\xA4C6' -> 2 | c >= '\xA4D0' && c <= '\xA95F' -> 1 | c >= '\xA960' && c <= '\xA97C' -> 2 | c >= '\xA980' && c <= '\xABF9' -> 1 | c >= '\xAC00' && c <= '\xD7FB' -> 2 | c >= '\xD800' && c <= '\xDFFF' -> 1 | c >= '\xE000' && c <= '\xF8FF' -> 1 -- ambiguous | c >= '\xF900' && c <= '\xFAFF' -> 2 | c >= '\xFB00' && c <= '\xFDFD' -> 1 | c >= '\xFE00' && c <= '\xFE0F' -> 1 -- ambiguous | c >= '\xFE10' && c <= '\xFE19' -> 2 | c >= '\xFE20' && c <= '\xFE26' -> 1 | c >= '\xFE30' && c <= '\xFE6B' -> 2 | c >= '\xFE70' && c <= '\xFEFF' -> 1 | c >= '\xFF01' && c <= '\xFF60' -> 2 | c >= '\xFF61' && c <= '\x16A38' -> 1 | c >= '\x1B000' && c <= '\x1B001' -> 2 | c >= '\x1D000' && c <= '\x1F1FF' -> 1 | c >= '\x1F200' && c <= '\x1F251' -> 2 | c >= '\x1F300' && c <= '\x1F773' -> 1 | c >= '\x20000' && c <= '\x3FFFD' -> 2 | otherwise -> 1
mstksg/hledger
hledger-lib/Hledger/Utils/String.hs
gpl-3.0
14,268
0
21
3,642
3,927
2,001
1,926
250
6
{-# 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.AutoScaling.DescribeTerminationPolicyTypes -- 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) -- -- Describes the termination policies supported by Auto Scaling. -- -- /See:/ <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_DescribeTerminationPolicyTypes.html AWS API Reference> for DescribeTerminationPolicyTypes. module Network.AWS.AutoScaling.DescribeTerminationPolicyTypes ( -- * Creating a Request describeTerminationPolicyTypes , DescribeTerminationPolicyTypes -- * Destructuring the Response , describeTerminationPolicyTypesResponse , DescribeTerminationPolicyTypesResponse -- * Response Lenses , dtptrsTerminationPolicyTypes , dtptrsResponseStatus ) where import Network.AWS.AutoScaling.Types import Network.AWS.AutoScaling.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'describeTerminationPolicyTypes' smart constructor. data DescribeTerminationPolicyTypes = DescribeTerminationPolicyTypes' deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DescribeTerminationPolicyTypes' with the minimum fields required to make a request. -- describeTerminationPolicyTypes :: DescribeTerminationPolicyTypes describeTerminationPolicyTypes = DescribeTerminationPolicyTypes' instance AWSRequest DescribeTerminationPolicyTypes where type Rs DescribeTerminationPolicyTypes = DescribeTerminationPolicyTypesResponse request = postQuery autoScaling response = receiveXMLWrapper "DescribeTerminationPolicyTypesResult" (\ s h x -> DescribeTerminationPolicyTypesResponse' <$> (x .@? "TerminationPolicyTypes" .!@ mempty >>= may (parseXMLList "member")) <*> (pure (fromEnum s))) instance ToHeaders DescribeTerminationPolicyTypes where toHeaders = const mempty instance ToPath DescribeTerminationPolicyTypes where toPath = const "/" instance ToQuery DescribeTerminationPolicyTypes where toQuery = const (mconcat ["Action" =: ("DescribeTerminationPolicyTypes" :: ByteString), "Version" =: ("2011-01-01" :: ByteString)]) -- | /See:/ 'describeTerminationPolicyTypesResponse' smart constructor. data DescribeTerminationPolicyTypesResponse = DescribeTerminationPolicyTypesResponse' { _dtptrsTerminationPolicyTypes :: !(Maybe [Text]) , _dtptrsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DescribeTerminationPolicyTypesResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dtptrsTerminationPolicyTypes' -- -- * 'dtptrsResponseStatus' describeTerminationPolicyTypesResponse :: Int -- ^ 'dtptrsResponseStatus' -> DescribeTerminationPolicyTypesResponse describeTerminationPolicyTypesResponse pResponseStatus_ = DescribeTerminationPolicyTypesResponse' { _dtptrsTerminationPolicyTypes = Nothing , _dtptrsResponseStatus = pResponseStatus_ } -- | The termination policies supported by Auto Scaling ('OldestInstance', -- 'OldestLaunchConfiguration', 'NewestInstance', -- 'ClosestToNextInstanceHour', and 'Default'). dtptrsTerminationPolicyTypes :: Lens' DescribeTerminationPolicyTypesResponse [Text] dtptrsTerminationPolicyTypes = lens _dtptrsTerminationPolicyTypes (\ s a -> s{_dtptrsTerminationPolicyTypes = a}) . _Default . _Coerce; -- | The response status code. dtptrsResponseStatus :: Lens' DescribeTerminationPolicyTypesResponse Int dtptrsResponseStatus = lens _dtptrsResponseStatus (\ s a -> s{_dtptrsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-autoscaling/gen/Network/AWS/AutoScaling/DescribeTerminationPolicyTypes.hs
mpl-2.0
4,471
0
15
857
494
295
199
69
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.ELB.SetLoadBalancerListenerSSLCertificate -- 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. -- | Sets the certificate that terminates the specified listener's SSL -- connections. The specified certificate replaces any prior certificate that -- was used on the same load balancer and port. -- -- For more information on updating your SSL certificate, see <http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/US_UpdatingLoadBalancerSSL.html Updating an SSLCertificate for a Load Balancer> in the /Elastic Load Balancing Developer Guide/. -- -- <http://docs.aws.amazon.com/ElasticLoadBalancing/latest/APIReference/API_SetLoadBalancerListenerSSLCertificate.html> module Network.AWS.ELB.SetLoadBalancerListenerSSLCertificate ( -- * Request SetLoadBalancerListenerSSLCertificate -- ** Request constructor , setLoadBalancerListenerSSLCertificate -- ** Request lenses , slblsslcLoadBalancerName , slblsslcLoadBalancerPort , slblsslcSSLCertificateId -- * Response , SetLoadBalancerListenerSSLCertificateResponse -- ** Response constructor , setLoadBalancerListenerSSLCertificateResponse ) where import Network.AWS.Prelude import Network.AWS.Request.Query import Network.AWS.ELB.Types import qualified GHC.Exts data SetLoadBalancerListenerSSLCertificate = SetLoadBalancerListenerSSLCertificate { _slblsslcLoadBalancerName :: Text , _slblsslcLoadBalancerPort :: Int , _slblsslcSSLCertificateId :: Text } deriving (Eq, Ord, Read, Show) -- | 'SetLoadBalancerListenerSSLCertificate' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'slblsslcLoadBalancerName' @::@ 'Text' -- -- * 'slblsslcLoadBalancerPort' @::@ 'Int' -- -- * 'slblsslcSSLCertificateId' @::@ 'Text' -- setLoadBalancerListenerSSLCertificate :: Text -- ^ 'slblsslcLoadBalancerName' -> Int -- ^ 'slblsslcLoadBalancerPort' -> Text -- ^ 'slblsslcSSLCertificateId' -> SetLoadBalancerListenerSSLCertificate setLoadBalancerListenerSSLCertificate p1 p2 p3 = SetLoadBalancerListenerSSLCertificate { _slblsslcLoadBalancerName = p1 , _slblsslcLoadBalancerPort = p2 , _slblsslcSSLCertificateId = p3 } -- | The name of the load balancer. slblsslcLoadBalancerName :: Lens' SetLoadBalancerListenerSSLCertificate Text slblsslcLoadBalancerName = lens _slblsslcLoadBalancerName (\s a -> s { _slblsslcLoadBalancerName = a }) -- | The port that uses the specified SSL certificate. slblsslcLoadBalancerPort :: Lens' SetLoadBalancerListenerSSLCertificate Int slblsslcLoadBalancerPort = lens _slblsslcLoadBalancerPort (\s a -> s { _slblsslcLoadBalancerPort = a }) -- | The Amazon Resource Number (ARN) of the SSL certificate chain to use. For -- more information on SSL certificates, see <http://docs.aws.amazon.com/IAM/latest/UserGuide/ManagingServerCerts.html Managing Server Certificates> in -- the /AWS Identity and Access Management User Guide/. slblsslcSSLCertificateId :: Lens' SetLoadBalancerListenerSSLCertificate Text slblsslcSSLCertificateId = lens _slblsslcSSLCertificateId (\s a -> s { _slblsslcSSLCertificateId = a }) data SetLoadBalancerListenerSSLCertificateResponse = SetLoadBalancerListenerSSLCertificateResponse deriving (Eq, Ord, Read, Show, Generic) -- | 'SetLoadBalancerListenerSSLCertificateResponse' constructor. setLoadBalancerListenerSSLCertificateResponse :: SetLoadBalancerListenerSSLCertificateResponse setLoadBalancerListenerSSLCertificateResponse = SetLoadBalancerListenerSSLCertificateResponse instance ToPath SetLoadBalancerListenerSSLCertificate where toPath = const "/" instance ToQuery SetLoadBalancerListenerSSLCertificate where toQuery SetLoadBalancerListenerSSLCertificate{..} = mconcat [ "LoadBalancerName" =? _slblsslcLoadBalancerName , "LoadBalancerPort" =? _slblsslcLoadBalancerPort , "SSLCertificateId" =? _slblsslcSSLCertificateId ] instance ToHeaders SetLoadBalancerListenerSSLCertificate instance AWSRequest SetLoadBalancerListenerSSLCertificate where type Sv SetLoadBalancerListenerSSLCertificate = ELB type Rs SetLoadBalancerListenerSSLCertificate = SetLoadBalancerListenerSSLCertificateResponse request = post "SetLoadBalancerListenerSSLCertificate" response = nullResponse SetLoadBalancerListenerSSLCertificateResponse
kim/amazonka
amazonka-elb/gen/Network/AWS/ELB/SetLoadBalancerListenerSSLCertificate.hs
mpl-2.0
5,427
0
9
980
469
288
181
65
1
{-# LANGUAGE TupleSections, OverloadedStrings, QuasiQuotes, TemplateHaskell, TypeFamilies, RecordWildCards, DeriveGeneric ,MultiParamTypeClasses ,FlexibleInstances #-} module Model where import Prelude import Yesod import Data.Time import Data.Text (Text) import Database.Persist.Quasi import Data.Typeable (Typeable) -- You can define all of your database entities in the entities file. -- You can find more information on persistent and how to declare entities -- at: -- http://www.yesodweb.com/book/persistent/ share [mkPersist sqlOnlySettings, mkMigrate "migrateAll"] $(persistFileWith lowerCaseSettings "config/models")
smurphy8/backoffice
Model.hs
bsd-3-clause
647
0
8
89
75
44
31
11
0
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 -} module VarEnv ( -- * Var, Id and TyVar environments (maps) VarEnv, IdEnv, TyVarEnv, CoVarEnv, TyCoVarEnv, -- ** Manipulating these environments emptyVarEnv, unitVarEnv, mkVarEnv, mkVarEnv_Directly, elemVarEnv, extendVarEnv, extendVarEnv_C, extendVarEnv_Acc, extendVarEnv_Directly, extendVarEnvList, plusVarEnv, plusVarEnv_C, plusVarEnv_CD, plusVarEnvList, alterVarEnv, delVarEnvList, delVarEnv, delVarEnv_Directly, minusVarEnv, intersectsVarEnv, lookupVarEnv, lookupVarEnv_NF, lookupWithDefaultVarEnv, mapVarEnv, zipVarEnv, modifyVarEnv, modifyVarEnv_Directly, isEmptyVarEnv, elemVarEnvByKey, lookupVarEnv_Directly, filterVarEnv, filterVarEnv_Directly, restrictVarEnv, partitionVarEnv, -- * Deterministic Var environments (maps) DVarEnv, DIdEnv, DTyVarEnv, -- ** Manipulating these environments emptyDVarEnv, mkDVarEnv, dVarEnvElts, extendDVarEnv, extendDVarEnv_C, extendDVarEnvList, lookupDVarEnv, isEmptyDVarEnv, foldDVarEnv, mapDVarEnv, modifyDVarEnv, alterDVarEnv, plusDVarEnv, plusDVarEnv_C, unitDVarEnv, delDVarEnv, delDVarEnvList, partitionDVarEnv, anyDVarEnv, -- * The InScopeSet type InScopeSet, -- ** Operations on InScopeSets emptyInScopeSet, mkInScopeSet, delInScopeSet, extendInScopeSet, extendInScopeSetList, extendInScopeSetSet, getInScopeVars, lookupInScope, lookupInScope_Directly, unionInScope, elemInScopeSet, uniqAway, varSetInScope, -- * The RnEnv2 type RnEnv2, -- ** Operations on RnEnv2s mkRnEnv2, rnBndr2, rnBndrs2, rnBndr2_var, rnOccL, rnOccR, inRnEnvL, inRnEnvR, rnOccL_maybe, rnOccR_maybe, rnBndrL, rnBndrR, nukeRnEnvL, nukeRnEnvR, rnSwap, delBndrL, delBndrR, delBndrsL, delBndrsR, addRnInScopeSet, rnEtaL, rnEtaR, rnInScope, rnInScopeSet, lookupRnInScope, rnEnvL, rnEnvR, -- * TidyEnv and its operation TidyEnv, emptyTidyEnv ) where import OccName import Var import VarSet import UniqFM import UniqDFM import Unique import Util import Maybes import Outputable import StaticFlags {- ************************************************************************ * * In-scope sets * * ************************************************************************ -} -- | A set of variables that are in scope at some point -- "Secrets of the Glasgow Haskell Compiler inliner" Section 3.2 provides -- the motivation for this abstraction. data InScopeSet = InScope (VarEnv Var) {-# UNPACK #-} !Int -- The (VarEnv Var) is just a VarSet. But we write it like -- this to remind ourselves that you can look up a Var in -- the InScopeSet. Typically the InScopeSet contains the -- canonical version of the variable (e.g. with an informative -- unfolding), so this lookup is useful. -- -- INVARIANT: the VarEnv maps (the Unique of) a variable to -- a variable with the same Unique. (This was not -- the case in the past, when we had a grevious hack -- mapping var1 to var2. -- -- The Int is a kind of hash-value used by uniqAway -- For example, it might be the size of the set -- INVARIANT: it's not zero; we use it as a multiplier in uniqAway instance Outputable InScopeSet where ppr (InScope s _) = text "InScope" <+> braces (fsep (map (ppr . Var.varName) (nonDetEltsUFM s))) -- It's OK to use nonDetEltsUFM here because it's -- only for pretty printing -- In-scope sets get big, and with -dppr-debug -- the output is overwhelming emptyInScopeSet :: InScopeSet emptyInScopeSet = InScope emptyVarSet 1 getInScopeVars :: InScopeSet -> VarEnv Var getInScopeVars (InScope vs _) = vs mkInScopeSet :: VarEnv Var -> InScopeSet mkInScopeSet in_scope = InScope in_scope 1 extendInScopeSet :: InScopeSet -> Var -> InScopeSet extendInScopeSet (InScope in_scope n) v = InScope (extendVarEnv in_scope v v) (n + 1) extendInScopeSetList :: InScopeSet -> [Var] -> InScopeSet extendInScopeSetList (InScope in_scope n) vs = InScope (foldl (\s v -> extendVarEnv s v v) in_scope vs) (n + length vs) extendInScopeSetSet :: InScopeSet -> VarEnv Var -> InScopeSet extendInScopeSetSet (InScope in_scope n) vs = InScope (in_scope `plusVarEnv` vs) (n + sizeUFM vs) delInScopeSet :: InScopeSet -> Var -> InScopeSet delInScopeSet (InScope in_scope n) v = InScope (in_scope `delVarEnv` v) n elemInScopeSet :: Var -> InScopeSet -> Bool elemInScopeSet v (InScope in_scope _) = v `elemVarEnv` in_scope -- | Look up a variable the 'InScopeSet'. This lets you map from -- the variable's identity (unique) to its full value. lookupInScope :: InScopeSet -> Var -> Maybe Var lookupInScope (InScope in_scope _) v = lookupVarEnv in_scope v lookupInScope_Directly :: InScopeSet -> Unique -> Maybe Var lookupInScope_Directly (InScope in_scope _) uniq = lookupVarEnv_Directly in_scope uniq unionInScope :: InScopeSet -> InScopeSet -> InScopeSet unionInScope (InScope s1 _) (InScope s2 n2) = InScope (s1 `plusVarEnv` s2) n2 varSetInScope :: VarSet -> InScopeSet -> Bool varSetInScope vars (InScope s1 _) = vars `subVarSet` s1 -- | @uniqAway in_scope v@ finds a unique that is not used in the -- in-scope set, and gives that to v. uniqAway :: InScopeSet -> Var -> Var -- It starts with v's current unique, of course, in the hope that it won't -- have to change, and thereafter uses a combination of that and the hash-code -- found in the in-scope set uniqAway in_scope var | var `elemInScopeSet` in_scope = uniqAway' in_scope var -- Make a new one | otherwise = var -- Nothing to do uniqAway' :: InScopeSet -> Var -> Var -- This one *always* makes up a new variable uniqAway' (InScope set n) var = try 1 where orig_unique = getUnique var try k | debugIsOn && (k > 1000) = pprPanic "uniqAway loop:" (ppr k <+> text "tries" <+> ppr var <+> int n) | uniq `elemVarSetByKey` set = try (k + 1) | debugIsOn && opt_PprStyle_Debug && (k > 3) = pprTrace "uniqAway:" (ppr k <+> text "tries" <+> ppr var <+> int n) setVarUnique var uniq | otherwise = setVarUnique var uniq where uniq = deriveUnique orig_unique (n * k) {- ************************************************************************ * * Dual renaming * * ************************************************************************ -} -- | Rename Environment 2 -- -- When we are comparing (or matching) types or terms, we are faced with -- \"going under\" corresponding binders. E.g. when comparing: -- -- > \x. e1 ~ \y. e2 -- -- Basically we want to rename [@x@ -> @y@] or [@y@ -> @x@], but there are lots of -- things we must be careful of. In particular, @x@ might be free in @e2@, or -- y in @e1@. So the idea is that we come up with a fresh binder that is free -- in neither, and rename @x@ and @y@ respectively. That means we must maintain: -- -- 1. A renaming for the left-hand expression -- -- 2. A renaming for the right-hand expressions -- -- 3. An in-scope set -- -- Furthermore, when matching, we want to be able to have an 'occurs check', -- to prevent: -- -- > \x. f ~ \y. y -- -- matching with [@f@ -> @y@]. So for each expression we want to know that set of -- locally-bound variables. That is precisely the domain of the mappings 1. -- and 2., but we must ensure that we always extend the mappings as we go in. -- -- All of this information is bundled up in the 'RnEnv2' data RnEnv2 = RV2 { envL :: VarEnv Var -- Renaming for Left term , envR :: VarEnv Var -- Renaming for Right term , in_scope :: InScopeSet } -- In scope in left or right terms -- The renamings envL and envR are *guaranteed* to contain a binding -- for every variable bound as we go into the term, even if it is not -- renamed. That way we can ask what variables are locally bound -- (inRnEnvL, inRnEnvR) mkRnEnv2 :: InScopeSet -> RnEnv2 mkRnEnv2 vars = RV2 { envL = emptyVarEnv , envR = emptyVarEnv , in_scope = vars } addRnInScopeSet :: RnEnv2 -> VarEnv Var -> RnEnv2 addRnInScopeSet env vs | isEmptyVarEnv vs = env | otherwise = env { in_scope = extendInScopeSetSet (in_scope env) vs } rnInScope :: Var -> RnEnv2 -> Bool rnInScope x env = x `elemInScopeSet` in_scope env rnInScopeSet :: RnEnv2 -> InScopeSet rnInScopeSet = in_scope -- | Retrieve the left mapping rnEnvL :: RnEnv2 -> VarEnv Var rnEnvL = envL -- | Retrieve the right mapping rnEnvR :: RnEnv2 -> VarEnv Var rnEnvR = envR rnBndrs2 :: RnEnv2 -> [Var] -> [Var] -> RnEnv2 -- ^ Applies 'rnBndr2' to several variables: the two variable lists must be of equal length rnBndrs2 env bsL bsR = foldl2 rnBndr2 env bsL bsR rnBndr2 :: RnEnv2 -> Var -> Var -> RnEnv2 -- ^ @rnBndr2 env bL bR@ goes under a binder @bL@ in the Left term, -- and binder @bR@ in the Right term. -- It finds a new binder, @new_b@, -- and returns an environment mapping @bL -> new_b@ and @bR -> new_b@ rnBndr2 env bL bR = fst $ rnBndr2_var env bL bR rnBndr2_var :: RnEnv2 -> Var -> Var -> (RnEnv2, Var) -- ^ Similar to 'rnBndr2' but returns the new variable as well as the -- new environment rnBndr2_var (RV2 { envL = envL, envR = envR, in_scope = in_scope }) bL bR = (RV2 { envL = extendVarEnv envL bL new_b -- See Note , envR = extendVarEnv envR bR new_b -- [Rebinding] , in_scope = extendInScopeSet in_scope new_b }, new_b) where -- Find a new binder not in scope in either term new_b | not (bL `elemInScopeSet` in_scope) = bL | not (bR `elemInScopeSet` in_scope) = bR | otherwise = uniqAway' in_scope bL -- Note [Rebinding] -- If the new var is the same as the old one, note that -- the extendVarEnv *deletes* any current renaming -- E.g. (\x. \x. ...) ~ (\y. \z. ...) -- -- Inside \x \y { [x->y], [y->y], {y} } -- \x \z { [x->x], [y->y, z->x], {y,x} } rnBndrL :: RnEnv2 -> Var -> (RnEnv2, Var) -- ^ Similar to 'rnBndr2' but used when there's a binder on the left -- side only. rnBndrL (RV2 { envL = envL, envR = envR, in_scope = in_scope }) bL = (RV2 { envL = extendVarEnv envL bL new_b , envR = envR , in_scope = extendInScopeSet in_scope new_b }, new_b) where new_b = uniqAway in_scope bL rnBndrR :: RnEnv2 -> Var -> (RnEnv2, Var) -- ^ Similar to 'rnBndr2' but used when there's a binder on the right -- side only. rnBndrR (RV2 { envL = envL, envR = envR, in_scope = in_scope }) bR = (RV2 { envR = extendVarEnv envR bR new_b , envL = envL , in_scope = extendInScopeSet in_scope new_b }, new_b) where new_b = uniqAway in_scope bR rnEtaL :: RnEnv2 -> Var -> (RnEnv2, Var) -- ^ Similar to 'rnBndrL' but used for eta expansion -- See Note [Eta expansion] rnEtaL (RV2 { envL = envL, envR = envR, in_scope = in_scope }) bL = (RV2 { envL = extendVarEnv envL bL new_b , envR = extendVarEnv envR new_b new_b -- Note [Eta expansion] , in_scope = extendInScopeSet in_scope new_b }, new_b) where new_b = uniqAway in_scope bL rnEtaR :: RnEnv2 -> Var -> (RnEnv2, Var) -- ^ Similar to 'rnBndr2' but used for eta expansion -- See Note [Eta expansion] rnEtaR (RV2 { envL = envL, envR = envR, in_scope = in_scope }) bR = (RV2 { envL = extendVarEnv envL new_b new_b -- Note [Eta expansion] , envR = extendVarEnv envR bR new_b , in_scope = extendInScopeSet in_scope new_b }, new_b) where new_b = uniqAway in_scope bR delBndrL, delBndrR :: RnEnv2 -> Var -> RnEnv2 delBndrL rn@(RV2 { envL = env, in_scope = in_scope }) v = rn { envL = env `delVarEnv` v, in_scope = in_scope `extendInScopeSet` v } delBndrR rn@(RV2 { envR = env, in_scope = in_scope }) v = rn { envR = env `delVarEnv` v, in_scope = in_scope `extendInScopeSet` v } delBndrsL, delBndrsR :: RnEnv2 -> [Var] -> RnEnv2 delBndrsL rn@(RV2 { envL = env, in_scope = in_scope }) v = rn { envL = env `delVarEnvList` v, in_scope = in_scope `extendInScopeSetList` v } delBndrsR rn@(RV2 { envR = env, in_scope = in_scope }) v = rn { envR = env `delVarEnvList` v, in_scope = in_scope `extendInScopeSetList` v } rnOccL, rnOccR :: RnEnv2 -> Var -> Var -- ^ Look up the renaming of an occurrence in the left or right term rnOccL (RV2 { envL = env }) v = lookupVarEnv env v `orElse` v rnOccR (RV2 { envR = env }) v = lookupVarEnv env v `orElse` v rnOccL_maybe, rnOccR_maybe :: RnEnv2 -> Var -> Maybe Var -- ^ Look up the renaming of an occurrence in the left or right term rnOccL_maybe (RV2 { envL = env }) v = lookupVarEnv env v rnOccR_maybe (RV2 { envR = env }) v = lookupVarEnv env v inRnEnvL, inRnEnvR :: RnEnv2 -> Var -> Bool -- ^ Tells whether a variable is locally bound inRnEnvL (RV2 { envL = env }) v = v `elemVarEnv` env inRnEnvR (RV2 { envR = env }) v = v `elemVarEnv` env lookupRnInScope :: RnEnv2 -> Var -> Var lookupRnInScope env v = lookupInScope (in_scope env) v `orElse` v nukeRnEnvL, nukeRnEnvR :: RnEnv2 -> RnEnv2 -- ^ Wipe the left or right side renaming nukeRnEnvL env = env { envL = emptyVarEnv } nukeRnEnvR env = env { envR = emptyVarEnv } rnSwap :: RnEnv2 -> RnEnv2 -- ^ swap the meaning of left and right rnSwap (RV2 { envL = envL, envR = envR, in_scope = in_scope }) = RV2 { envL = envR, envR = envL, in_scope = in_scope } {- Note [Eta expansion] ~~~~~~~~~~~~~~~~~~~~ When matching (\x.M) ~ N we rename x to x' with, where x' is not in scope in either term. Then we want to behave as if we'd seen (\x'.M) ~ (\x'.N x') Since x' isn't in scope in N, the form (\x'. N x') doesn't capture any variables in N. But we must nevertheless extend the envR with a binding [x' -> x'], to support the occurs check. For example, if we don't do this, we can get silly matches like forall a. (\y.a) ~ v succeeding with [a -> v y], which is bogus of course. ************************************************************************ * * Tidying * * ************************************************************************ -} -- | Tidy Environment -- -- When tidying up print names, we keep a mapping of in-scope occ-names -- (the 'TidyOccEnv') and a Var-to-Var of the current renamings type TidyEnv = (TidyOccEnv, VarEnv Var) emptyTidyEnv :: TidyEnv emptyTidyEnv = (emptyTidyOccEnv, emptyVarEnv) {- ************************************************************************ * * \subsection{@VarEnv@s} * * ************************************************************************ -} -- | Variable Environment type VarEnv elt = UniqFM elt -- | Identifier Environment type IdEnv elt = VarEnv elt -- | Type Variable Environment type TyVarEnv elt = VarEnv elt -- | Type or Coercion Variable Environment type TyCoVarEnv elt = VarEnv elt -- | Coercion Variable Environment type CoVarEnv elt = VarEnv elt emptyVarEnv :: VarEnv a mkVarEnv :: [(Var, a)] -> VarEnv a mkVarEnv_Directly :: [(Unique, a)] -> VarEnv a zipVarEnv :: [Var] -> [a] -> VarEnv a unitVarEnv :: Var -> a -> VarEnv a alterVarEnv :: (Maybe a -> Maybe a) -> VarEnv a -> Var -> VarEnv a extendVarEnv :: VarEnv a -> Var -> a -> VarEnv a extendVarEnv_C :: (a->a->a) -> VarEnv a -> Var -> a -> VarEnv a extendVarEnv_Acc :: (a->b->b) -> (a->b) -> VarEnv b -> Var -> a -> VarEnv b extendVarEnv_Directly :: VarEnv a -> Unique -> a -> VarEnv a plusVarEnv :: VarEnv a -> VarEnv a -> VarEnv a plusVarEnvList :: [VarEnv a] -> VarEnv a extendVarEnvList :: VarEnv a -> [(Var, a)] -> VarEnv a lookupVarEnv_Directly :: VarEnv a -> Unique -> Maybe a filterVarEnv_Directly :: (Unique -> a -> Bool) -> VarEnv a -> VarEnv a delVarEnv_Directly :: VarEnv a -> Unique -> VarEnv a partitionVarEnv :: (a -> Bool) -> VarEnv a -> (VarEnv a, VarEnv a) restrictVarEnv :: VarEnv a -> VarSet -> VarEnv a delVarEnvList :: VarEnv a -> [Var] -> VarEnv a delVarEnv :: VarEnv a -> Var -> VarEnv a minusVarEnv :: VarEnv a -> VarEnv b -> VarEnv a intersectsVarEnv :: VarEnv a -> VarEnv a -> Bool plusVarEnv_C :: (a -> a -> a) -> VarEnv a -> VarEnv a -> VarEnv a plusVarEnv_CD :: (a -> a -> a) -> VarEnv a -> a -> VarEnv a -> a -> VarEnv a mapVarEnv :: (a -> b) -> VarEnv a -> VarEnv b modifyVarEnv :: (a -> a) -> VarEnv a -> Var -> VarEnv a isEmptyVarEnv :: VarEnv a -> Bool lookupVarEnv :: VarEnv a -> Var -> Maybe a filterVarEnv :: (a -> Bool) -> VarEnv a -> VarEnv a lookupVarEnv_NF :: VarEnv a -> Var -> a lookupWithDefaultVarEnv :: VarEnv a -> a -> Var -> a elemVarEnv :: Var -> VarEnv a -> Bool elemVarEnvByKey :: Unique -> VarEnv a -> Bool elemVarEnv = elemUFM elemVarEnvByKey = elemUFM_Directly alterVarEnv = alterUFM extendVarEnv = addToUFM extendVarEnv_C = addToUFM_C extendVarEnv_Acc = addToUFM_Acc extendVarEnv_Directly = addToUFM_Directly extendVarEnvList = addListToUFM plusVarEnv_C = plusUFM_C plusVarEnv_CD = plusUFM_CD delVarEnvList = delListFromUFM delVarEnv = delFromUFM minusVarEnv = minusUFM intersectsVarEnv e1 e2 = not (isEmptyVarEnv (e1 `intersectUFM` e2)) plusVarEnv = plusUFM plusVarEnvList = plusUFMList lookupVarEnv = lookupUFM filterVarEnv = filterUFM lookupWithDefaultVarEnv = lookupWithDefaultUFM mapVarEnv = mapUFM mkVarEnv = listToUFM mkVarEnv_Directly= listToUFM_Directly emptyVarEnv = emptyUFM unitVarEnv = unitUFM isEmptyVarEnv = isNullUFM lookupVarEnv_Directly = lookupUFM_Directly filterVarEnv_Directly = filterUFM_Directly delVarEnv_Directly = delFromUFM_Directly partitionVarEnv = partitionUFM restrictVarEnv env vs = filterVarEnv_Directly keep env where keep u _ = u `elemVarSetByKey` vs zipVarEnv tyvars tys = mkVarEnv (zipEqual "zipVarEnv" tyvars tys) lookupVarEnv_NF env id = case lookupVarEnv env id of Just xx -> xx Nothing -> panic "lookupVarEnv_NF: Nothing" {- @modifyVarEnv@: Look up a thing in the VarEnv, then mash it with the modify function, and put it back. -} modifyVarEnv mangle_fn env key = case (lookupVarEnv env key) of Nothing -> env Just xx -> extendVarEnv env key (mangle_fn xx) modifyVarEnv_Directly :: (a -> a) -> UniqFM a -> Unique -> UniqFM a modifyVarEnv_Directly mangle_fn env key = case (lookupUFM_Directly env key) of Nothing -> env Just xx -> addToUFM_Directly env key (mangle_fn xx) -- Deterministic VarEnv -- See Note [Deterministic UniqFM] in UniqDFM for explanation why we need -- DVarEnv. -- | Deterministic Variable Environment type DVarEnv elt = UniqDFM elt -- | Deterministic Identifier Environment type DIdEnv elt = DVarEnv elt -- | Deterministic Type Variable Environment type DTyVarEnv elt = DVarEnv elt emptyDVarEnv :: DVarEnv a emptyDVarEnv = emptyUDFM dVarEnvElts :: DVarEnv a -> [a] dVarEnvElts = eltsUDFM mkDVarEnv :: [(Var, a)] -> DVarEnv a mkDVarEnv = listToUDFM extendDVarEnv :: DVarEnv a -> Var -> a -> DVarEnv a extendDVarEnv = addToUDFM lookupDVarEnv :: DVarEnv a -> Var -> Maybe a lookupDVarEnv = lookupUDFM foldDVarEnv :: (a -> b -> b) -> b -> DVarEnv a -> b foldDVarEnv = foldUDFM mapDVarEnv :: (a -> b) -> DVarEnv a -> DVarEnv b mapDVarEnv = mapUDFM alterDVarEnv :: (Maybe a -> Maybe a) -> DVarEnv a -> Var -> DVarEnv a alterDVarEnv = alterUDFM plusDVarEnv :: DVarEnv a -> DVarEnv a -> DVarEnv a plusDVarEnv = plusUDFM plusDVarEnv_C :: (a -> a -> a) -> DVarEnv a -> DVarEnv a -> DVarEnv a plusDVarEnv_C = plusUDFM_C unitDVarEnv :: Var -> a -> DVarEnv a unitDVarEnv = unitUDFM delDVarEnv :: DVarEnv a -> Var -> DVarEnv a delDVarEnv = delFromUDFM delDVarEnvList :: DVarEnv a -> [Var] -> DVarEnv a delDVarEnvList = delListFromUDFM isEmptyDVarEnv :: DVarEnv a -> Bool isEmptyDVarEnv = isNullUDFM extendDVarEnv_C :: (a -> a -> a) -> DVarEnv a -> Var -> a -> DVarEnv a extendDVarEnv_C = addToUDFM_C modifyDVarEnv :: (a -> a) -> DVarEnv a -> Var -> DVarEnv a modifyDVarEnv mangle_fn env key = case (lookupDVarEnv env key) of Nothing -> env Just xx -> extendDVarEnv env key (mangle_fn xx) partitionDVarEnv :: (a -> Bool) -> DVarEnv a -> (DVarEnv a, DVarEnv a) partitionDVarEnv = partitionUDFM extendDVarEnvList :: DVarEnv a -> [(Var, a)] -> DVarEnv a extendDVarEnvList = addListToUDFM anyDVarEnv :: (a -> Bool) -> DVarEnv a -> Bool anyDVarEnv = anyUDFM
snoyberg/ghc
compiler/basicTypes/VarEnv.hs
bsd-3-clause
21,678
0
14
5,660
4,755
2,630
2,125
322
2
module Main where import Control.Conditional (unlessM) import Data.Time.Clock import Prelude hiding (readFile, writeFile) import ALife.Creatur import ALife.Creatur.Wain hiding (size) import ALife.Creatur.Wain.Brain import ALife.Realtra.Wain import ALife.Realtra.Image import Control.Monad (replicateM) import Control.Monad.Random (evalRandIO) import Data.ByteString (readFile, writeFile) import qualified Data.Serialize as DS import Data.Version (showVersion) import Paths_creatur_realtra (version) import System.Directory (doesFileExist) imageBenchmark :: Image -> IO () imageBenchmark img = do let imgs = replicate 100 img mapM_ imageBenchmark' imgs imageBenchmark' :: Image -> IO () imageBenchmark' img = do let x = encode img (decode x :: Either String Image) `seq` return () runBenchmark :: String -> IO () -> IO () runBenchmark s b = do start <- getCurrentTime b end <- getCurrentTime putStrLn $ s ++ " took " ++ show (diffUTCTime end start) prep :: IO () prep = do putStrLn "WARNING: Generating image for test. Run this a second time to get accurate results." img <- readImage $ "/home/amy/GalaxyZoo/table2/tiny-images/587742903940153520.jpeg" writeAstronomer testImageFilename w main :: IO () main = do putStrLn $ "creatur-realtra v" ++ showVersion version putStrLn ALife.Creatur.Wain.programVersion putStrLn ALife.Creatur.programVersion img <- readImage $ "/home/amy/GalaxyZoo/table2/tiny-images/587742903940153520.jpeg" runBenchmark "imageBenchmark" (imageBenchmark img)
mhwombat/creatur-realtra.OLD
test/Benchmark2.hs
bsd-3-clause
1,523
0
10
224
433
226
207
42
1
{-# OPTIONS_GHC -Wall #-} module Validate (Result, module') where import Control.Monad (foldM_, when) import qualified Data.Map as Map import qualified Data.Maybe as Maybe import qualified Data.Set as Set import qualified Data.Foldable as F import qualified Data.Traversable as T import AST.Expression.General as Expr import qualified AST.Effects as Effects import qualified AST.Expression.Source as Source import qualified AST.Expression.Valid as Valid import qualified AST.Declaration as D import qualified AST.Module as Module import qualified AST.Module.Name as ModuleName import qualified AST.Pattern as Pattern import qualified AST.Type as Type import qualified Elm.Compiler.Imports as Imports import qualified Elm.Package as Package import Elm.Utils ((|>)) import qualified Reporting.Annotation as A import qualified Reporting.Error.Syntax as Error import qualified Reporting.Region as R import qualified Reporting.Result as Result type Result warning a = Result.Result () warning Error.Error a -- MODULES module' :: Module.Source -> Result wrn Module.Valid module' (Module.Module name path info) = let (ModuleName.Canonical pkgName _) = name (Module.Source tag settings docs exports imports decls) = info in do (ValidStuff ports structure) <- validateDecls decls validEffects <- validateEffects tag settings ports (D._defs structure) return $ Module.Module name path $ Module.Valid docs exports (addDefaults pkgName imports) structure validEffects -- IMPORTS addDefaults :: Package.Name -> [Module.UserImport] -> ([Module.DefaultImport], [Module.UserImport]) addDefaults pkgName imports = flip (,) imports $ if pkgName == Package.core then [] else Imports.defaults -- EFFECTS validateEffects :: Module.SourceTag -> Module.SourceSettings -> [A.Commented Effects.PortRaw] -> [A.Commented Valid.Def] -> Result wrn Effects.Raw validateEffects tag settings@(A.A _ pairs) ports validDefs = case tag of Module.Normal -> do noSettings Error.SettingsOnNormalModule settings noPorts ports return Effects.None Module.Port _ -> do noSettings Error.SettingsOnPortModule settings return (Effects.Port ports) Module.Effect tagRegion -> let collectSettings (A.A region setting, userValue) dict = Map.insertWith (++) setting [(region, userValue)] dict settingsDict = foldr collectSettings Map.empty pairs in do noPorts ports managerType <- toManagerType tagRegion settingsDict (r0, r1, r2) <- checkManager tagRegion managerType validDefs return (Effects.Manager () (Effects.Info tagRegion r0 r1 r2 managerType)) noSettings :: Error.Error -> Module.SourceSettings -> Result wrn () noSettings errorMsg (A.A region settings) = case settings of [] -> Result.ok () _ : _ -> Result.throw region errorMsg noPorts :: [A.Commented Effects.PortRaw] -> Result wrn () noPorts ports = case ports of [] -> Result.ok () _ : _ -> let toError (A.A (region, _) (Effects.PortRaw name _)) = A.A region (Error.UnexpectedPort name) in Result.throwMany (map toError ports) toManagerType :: R.Region -> Map.Map String [(R.Region, A.Located String)] -> Result wrn Effects.ManagerType toManagerType tagRegion settingsDict = let toErrors name entries = map (\entry -> A.A (fst entry) (Error.BadSettingOnEffectModule name)) entries errors = settingsDict |> Map.delete "command" |> Map.delete "subscription" |> Map.mapWithKey toErrors |> Map.elems |> concat in do when (not (null errors)) (Result.throwMany errors) maybeEffects <- (,) <$> extractOne "command" settingsDict <*> extractOne "subscription" settingsDict -- TODO check that cmd and sub types exist? case maybeEffects of (Nothing, Nothing) -> Result.throw tagRegion Error.NoSettingsOnEffectModule (Just cmd, Nothing) -> return (Effects.CmdManager cmd) (Nothing, Just sub) -> return (Effects.SubManager sub) (Just cmd, Just sub) -> return (Effects.FxManager cmd sub) extractOne :: String -> Map.Map String [(R.Region, A.Located String)] -> Result wrn (Maybe (A.Located String)) extractOne name settingsDict = case Map.lookup name settingsDict of Nothing -> return Nothing Just [] -> error "Empty lists should never be added to the dictionary of effect module settings." Just [(_, userType)] -> return (Just userType) Just ((region, _) : _) -> Result.throw region (Error.DuplicateSettingOnEffectModule name) -- CHECK EFFECT MANAGER checkManager :: R.Region -> Effects.ManagerType -> [A.Commented Valid.Def] -> Result wrn (R.Region, R.Region, R.Region) checkManager tagRegion managerType validDefs = let regionDict = Map.fromList (Maybe.mapMaybe getSimpleDefRegion validDefs) in const (,,) <$> requireMaps tagRegion regionDict managerType <*> requireRegion tagRegion regionDict "init" <*> requireRegion tagRegion regionDict "onEffects" <*> requireRegion tagRegion regionDict "onSelfMsg" getSimpleDefRegion :: A.Commented Valid.Def -> Maybe (String, R.Region) getSimpleDefRegion decl = case decl of A.A (region, _) (Valid.Def (A.A _ (Pattern.Var name)) _ _) -> Just (name, region) _ -> Nothing requireMaps :: R.Region -> Map.Map String R.Region -> Effects.ManagerType -> Result wrn () requireMaps tagRegion regionDict managerType = let check name = when (Map.notMember name regionDict) $ Result.throw tagRegion (Error.MissingManagerOnEffectModule name) in case managerType of Effects.CmdManager _ -> check "cmdMap" Effects.SubManager _ -> check "subMap" Effects.FxManager _ _ -> check "cmdMap" <* check "subMap" requireRegion :: R.Region -> Map.Map String R.Region -> String -> Result wrn R.Region requireRegion tagRegion regionDict name = case Map.lookup name regionDict of Just region -> return region Nothing -> Result.throw tagRegion (Error.MissingManagerOnEffectModule name) -- COLLAPSE COMMENTS collapseComments :: [D.CommentOr (A.Located a)] -> Result wrn [A.Commented a] collapseComments listWithComments = case listWithComments of [] -> Result.ok [] D.Comment (A.A _ msg) : D.Whatever (A.A region a) : rest -> let entry = A.A (region, Just msg) a in fmap (entry:) (collapseComments rest) D.Comment (A.A region _) : rest -> collapseComments rest <* Result.throw region Error.CommentOnNothing D.Whatever (A.A region a) : rest -> let entry = A.A (region, Nothing) a in fmap (entry:) (collapseComments rest) -- VALIDATE STRUCTURED SOURCE validateDecls :: [D.Source] -> Result wrn ValidStuff validateDecls sourceDecls = do rawDecls <- collapseComments sourceDecls validStuff <- validateRawDecls rawDecls let (D.Decls _ unions aliases _) = _structure validStuff return validStuff <* F.traverse_ checkTypeVarsInUnion unions <* F.traverse_ checkTypeVarsInAlias aliases <* checkDuplicates validStuff -- VALIDATE DECLARATIONS data ValidStuff = ValidStuff { _ports :: [A.Commented Effects.PortRaw] , _structure :: D.Valid } validateRawDecls :: [A.Commented D.Raw] -> Result wrn ValidStuff validateRawDecls commentedDecls = vrdHelp commentedDecls [] (D.Decls [] [] [] []) vrdHelp :: [A.Commented D.Raw] -> [A.Commented Effects.PortRaw] -> D.Valid -> Result wrn ValidStuff vrdHelp commentedDecls ports structure = case commentedDecls of [] -> Result.ok (ValidStuff ports structure) A.A ann decl : rest -> case decl of D.Union (D.Type name tvars ctors) -> vrdHelp rest ports (D.addUnion (A.A ann (D.Type name tvars ctors)) structure) D.Alias (D.Type name tvars alias) -> vrdHelp rest ports (D.addAlias (A.A ann (D.Type name tvars alias)) structure) D.Fixity fixity -> vrdHelp rest ports (D.addInfix fixity structure) D.Def (A.A region def) -> vrdDefHelp rest (A.A (region, snd ann) def) ports structure D.Port name tipe -> vrdHelp rest (A.A ann (Effects.PortRaw name tipe) : ports) structure vrdDefHelp :: [A.Commented D.Raw] -> A.Commented Source.Def' -> [A.Commented Effects.PortRaw] -> D.Valid -> Result wrn ValidStuff vrdDefHelp remainingDecls (A.A ann def) ports structure = let addDef validDef (ValidStuff finalPorts struct) = ValidStuff finalPorts (D.addDef (A.A ann validDef) struct) in case def of Source.Definition pat expr -> addDef <$> validateDef pat expr Nothing <*> vrdHelp remainingDecls ports structure Source.Annotation name tipe -> case remainingDecls of A.A _ (D.Def (A.A _ (Source.Definition pat expr))) : rest | Pattern.isVar name pat -> addDef <$> validateDef pat expr (Just tipe) <*> vrdHelp rest ports structure _ -> vrdHelp remainingDecls ports structure <* Result.throw (fst ann) (Error.TypeWithoutDefinition name) -- VALIDATE DEFINITIONS definitions :: [Source.Def] -> Result wrn [Valid.Def] definitions sourceDefs = do validDefs <- definitionsHelp sourceDefs validDefs |> map Valid.getPattern |> concatMap Pattern.boundVars |> detectDuplicates Error.DuplicateDefinition return validDefs definitionsHelp :: [Source.Def] -> Result wrn [Valid.Def] definitionsHelp sourceDefs = case sourceDefs of [] -> return [] A.A _ (Source.Definition pat expr) : rest -> (:) <$> validateDef pat expr Nothing <*> definitionsHelp rest A.A region (Source.Annotation name tipe) : rest -> case rest of A.A _ (Source.Definition pat expr) : rest' | Pattern.isVar name pat -> (:) <$> validateDef pat expr (Just tipe) <*> definitionsHelp rest' _ -> Result.throw region (Error.TypeWithoutDefinition name) validateDef :: Pattern.Raw -> Source.Expr -> Maybe Type.Raw -> Result wrn Valid.Def validateDef pat expr maybeType = do validExpr <- expression expr validateDefPattern pat validExpr return $ Valid.Def pat validExpr maybeType validateDefPattern :: Pattern.Raw -> Valid.Expr -> Result wrn () validateDefPattern pattern body = case fst (Expr.collectLambdas body) of [] -> return () args -> case pattern of A.A _ (Pattern.Var funcName) -> checkArguments funcName args _ -> let (A.A start _) = pattern (A.A end _) = last args in Result.throw (R.merge start end) (Error.BadFunctionName (length args)) checkArguments :: String -> [Pattern.Raw] -> Result wrn () checkArguments funcName args = let vars = concatMap Pattern.boundVars args checkDups seenArgs (A.A region arg) = if Set.member arg seenArgs then Result.throw region (Error.DuplicateArgument funcName arg) else return (Set.insert arg seenArgs) in foldM_ checkDups Set.empty vars -- VALIDATE EXPRESSIONS expression :: Source.Expr -> Result wrn Valid.Expr expression (A.A ann sourceExpression) = A.A ann <$> case sourceExpression of Var x -> return (Var x) Lambda pattern body -> Lambda <$> validatePattern pattern <*> expression body Binop op leftExpr rightExpr -> Binop op <$> expression leftExpr <*> expression rightExpr Case e branches -> Case <$> expression e <*> T.traverse (\(p,b) -> (,) <$> validatePattern p <*> expression b) branches Data name args -> Data name <$> T.traverse expression args Literal lit -> return (Literal lit) Range lowExpr highExpr -> Range <$> expression lowExpr <*> expression highExpr ExplicitList expressions -> ExplicitList <$> T.traverse expression expressions App funcExpr argExpr -> App <$> expression funcExpr <*> expression argExpr If branches finally -> If <$> T.traverse both branches <*> expression finally Access record field -> Access <$> expression record <*> return field Update record fields -> Update <$> expression record <*> T.traverse second fields Record fields -> let checkDups seenFields (field,_) = if Set.member field seenFields then Result.throw ann (Error.DuplicateFieldName field) else return (Set.insert field seenFields) in do foldM_ checkDups Set.empty fields Record <$> T.traverse second fields Let defs body -> Let <$> definitions defs <*> expression body Cmd moduleName -> return (Cmd moduleName) Sub moduleName -> return (Sub moduleName) OutgoingPort name tipe -> return (OutgoingPort name tipe) IncomingPort name tipe -> return (IncomingPort name tipe) Program _ _ -> error "DANGER - Program AST nodes should not be in validation phase." SaveEnv moduleName effects -> return (SaveEnv moduleName effects) GLShader uid src gltipe -> return (GLShader uid src gltipe) second :: (a, Source.Expr) -> Result wrn (a, Valid.Expr) second (value, expr) = (,) value <$> expression expr both :: (Source.Expr, Source.Expr) -> Result wrn (Valid.Expr, Valid.Expr) both (expr1, expr2) = (,) <$> expression expr1 <*> expression expr2 -- VALIDATE PATTERNS validatePattern :: Pattern.Raw -> Result wrn Pattern.Raw validatePattern pattern = do detectDuplicates Error.BadPattern (Pattern.boundVars pattern) return pattern -- DETECT DUPLICATES checkDuplicates :: ValidStuff -> Result wrn () checkDuplicates (ValidStuff ports (D.Decls defs unions aliases _)) = let -- SIMPLE NAMES defValues = concatMap (Pattern.boundVars . Valid.getPattern . A.drop) defs portValues = map fromPort ports fromPort (A.A (region, _) (Effects.PortRaw name _)) = A.A region name -- TYPE NAMES (types, typeValues) = unzip (map fromUnion unions ++ map fromAlias aliases) fromUnion (A.A (region, _) (D.Type name _ ctors)) = ( A.A region name , map (A.A region . fst) ctors ) fromAlias (A.A (region, _) (D.Type name _ (A.A _ tipe))) = (,) (A.A region name) $ case tipe of Type.RRecord _ _ -> [A.A region name] _ -> [] in F.sequenceA_ [ detectDuplicates Error.DuplicateValueDeclaration (portValues ++ defValues) , detectDuplicates Error.DuplicateValueDeclaration (concat typeValues) , detectDuplicates Error.DuplicateTypeDeclaration types ] detectDuplicates :: (String -> Error.Error) -> [A.Located String] -> Result wrn () detectDuplicates tag names = let add (A.A region name) dict = Map.insertWith (++) name [region] dict makeGroups pairs = Map.toList (foldr add Map.empty pairs) check (name, regions) = case regions of _ : region : _ -> Result.throw region (tag name) _ -> return () in F.traverse_ check (makeGroups names) -- UNBOUND TYPE VARIABLES checkTypeVarsInUnion :: A.Commented (D.Union Type.Raw) -> Result wrn () checkTypeVarsInUnion (A.A (region,_) (D.Type name boundVars ctors)) = case diff boundVars (concatMap freeVars (concatMap snd ctors)) of (_, []) -> return () (_, unbound) -> Result.throw region (Error.UnboundTypeVarsInUnion name boundVars unbound) checkTypeVarsInAlias :: A.Commented (D.Alias Type.Raw) -> Result wrn () checkTypeVarsInAlias (A.A (region,_) (D.Type name boundVars tipe)) = case diff boundVars (freeVars tipe) of ([], []) -> return () ([], unbound) -> Result.throw region (Error.UnboundTypeVarsInAlias name boundVars unbound) (unused, []) -> Result.throw region (Error.UnusedTypeVarsInAlias name boundVars unused) (unused, unbound) -> Result.throw region (Error.MessyTypeVarsInAlias name boundVars unused unbound) diff :: [String] -> [A.Located String] -> ([String], [String]) diff left right = let leftSet = Set.fromList left rightSet = Set.fromList (map A.drop right) in ( Set.toList (Set.difference leftSet rightSet) , Set.toList (Set.difference rightSet leftSet) ) freeVars :: Type.Raw -> [A.Located String] freeVars (A.A region tipe) = case tipe of Type.RLambda t1 t2 -> freeVars t1 ++ freeVars t2 Type.RVar x -> [A.A region x] Type.RType _ -> [] Type.RApp t ts -> concatMap freeVars (t:ts) Type.RRecord fields ext -> maybe [] freeVars ext ++ concatMap (freeVars . snd) fields
mgold/Elm
src/Validate.hs
bsd-3-clause
17,604
0
21
4,818
5,745
2,851
2,894
479
22
{-# 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.AutoScaling.SetDesiredCapacity -- 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. -- | Sets the size of the specified 'AutoScalingGroup'. -- -- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_SetDesiredCapacity.html> module Network.AWS.AutoScaling.SetDesiredCapacity ( -- * Request SetDesiredCapacity -- ** Request constructor , setDesiredCapacity -- ** Request lenses , sdcAutoScalingGroupName , sdcDesiredCapacity , sdcHonorCooldown -- * Response , SetDesiredCapacityResponse -- ** Response constructor , setDesiredCapacityResponse ) where import Network.AWS.Prelude import Network.AWS.Request.Query import Network.AWS.AutoScaling.Types import qualified GHC.Exts data SetDesiredCapacity = SetDesiredCapacity { _sdcAutoScalingGroupName :: Text , _sdcDesiredCapacity :: Int , _sdcHonorCooldown :: Maybe Bool } deriving (Eq, Ord, Read, Show) -- | 'SetDesiredCapacity' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'sdcAutoScalingGroupName' @::@ 'Text' -- -- * 'sdcDesiredCapacity' @::@ 'Int' -- -- * 'sdcHonorCooldown' @::@ 'Maybe' 'Bool' -- setDesiredCapacity :: Text -- ^ 'sdcAutoScalingGroupName' -> Int -- ^ 'sdcDesiredCapacity' -> SetDesiredCapacity setDesiredCapacity p1 p2 = SetDesiredCapacity { _sdcAutoScalingGroupName = p1 , _sdcDesiredCapacity = p2 , _sdcHonorCooldown = Nothing } -- | The name of the Auto Scaling group. sdcAutoScalingGroupName :: Lens' SetDesiredCapacity Text sdcAutoScalingGroupName = lens _sdcAutoScalingGroupName (\s a -> s { _sdcAutoScalingGroupName = a }) -- | The number of EC2 instances that should be running in the Auto Scaling group. sdcDesiredCapacity :: Lens' SetDesiredCapacity Int sdcDesiredCapacity = lens _sdcDesiredCapacity (\s a -> s { _sdcDesiredCapacity = a }) -- | By default, 'SetDesiredCapacity' overrides any cooldown period associated with -- the Auto Scaling group. Specify 'True' to make Auto Scaling to wait for the -- cool-down period associated with the Auto Scaling group to complete before -- initiating a scaling activity to set your Auto Scaling group to its new -- capacity. sdcHonorCooldown :: Lens' SetDesiredCapacity (Maybe Bool) sdcHonorCooldown = lens _sdcHonorCooldown (\s a -> s { _sdcHonorCooldown = a }) data SetDesiredCapacityResponse = SetDesiredCapacityResponse deriving (Eq, Ord, Read, Show, Generic) -- | 'SetDesiredCapacityResponse' constructor. setDesiredCapacityResponse :: SetDesiredCapacityResponse setDesiredCapacityResponse = SetDesiredCapacityResponse instance ToPath SetDesiredCapacity where toPath = const "/" instance ToQuery SetDesiredCapacity where toQuery SetDesiredCapacity{..} = mconcat [ "AutoScalingGroupName" =? _sdcAutoScalingGroupName , "DesiredCapacity" =? _sdcDesiredCapacity , "HonorCooldown" =? _sdcHonorCooldown ] instance ToHeaders SetDesiredCapacity instance AWSRequest SetDesiredCapacity where type Sv SetDesiredCapacity = AutoScaling type Rs SetDesiredCapacity = SetDesiredCapacityResponse request = post "SetDesiredCapacity" response = nullResponse SetDesiredCapacityResponse
romanb/amazonka
amazonka-autoscaling/gen/Network/AWS/AutoScaling/SetDesiredCapacity.hs
mpl-2.0
4,246
0
9
885
469
286
183
60
1
<?xml version='1.0' encoding='ISO-8859-1' ?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "../dtd/helpset_2_0.dtd"> <helpset version="1.0"> <!-- title --> <title>jAudio Help</title> <!-- maps --> <maps> <homeID>top</homeID> <mapref location="Map.jhm"/> </maps> <!-- views --> <view> <name>TOC</name> <label>Table Of Contents</label> <type>javax.help.TOCView</type> <data>SampleTOC.xml</data> </view> <!-- <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>SampleIndex.xml</data> </view> --> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <presentation default="true" displayviewimages="false"> <name>main window</name> <size width="700" height="400" /> <location x="200" y="200" /> <title>jAudio Help</title> <image>toplevelfolder</image> <toolbar> <helpaction>javax.help.BackAction</helpaction> <helpaction>javax.help.ForwardAction</helpaction> <helpaction>javax.help.SeparatorAction</helpaction> <helpaction>javax.help.HomeAction</helpaction> <helpaction>javax.help.ReloadAction</helpaction> <helpaction>javax.help.SeparatorAction</helpaction> <helpaction>javax.help.PrintAction</helpaction> <helpaction>javax.help.PrintSetupAction</helpaction> </toolbar> </presentation> <presentation> <name>main</name> <size width="400" height="400" /> <location x="200" y="200" /> <title>jAudio Help</title> </presentation> </helpset>
dmcennis/jAudioGIT
extras/Sample.hs
lgpl-2.1
1,793
142
48
358
675
373
302
-1
-1
{-# LANGUAGE PatternGuards #-} module Language.Nix.Path ( Path, mkPath, path ) where import Control.Lens import Distribution.Nixpkgs.Util.PrettyPrinting ( Pretty(..), punctuate, hcat, char ) import Language.Nix.Identifier -- | Paths are non-empty lists of identifiers in Nix. newtype Path = Path { _segments :: [Identifier] } deriving (Show, Eq, Ord) mkPath :: [Identifier] -> Path mkPath [] = error "Nix paths cannot be empty" mkPath p | [Identifier s] <- p, needsQuoting s = error ("invalid Nix path: " ++ show p) | otherwise = Path p path :: Lens' Path [Identifier] path f (Path ids) = mkPath `fmap` f ids instance Pretty Path where pPrint p = hcat $ punctuate (char '.') $ pPrint <$> p^.path
spencerjanssen/cabal2nix
src/Language/Nix/Path.hs
bsd-3-clause
736
0
12
154
247
135
112
16
1
------------------------------------------------------------------------------- -- | -- Module : CCO.Tree.ATerm -- Copyright : (c) 2008 Utrecht University -- License : All rights reserved -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- A straightforward implementation of the ATerm format for exchanging -- tree-structured data; see -- -- * Mark van den Brand, Hayco de Jong, Paul Klint, and Pieter A. Olivier. -- Efficient annotated terms. -- /Software - Practice and Experience (SPE)/, 30(3):259-291, 2000. -- ------------------------------------------------------------------------------- module CCO.Tree.ATerm ( -- * The @ATerm@ type ATerm (..) -- instances: Eq, Read, Show, Printable , Con -- = String ) where import CCO.Printing import Data.List ------------------------------------------------------------------------------- -- The ATerm type ------------------------------------------------------------------------------- -- | Node constructors. type Con = String -- | Terms. data ATerm = Integer Integer -- ^Integer literal. | Float Double -- ^Floating-point literal. | String String -- ^Textual literal. | App Con [ATerm] -- ^Constructor application. | Tuple [ATerm] -- ^Tuple of terms. | List [ATerm] -- ^List of terms. | Ann ATerm [ATerm] -- ^Annotated term. deriving (Eq, Read, Show) instance Printable ATerm where pp = ppATerm ------------------------------------------------------------------------------- -- Pretty printing ------------------------------------------------------------------------------- -- We distinguish between two fundamental modes for printing compound 'ATerm's -- (i.e., 'App's, 'Tuple's, 'List's, and 'Ann's): single-line mode and -- multi-line mode. -- Subterms of a term printed in single-line mode are themselves required to -- be printed in single-line mode; subterms of a term printed in multi-line -- mode may be printed in either mode. -- | Representation of the printing modes: a function that takes the a -- \"preamble\", a left bracket symbol, a right bracket symbol, and a list of -- subterms as arguments and produces a 'Doc' for the compound term that is to -- be printed. type Mode = Doc -> -- \"Preamble\". Doc -> -- Left bracket. Doc -> -- Right bracket. [ATerm] -> -- List of subterms. Doc -- 'Doc' for the compound term. -- | Single-line mode. singleLineMode :: Mode singleLineMode = \pre l r ts -> let docs = [ppATermIn singleLineMode t | t <- ts] `sepBy` text ", " in pre >|< l >|< docs >|< r -- | Multi-line mode. multiLineMode :: Mode multiLineMode = \pre l r ts -> singleLineMode pre l r ts >//< case ts of [] -> pre >|< l >-< r t : ts' -> let p = if isEmpty pre then l >|< text " " else pre >|< l >-< text " " in p >|< ppATermIn multiLineMode t >-< above [text ", " >|< ppATermIn multiLineMode t' | t' <- ts'] >-< r -- | Pretty prints an 'ATerm' in multi-line mode. ppATerm :: ATerm -> Doc ppATerm = ppATermIn multiLineMode ppATermIn :: Mode -> ATerm -> Doc ppATermIn _ (Integer n) = pp n ppATermIn _ (Float r) = pp r ppATermIn _ (String txt) = text (show txt) ppATermIn _ (App c []) = blue (text c) ppATermIn mode (App c ts) = mode (blue (text c)) lparen rparen ts ppATermIn mode (Tuple ts) = mode empty lparen rparen ts ppATermIn mode (List ts) = mode empty lbracket rbracket ts ppATermIn mode (Ann t ts) = mode (ppATermIn mode t) lbrace rbrace ts
UU-ComputerScience/uu-cco
uu-cco/src/CCO/Tree/ATerm.hs
bsd-3-clause
3,714
0
17
888
659
367
292
44
3
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE ScopedTypeVariables #-} -- | Dealing with the 01-index file and all its cabal files. module Stack.PackageIndex ( updateAllIndices , getPackageCaches , getPackageVersions , lookupPackageVersions , CabalLoader (..) , HasCabalLoader (..) , configPackageIndex , configPackageIndexRoot ) where import qualified Codec.Archive.Tar as Tar import Stack.Prelude import Data.Aeson.Extended import qualified Data.ByteString.Char8 as B8 import qualified Data.ByteString.Lazy as L import Data.Conduit.Zlib (ungzip) import qualified Data.List.NonEmpty as NE import qualified Data.HashMap.Strict as HashMap import qualified Data.Set as Set import Data.Store.Version import Data.Store.VersionTagged import qualified Data.Text as T import Data.Text.Unsafe (unsafeTail) import Data.Time (getCurrentTime) import qualified Hackage.Security.Client as HS import qualified Hackage.Security.Client.Repository.Cache as HS import qualified Hackage.Security.Client.Repository.Remote as HS import qualified Hackage.Security.Client.Repository.HttpLib.HttpClient as HS import qualified Hackage.Security.Util.Path as HS import qualified Hackage.Security.Util.Pretty as HS import Network.HTTP.Client.TLS (getGlobalManager) import Network.HTTP.Download import Network.URI (parseURI) import Path (toFilePath, parseAbsFile, mkRelDir, mkRelFile, (</>), parseRelDir) import Path.Extra (tryGetModificationTime) import Path.IO import Stack.Types.PackageIdentifier import Stack.Types.PackageIndex import Stack.Types.PackageName import Stack.Types.Runner (HasRunner) import Stack.Types.Version import qualified System.Directory as D import System.FilePath ((<.>)) -- | Populate the package index caches and return them. populateCache :: HasCabalLoader env => PackageIndex -> RIO env (PackageCache ()) populateCache index = do requireIndex index -- This uses full on lazy I/O instead of ResourceT to provide some -- protections. Caveat emptor path <- configPackageIndex (indexName index) let loadPIS = withLazyFile (Path.toFilePath path) $ \lbs -> do logSticky "Populating index cache ..." loop 0 HashMap.empty (Tar.read lbs) pis0 <- loadPIS `catch` \e -> do logWarn $ "Exception encountered when parsing index tarball: " <> T.pack (show (e :: Tar.FormatError)) logWarn "Automatically updating index and trying again" updateIndex index loadPIS when (indexRequireHashes index) $ forM_ (HashMap.toList pis0) $ \(ident, (mpd, _)) -> case mpd :: Maybe PackageDownload of Just _ -> return () Nothing -> throwM $ MissingRequiredHashes (indexName index) ident cache <- fmap mconcat $ mapM convertPI $ HashMap.toList pis0 logStickyDone "Populated index cache." return cache where convertPI :: MonadIO m => (PackageIdentifier, (Maybe PackageDownload, Endo [([CabalHash], OffsetSize)])) -> m (PackageCache ()) convertPI (ident@(PackageIdentifier name version), (mpd, Endo front)) = case NE.nonEmpty $ front [] of Nothing -> throwString $ "Missing cabal file info for: " ++ show ident Just files -> return $ PackageCache $ HashMap.singleton name $ HashMap.singleton version ((), mpd, files) loop :: MonadThrow m => Int64 -> HashMap PackageIdentifier (Maybe PackageDownload, Endo [([CabalHash], OffsetSize)]) -> Tar.Entries Tar.FormatError -> m (HashMap PackageIdentifier (Maybe PackageDownload, Endo [([CabalHash], OffsetSize)])) loop !blockNo !m (Tar.Next e es) = loop (blockNo + entrySizeInBlocks e) (goE blockNo m e) es loop _ m Tar.Done = return m loop _ _ (Tar.Fail e) = throwM e goE :: Int64 -> HashMap PackageIdentifier (Maybe PackageDownload, Endo [([CabalHash], OffsetSize)]) -> Tar.Entry -> HashMap PackageIdentifier (Maybe PackageDownload, Endo [([CabalHash], OffsetSize)]) goE blockNo m e = case Tar.entryContent e of Tar.NormalFile lbs size -> case parseNameVersionSuffix $ Tar.entryPath e of Just (ident, ".cabal") -> addCabal lbs ident size Just (ident, ".json") -> addJSON id ident lbs _ -> case parsePackageJSON $ Tar.entryPath e of Just ident -> addJSON unHSPackageDownload ident lbs Nothing -> m _ -> m where addCabal lbs ident size = HashMap.alter (\case Nothing -> Just (Nothing, newEndo) Just (mpd, oldEndo) -> Just (mpd, oldEndo <> newEndo)) ident m where !cabalHash = computeCabalHash lbs -- Some older Stackage snapshots ended up with slightly -- modified cabal files, in particular having DOS-style -- line endings (CRLF) converted to Unix-style (LF). As a -- result, we track both hashes with and without CR -- characters stripped for compatibility with these older -- snapshots. cr = 13 cabalHashes | cr `L.elem` lbs = let !cabalHash' = computeCabalHash (L.filter (/= cr) lbs) in [cabalHash, cabalHash'] | otherwise = [cabalHash] offsetSize = OffsetSize ((blockNo + 1) * 512) size newPair = (cabalHashes, offsetSize) newEndo = Endo (newPair:) addJSON :: FromJSON a => (a -> PackageDownload) -> PackageIdentifier -> L.ByteString -> HashMap PackageIdentifier (Maybe PackageDownload, Endo [([CabalHash], OffsetSize)]) addJSON unwrap ident lbs = case decode lbs of Nothing -> m Just (unwrap -> pd) -> HashMap.alter (\case Nothing -> Just (Just pd, mempty) Just (Just oldPD, _) | oldPD /= pd -> error $ concat [ "Conflicting package hash information discovered for " , packageIdentifierString ident , "\nFound both: \n- " , show oldPD , "\n- " , show pd , "\n\nThis should not happen. See: https://github.com/haskell/hackage-security/issues/189" ] Just (_, files) -> Just (Just pd, files)) ident m breakSlash x | T.null z = Nothing | otherwise = Just (y, unsafeTail z) where (y, z) = T.break (== '/') x parseNameVersion t1 = do (p', t3) <- breakSlash $ T.map (\c -> if c == '\\' then '/' else c) $ T.pack t1 p <- parsePackageName p' (v', t5) <- breakSlash t3 v <- parseVersion v' return (p', p, v, t5) parseNameVersionSuffix t1 = do (p', p, v, t5) <- parseNameVersion t1 let (t6, suffix) = T.break (== '.') t5 guard $ t6 == p' return (PackageIdentifier p v, suffix) parsePackageJSON t1 = do (_, p, v, t5) <- parseNameVersion t1 guard $ t5 == "package.json" return $ PackageIdentifier p v data PackageIndexException = GitNotAvailable IndexName | MissingRequiredHashes IndexName PackageIdentifier deriving Typeable instance Exception PackageIndexException instance Show PackageIndexException where show (GitNotAvailable name) = concat [ "Package index " , T.unpack $ indexNameText name , " only provides Git access, and you do not have" , " the git executable on your PATH" ] show (MissingRequiredHashes name ident) = concat [ "Package index " , T.unpack $ indexNameText name , " is configured to require package hashes, but no" , " hash is available for " , packageIdentifierString ident ] -- | Require that an index be present, updating if it isn't. requireIndex :: HasCabalLoader env => PackageIndex -> RIO env () requireIndex index = do tarFile <- configPackageIndex $ indexName index exists <- doesFileExist tarFile unless exists $ updateIndex index -- | Update all of the package indices updateAllIndices :: HasCabalLoader env => RIO env () updateAllIndices = do clearPackageCaches cl <- view cabalLoaderL mapM_ updateIndex (clIndices cl) -- | Update the index tarball updateIndex :: HasCabalLoader env => PackageIndex -> RIO env () updateIndex index = do let name = indexName index url = indexLocation index logSticky $ "Updating package index " <> indexNameText (indexName index) <> " (mirrored at " <> url <> ") ..." case indexType index of ITVanilla -> updateIndexHTTP name url ITHackageSecurity hs -> updateIndexHackageSecurity name url hs logStickyDone "Update complete" -- Copy to the 00-index.tar filename for backwards -- compatibility. First wipe out the cache file if present. tarFile <- configPackageIndex name oldTarFile <- configPackageIndexOld name oldCacheFile <- configPackageIndexCacheOld name liftIO $ ignoringAbsence (removeFile oldCacheFile) withSourceFile (toFilePath tarFile) $ \src -> withSinkFile (toFilePath oldTarFile) $ \sink -> runConduit $ src .| sink -- | Update the index tarball via HTTP updateIndexHTTP :: HasCabalLoader env => IndexName -> Text -- ^ url -> RIO env () updateIndexHTTP indexName' url = do req <- parseRequest $ T.unpack url logInfo ("Downloading package index from " <> url) gz <- configPackageIndexGz indexName' tar <- configPackageIndex indexName' wasDownloaded <- redownload req gz shouldUnpack <- if wasDownloaded then return True else not `liftM` doesFileExist tar if not shouldUnpack then packageIndexNotUpdated indexName' else do let tmp = toFilePath tar <.> "tmp" tmpPath <- parseAbsFile tmp deleteCache indexName' liftIO $ do withSourceFile (toFilePath gz) $ \input -> withSinkFile tmp $ \output -> -- FIXME use withSinkFileCautious runConduit $ input .| ungzip .| output renameFile tmpPath tar -- | Update the index tarball via Hackage Security updateIndexHackageSecurity :: HasCabalLoader env => IndexName -> Text -- ^ base URL -> HackageSecurity -> RIO env () updateIndexHackageSecurity indexName' url (HackageSecurity keyIds threshold) = do baseURI <- case parseURI $ T.unpack url of Nothing -> throwString $ "Invalid Hackage Security base URL: " ++ T.unpack url Just x -> return x manager <- liftIO getGlobalManager root <- configPackageIndexRoot indexName' run <- askRunInIO let logTUF = run . logInfo . T.pack . HS.pretty withRepo = HS.withRepository (HS.makeHttpLib manager) [baseURI] HS.defaultRepoOpts HS.Cache { HS.cacheRoot = HS.fromAbsoluteFilePath $ toFilePath root , HS.cacheLayout = HS.cabalCacheLayout -- Have Hackage Security write to a temporary file -- to avoid invalidating the cache... continued -- below at case didUpdate { HS.cacheLayoutIndexTar = HS.rootPath $ HS.fragment "01-index.tar-tmp" } } HS.hackageRepoLayout HS.hackageIndexLayout logTUF didUpdate <- liftIO $ withRepo $ \repo -> HS.uncheckClientErrors $ do needBootstrap <- HS.requiresBootstrap repo when needBootstrap $ do HS.bootstrap repo (map (HS.KeyId . T.unpack) keyIds) (HS.KeyThreshold (fromIntegral threshold)) now <- getCurrentTime HS.checkForUpdates repo (Just now) case didUpdate of HS.NoUpdates -> packageIndexNotUpdated indexName' HS.HasUpdates -> do -- The index actually updated. Delete the old cache, and -- then move the temporary unpacked file to its real -- location tar <- configPackageIndex indexName' deleteCache indexName' liftIO $ D.renameFile (toFilePath tar ++ "-tmp") (toFilePath tar) logInfo "Updated package index downloaded" -- If the index is newer than the cache, delete it so that -- the next 'getPackageCaches' call recomputes it. This -- could happen if a prior run of stack updated the index, -- but exited before deleting the cache. -- -- See https://github.com/commercialhaskell/stack/issues/3033 packageIndexNotUpdated :: HasCabalLoader env => IndexName -> RIO env () packageIndexNotUpdated indexName' = do mindexModTime <- tryGetModificationTime =<< configPackageIndex indexName' mcacheModTime <- tryGetModificationTime =<< configPackageIndexCache indexName' case (mindexModTime, mcacheModTime) of (Right indexModTime, Right cacheModTime) | cacheModTime < indexModTime -> do deleteCache indexName' logInfo "No updates to your package index were found, but clearing the index cache as it is older than the index." (Left _, _) -> do deleteCache indexName' logError "Error: No updates to your package index were found, but downloaded index is missing." _ -> logInfo "No updates to your package index were found" -- | Delete the package index cache deleteCache :: HasCabalLoader env => IndexName -> RIO env () deleteCache indexName' = do fp <- configPackageIndexCache indexName' eres <- liftIO $ tryIO $ removeFile fp case eres of Left e -> logDebug $ "Could not delete cache: " <> T.pack (show e) Right () -> logDebug $ "Deleted index cache at " <> T.pack (toFilePath fp) -- | Get the known versions for a given package from the package caches. -- -- See 'getPackageCaches' for performance notes. getPackageVersions :: HasCabalLoader env => PackageName -> RIO env (Set Version) getPackageVersions pkgName = lookupPackageVersions pkgName <$> getPackageCaches lookupPackageVersions :: PackageName -> PackageCache index -> Set Version lookupPackageVersions pkgName (PackageCache m) = maybe Set.empty (Set.fromList . HashMap.keys) $ HashMap.lookup pkgName m -- | Load the package caches, or create the caches if necessary. -- -- This has two levels of caching: in memory, and the on-disk cache. So, -- feel free to call this function multiple times. getPackageCaches :: HasCabalLoader env => RIO env (PackageCache PackageIndex) getPackageCaches = do cl <- view cabalLoaderL mcached <- readIORef (clCache cl) case mcached of Just cached -> return cached Nothing -> do result <- liftM mconcat $ forM (clIndices cl) $ \index -> do fp <- configPackageIndexCache (indexName index) PackageCache pis <- $(versionedDecodeOrLoad (storeVersionConfig "pkg-v5" "A607WaDwhg5VVvZTxNgU9g52DO8=" :: VersionConfig (PackageCache ()))) fp (populateCache index) return $ PackageCache ((fmap.fmap) (\((), mpd, files) -> (index, mpd, files)) pis) liftIO $ writeIORef (clCache cl) (Just result) return result -- | Clear the in-memory hackage index cache. This is needed when the -- hackage index is updated. clearPackageCaches :: HasCabalLoader env => RIO env () clearPackageCaches = do cl <- view cabalLoaderL writeIORef (clCache cl) Nothing class HasRunner env => HasCabalLoader env where cabalLoaderL :: Lens' env CabalLoader data CabalLoader = CabalLoader { clCache :: !(IORef (Maybe (PackageCache PackageIndex))) , clIndices :: ![PackageIndex] -- ^ Information on package indices. This is left biased, meaning that -- packages in an earlier index will shadow those in a later index. -- -- Warning: if you override packages in an index vs what's available -- upstream, you may correct your compiled snapshots, as different -- projects may have different definitions of what pkg-ver means! This -- feature is primarily intended for adding local packages, not -- overriding. Overriding is better accomplished by adding to your -- list of packages. -- -- Note that indices specified in a later config file will override -- previous indices, /not/ extend them. -- -- Using an assoc list instead of a Map to keep track of priority , clStackRoot :: !(Path Abs Dir) -- ^ ~/.stack more often than not , clUpdateRef :: !(MVar Bool) -- ^ Want to try updating the index once during a single run for missing -- package identifiers. We also want to ensure we only update once at a -- time. Start at @True@. -- -- TODO: probably makes sense to move this concern into getPackageCaches , clConnectionCount :: !Int -- ^ How many concurrent connections are allowed when downloading , clIgnoreRevisionMismatch :: !Bool -- ^ Ignore a revision mismatch when loading up cabal files, -- and fall back to the latest revision. See: -- <https://github.com/commercialhaskell/stack/issues/3520> } -- | Root for a specific package index configPackageIndexRoot :: HasCabalLoader env => IndexName -> RIO env (Path Abs Dir) configPackageIndexRoot (IndexName name) = do cl <- view cabalLoaderL let root = clStackRoot cl dir <- parseRelDir $ B8.unpack name return (root </> $(mkRelDir "indices") </> dir) -- | Location of the 01-index.tar file configPackageIndex :: HasCabalLoader env => IndexName -> RIO env (Path Abs File) configPackageIndex name = (</> $(mkRelFile "01-index.tar")) <$> configPackageIndexRoot name -- | Location of the 01-index.cache file configPackageIndexCache :: HasCabalLoader env => IndexName -> RIO env (Path Abs File) configPackageIndexCache name = (</> $(mkRelFile "01-index.cache")) <$> configPackageIndexRoot name -- | Location of the 00-index.cache file configPackageIndexCacheOld :: HasCabalLoader env => IndexName -> RIO env (Path Abs File) configPackageIndexCacheOld = liftM (</> $(mkRelFile "00-index.cache")) . configPackageIndexRoot -- | Location of the 00-index.tar file. This file is just a copy of -- the 01-index.tar file, provided for tools which still look for the -- 00-index.tar file. configPackageIndexOld :: HasCabalLoader env => IndexName -> RIO env (Path Abs File) configPackageIndexOld = liftM (</> $(mkRelFile "00-index.tar")) . configPackageIndexRoot -- | Location of the 01-index.tar.gz file configPackageIndexGz :: HasCabalLoader env => IndexName -> RIO env (Path Abs File) configPackageIndexGz = liftM (</> $(mkRelFile "01-index.tar.gz")) . configPackageIndexRoot --------------- Lifted from cabal-install, Distribution.Client.Tar: -- | Return the number of blocks in an entry. entrySizeInBlocks :: Tar.Entry -> Int64 entrySizeInBlocks entry = 1 + case Tar.entryContent entry of Tar.NormalFile _ size -> bytesToBlocks size Tar.OtherEntryType _ _ size -> bytesToBlocks size _ -> 0 where bytesToBlocks s = 1 + ((fromIntegral s - 1) `div` 512)
anton-dessiatov/stack
src/Stack/PackageIndex.hs
bsd-3-clause
20,647
0
26
5,915
4,461
2,287
2,174
378
14
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="sl-SI"> <title>GraphQL Support Add-on</title> <maps> <homeID>graphql</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/graphql/src/main/javahelp/org/zaproxy/addon/graphql/resources/help_sl_SI/helpset_sl_SI.hs
apache-2.0
971
82
53
157
396
209
187
-1
-1
-- $Id: LexUtil.hs,v 1.4 2001/11/08 22:09:28 hallgren Exp $ module LexUtil (isIdent,isLower_, -- Char -> Bool isSymbol, -- Char -> Bool readInteger, -- String -> Integer readNumber, -- Integer -> String -> Integer readRational) -- String -> Rational where import HsName(isSymbol) import Char(isDigit, isOctDigit, isHexDigit, digitToInt, isAlpha, isLower) import Ratio isIdent c = isAlpha c || isDigit c || c == '\'' || c == '_' isLower_ c = isLower c || c == '_' readInteger :: String -> Integer readInteger ('0':'o':ds) = readInteger2 8 isOctDigit ds readInteger ('0':'O':ds) = readInteger2 8 isOctDigit ds readInteger ('0':'x':ds) = readInteger2 16 isHexDigit ds readInteger ('0':'X':ds) = readInteger2 16 isHexDigit ds readInteger ds = readInteger2 10 isDigit ds readNumber :: Integer -> String -> Integer readNumber radix ds = readInteger2 radix (const True) ds readInteger2 :: Integer -> (Char -> Bool) -> String -> Integer readInteger2 radix isDig ds = foldl1 (\n d -> n * radix + d) (map (fromIntegral . digitToInt) (takeWhile isDig ds)) readRational :: String -> Rational readRational xs = (readInteger (i ++ m))%1 * 10^^((case e of "" -> 0 ('+':e2) -> read e2 _ -> read e) - length m) where (i, r1) = span isDigit xs (m, r2) = span isDigit (dropWhile (== '.') r1) e = dropWhile (== 'e') r2
forste/haReFork
tools/base/parse/LexUtil.hs
bsd-3-clause
1,428
14
14
344
524
278
246
31
3
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude, MagicHash #-} {-# OPTIONS_HADDOCK hide #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.Err -- Copyright : (c) The University of Glasgow, 1994-2002 -- License : see libraries/base/LICENSE -- -- Maintainer : [email protected] -- Stability : internal -- Portability : non-portable (GHC extensions) -- -- The "GHC.Err" module defines the code for the wired-in error functions, -- which have a special type in the compiler (with \"open tyvars\"). -- -- We cannot define these functions in a module where they might be used -- (e.g., "GHC.Base"), because the magical wired-in type will get confused -- with what the typechecker figures out. -- ----------------------------------------------------------------------------- module GHC.Err( absentErr, error, undefined ) where import GHC.CString () import GHC.Types import GHC.Prim import GHC.Integer () -- Make sure Integer is compiled first -- because GHC depends on it in a wired-in way -- so the build system doesn't see the dependency import {-# SOURCE #-} GHC.Exception( errorCallException ) -- | 'error' stops execution and displays an error message. error :: [Char] -> a error s = raise# (errorCallException s) -- | A special case of 'error'. -- It is expected that compilers will recognize this and insert error -- messages which are more appropriate to the context in which 'undefined' -- appears. undefined :: a undefined = error "Prelude.undefined" -- | Used for compiler-generated error message; -- encoding saves bytes of string junk. absentErr :: a absentErr = error "Oops! The program has entered an `absent' argument!\n"
beni55/haste-compiler
libraries/ghc-7.10/base/GHC/Err.hs
bsd-3-clause
1,773
0
7
324
140
94
46
15
1
{-# LANGUAGE PartialTypeSignatures #-} module PatBind where foo :: _ Just foo = Just id
siddhanathan/ghc
testsuite/tests/partial-sigs/should_compile/PatBind.hs
bsd-3-clause
89
0
5
16
22
12
10
4
1
module Crypto.Enigma where import Crypto.Enigma.Helper type State = [Char] -- state of the enigma machine data Direction = Fwd | Bwd deriving (Show, Eq) data RotorSignalDir = SignalIn | SignalOut deriving (Show, Eq) data Conf = Conf { getPlugboard :: String , getRefl :: String , getType :: [(String, Char)] , getRing :: [Char]} deriving (Show) -- enigma machine functions --------------------------------------------------- -- this is for re-routing the signal to a different character plugboard :: Direction -> String -> Char -> Char plugboard Bwd pbConf c = alphs !! getIndex c pbConf plugboard Fwd pbConf c = pbConf !! charToInt c -- rotates a single rotor depending on the state and its configuration rotateRotor :: Int -> Conf -> State -> State rotateRotor 2 _ state = (init state) ++ [cycleChar $ last state] -- move the last element rotateRotor x conf state | cycleChar pawlLoc == rightLoc = part1 ++ (cycleChar currentLoc):part2 | otherwise = state where (part1,_:part2) = splitAt x state pawlLoc = snd (getType conf !! (x+1)) rightLoc = state !! (x+1) currentLoc = state !! x -- like the plugboard, also for re-routing the signal reflector :: String -> Char -> Char reflector = plugboard Bwd -- encodes a single character using a single rotor, -- depends on the signal direction, rotor type, ring setting, -- rotor location and of course the input character respectively rotor :: Direction -> (String,Char) -> Char -> Char -> Char -> Char rotor dir rtype ring loc = -- where rtype is rotor type ((rotorOffset SignalOut ring loc) .(rotorWiring dir rtype) .(rotorOffset SignalIn ring loc)) -- helper function for rotor: performs the offset rotorOffset :: RotorSignalDir -> Char -> Char -> Char -> Char rotorOffset dir ring loc c | dir == SignalIn = intToChar $ rem26 $ ic + iloc - iring | dir == SignalOut = intToChar $ rem26 $ ic - iloc + iring | otherwise = error "Critical error in rotorOffset." where ic = charToInt c iloc = charToInt loc iring = charToInt ring -- helper function for rotor: uses the wiring table to reroute the signal rotorWiring :: Direction -> (String,Char) -> Char -> Char rotorWiring Fwd (wiring,_) c = wiring !! charToInt c rotorWiring Bwd (wiring,_) c = alphs !! getIndex c wiring -- this function runs the enigma machine for a single character -- this does not change the machine state enigmaChar :: Conf -> State -> Char -> Char enigmaChar conf state = plugboard Bwd (getPlugboard conf) . rotor Bwd ((getType conf) !! 2) ((getRing conf) !! 2) (state !! 2) . rotor Bwd ((getType conf) !! 1) ((getRing conf) !! 1) (state !! 1) . rotor Bwd ((getType conf) !! 0) ((getRing conf) !! 0) (state !! 0) . reflector (getRefl conf) . rotor Fwd ((getType conf) !! 0) ((getRing conf) !! 0) (state !! 0) . rotor Fwd ((getType conf) !! 1) ((getRing conf) !! 1) (state !! 1) . rotor Fwd ((getType conf) !! 2) ((getRing conf) !! 2) (state !! 2) . plugboard Fwd (getPlugboard conf) -- runs the enigma machine for a string enigma :: Conf -> State -> String -> String enigma _ _ [] = [] enigma conf state (x:rest) = let newState = ((rotateRotor 0 conf) . (rotateRotor 1 conf) . (rotateRotor 2 conf)) state in (enigmaChar conf newState x) : (enigma conf newState rest) -- at the moment we're not including plugboard settings intToSetting :: (Conf,State) -> [(String, Char)] -> [String] -> Integer -> (Conf,State) intToSetting (conf,state) allRTypes allReflectors n | n < 0 = error "4th input (n) cannot be negative" | otherwise = (Conf newPlugs newRefl newRType newRing, newState) where newPlugs = getPlugboard conf -- not considered at the moment newRefl = nthElemSetting (nextReflector allReflectors) (m `quot` 18534946560) (getRefl conf) newRType = nthElemSetting (nextRotorType allRTypes) (m `quot` 308915776) (getType conf) newRing = nthElemSetting nextRingLoc (m `quot` 17576) (getRing conf) newState = nthElemSetting nextRingLoc (m `rem` 17576) state m = n `rem` 37069893120 -- (26^3 * 26^3 * 60 * 2) plugs not included intToSettingDefault :: Integer -> (Conf, State) intToSettingDefault = intToSetting (Conf plugs refB [rtypeI,rtypeII,rtypeIII] "AAA", "AAA") [rtypeI, rtypeII, rtypeIII, rtypeIV, rtypeV] [refB, refC] -- some default configurations plugs :: String refB :: String refC :: String rtypeI :: (String, Char) rtypeII :: (String, Char) rtypeIII :: (String, Char) rtypeIV :: (String, Char) rtypeV :: (String, Char) plugs = ['A'..'Z'] -- plug locations, only wires in real enigma refB = "YRUHQSLDPXNGOKMIEBFZCWVJAT" -- M3 B reflector refC = "FVPJIAOYEDRZXWGCTKUQSBNMHL" -- M3 C reflector rtypeI = ("EKMFLGDQVZNTOWYHXUSPAIBRCJ", 'Q') -- rotor type I rtypeII = ("AJDKSIRUXBLHWTMCQGZNPYFVOE", 'E') -- rotor type II rtypeIII = ("BDFHJLCPRTXVZNYEIWGAKMUSQO", 'V') -- rotor type III rtypeIV = ("ESOVPZJAYQUIRHXLNFTGKDCMWB", 'J') -- rotor type IV rtypeV = ("VZBRGITYUPSDNHLXAWMJQOFECK", 'Z') -- rotor type V
kc1212/enigma-hs
Crypto/Enigma.hs
mit
5,159
2
17
1,117
1,599
872
727
94
1
import Data.Attoparsec.Char8 import qualified Data.HashMap.Strict as M import Test.Hspec import Mockups.Elements.Element import Mockups.Parsers.Element main :: IO () main = hspec $ do describe "simple element parser" $ do it "parses image elements with attrs" $ do let exp = SimpleElement $ Img $ M.fromList [("src", ImgSrc "bla")] parseOnly (eltParser 0) "img [ src = \"bla\" ]\n" `shouldBe` Right exp it "parses image elements without attrs" $ do let exp = SimpleElement $ Img $ M.fromList [] parseOnly (eltParser 0) "img\n" `shouldBe` Right exp
ostapneko/tiny-mockups
src/tests/Suite.hs
mit
618
0
21
153
186
94
92
14
1
module Wyas where import System.Environment import Wyas.Eval import Wyas.Parser import Wyas.Types (extractValue, trapError) main :: IO () main = do args <- getArgs let evaled = fmap show $ readExpr (head args) >>= eval putStrLn $ extractValue $ trapError evaled
saclark/wyas
src/Wyas.hs
mit
318
0
14
96
97
50
47
10
1
module Settings.Builders.Ar (arBuilderArgs, arCmd, chunksOfSize) where import Settings.Builders.Common arBuilderArgs :: Args arBuilderArgs = builder Ar ? mconcat [ arg "q" , arg =<< getOutput , getInputs ] -- This count includes arg "q" and arg file parameters in arBuilderArgs. -- Update this value appropriately when changing arBuilderArgs. arFlagsCount :: Int arFlagsCount = 2 -- | Invoke 'Ar' builder given a path to it and a list of arguments. Take care -- not to exceed the limit on command line length, which differs across -- supported operating systems (see 'cmdLineLengthLimit'). 'Ar' needs to be -- handled in a special way because we sometimes need to archive __a lot__ of -- files (in Cabal package, for example, command line length can reach 2MB!). -- To work around the limit on the command line length we pass the list of files -- to be archived via a temporary file, or alternatively, we split argument list -- into chunks and call 'Ar' multiple times (when passing arguments via a -- temporary file is not supported). arCmd :: FilePath -> [String] -> Action () arCmd path argList = do arSupportsAtFile <- flag ArSupportsAtFile let flagArgs = take arFlagsCount argList fileArgs = drop arFlagsCount argList if arSupportsAtFile then useAtFile path flagArgs fileArgs else useSuccessiveInvocations path flagArgs fileArgs useAtFile :: FilePath -> [String] -> [String] -> Action () useAtFile path flagArgs fileArgs = withTempFile $ \tmp -> do writeFile' tmp $ unwords fileArgs cmd [path] flagArgs ('@' : tmp) useSuccessiveInvocations :: FilePath -> [String] -> [String] -> Action () useSuccessiveInvocations path flagArgs fileArgs = do maxChunk <- cmdLineLengthLimit forM_ (chunksOfSize maxChunk fileArgs) $ \argsChunk -> unit . cmd [path] $ flagArgs ++ argsChunk -- | @chunksOfSize size strings@ splits a given list of strings into chunks not -- exceeding the given @size@. If that is impossible, it uses singleton chunks. chunksOfSize :: Int -> [String] -> [[String]] chunksOfSize n = repeatedly f where f xs = splitAt (max 1 $ length $ takeWhile (<= n) $ scanl1 (+) $ map length xs) xs
izgzhen/hadrian
src/Settings/Builders/Ar.hs
mit
2,237
0
13
473
430
227
203
28
2
-- Copyright (C) 2014 Google Inc. All rights reserved. -- -- Licensed under the Apache License, Version 2.0 (the "License"); you may not -- use this file except in compliance with the License. You may obtain a copy -- of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -- WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -- License for the specific language governing permissions and limitations -- under the License. module Gemstone.Util where import Data.Word import Foreign import Graphics.Rendering.OpenGL checkerboard :: [Word8] checkerboard = map (* 255) [ (x + y) `mod` 2 | x <- [0..7], y <- [0..7] ] withWord8Ptr :: [Word8] -> (Ptr Word8 -> IO b) -> IO b withWord8Ptr bytes action = let len = length bytes indexed = zip [0..] bytes in allocaBytes len $ \ptr -> do mapM_ (uncurry $ pokeElemOff ptr) indexed action ptr -- | Pack a finite list of Word8s into a texture. word8ToTexture :: Int -> Int -> [Word8] -> IO TextureObject word8ToTexture width height bytes = do [texobj] <- genObjectNames 1 textureBinding Texture2D $= Just texobj textureFilter Texture2D $= ((Nearest, Nothing), Nearest) withWord8Ptr bytes $ \ptr -> let pd = PixelData Luminance UnsignedByte ptr size = TextureSize2D (fromIntegral width) (fromIntegral height) in texImage2D Nothing NoProxy 0 Luminance' size 0 pd textureBinding Texture2D $= Nothing return texobj checkerboardTexture :: IO TextureObject checkerboardTexture = word8ToTexture 8 8 checkerboard
MostAwesomeDude/gemstone
Gemstone/Util.hs
mit
1,709
0
15
339
392
204
188
26
1
module Takeaway.Data.Permissions where import Data.Bits data Rights = Read | Add | Change | Delete | (:&) Rights Rights deriving (Show) allRights :: Rights allRights = Read :& Add :& Change :& Delete newtype Bitflag a = Bitflag { bitflag :: Word } deriving (Eq, Show) rightsToWord :: Rights -> Word rightsToWord r = case r of Read -> 1 Add -> 2 Change -> 4 Delete -> 8 a :& b -> rightsToWord a .|. rightsToWord b fromRights :: Rights -> Bitflag Rights fromRights = Bitflag . rightsToWord -- | Set new rights setRights :: Bitflag Rights -> Rights -> Bitflag Rights setRights (Bitflag w) r = Bitflag $ rightsToWord r .|. w -- | Remove rights remRights :: Bitflag Rights -> Rights -> Bitflag Rights remRights (Bitflag w) r = Bitflag $ complement (rightsToWord r) .&. w -- | Test if bitflag contains all rights hasRights :: Bitflag Rights -> Rights -> Bool hasRights (Bitflag w) r = let r' = rightsToWord r in (r' .&. w) == r' -- | No rights at all noRights :: Bitflag Rights noRights = Bitflag 0 data Permission = Permission { owner :: Bitflag Rights , group :: Bitflag Rights , other :: Bitflag Rights } -- | Default permission with all rights for owner but none for group/other defaultPermission :: Permission defaultPermission = Permission { owner = fromRights allRights , group = noRights , other = noRights }
mcmaniac/takeaway
src/Takeaway/Data/Permissions.hs
mit
1,373
12
9
300
431
227
204
39
5
module Data.YahooPortfolioManager.Types where -- | Provide a Symbol type for clarity. -- These should be the stock symbols used by Yahoo type Symbol = String {- | Haskell structure that represents the command line output table including yahoo quotes and portfolio position info -} data Portfolio = Portfolio { prtfalloc :: Double, prtfprice :: Double, prtfdiv :: Maybe Double, prtfsymbol :: String, prtfcost :: Double, prtfcurrent :: Maybe Double, prtfchange :: Maybe Double, prtfpctchange :: Maybe Double, prtfpnl :: Maybe Double, prtfpctpnl :: Maybe Double } deriving (Show, Ord, Eq) {-| Haskell structure that contains the portfolio position information entered by the user -} data Position = Position { possymbol :: String, poscurrency :: String, posdate :: String, posposition :: Double, posstrike :: Double } deriving (Show, Ord, Eq) {-| Haskell structure that contains the fx to convert yahoo quotes into the symbol currency entered by the user -} data Fx = Fx { fxToCcy :: String, fxFromCcy :: String, fx :: Double, prtfFx :: Double } deriving (Show, Ord, Eq) {-| Haskell structure that contains the portfolio position information entered by the user -} data Dividend = Dividend { divsymbol :: String, dividend :: Double, divdate :: String } deriving (Show, Ord, Eq) data Stock = Stock { stockPosition :: Double, stockPrice :: Double } deriving (Show, Ord, Eq)
lhoghu/yahoo-portfolio-manager
src/Data/YahooPortfolioManager/Types.hs
mit
1,578
0
9
429
301
182
119
36
0
module CLaSH.DepCore.Environment where import Bound (Scope (..)) import Bound.Var (Var (..)) import Data.Functor ((<$>)) import CLaSH.DepCore.Term (Term (..), Type) data Env n a = Env { lookupTy :: a -> Type n a , lookupDef :: a -> Maybe (Term n a) } extendEnv :: Eq a => Show n => Show a => (Env n a -> Term n a -> Type n a) -- ^ Type inference (for lifted terms) -> Env n a -- ^ Current environment -> Type n a -- ^ Type to add -> Maybe (Term n a) -- ^ Term to Add -> Env n (Var b (Term n a)) -- ^ Environment for scoped variable extendEnv inferType env@(Env ctx defs) bType bTerm = Env ctx' defs' where ctx' (B _) = F . Var <$> bType ctx' (F tm) = F . Var <$> inferType env tm defs' (B _) = Nothing defs' (F (Var x)) = fmap (F . Var) <$> defs x defs' (F tm) = Just (F . Var <$> tm) declarePat = undefined
christiaanb/NewCore
src/CLaSH/DepCore/Environment.hs
mit
1,044
0
16
411
390
206
184
-1
-1
module Main where import Criterion.Main import Math.NumberTheory.ArithmeticFunctionsBench as ArithmeticFunctions import Math.NumberTheory.PowersBench as Powers import Math.NumberTheory.PrimesBench as Primes import Math.NumberTheory.RecurrenciesBench as Recurrencies main = defaultMain [ ArithmeticFunctions.benchSuite , Powers.benchSuite , Primes.benchSuite , Recurrencies.benchSuite ]
cfredric/arithmoi
benchmark/Bench.hs
mit
399
0
7
46
69
46
23
11
1
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} import Yage.Prelude import Yage.Core.Application import Yage.Rendering.Shader as Shader import qualified Data.Map.Strict as M import Filesystem.Path import qualified Yage.Core.OpenGL as GL config :: ApplicationConfig config = defaultAppConfig hints :: [WindowHint] hints = [ WindowHint'ContextVersionMajor 4 , WindowHint'ContextVersionMinor 1 , WindowHint'OpenGLProfile OpenGLProfile'Core , WindowHint'OpenGLForwardCompat True , WindowHint'Visible False ] -- | currently just printing the GLUtil ShaderProgram main :: IO () main = do (shaderFile0::FilePath, shaderFile1::FilePath) <- readArgs execApplication "ShaderTool" config $ do win <- createWindowWithHints hints 800 600 "Context Window" withWindowAsCurrent win $ \w -> do prog <- io $ Shader.loadShaderProgram =<< mapM shaderPairs [ shaderFile0, shaderFile1 ] printTF "loaded Shader:\n0: {}\n1: {}\n{}\n\n" ( Shown shaderFile0 , Shown shaderFile1 , Shown prog ) print "attributes:" mapM_ printField (M.toList $ GL.attribs prog) print "uniforms:" mapM_ printField (M.toList $ GL.uniforms prog) let glProg = GL.program prog unis <- io $ GL.get (GL.activeUniforms glProg) io $ print unis destroyWindow win where printField (name, (loc, t)) = printTF "{}:{}:{}\n" (Shown loc, Shown name, Shown t) shaderPairs :: FilePath -> IO (GL.ShaderType, ByteString) shaderPairs fp = case extension fp of Just "vert" -> (GL.VertexShader,) <$> readFile fp Just "frag" -> (GL.FragmentShader,) <$> readFile fp Just ext -> error $ "invalid shader extension" ++ show ext ++ ". Onnly .vert and .frag accepted" Nothing -> error "shaderfile without extension"
MaxDaten/yage
shader-tool/ShaderTool.hs
mit
2,130
0
19
689
500
252
248
44
4
import qualified System.Environment as SE import qualified Data.ByteString.Lazy.Char8 as LC import qualified Data.ByteString.Char8 as BC import qualified Data.List as DL import qualified Data.Map as DM import qualified Data.Vector as DV import qualified Statistics.Sample as SS import qualified Statistics.Quantile as SQ import Text.Printf main :: IO() main = do input <- LC.getContents output (nums $ LC.lines input) -- clean input into a list of numbers nums :: [LC.ByteString] -> [Double] nums llns = floats $ map BC.unpack $ slns llns where slns = map (BC.concat . LC.toChunks) floats [] = [] floats [x] = [read x :: Double] floats (x:xs) = [read x :: Double] ++ floats xs -- | calculate the frequency of items in a set -- [ [(number, frequency), .... freqs xs = DM.toList $ DM.fromListWith (+) [(c, 1) | c <- xs] -- | calculate the mode of a list of numbers mode xs = (fst . DL.head) $ DL.sortBy sortGT $ freqs xs where sortGT (a1, b1) (a2, b2) | b1 < b2 = GT | b1 > b2 = LT | b1 == b2 = compare b1 b2 -- | calculate a quantile point qtile q t xs = (SQ.continuousBy SQ.medianUnbiased q t) $ DV.fromList xs -- | calculate the midhinge midhinge xs = (qtile 1 4 xs + qtile 3 4 xs) / 2 -- | calculate the trimean trimean xs = (qtile 2 4 xs + midhinge xs) / 2 h :: (Floating a, Ord t) => [t] -> a -- | calculate Shannon Entropy h xs = negate . sum . map (\(i,j) -> (p j xs) * (logBase 2 $ p j xs)) $ freqs xs where p n lst = (/) n tot_len tot_len = (fromIntegral $ length xs) -- | string formatter: round to 4 decimal places format f n = printf "%.4f" (f $ DV.fromList n) -- | display output formatting display xs = sequence_ [putStrLn (a++" : "++b) | (a,b) <- xs] output :: [Double] -> IO () output xs = display table where table = [("Length", show $ length xs) ,("Min", show $ minimum xs) ,("Max", show $ maximum xs) ,("Range", printf "%.4f" $ maximum xs - minimum xs) ,("Q1", format (SQ.continuousBy SQ.medianUnbiased 1 4) xs) ,("Q2", format (SQ.continuousBy SQ.medianUnbiased 2 4) xs) ,("Q3", format (SQ.continuousBy SQ.medianUnbiased 3 4) xs) ,("IQR", format (SQ.midspread SQ.medianUnbiased 4) xs) ,("Trimean", printf "%.4f" $ trimean xs) ,("Midhinge", printf "%.4f" $ midhinge xs) ,("Mean", format SS.mean xs) ,("Mode", show $ mode xs) ,("Kurtosis", format SS.kurtosis xs) ,("Skewness", format SS.skewness xs) ,("Entropy", printf "%.4f" ((h xs) :: Float))]
drbunsen/describe
describe.hs
mit
2,741
3
13
804
1,034
557
477
51
3
-- | -- Pure computations on a reified data. module GraphDB.Macros.Analysis where import GraphDB.Util.Prelude import GraphDB.Util.Prelude.TH import qualified GraphDB.Util.TH.Type as TH import qualified GraphDB.Model as M import qualified GraphDB.Graph as G import qualified GraphDB.Macros.Templates as T type Root = Type -- | A source and target type of an edge. type EdgeInfo = (Type, Type) decs :: Root -> [EdgeInfo] -> T.Decs decs root infos = let assocs = edgeInfosToConAssocs root infos indexes = map conAssocToIndex assocs values = nub $ concatMap conAssocToValues assocs indexesFunctionClauses = map conAssocToIndexesClause assocs polyIndexInstances = map (\(c, t) -> (root, c, t)) indexes polyValueInstances = map (\(c, t) -> (root, c, t)) values hashableInstances = nub $ concat $ [ ConT ''G.Index `AppT` root, ConT ''G.Value `AppT` root ] : indexTypes : valueTypes : leafTypes where indexTypes = indexes |> map sumConType valueTypes = values |> map sumConType leafTypes = map TH.monoTypes valueTypes serializableInstances = hashableInstances in ( polyIndexInstances, polyValueInstances, hashableInstances, serializableInstances, ( root, indexes, values, indexesFunctionClauses ) ) -- | An association of an index, source and target. type ConAssoc = (T.SumConstructor, T.SumConstructor, T.SumConstructor) edgeInfosToConAssocs :: Root -> [EdgeInfo] -> [ConAssoc] edgeInfosToConAssocs root infos = runST $ do regIndexType <- regType <$> pure indexPrefix <*> newSTRef 0 <*> newSTRef [] regValueType <- regType <$> pure valuePrefix <*> newSTRef 0 <*> newSTRef [] forM infos $ \(l, r) -> do let indexT = ConT ''M.Index `AppT` l `AppT` r index <- regIndexType indexT lc <- regValueType l rc <- regValueType r return (index, lc, rc) where regType prefix counterRef tableRef t = do readSTRef tableRef >>= return . lookup t >>= \case Just c -> return (c, t) Nothing -> do i <- readSTRef counterRef let c = mkName $ prefix <> show i modifySTRef tableRef ((t, c) :) writeSTRef counterRef (succ i) return (c, t) rootName = case root of ConT n -> n _ -> $bug $ "Not a constructor type: " <> show root indexPrefix = "GraphDB_Index_" <> nameBase rootName <> "_" valuePrefix = "GraphDB_Value_" <> nameBase rootName <> "_" conAssocToIndex :: ConAssoc -> T.SumConstructor conAssocToIndex (i, _, _) = i conAssocToValues :: ConAssoc -> [T.SumConstructor] conAssocToValues (_, l, r) = [l, r] conAssocToIndexesClause :: ConAssoc -> T.IndexesClause conAssocToIndexesClause ((n, _), (n', _), (n'', _)) = (n, n', n'') sumConType :: T.SumConstructor -> Type sumConType (_, t) = t
nikita-volkov/graph-db
library/GraphDB/Macros/Analysis.hs
mit
2,958
0
19
783
906
494
412
-1
-1
----------------------------------------------------------------------------- -- -- Module : Transient.Move -- Copyright : -- License : GPL-3 -- -- Maintainer : [email protected] -- Stability : -- Portability : -- -- | see <https://www.fpcomplete.com/user/agocorona/moving-haskell-processes-between-nodes-transient-effects-iv> ----------------------------------------------------------------------------- {-# LANGUAGE DeriveDataTypeable , ExistentialQuantification, OverloadedStrings ,ScopedTypeVariables, StandaloneDeriving, RecordWildCards, FlexibleContexts, CPP ,GeneralizedNewtypeDeriving #-} module Transient.Move( Cloud(..),runCloudIO, runCloudIO',local,onAll,lazy, loggedc, lliftIO,localIO, listen, Transient.Move.connect, connect', fullStop, -- * primitives for communication wormhole, teleport, copyData, -- * single node invocation beamTo, forkTo, streamFrom, callTo, runAt, atRemote, -- * invocation of many nodes clustered, mclustered, callNodes, -- * messaging newMailbox, putMailbox,getMailbox,cleanMailbox, -- * thread control single, #ifndef ghcjs_HOST_OS setBuffSize, getBuffSize, #endif -- * node management createNode, createWebNode, createNodeServ, getMyNode, getNodes, addNodes, shuffleNodes, -- * low level getWebServerNode, Node(..), nodeList, Connection(..), Service(), isBrowserInstance, Prefix(..), addPrefix ,defConnection ) where import Transient.Internals hiding ((!>)) import Transient.Logged import Transient.Indeterminism(choose) import Transient.Backtrack import Transient.EVars import Data.Typeable import Control.Applicative #ifndef ghcjs_HOST_OS import Network import Network.Info --import qualified Data.IP as IP import qualified Network.Socket as NS import qualified Network.BSD as BSD import qualified Network.WebSockets as NWS(RequestHead(..)) import qualified Network.WebSockets.Connection as WS import Network.WebSockets.Stream hiding(parse) import qualified Data.ByteString as B (ByteString,concat) import qualified Data.ByteString.Char8 as BC import qualified Data.ByteString.Lazy.Internal as BLC import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString.Lazy.Char8 as BS import Network.Socket.ByteString as SBS(send,sendMany,sendAll,recv) import qualified Network.Socket.ByteString.Lazy as SBSL import Data.CaseInsensitive(mk) import Data.Char(isSpace) --import GHCJS.Perch (JSString) #else import JavaScript.Web.WebSocket import qualified JavaScript.Web.MessageEvent as JM import GHCJS.Prim (JSVal) import GHCJS.Marshal(fromJSValUnchecked) import qualified Data.JSString as JS import JavaScript.Web.MessageEvent.Internal import GHCJS.Foreign.Callback.Internal (Callback(..)) import qualified GHCJS.Foreign.Callback as CB import Data.JSString (JSString(..), pack) #endif import qualified Data.Text as T import Control.Monad.State import System.IO import Control.Exception import Data.Maybe import Unsafe.Coerce --import System.Directory import Control.Monad import System.IO.Unsafe import Control.Concurrent.STM as STM import Control.Concurrent.MVar import Data.Monoid import qualified Data.Map as M import Data.List (nub,(\\),find, insert) import Data.IORef import System.IO import Control.Concurrent import System.Random import Data.Dynamic import Data.String import System.Mem.StableName import Unsafe.Coerce #ifdef ghcjs_HOST_OS type HostName = String newtype PortID = PortNumber Int deriving (Read, Show, Eq, Typeable) #endif data Node= Node{ nodeHost :: HostName , nodePort :: Int , connection :: MVar Pool , nodeServices :: [Service] } deriving (Typeable) instance Ord Node where compare node1 node2= compare (nodeHost node1,nodePort node1)(nodeHost node2,nodePort node2) -- The cloud monad is a thin layer over Transient in order to make sure that the type system -- forces the logging of intermediate results newtype Cloud a= Cloud {runCloud ::TransIO a} deriving (Functor,Applicative,Monoid,Alternative, Monad, MonadState EventF) -- -- --instance Applicative Cloud where -- -- pure = return -- -- x <*> y= Cloud . Transient $ do -- l1 <- liftIO $ newIORef Nothing -- l2 <- liftIO $ newIORef Nothing -- runTrans $ do -- Log _ _ full <- getData `onNothing` error "instance Applicative: no log" -- r <- runCloud (eval l1 x) <*> runCloud (eval l2 y) -- Just v1 <- localIO $ readIORef l1 -- Just v2 <- localIO $ readIORef l2 -- let full' = Var (toIDyn v1) : Var (toIDyn v2) : full -- setData $ Log False full' full' -- return r -- where -- eval l x= x >>= \v -> localIO (writeIORef l $ Just v) >> return v -- -- --instance Monoid a => Monoid (Cloud a) where -- mappend x y = mappend <$> x <*> y -- mempty= return mempty -- | Means that this computation will be executed in the current node. the result will be logged -- so the closure will be recovered if the computation is translated to other node by means of -- primitives like `beamTo`, `forkTo`, `runAt`, `teleport`, `clustered`, `mclustered` etc local :: Loggable a => TransIO a -> Cloud a local = Cloud . logged --stream :: Loggable a => TransIO a -> Cloud (StreamVar a) --stream= Cloud . transport -- #ifndef ghcjs_HOST_OS -- | run the cloud computation. runCloudIO :: Typeable a => Cloud a -> IO a runCloudIO (Cloud mx)= keep mx -- | run the cloud computation with no console input runCloudIO' :: Typeable a => Cloud a -> IO a runCloudIO' (Cloud mx)= keep' mx -- #endif -- | alternative to `local` It means that if the computation is translated to other node -- this will be executed again if this has not been executed inside a `local` computation. -- -- > onAll foo -- > local foo' -- > local $ do -- > bar -- > runCloud $ do -- > onAll baz -- > runAt node .... -- > callTo node' ..... -- -- Here foo will be executed in node' but foo' bar and baz don't. -- -- However foo bar and baz will e executed in node. -- onAll :: TransIO a -> Cloud a onAll = Cloud lazy :: TransIO a -> Cloud a lazy mx= onAll $ getCont >>= \st -> Transient $ return $ unsafePerformIO $ runStateT (runTrans mx) st >>= return .fst -- log the result a cloud computation. like `loogged`, This eliminated all the log produced by computations -- inside and substitute it for that single result when the computation is completed. loggedc :: Loggable a => Cloud a -> Cloud a loggedc (Cloud mx)= Cloud $ logged mx -- | the `Cloud` monad has no `MonadIO` instance. `lliftIO= local . liftIO` lliftIO :: Loggable a => IO a -> Cloud a lliftIO= local . liftIO -- | locally perform IO. `localIO = lliftIO` localIO :: Loggable a => IO a -> Cloud a localIO= lliftIO --remote :: Loggable a => TransIO a -> Cloud a --remote x= Cloud $ step' x $ \full x -> Transient $ do -- let add= Wormhole: full -- setData $ Log False add add -- -- r <- runTrans x -- -- let add= WaitRemote: full -- (setData $ Log False add add) -- !!> "AFTER STEP" -- return r -- | stop the current computation and does not execute any alternative computation fullStop :: Cloud stop fullStop= onAll $ setData WasRemote >> stop -- | continue the execution in a new node -- all the previous actions from `listen` to this statement must have been logged beamTo :: Node -> Cloud () beamTo node = wormhole node teleport -- | execute in the remote node a process with the same execution state forkTo :: Node -> Cloud () forkTo node= beamTo node <|> return() -- | open a wormhole to another node and executes an action on it. -- currently by default it keep open the connection to receive additional requests -- and responses (streaming) callTo :: Loggable a => Node -> Cloud a -> Cloud a callTo node remoteProc= wormhole node $ atRemote remoteProc -- | Within an open connection to other node opened by `wormhole`, it run the computation in the remote node and return -- the result back to the original node. atRemote proc= loggedc $ do teleport -- !> "teleport 1111" r <- Cloud $ runCloud proc <** setData WasRemote teleport -- !> "teleport 2222" return r -- | synonymous of `callTo` runAt :: Loggable a => Node -> Cloud a -> Cloud a runAt= callTo -- | execute a single thread for each connection -- -- > box <- foo -- > r <- runAt node . local . single $ getMailbox box -- > localIO $ print r -- -- if foo would return many values, the above code would monitor one remote mailbox -- each time: the last one entered. -- Without single, it would monitor all of them. single :: TransIO a -> TransIO a single f= do con@Connection{closChildren=rmap} <- getSData <|> error "single: only works within a wormhole" mapth <- liftIO $ readIORef rmap id <- liftIO $ makeStableName f >>= return . hashStableName chs <- let mx = M.lookup id mapth in case mx of Just tv -> return tv Nothing -> liftIO $ newTVarIO [] modify $ \ s -> s{children= chs} -- to allow his own thread control liftIO $ killChildren chs f <** do id <- liftIO $ makeStableName f >>= return . hashStableName liftIO $ modifyIORef rmap $ \mapth -> M.insert id chs mapth msend :: Loggable a => Connection -> StreamData a -> TransIO () #ifndef ghcjs_HOST_OS msend (Connection _(Just (Node2Node _ sock _)) _ _ blocked _ _ _) r= do r <- liftIO $ do withMVar blocked $ const $ do SBS.send sock $ BC.pack (show r) return Nothing `catch` (\(e::SomeException) -> return $ Just e) case r of Nothing -> return() juste -> finish juste msend (Connection _(Just (Node2Web sconn)) _ _ blocked _ _ _) r=liftIO $ withMVar blocked $ const $ WS.sendTextData sconn $ BS.pack (show r) #else msend (Connection _ (Just (Web2Node sconn)) _ _ blocked _ _ _) r= liftIO $ withMVar blocked $ const $ JavaScript.Web.WebSocket.send (JS.pack $ show r) sconn -- !!> "MSEND SOCKET" #endif msend (Connection _ Nothing _ _ _ _ _ _) _= error "msend out of wormhole context" mread :: Loggable a => Connection -> TransIO (StreamData a) #ifdef ghcjs_HOST_OS mread (Connection _ (Just (Web2Node sconn)) _ _ _ _ _ _)= wsRead sconn wsRead :: Loggable a => WebSocket -> TransIO a wsRead ws= do dat <- react (hsonmessage ws) (return ()) case JM.getData dat of JM.StringData str -> return (read' $ JS.unpack str) -- !> ("Browser webSocket read", str) !> "<------<----<----<------" JM.BlobData blob -> error " blob" JM.ArrayBufferData arrBuffer -> error "arrBuffer" {- wsRead1 :: Loggable a => WebSocket -> TransIO (StreamData a) wsRead1 ws= do reactStream (makeCallback MessageEvent) (js_onmessage ws) CB.releaseCallback (return ()) where reactStream createHandler setHandler removeHandler iob= Transient $ do cont <- getCont hand <- liftIO . createHandler $ \dat ->do runStateT (setData dat >> runCont cont) cont iob mEvData <- getSessionData case mEvData of Nothing -> liftIO $ do setHandler hand return Nothing Just dat -> do liftIO $ print "callback called 2*****" delSessionData dat dat' <- case getData dat of StringData str -> liftIO $ putStrLn "WSREAD RECEIVED " >> print str >> return (read $ JS.unpack str) BlobData blob -> error " blob" ArrayBufferData arrBuffer -> error "arrBuffer" liftIO $ case dat' of SDone -> do removeHandler $ Callback hand empty sl@(SLast x) -> do removeHandler $ Callback hand -- !!> "REMOVEHANDLER" return $ Just sl SError e -> do removeHandler $ Callback hand print e empty more -> return (Just more) -} wsOpen :: JS.JSString -> TransIO WebSocket wsOpen url= do ws <- liftIO $ js_createDefault url -- !> ("wsopen",url) react (hsopen ws) (return ()) -- !!> "react" return ws -- !!> "AFTER ReACT" foreign import javascript safe "window.location.hostname" js_hostname :: JSVal foreign import javascript safe "(function(){var res=window.location.href.split(':')[2];if (res === undefined){return 80} else return res.split('/')[0];})()" js_port :: JSVal foreign import javascript safe "$1.onmessage =$2;" js_onmessage :: WebSocket -> JSVal -> IO () getWebServerNode :: TransIO Node getWebServerNode = liftIO $ do h <- fromJSValUnchecked js_hostname p <- fromIntegral <$> (fromJSValUnchecked js_port :: IO Int) createNode h p hsonmessage ::WebSocket -> (MessageEvent ->IO()) -> IO () hsonmessage ws hscb= do cb <- makeCallback MessageEvent hscb js_onmessage ws cb foreign import javascript safe "$1.onopen =$2;" js_open :: WebSocket -> JSVal -> IO () newtype OpenEvent = OpenEvent JSVal deriving Typeable hsopen :: WebSocket -> (OpenEvent ->IO()) -> IO () hsopen ws hscb= do cb <- makeCallback OpenEvent hscb js_open ws cb makeCallback :: (JSVal -> a) -> (a -> IO ()) -> IO JSVal makeCallback f g = do Callback cb <- CB.syncCallback1 CB.ContinueAsync (g . f) return cb foreign import javascript safe "new WebSocket($1)" js_createDefault :: JS.JSString -> IO WebSocket #else mread (Connection _(Just (Node2Node _ _ _)) _ _ blocked _ _ _) = parallelReadHandler -- !> "mread" mread (Connection node (Just (Node2Web sconn )) bufSize events blocked _ _ _)= parallel $ do s <- WS.receiveData sconn return . read' $ BS.unpack s -- !> ("WS MREAD RECEIVED ---->", s) -- `catch`(\(e ::SomeException) -> return $ SError e) getWebServerNode :: TransIO Node getWebServerNode = getMyNode #endif read' s= case readsPrec' 0 s of [(x,"")] -> x _ -> error $ "reading " ++ s -- | A wormhole opens a connection with another node anywhere in a computation. -- `teleport` uses this connection to translate the computation back and forth between the two nodes connected wormhole :: Loggable a => Node -> Cloud a -> Cloud a wormhole node (Cloud comp) = local $ Transient $ do moldconn <- getData :: StateIO (Maybe Connection) mclosure <- getData :: StateIO (Maybe Closure) logdata@(Log rec log fulLog) <- getData `onNothing` return (Log False [][]) mynode <- runTrans getMyNode -- debug if not rec -- !> ("wormhole recovery", rec) then runTrans $ (do conn <- mconnect node -- !> (mynode,"connecting node ", node) setData conn{calling= True} #ifdef ghcjs_HOST_OS addPrefix -- for the DOM identifiers #endif comp ) <*** do when (isJust moldconn) . setData $ fromJust moldconn when (isJust mclosure). setData $ fromJust mclosure -- <** is not enough else do let conn = fromMaybe (error "wormhole: no connection in remote node") moldconn -- conn <- getData `onNothing` error "wormhole: no connection in remote node" setData $ conn{calling= False} runTrans $ comp <*** do -- when (null log) $ setData WasRemote !> "NULLLOG" when (isJust mclosure) . setData $ fromJust mclosure #ifndef ghcjs_HOST_OS type JSString= String pack= id #endif newtype Prefix= Prefix JSString deriving(Read,Show) addPrefix= Transient $ do r <- liftIO $ replicateM 5 (randomRIO ('a','z')) setData $ Prefix $ pack r return $ Just () -- | translates computations back and forth between two nodes -- reusing a connection opened by `wormhole` -- -- each teleport transport to the other node what is new in the log since the -- last teleport -- -- It is used trough other primitives like `runAt` which involves two teleports: -- -- runAt node= wormhole node $ loggedc $ do -- > teleport -- > r <- Cloud $ runCloud proc <** setData WasRemote -- > teleport -- > return r teleport :: Cloud () teleport = do local $ Transient $ do cont <- get -- send log with closure at head Log rec log fulLog <- getData `onNothing` return (Log False [][]) if not rec -- !> ("teleport rec,loc fulLog=",rec,log,fulLog) -- if is not recovering in the remote node then it is active then do conn@Connection{closures= closures,calling= calling} <- getData `onNothing` error "teleport: No connection defined: use wormhole" --read this Closure Closure closRemote <- getData `onNothing` return (Closure 0 ) --set his own closure in his Node data let closLocal = sum $ map (\x-> case x of Wait -> 100000; Exec -> 1000 _ -> 1) fulLog -- closLocal <- liftIO $ randomRIO (0,1000000) liftIO $ modifyMVar_ closures $ \map -> return $ M.insert closLocal (fulLog,cont) map let tosend= reverse $ if closRemote==0 then fulLog else log -- drop offset $ reverse fulLog !> ("fulLog", fulLog) runTrans $ msend conn $ SMore (closRemote,closLocal, tosend ) -- !> ("teleport sending", tosend ) -- !> "--------->------>---------->" setData $ if (not calling) then WasRemote else WasParallel return Nothing else do delData WasRemote -- !> "deleting wasremote in teleport" -- it is recovering, therefore it will be the -- local, not remote return (Just ()) -- !> "TELEPORT remote" -- | copy a session data variable from the local to the remote node. -- If there is none set in the local node, The parameter is the default value. -- In this case, the default value is also set in the local node. copyData def = do r <- local getSData <|> return def onAll $ setData r return r -- | `callTo` can stream data but can not inform the receiving process about the finalization. This call -- does it. streamFrom :: Loggable a => Node -> Cloud (StreamData a) -> Cloud (StreamData a) streamFrom = callTo --release (Node h p rpool _) hand= liftIO $ do ---- print "RELEASED" -- atomicModifyIORef rpool $ \ hs -> (hand:hs,()) -- -- !!> "RELEASED" mclose :: Connection -> IO () #ifndef ghcjs_HOST_OS mclose (Connection _ (Just (Node2Node _ sock _ )) _ _ _ _ _ _)= NS.sClose sock mclose (Connection node (Just (Node2Web sconn )) bufSize events blocked _ _ _)= WS.sendClose sconn ("closemsg" :: BS.ByteString) #else mclose (Connection _ (Just (Web2Node sconn)) _ _ blocked _ _ _)= JavaScript.Web.WebSocket.close Nothing Nothing sconn #endif liftIOF :: IO b -> TransIO b liftIOF mx=do ex <- liftIO $ (mx >>= return . Right) `catch` (\(e :: SomeException) -> return $ Left e) case ex of Left e -> finish $ Just e Right x -> return x mconnect :: Node -> TransIO Connection mconnect node@(Node _ _ _ _ )= do nodes <- getNodes -- !> ("connecting node", node) let fnode = filter (==node) nodes case fnode of [] -> addNodes [node] >> mconnect node [Node host port pool _] -> do plist <- liftIO $ readMVar pool case plist of handle:_ -> do delData $ Closure undefined return handle -- !> ("REUSED!", node) _ -> do -- liftIO $ putStr "*****CONNECTING NODE: " >> print node my <- getMyNode -- liftIO $ putStr "OPENING CONNECTION WITH :" >> print port Connection{comEvent= ev} <- getSData <|> error "connect: listen not set for this node" #ifndef ghcjs_HOST_OS conn <- liftIOF $ do let size=8192 sock <- connectTo' size host $ PortNumber $ fromIntegral port -- !> ("CONNECTING ",port) conn <- defConnection >>= \c -> return c{myNode=my,comEvent= ev,connData= Just $ Node2Node u sock (error $ "addr: outgoing connection")} SBS.send sock "CLOS a b\n\n" -- !> "sending CLOS" return conn #else conn <- do ws <- connectToWS host $ PortNumber $ fromIntegral port conn <- defConnection >>= \c -> return c{comEvent= ev,connData= Just $ Web2Node ws} return conn -- !> ("websocker CONNECION") #endif chs <- liftIO $ newIORef M.empty let conn'= conn{closChildren= chs} liftIO $ modifyMVar_ pool $ \plist -> return $ conn':plist putMailbox "connections" (conn',node) delData $ Closure undefined return conn where u= undefined -- mconnect _ = empty #ifndef ghcjs_HOST_OS connectTo' bufSize hostname (PortNumber port) = do proto <- BSD.getProtocolNumber "tcp" bracketOnError (NS.socket NS.AF_INET NS.Stream proto) (sClose) -- only done if there's an error (\sock -> do NS.setSocketOption sock NS.RecvBuffer bufSize NS.setSocketOption sock NS.SendBuffer bufSize he <- BSD.getHostByName hostname NS.connect sock (NS.SockAddrInet port (BSD.hostAddress he)) return sock) #else connectToWS h (PortNumber p) = wsOpen $ JS.pack $ "ws://"++ h++ ":"++ show p #endif #ifndef ghcjs_HOST_OS -- | A connectionless version of callTo for long running remote calls callTo' :: (Show a, Read a,Typeable a) => Node -> Cloud a -> Cloud a callTo' node remoteProc= do mynode <- local getMyNode beamTo node r <- remoteProc beamTo mynode return r #endif type Blocked= MVar () type BuffSize = Int data ConnectionData= #ifndef ghcjs_HOST_OS Node2Node{port :: PortID ,socket ::Socket ,remoteNode :: NS.SockAddr } | Node2Web{webSocket :: WS.Connection} #else Web2Node{webSocket :: WebSocket} #endif data Connection= Connection{myNode :: Node ,connData :: Maybe(ConnectionData) ,bufferSize :: BuffSize -- Used by getMailBox, putMailBox ,comEvent :: IORef (M.Map T.Text (EVar Dynamic)) -- multiple wormhole/teleport use the same connection concurrently ,blocked :: Blocked ,calling :: Bool -- local closures with his log and his continuation ,closures :: MVar (M.Map IdClosure ([LogElem], EventF)) -- for each remote closure that points to local closure 0, -- a new container of child processes -- in order to treat them separately -- so that 'killChilds' do not kill unrelated processes ,closChildren :: IORef (M.Map Int (TVar[EventF]))} deriving Typeable -- Mailboxes are node-wide, for all processes that share the same connection data, that is, are under the -- same `listen` or `connect` -- while EVars are only visible by the process that initialized it and his children. -- Internally, the mailbox is in a well known EVar stored by `listen` in the `Connection` state. newMailbox :: T.Text -> TransIO () newMailbox name= do -- return () -- !> "newMailBox" Connection{comEvent= mv} <- getData `onNothing` errorMailBox ev <- newEVar liftIO $ atomicModifyIORef mv $ \mailboxes -> (M.insert name ev mailboxes,()) -- | write to the mailbox putMailbox :: Typeable a => T.Text -> a -> TransIO () putMailbox name dat= do -- sendNodeEvent (name, Just dat) Connection{comEvent= mv} <- getData `onNothing` errorMailBox mbs <- liftIO $ readIORef mv let mev = M.lookup name mbs case mev of Nothing ->newMailbox name >> putMailbox name dat Just ev -> writeEVar ev $ toDyn dat errorMailBox= error "MailBox: No connection open.Use wormhole" -- | get messages from the mailbox that matches with the type expected. -- The order of reading is defined by `readTChan` -- This is reactive. it means that each new message trigger the execution of the continuation -- each message wake up all the `getMailbox` computations waiting for it. getMailbox name= do Connection{comEvent= mv} <- getData `onNothing` errorMailBox mbs <- liftIO $ readIORef mv let mev = M.lookup name mbs case mev of Nothing ->newMailbox name >> getMailbox name Just ev ->do d <- readEVar ev case fromDynamic d of -- !> "getMailBox" of Nothing -> empty Just x -> return x -- | delete all subscriptions for that mailbox expecting this kind of data. cleanMailbox :: Typeable a => T.Text -> a -> TransIO () cleanMailbox name witness= do Connection{comEvent= mv} <- getData `onNothing` error "getMailBox: accessing network events out of listen" mbs <- liftIO $readIORef mv let mev = M.lookup name mbs case mev of Nothing -> return() Just ev -> do cleanEVar ev liftIO $ atomicModifyIORef mv $ \mbs -> (M.delete name mbs,()) defConnection :: MonadIO m => m Connection -- #ifndef ghcjs_HOST_OS defConnection = liftIO $ do x <- newMVar () y <- newMVar M.empty z <- return $ error "closchildren newIORef M.empty" return $ Connection (error "node in default connection") Nothing 8192 (error "defConnection: accessing network events out of listen") x False y z #ifndef ghcjs_HOST_OS setBuffSize :: Int -> TransIO () setBuffSize size= Transient $ do conn<- getData `onNothing` defConnection setData $ conn{bufferSize= size} return $ Just () getBuffSize= (do getSData >>= return . bufferSize) <|> return 8192 listen :: Node -> Cloud () listen (node@(Node _ port _ _ )) = onAll $ do addThreads 1 setData $ Log False [] [] conn' <- getSData <|> defConnection ev <- liftIO $ newIORef M.empty chs <- liftIO $ newIORef M.empty let conn= conn'{myNode=node, comEvent=ev,closChildren=chs} setData conn addNodes [node] mlog <- listenNew (fromIntegral port) conn <|> listenResponses execLog mlog listenNew port conn= do sock <- liftIO . listenOn $ PortNumber port let bufSize= bufferSize conn liftIO $ do NS.setSocketOption sock NS.RecvBuffer bufSize NS.setSocketOption sock NS.SendBuffer bufSize (sock,addr) <- waitEvents $ NS.accept sock -- !!> "BEFORE ACCEPT" chs <- liftIO $ newIORef M.empty -- case addr of -- NS.SockAddrInet port host -> liftIO $ print("connection from", port, host) -- NS.SockAddrInet6 a b c d -> liftIO $ print("connection from", a, b,c,d) initFinish onFinish $ const $ do -- return() !> "onFinish closures receivedd with LISTEN" let Connection{closures=closures}= conn -- !> "listenNew closures empty" liftIO $ modifyMVar_ closures $ const $ return M.empty (method,uri, headers) <- receiveHTTPHead sock case method of "CLOS" -> do -- return () !> "CLOS detected" setData $ conn{connData=Just (Node2Node (PortNumber port) sock addr),closChildren=chs} -- killOnFinish $ parallel $ readHandler -- !> "read Listen" -- :: TransIO (StreamData [LogElem]) parallelReadHandler _ -> do sconn <- httpMode (method, uri, headers) sock -- stay serving pages until a websocket request is received setData conn{connData= Just (Node2Web sconn ),closChildren=chs} killOnFinish $ parallel $ do msg <- WS.receiveData sconn -- WebSockets return . read $ BC.unpack msg -- !> ("Server WebSocket msg read",msg) !> "<-------<---------<--------------" --instance Read PortNumber where -- readsPrec n str= let [(n,s)]= readsPrec n str in [(fromIntegral n,s)] --deriving instance Read PortID --deriving instance Typeable PortID #endif listenResponses= do (conn, node) <- getMailbox "connections" setData conn #ifndef ghcjs_HOST_OS case conn of Connection _(Just (Node2Node _ sock _)) _ _ _ _ _ _ -> do input <- liftIO $ SBSL.getContents sock setData $ (ParseContext (error "SHOULD NOT READ 2") input :: ParseContext BS.ByteString) #endif initFinish onFinish $ const $ do liftIO $ putStrLn "removing node: ">> print node nodes <- getNodes setNodes $ nodes \\ [node] let Connection{closures=closures}= conn liftIO $ modifyMVar_ closures $ const $ return M.empty killOnFinish $ mread conn type IdClosure= Int data Closure= Closure IdClosure execLog mlog = Transient $ do case mlog of -- !> ("RECEIVED ", mlog ) of SError e -> do runTrans $ finish $ Just e return Nothing SDone -> runTrans(finish Nothing) >> return Nothing SMore r -> process r False SLast r -> process r True where process (closl,closr,log) deleteClosure= do conn@Connection {closures=closures,closChildren=mapThreads} <- getData `onNothing` error "Listen: myNode not set" if closl== 0 then do setData $ Log True log $ reverse log setData $ Closure closr -- -- chs <- liftIO $ atomicModifyIORef mapThreads -- $ \mapth -> -- let mx = M.lookup closr mapth -- in case mx of -- Just tv -> (mapth,tv) !> "FOUND" -- Nothing -> -- let tv = unsafePerformIO $ newTVarIO [] -- in (M.insert closr tv mapth, tv) -- -- modify $ \ s -> s{children= chs} -- to allow his own thread control return $ Just () -- !> "executing top level closure" else do mcont <- liftIO $ modifyMVar closures $ \map -> return (if deleteClosure then M.delete closl map else map, M.lookup closl map) -- !> ("closures=", M.size map) case mcont of Nothing -> do runTrans $ msend conn $ SLast (closr,closl, [] :: [()] ) -- to delete the remote closure error ("request received for non existent closure: " ++ show closl) -- execute the closure Just (fulLog,cont) -> liftIO $ runStateT (do let nlog= reverse log ++ fulLog setData $ Log True log nlog setData $ Closure closr runCont cont) cont -- !> ("executing closure",closr) return Nothing -- !> "FINISH CLOSURE" #ifdef ghcjs_HOST_OS listen node = onAll $ do addNodes [node] events <- liftIO $ newIORef M.empty conn <- defConnection >>= \c -> return c{myNode=node,comEvent=events} setData conn r <- listenResponses execLog r #endif type Pool= [Connection] type Package= String type Program= String type Service= (Package, Program) -- * Level 2: connections node lists and operations with the node list {-# NOINLINE emptyPool #-} emptyPool :: MonadIO m => m (MVar Pool) emptyPool= liftIO $ newMVar [] createNodeServ :: HostName -> Integer -> [Service] -> IO Node createNodeServ h p svs= do pool <- emptyPool return $ Node h ( fromInteger p) pool svs createNode :: HostName -> Integer -> IO Node createNode h p= createNodeServ h p [] createWebNode :: IO Node createWebNode= do pool <- emptyPool return $ Node "webnode" ( fromInteger 0) pool [("webnode","")] instance Eq Node where Node h p _ _ ==Node h' p' _ _= h==h' && p==p' instance Show Node where show (Node h p _ servs )= show (h,p, servs) instance Read Node where readsPrec _ s= let r= readsPrec' 0 s in case r of [] -> [] [((h,p,ss),s')] -> [(Node h p empty ( ss),s')] where empty= unsafePerformIO emptyPool -- #ifndef ghcjs_HOST_OS --instance Read NS.SockAddr where -- readsPrec _ ('[':s)= -- let (s',r1)= span (/=']') s -- [(port,r)]= readsPrec 0 $ tail $ tail r1 -- in [(NS.SockAddrInet6 port 0 (IP.toHostAddress6 $ read s') 0, r)] -- readsPrec _ s= -- let (s',r1)= span(/= ':') s -- [(port,r)]= readsPrec 0 $ tail r1 -- in [(NS.SockAddrInet port (IP.toHostAddress $ read s'),r)] -- #endif --newtype MyNode= MyNode Node deriving(Read,Show,Typeable) --instance Indexable MyNode where key (MyNode Node{nodePort=port}) = "MyNode "++ show port -- --instance Serializable MyNode where -- serialize= BS.pack . show -- deserialize= read . BS.unpack nodeList :: TVar [Node] nodeList = unsafePerformIO $ newTVarIO [] deriving instance Ord PortID --myNode :: Int -> DBRef MyNode --myNode= getDBRef $ key $ MyNode undefined errorMyNode f= error $ f ++ ": Node not set. initialize it with connect, listen, initNode..." getMyNode :: TransIO Node -- (MonadIO m, MonadState EventF m) => m Node getMyNode = do Connection{myNode= node} <- getSData <|> errorMyNode "getMyNode" :: TransIO Connection return node -- | return the list of nodes connected to the local node getNodes :: MonadIO m => m [Node] getNodes = liftIO $ atomically $ readTVar nodeList -- | add nodes to the list of nodes addNodes :: [Node] -> TransIO () -- (MonadIO m, MonadState EventF m) => [Node] -> m () addNodes nodes= do my <- getMyNode -- mynode must be first liftIO . atomically $ do prevnodes <- readTVar nodeList writeTVar nodeList $ my: (( nub $ nodes ++ prevnodes) \\[my]) -- | set the list of nodes setNodes nodes= liftIO $ atomically $ writeTVar nodeList $ nodes shuffleNodes :: MonadIO m => m [Node] shuffleNodes= liftIO . atomically $ do nodes <- readTVar nodeList let nodes'= tail nodes ++ [head nodes] writeTVar nodeList nodes' return nodes' --getInterfaces :: TransIO TransIO HostName --getInterfaces= do -- host <- logged $ do -- ifs <- liftIO $ getNetworkInterfaces -- liftIO $ mapM_ (\(i,n) ->putStrLn $ show i ++ "\t"++ show (ipv4 n) ++ "\t"++name n)$ zip [0..] ifs -- liftIO $ putStrLn "Select one: " -- ind <- input ( < length ifs) -- return $ show . ipv4 $ ifs !! ind -- | execute a Transient action in each of the nodes connected. -- -- The response of each node is received by the invoking node and processed by the rest of the procedure. -- By default, each response is processed in a new thread. To restrict the number of threads -- use the thread control primitives. -- -- this snippet receive a message from each of the simulated nodes: -- -- > main = keep $ do -- > let nodes= map createLocalNode [2000..2005] -- > addNodes nodes -- > (foldl (<|>) empty $ map listen nodes) <|> return () -- > -- > r <- clustered $ do -- > Connection (Just(PortNumber port, _, _, _)) _ <- getSData -- > return $ "hi from " ++ show port++ "\n" -- > liftIO $ putStrLn r -- > where -- > createLocalNode n= createNode "localhost" (PortNumber n) clustered :: Loggable a => Cloud a -> Cloud a clustered proc= callNodes (<|>) empty proc -- A variant of `clustered` that wait for all the responses and `mappend` them mclustered :: (Monoid a, Loggable a) => Cloud a -> Cloud a mclustered proc= callNodes (<>) mempty proc callNodes op init proc= loggedc $ do nodes <- local getNodes let nodes' = filter (not . isWebNode) nodes foldr op init $ map (\node -> runAt node proc) nodes' where isWebNode Node {nodeServices=srvs} | ("webnode","") `elem` srvs = True | otherwise = False -- | set the rest of the computation as a new node (first parameter) and connect it -- to an existing node (second parameter). then it uses `connect`` to synchronize the list of nodes connect :: Node -> Node -> Cloud () #ifndef ghcjs_HOST_OS connect node remotenode = do listen node <|> return () -- listen1 node remotenode connect' remotenode -- | synchronize the list of nodes with a remote node and all the nodes connected to it -- the final effect is that all the nodes reachable share the same list of nodes connect' remotenode= do nodes <- local getNodes local $ liftIO $ putStrLn $ "connecting to: "++ show remotenode newNodes <- runAt remotenode $ do local $ do conn@(Connection _(Just (Node2Node _ _ _)) _ _ _ _ _ _) <- getSData <|> error ("connect': need to be connected to a node: use wormhole/connect/listen") let nodeConnecting= head nodes liftIO $ modifyMVar_ (connection nodeConnecting) $ const $ return [conn] onFinish . const $ do liftIO $ putStrLn "removing node: ">> print nodeConnecting nodes <- getNodes setNodes $ nodes \\ [nodeConnecting] -- renameMyNode remotenode return nodes mclustered . local . addNodes $ nodes local $ do allNodes <- getNodes liftIO $ putStrLn "Known nodes: " >> print allNodes return allNodes let n = newNodes \\ nodes when (not $ null n) $ mclustered $ local $ do liftIO $ putStrLn "New nodes: " >> print n addNodes n -- add the new discovered nodes local $ do addNodes nodes nodes <- getNodes liftIO $ putStrLn "Known nodes: " >> print nodes -- where -- renameMyNode new= do -- con <- getSData <|> error "connection not set. please initialize it" -- mynode <- liftIO $ readIORef $ myNode con -- liftIO $ writeIORef (myNode con) new -- -- nodes <- getNodes !> ("renaming", mynode, new) -- setNodes $ new:(nodes \\[mynode]) #else connect _ _= empty connect' _ = empty #endif -------------------------------------------- #ifndef ghcjs_HOST_OS readFrom :: Socket -- ^ Connected socket -> IO BS.ByteString -- ^ Data received readFrom sock = loop where -- do -- s <- SBS.recv sock 40980 -- BLC.Chunk <$> return s <*> return BLC.Empty loop = unsafeInterleaveIO $ do s <- SBS.recv sock 4098 if BC.null s then return BLC.Empty -- !> "EMPTY SOCK" else BLC.Chunk s `liftM` loop toStrict= B.concat . BS.toChunks httpMode (method,uri, headers) conn = do -- return () !> ("HTTP request",method,uri, headers) if isWebSocketsReq headers then liftIO $ do stream <- makeStream -- !!> "WEBSOCKETS request" (do bs <- SBS.recv conn 4096 -- readFrom conn return $ if BC.null bs then Nothing else Just bs) (\mbBl -> case mbBl of Nothing -> return () Just bl -> SBS.sendMany conn (BL.toChunks bl) >> return()) -- !!> show ("SOCK RESP",bl) let pc = WS.PendingConnection { WS.pendingOptions = WS.defaultConnectionOptions , WS.pendingRequest = NWS.RequestHead uri headers False -- RequestHead (BC.pack $ show uri) -- (map parseh headers) False , WS.pendingOnAccept = \_ -> return () , WS.pendingStream = stream } sconn <- WS.acceptRequest pc -- !!> "accept request" WS.forkPingThread sconn 30 return sconn else do let uri'= BC.tail $ uriPath uri -- !> "HTTP REQUEST" file= if BC.null uri' then "index.html" else uri' content <- liftIO $ BL.readFile ( "./static/out.jsexe/"++ BC.unpack file) `catch` (\(e:: SomeException) -> return "Not found file: index.html<br/> please compile with ghcjs<br/> ghcjs program.hs -o static/out") n <- liftIO $ SBS.sendMany conn $ ["HTTP/1.0 200 OK\nContent-Type: text/html\nConnection: close\nContent-Length: " <> BC.pack (show $ BL.length content) <>"\n\n"] ++ (BL.toChunks content ) empty where uriPath = BC.dropWhile (/= '/') isWebSocketsReq = not . null . filter ( (== mk "Sec-WebSocket-Key") . fst) data ParseContext a = IsString a => ParseContext (IO a) a deriving Typeable --giveData s= do -- r <- readFrom s -- 80000 -- return r -- !> ( "giveData ", r) receiveHTTPHead s = do input <- liftIO $ SBSL.getContents s setData $ (ParseContext (error "request truncated. Maybe the browser program does not match the server one. \nRecompile the program again with ghcjs <prog> -o static/out") input ::ParseContext BS.ByteString) (method, uri, vers) <- (,,) <$> getMethod <*> getUri <*> getVers headers <- many $ (,) <$> (mk <$> getParam) <*> getParamValue -- !> (method, uri, vers) return (method, toStrict uri, headers) -- !> (method, uri, headers) where getMethod= getString getUri= getString getVers= getString getParam= do dropSpaces r <- tTakeWhile (\x -> x /= ':' && not (endline x)) if BS.null r || r=="\r" then empty else dropChar >> return(toStrict r) getParamValue= toStrict <$> ( dropSpaces >> tTakeWhile (\x -> not (endline x))) dropSpaces= parse $ \str ->((),BS.dropWhile isSpace str) dropChar= parse $ \r -> ((), BS.tail r) endline c= c== '\n' || c =='\r' --tGetLine= tTakeWhile . not . endline readStream :: (Typeable a, Read a) => BS.ByteString -> [StreamData a] readStream s= readStream1 $ BS.unpack s where readStream1 s= let [(x,r)] = readsPrec' 0 s in x : readStream1 r parallelReadHandler :: Loggable a => TransIO (StreamData a) parallelReadHandler= do ParseContext readit str <- getSData <|> error "parallelReadHandler: ParseContext not found" :: (TransIO (ParseContext BS.ByteString)) r <- killOnFinish $ choose $ readStream str return r -- !> ("read",r) -- !> "<-------<----------<--------<----------" getString= do dropSpaces tTakeWhile (not . isSpace) tTakeWhile :: (Char -> Bool) -> TransIO BS.ByteString tTakeWhile cond= parse (BS.span cond) parse :: Monoid b => (BS.ByteString -> (b, BS.ByteString)) -> TransIO b parse split= do ParseContext readit str <- getSData <|> error "parse: ParseContext not found" :: TransIO (ParseContext BS.ByteString) if str == mempty then do str3 <- liftIO readit setData $ ParseContext readit str3 -- !> str3 if str3== mempty then empty else parse split else if BS.take 2 str =="\n\n" then do setData $ ParseContext readit (BS.drop 2 str) ; empty else if BS.take 4 str== "\r\n\r\n" then do setData $ ParseContext readit (BS.drop 4 str) ; empty else do let (ret,str3) = split str setData $ ParseContext readit str3 if str3== mempty then return ret <> (parse split <|> return mempty) else return ret #endif #ifdef ghcjs_HOST_OS isBrowserInstance= True #else isBrowserInstance= False #endif
geraldus/transient-universe
src/Transient/Move.hs
mit
46,457
15
30
14,884
9,369
4,826
4,543
591
7
-- | -- Module: Hakyll.Web.PureScript -- Copyright: (C) 2015 Braden Walters -- License: MIT (see LICENSE file) -- Maintainer: Braden Walters <[email protected]> -- Stability: experimental -- Portability: ghc module Hakyll.Web.PureScript ( Options(..) , pureScriptCompiler , pureScriptCompilerWith , renderPureScript , renderPureScriptWith ) where import Control.Monad.Writer.Strict import Data.Functor import qualified Data.Map as Map import Hakyll.Core.Compiler import Hakyll.Core.Identifier import Hakyll.Core.Item import Language.PureScript.AST.Declarations import Language.PureScript.Errors import Language.PureScript.Make import Language.PureScript.Names import Language.PureScript.Options import Language.PureScript.Parser.Declarations import System.Directory import System.FilePath import System.IO -- |Compiles a PureScript file into a JavaScript file containing all of the -- modules. pureScriptCompiler :: Compiler (Item String) pureScriptCompiler = getResourceBody >>= renderPureScript -- |Compiles a PureScript file into a JavaScript file containing all of the -- modules. Compiler options can be given. pureScriptCompilerWith :: Options -> Compiler (Item String) pureScriptCompilerWith options = getResourceBody >>= renderPureScriptWith options -- |Compiles a PureScript file item into a JavaScript file containing all of the -- modules. renderPureScript :: Item String -> Compiler (Item String) renderPureScript = renderPureScriptWith defaultOptions -- |Compiles a PureScript file item into a JavaScript file containing all of the -- modules. Compiler options can be given. renderPureScriptWith :: Options -> Item String -> Compiler (Item String) renderPureScriptWith options item = do result <- unsafeCompiler $ ioCompiler options $ itemFilenameAndContents item makeItem result -- Get the file path and contents of an item (PureScript file). itemFilenameAndContents :: Item String -> (FilePath, String) itemFilenameAndContents item = (toFilePath $ itemIdentifier item, itemBody item) -- |Compiles PureScript file contents with specified options and returns the -- JavaScript. If multiple modules exist in the PureScript file, all of their -- compiled results appear in the returned string. ioCompiler :: Options -> (FilePath, String) -> IO String ioCompiler options filenameAndContents = do -- Specify the working directory under the temporary directory. tmpDir <- getTemporaryDirectory let tmpWorkDir = tmpDir ++ "/purescript-hakyll" -- Try to parse the modules from the PureScript file. case parseModulesFromFiles id [filenameAndContents] of Left errors -> fail $ prettyPrintMultipleErrors True errors Right filesAndModules -> do let modules = map snd filesAndModules modNamesToFiles = Map.fromList (map (\(file, mod) -> (getModuleName mod, Right file)) filesAndModules) -- Build compilation actions compiling the modules without foreign -- imports. makeActions = buildMakeActions tmpWorkDir modNamesToFiles Map.empty False -- Compile the PureScript to JavaScript. (successOrErrors, _) <- runMake options $ make makeActions modules case successOrErrors of Left errors -> fail $ prettyPrintMultipleErrors True errors Right _ -> do -- Load the module contents for all output modules. moduleContents <- mapM (loadModuleContents tmpWorkDir) modules -- Concatenate all results. let allModuleContents = concat moduleContents return allModuleContents -- |Use the path of the temporary working directory and the module and return -- the JavaScript contents. loadModuleContents :: FilePath -> Module -> IO String loadModuleContents workingDir mod = readFile (workingDir ++ "/" ++ runModuleName (getModuleName mod) ++ "/index.js")
meoblast001/hakyll-purescript
src/Hakyll/Web/PureScript.hs
mit
3,903
0
21
720
652
351
301
58
3
----------------------------------------------------------- -- | -- Module: Bob -- Description: A lackadaisical teenager implemntation -- Copyright: (c) 2015 Alex Dzyoba <[email protected]> -- License: MIT ----------------------------------------------------------- module Bob (responseFor) where import Data.Char (toUpper, isSpace, isControl, isLetter) data Tone = Question | Yell | None | Whatever deriving Show -- | Check whether character is visible isVisible :: Char -> Bool isVisible c = not $ isSpace c || isControl c -- | Check whether string is empty, i.e. doesn't contain visible chars isEmpty :: String -> Bool isEmpty s = not (any isVisible s) -- | Check if string is a Yell: its letters is all capital isYell :: String -> Bool isYell s = map toUpper letters == letters && not (isEmpty letters) -- String may not contain letters where letters = filter isLetter s -- | Determine Tone of the sentence tone :: String -> Tone tone s | isEmpty s = None | isYell s = Yell | last s == '?' = Question | otherwise = Whatever -- | Generate Bob's response by determining Tone of the sentence responseFor :: String -> String responseFor req = case tone req of None -> "Fine. Be that way!" Question -> "Sure." Yell -> "Whoa, chill out!" Whatever -> "Whatever."
dzeban/haskell-exercism
bob/Bob.hs
mit
1,338
0
9
282
281
149
132
24
4
module ParserTypes ( Type(..) , Global(..) , Expr(..) , VKind(..) , Instruction(..) , Initialization(..) , ListOfDef(..) , Ident(..) , getPos ) where data Type = Type Ident | ArrayOf Type [Maybe Expr] | ReferenceTo Type | TypeStruct { typeIdent :: Ident, listDef :: ListOfDef} | TypeUnion { typeIdent :: Ident, listDef :: ListOfDef} | TypeEnum { typeIdent :: Ident, init :: [Initialization]} deriving (Show) data Instruction = LocalVar Type [Initialization] | Assign String Expr Expr (Int, Int) | If [(Maybe Expr, [Instruction])] | Loop [Instruction] | While Expr [Instruction] | For Type Ident Expr [Instruction] | Break | Continue | Return (Maybe Expr) | Print [Expr] | Grab Expr | VoidCall Ident [(Maybe Ident, Expr)] deriving (Show) data Global = GlobalVar VKind Type [Initialization] | TypeDef Ident Type | Function Ident [(Ident, Maybe Expr, Type)] Type [Instruction] | DefCombine Type deriving (Show) data Expr = B String Expr Expr (Int, Int) | U String Expr (Int, Int) | Field Expr Ident | Char String (Int, Int) | Number String (Int, Int) | Float String (Int, Int) | Bool String (Int, Int) | Str String (Int, Int) | Var Ident | FunctionCall Ident [(Maybe Ident, Expr)] | TypeCast Expr Ident | R Expr Expr Expr (Int, Int) deriving (Show) data VKind = VarKind | Const | Static | EnumVar | ExtendedTypeVar deriving (Show, Ord, Eq) type Initialization = (Ident, Maybe Expr) type ListOfDef = [(Type, [Initialization])] data Ident = Ident { identName :: String , line :: Int , column :: Int } deriving (Show, Ord, Eq) getPos :: Expr -> (Int, Int) getPos (B _ _ _ x) = x getPos (U _ _ x) = x getPos (Field _ e) = (line e, column e) getPos (Var e) = (line e, column e) getPos (FunctionCall ident _) = (line ident, column ident) getPos (TypeCast _ ident) = (line ident, column ident) getPos (Char _ x) = x getPos (Number _ x) = x getPos (Float _ x) = x getPos (Bool _ x) = x getPos (Str _ x) = x getPos _ = ((-1), (-1))
scast/bigbrother
src/ParserTypes.hs
gpl-2.0
2,613
0
9
1,040
895
519
376
70
1
module SpecifyTree where import Control.Applicative import Data.Map (Map, fromList, fromListWith, findWithDefault, (!)) import Data.Tree import Text.JSON import Squarify (TreeMapTree(..)) type NodeID = Int type RankID = Int type ParentID = Maybe NodeID data SpecifyTreeNode = SpecifyTreeNode { nodeId :: NodeID, rankId :: RankID, parentId :: ParentID, name :: String, fullName :: String, count :: Int } deriving Show data SpecifyTree = SpecifyTree [SpecifyTreeNode] deriving Show instance JSON SpecifyTreeNode where readJSON (JSArray row) = do nodeId <- getVal row 0 rankId <- getVal row 1 parentId <- case row !! 2 of JSNull -> Ok Nothing v -> Just <$> readJSON v name <- getVal row 3 fullName <- getVal row 4 count <- getVal row 5 return $ SpecifyTreeNode nodeId rankId parentId name fullName count where getVal vals n = readJSON $ vals !! n showJSON = undefined instance JSON SpecifyTree where readJSON (JSArray rows) = SpecifyTree <$> mapM readJSON rows showJSON = undefined type NodesByParent = Map ParentID [SpecifyTreeNode] groupByParent :: SpecifyTree -> NodesByParent groupByParent (SpecifyTree nodes) = fromListWith (++) [(parentId n, [n]) | n <- nodes] type NodesById = Map NodeID SpecifyTreeNode nodesById :: SpecifyTree -> NodesById nodesById (SpecifyTree nodes) = fromList [(nodeId n, n) | n <- nodes] makeTree :: NodesById -> NodesByParent -> Maybe NodeID -> TreeMapTree makeTree byId byParent nId = case children of [child] | thisSize == 0 -> child children | thisSize > 0 -> Node (size, name) $ (Node (thisSize, name) []):children children -> Node (size, name) children where size = thisSize + sum [size | (Node (size, _) _) <- children] (thisSize, name) = case nId of Nothing -> (0, "") Just nId -> (count n, fullName n) where n = byId ! nId children = map (treeFromNodeId . Just . nodeId) childNodes treeFromNodeId nId = makeTree byId byParent nId childNodes = findWithDefault [] nId byParent specifyToTree :: SpecifyTree -> TreeMapTree specifyToTree specifyTree = makeTree byId byParent Nothing where byId = nodesById specifyTree byParent = groupByParent specifyTree treeFromJson :: String -> TreeMapTree treeFromJson s = case (decode s) of Ok st -> specifyToTree st _ -> error "couldn't parse json"
specify/TreeMap
SpecifyTree.hs
gpl-2.0
2,433
0
14
562
823
432
391
62
4
{-# LANGUAGE CPP, TypeFamilies, DeriveDataTypeable #-} module PGIP.Output.Proof ( ProofFormatterOptions , proofFormatterOptions , pfoIncludeProof , pfoIncludeDetails , ProofResult , formatProofs ) where import PGIP.Output.Formatting import PGIP.Output.Mime import PGIP.Output.Provers (Prover, prepareFormatProver) import Interfaces.GenericATPState (tsTimeLimit, tsExtraOpts) import Logic.Comorphism (AnyComorphism) import qualified Logic.Prover as LP import Proofs.AbstractState (G_proof_tree, ProverOrConsChecker) import Common.Json (ppJson, asJson) import Common.ToXml (asXml) import Common.Utils (readMaybe) import Data.Data import Data.Time.LocalTime import Numeric import Text.XML.Light (ppTopElement) import Text.Printf (printf) type ProofResult = (String, String, String, ProverOrConsChecker, -- (goalName, goalResult, goalDetails, prover, AnyComorphism, Maybe (LP.ProofStatus G_proof_tree)) -- translation, proofStatusM) type ProofFormatter = ProofFormatterOptions -> [(String, [ProofResult])] -> (String, String) -- [(dgNodeName, result)] -> (responseType, response) data ProofFormatterOptions = ProofFormatterOptions { pfoIncludeProof :: Bool , pfoIncludeDetails :: Bool } deriving (Show, Eq) proofFormatterOptions :: ProofFormatterOptions proofFormatterOptions = ProofFormatterOptions { pfoIncludeProof = True , pfoIncludeDetails = True } formatProofs :: Maybe String -> ProofFormatter formatProofs format options proofs = case format of Just "json" -> formatAsJSON _ -> formatAsXML where proof :: [Proof] proof = map convertProof proofs formatAsJSON :: (String, String) formatAsJSON = (jsonC, ppJson $ asJson proof) formatAsXML :: (String, String) formatAsXML = (xmlC, ppTopElement $ asXml proof) convertProof :: (String, [ProofResult]) -> Proof convertProof (nodeName, proofResults) = Proof { node = nodeName , goals = map convertGoal proofResults } convertGoal :: ProofResult -> ProofGoal convertGoal (goalName, goalResult, goalDetails, proverOrConsChecker, translation, proofStatusM) = ProofGoal { name = goalName , result = goalResult , details = if pfoIncludeDetails options then Just goalDetails else Nothing , usedProver = prepareFormatProver proverOrConsChecker , usedTranslation = showComorph translation , tacticScript = convertTacticScript proofStatusM , proofTree = fmap (show . LP.proofTree) proofStatusM , usedTime = fmap (convertTime . LP.usedTime) proofStatusM , usedAxioms = fmap LP.usedAxioms proofStatusM , proverOutput = if pfoIncludeProof options then fmap (unlines . LP.proofLines) proofStatusM else Nothing } convertTime :: TimeOfDay -> ProofTime convertTime tod = ProofTime { seconds = printf "%.3f" (read $ init $ show $ timeOfDayToTime tod :: Double) , components = convertTimeComponents tod } convertTimeComponents :: TimeOfDay -> ProofTimeComponents convertTimeComponents tod = ProofTimeComponents { hours = todHour tod , mins = todMin tod , secs = case readSigned readFloat $ show $ todSec tod of [(n, "")] -> n _ -> error $ "Failed reading the number " ++ show (todSec tod) } convertTacticScript :: Maybe (LP.ProofStatus G_proof_tree) -> Maybe TacticScript convertTacticScript Nothing = Nothing convertTacticScript (Just ps) = case (\ (LP.TacticScript ts) -> readMaybe ts) $ LP.tacticScript ps of Nothing -> Nothing Just atp -> Just TacticScript { timeLimit = tsTimeLimit atp , extraOptions = tsExtraOpts atp } data Proof = Proof { node :: String , goals :: [ProofGoal] } deriving (Show, Typeable, Data) data ProofGoal = ProofGoal { name :: String , result :: String , details :: Maybe String , usedProver :: Prover , usedTranslation :: String , tacticScript :: Maybe TacticScript , proofTree :: Maybe String , usedTime :: Maybe ProofTime , usedAxioms :: Maybe [String] , proverOutput :: Maybe String } deriving (Show, Typeable, Data) data TacticScript = TacticScript { timeLimit :: Int , extraOptions :: [String] } deriving (Show, Typeable, Data) data ProofTime = ProofTime { seconds :: String , components :: ProofTimeComponents } deriving (Show, Typeable, Data) data ProofTimeComponents = ProofTimeComponents { hours :: Int , mins :: Int , secs :: Double } deriving (Show, Typeable, Data)
gnn/Hets
PGIP/Output/Proof.hs
gpl-2.0
4,668
0
15
1,079
1,179
676
503
117
7
{-# LANGUAGE OverloadedLists #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module Config.Ghc90x ( ghc90x ) where import Config.ForcedExecutables import Oracle.Hackage ( ) import Types import MyCabal import Control.Monad import qualified Data.List as List import qualified Data.Map as Map import Data.Map.Strict ( fromList, toList ) import Data.Maybe import qualified Data.Set as Set import Development.Shake ghc90x :: Action PackageSetConfig ghc90x = do let compiler = "ghc-9.0.1" flagAssignments = fromList (readFlagAssignents flagList) forcedExectables = forcedExectableNames corePackages = ghcCorePackages packageSet <- fromList <$> forM (toList constraintList) (\(pn,vr) -> (,) pn <$> askOracle (PackageVersionConstraint pn vr)) checkConsistency (PackageSetConfig {..}) {- targetPackages :: ConstraintSet targetPackages = [ "alex >=3.2.5" , "cabal-install ==3.2.*" , "cabal2spec >=2.6" , "cabal-plan" , "distribution-opensuse >= 1.1.1" , "git-annex" , "happy >=1.19.12" , "hledger", "hledger-ui", "hledger-interest" , "hlint" , "ghcid" , "pandoc >=2.9.2.1" , "citeproc >=0.17" , "postgresql-simple" -- needed by emu-incident-report , "SDL >=0.6.6.0" -- Dmitriy Perlow <[email protected]> needs the , "SDL-image >=0.6.2.0" -- SDL packages for games/raincat. , "SDL-mixer >=0.6.3.0" , "shake" , "ShellCheck >=0.7.1" , "weeder" , "xmobar >= 0.33" , "xmonad >= 0.15" , "xmonad-contrib >= 0.16" ] resolveConstraints :: String resolveConstraints = unwords ["cabal", "install", "--dry-run", "--minimize-conflict-set", constraints, flags, pkgs] where pkgs = intercalate " " (display <$> keys targetPackages) constraints = "--constraint=" <> intercalate " --constraint=" (show <$> environment) environment = display . (\(n,v) -> PackageVersionConstraint n v) <$> toList (corePackages `union` targetPackages) flags = unwords [ "--constraint=" <> show (unwords [unPackageName pn, flags']) | pn <- keys targetPackages , Just flags' <- [lookup (unPackageName pn) flagList] ] -} constraintList :: ConstraintSet constraintList = [ "abstract-deque" , "abstract-par" , "adjunctions" , "aeson" , "aeson-pretty" , "aeson-yaml" , "alex" , "algebraic-graphs" , "alsa-core" , "alsa-mixer" , "annotated-wl-pprint" , "ansi-terminal" , "ansi-wl-pprint" , "ap-normalize" , "appar" , "ascii-progress" , "asn1-encoding" , "asn1-parse" , "asn1-types" , "assoc" , "async" , "async-timer" , "atomic-primops" , "atomic-write" , "attoparsec" , "attoparsec-iso8601" , "authenticate-oauth" , "auto-update" , "aws" , "base-compat" , "base-compat-batteries" , "base-noprelude" , "base-orphans" , "base-prelude" , "base16-bytestring" , "base58-bytestring" , "base64" , "base64-bytestring" , "base64-bytestring-type" , "basement" , "bech32" , "bech32-th" , "bencode" , "bifunctors" , "bimap" , "binary-orphans" , "bindings-DSL" , "bindings-uname" , "bitarray" , "blaze-builder" , "blaze-html" , "blaze-markup" , "bloomfilter" , "boring" , "boxes" , "brick" , "bsb-http-chunked" , "byteable" , "byteorder" , "bytestring-builder" , "bzlib-conduit" , "c2hs" , "cabal-doctest" , "cabal-install" , "cabal-plan" , "cabal2spec" , "call-stack" , "canonical-json" , "case-insensitive" , "casing" , "cassava" , "cassava-megaparsec" , "cborg" , "cborg-json" , "cereal" , "charset" , "cipher-aes" , "citeproc" , "clay" , "clientsession" , "clock" , "cmark-gfm" , "cmdargs" , "code-page" , "colour" , "commonmark" , "commonmark-extensions" , "commonmark-pandoc" , "comonad" , "concurrency" , "concurrent-output" , "conduit" , "conduit-combinators" , "conduit-extra" , "conduit-zstd" , "config-ini" , "connection" , "constraints" , "contravariant" , "control-monad-free" , "cookie" , "cpphs" , "cprng-aes" , "criterion" , "criterion-measurement" , "crypto-api" , "crypto-cipher-types" , "crypto-pubkey-types" , "crypto-random" , "cryptohash" , "cryptohash-conduit" , "cryptohash-md5" , "cryptohash-sha1" , "cryptohash-sha256" , "cryptonite" , "cryptonite-conduit" , "css-text" , "csv" , "data-clist" , "data-default" , "data-default-class" , "data-default-instances-containers" , "data-default-instances-dlist" , "data-default-instances-old-locale" , "data-fix" , "DAV" , "dbus" , "dec" , "Decimal" , "dense-linear-algebra" , "dhall" , "dhall-json" , "dhall-yaml" , "Diff" , "digest" , "disk-free-space" , "distribution-opensuse" , "distributive" , "dlist" , "doclayout" , "doctemplates" , "dotgen" , "double-conversion" , "easy-file" , "echo" , "ed25519" , "edit-distance" , "either" , "ekg" , "ekg-core" , "ekg-json" , "email-validate" , "emojis" , "enclosed-exceptions" , "entropy" , "erf" , "errors" , "extensible-exceptions" , "extra" , "fail" , "fast-logger" , "fdo-notify" , "feed" , "fgl" , "file-embed" , "filelock" , "filemanip" , "filepath-bytestring" , "filepattern" , "filtrable" , "fingertree" , "fmlist" , "fmt" , "foldl" , "formatting" , "foundation" , "free" , "fsnotify" , "generic-data" , "generic-deriving" , "generic-monoid" , "generic-random" , "generic-lens" , "generic-lens-core" , "ghc-bignum-orphans" , "ghc-byteorder" , "ghc-lib-parser == 9.0.*" -- drop this package ASAP , "ghc-lib-parser-ex" , "ghc-paths" , "ghcid" , "git-annex" , "git-lfs" , "githash" , "gitrev" , "Glob" , "gray-code" , "groups" , "hackage-security" , "haddock-library <1.11" , "half" , "happy" , "hashable" , "hashtables" , "haskell-lexer" , "heaps" , "hedgehog" , "hedgehog-corpus" , "hedgehog-quickcheck" , "hi-file-parser" , "hinotify" , "hjsmin" , "hledger" , "hledger-interest" , "hledger-lib" , "hledger-ui" , "hlint" , "hostname" , "hourglass" , "hpack" , "hs-bibutils" , "hscolour" , "hsemail" , "hslogger" , "hslua" , "hslua-classes" , "hslua-core" , "hslua-marshalling" , "hslua-module-path" , "hslua-module-system" , "hslua-module-text" , "hslua-module-version" , "hslua-objectorientation" , "hslua-packaging" , "hspec" , "hspec-core" , "hspec-discover" , "hspec-expectations" , "hspec-golden-aeson" , "hspec-smallcheck" , "HsYAML" , "HsYAML-aeson" , "hsyslog" , "html" , "HTTP" , "http-api-data" , "http-client" , "http-client-restricted" , "http-client-tls" , "http-conduit" , "http-date" , "http-media" , "http-types" , "http2" , "HUnit" , "hxt" , "hxt-charproperties" , "hxt-regex-xmlschema" , "hxt-unicode" , "IfElse" , "indexed-profunctors" , "indexed-traversable" , "indexed-traversable-instances" , "infer-license" , "integer-logarithms" , "intern" , "invariant" , "io-streams" , "io-streams-haproxy" , "iproute" , "ipynb" , "iso8601-time" , "iwlib" , "jira-wiki-markup" , "js-chart" , "js-dgtable" , "js-flot" , "js-jquery" , "JuicyPixels" , "kan-extensions" , "katip" , "language-c" , "language-javascript" , "lens" , "lens-aeson" , "lens-family-core" , "libmpd" , "libsystemd-journal" , "libxml-sax" , "libyaml" , "lift-type" , "lifted-async" , "lifted-base" , "ListLike" , "logict" , "lua" , "lucid" , "lukko" , "magic" , "managed" , "math-functions" , "megaparsec" , "memory" , "mersenne-random-pure64" , "microlens" , "microlens-ghc" , "microlens-mtl" , "microlens-platform" , "microlens-th" , "microstache" , "mime-mail" , "mime-types" , "mintty" , "mmorph" , "monad-control" , "monad-logger" , "monad-loops" , "monad-par" , "monad-par-extras" , "MonadRandom" , "mono-traversable" , "moo" , "mountpoints" , "mtl-compat" , "mustache" , "mwc-random" , "neat-interpolation" , "netlink" , "network" , "network-bsd" , "network-byte-order" , "network-info" , "network-multicast" , "network-uri < 2.7.0.0 || > 2.7.0.0" , "nothunks" , "OddWord" , "old-locale" , "old-time" , "Only" , "OneTuple" , "open-browser" , "optics" , "optics-core" , "optics-extra" , "optics-th" , "optional-args" , "optparse-applicative" , "optparse-generic" , "optparse-simple" , "optparse-generic" , "pandoc" , "pandoc-types" , "parallel" , "parsec-class" , "parsec-numbers" , "parser-combinators" , "parsers" , "partial-order" , "path" , "path-io" , "path-pieces" , "pem" , "persistent < 2.12.0.0 || > 2.12.0.0" -- buggy release , "persistent-sqlite" , "persistent-template" , "pipes" , "pipes-safe" , "polyparse" , "postgresql-libpq" , "postgresql-simple" , "pretty-hex" , "pretty-show" , "pretty-simple" , "prettyprinter" , "prettyprinter-ansi-terminal" , "primitive" , "process-extras" , "profunctors" , "prometheus" , "protolude" , "psqueues" , "QuickCheck" , "quickcheck-arbitrary-adt" , "quickcheck-instances" , "quickcheck-io" , "quiet" , "random" , "random-shuffle" , "readable" , "recursion-schemes" , "reducers" , "refact" , "reflection" , "regex-applicative" , "regex-applicative-text" , "regex-base" , "regex-compat" , "regex-pcre-builtin" , "regex-posix" , "regex-tdfa" , "repline" , "resolv" , "resource-pool" , "resourcet" , "retry" , "rfc5051" , "rio" , "rio-orphans" , "rio-prettyprint" , "RSA" , "safe" , "safe-exceptions" , "SafeSemaphore" , "sandi" , "scientific" , "scrypt" , "SDL" , "SDL-image" , "SDL-mixer" , "securemem" , "semialign" , "semigroupoids" , "semigroups" , "serialise" , "servant" , "servant-client" , "servant-client-core" , "servant-server" , "setenv" , "setlocale" , "SHA" , "shake" , "shakespeare" , "ShellCheck" , "shelltestrunner" , "shelly" , "show-combinators" , "silently" , "simple-sendfile" , "singleton-bool" , "skein" , "skylighting" , "skylighting-core" , "smallcheck" , "smtp-mail" , "snap-core" , "snap-server" , "socks" , "some" , "sop-core" , "split" , "splitmix" , "StateVar" , "statistics" , "statistics-linreg" , "stm-chans" , "store-core" , "streaming" , "streaming-binary" , "streaming-bytestring" , "streaming-commons" , "strict" , "strict-concurrency" , "string-conv" , "string-conversions" , "string-qq" , "syb" , "system-fileio" , "system-filepath" , "systemd" , "tabular" , "tagged" , "tagsoup" , "tar" , "tar-conduit" , "tasty" , "tasty-hedgehog" , "tasty-hunit" , "tasty-quickcheck" , "tasty-rerun" , "tdigest" , "temporary" , "terminal-size" , "test-framework" , "test-framework-hunit" , "texmath" , "text-conversions" , "text-format" , "text-icu" , "text-manipulate" , "text-metrics" , "text-short" , "text-zipper" , "tf-random" , "th-abstraction" , "th-compat" , "th-expand-syns" , "th-lift" , "th-lift-instances" , "th-orphans" , "th-reify-many" , "th-utilities" , "these" , "threepenny-gui" , "time-compat" , "time-locale-compat" , "time-manager" , "time-units" , "timeit" , "timezone-olson" , "timezone-series" , "tls" , "tls-session-manager" , "topograph" , "torrent" , "transformers-base" , "transformers-compat" , "transformers-except" , "tree-diff" , "turtle" , "type-equality" , "typed-process" , "typerep-map" , "uglymemo" , "unbounded-delays" , "unicode-collation" , "unicode-data" , "unicode-transforms" , "uniplate" , "Unique" , "unix-bytestring" , "unix-compat" , "unix-time" , "unliftio" , "unliftio-core" , "unordered-containers" , "uri-encode" , "utf8-string" , "utility-ht" , "uuid" , "uuid-types" , "vault" , "vector" , "vector-algorithms" , "vector-binary-instances" , "vector-builder" , "vector-th-unbox" , "void" , "vty" , "wai" , "wai-app-static" , "wai-extra" , "wai-logger" , "warp" , "warp-tls" , "wcwidth" , "websockets" , "websockets-snap" , "weeder" , "witherable" , "wizards" , "wl-pprint-annotated" , "wl-pprint-text" , "word-wrap" , "word8" , "wreq" , "X11" , "X11-xft" , "x509" , "x509-store" , "x509-system" , "x509-validation" , "xml" , "xml-conduit" , "xml-hamlet" , "xml-types" , "xmobar" , "xmonad" , "xmonad-contrib" , "xss-sanitize" , "yaml" , "yesod" , "yesod-core" , "yesod-form" , "yesod-persistent" , "yesod-static" , "zip" , "zip-archive" , "zlib" , "zlib-bindings" , "zstd" ] flagList :: [(String,String)] flagList = [ ("cabal-plan", "exe") -- Don't build hardware-specific optimizations into the binary based on what the -- build machine supports or doesn't support. , ("cryptonite", "-support_aesni -support_rdrand -support_blake2_sse") -- Don't use the bundled sqlite3 library. , ("direct-sqlite", "systemlib") -- dont optimize happy with happy ( dep on same package ..) , ("happy", "-bootstrap") -- Build the standalone executable and prefer pcre-light, which uses the system -- library rather than a bundled copy. , ("highlighting-kate", "executable pcre-light") -- Don't use the bundled sass library. , ("hlibsass", "externalLibsass") -- Use the bundled lua library. People expect this package to provide LUA -- 5.3, but we don't have that yet in openSUSE. , ("hslua", "-system-lua") -- Allow compilation without having Nix installed. , ("nix-paths", "allow-relative-paths") -- Build the standalone executable. , ("texmath", "executable") -- Enable almost all extensions. , ("xmobar", "all_extensions") -- Enable additional features , ("idris", "ffi gmp") -- Disable dependencies we don't have. , ("invertible", "-hlist -piso") -- Use the system sqlite library rather than the bundled one. , ("persistent-sqlite", "systemlib") -- Make sure we're building with the test suite enabled. , ("git-annex", "testsuite") -- Compile against the system library, not the one bundled in the Haskell -- source tarball. , ("cmark", "pkgconfig") -- Fix build with modern compilers. , ("cassava", "-bytestring--lt-0_10_4") -- Prefer the system's library over the bundled one. , ("libyaml", "system-libyaml") -- Configure a production-like build environment. , ("stack", "hide-dependency-versions disable-git-info supported-build") -- The command-line utility pulls in other dependencies. , ("aeson-pretty", "lib-only") -- Build the standalone executable for skylighting. , ("skylighting", "executable") -- Compile against system zstd library , ("zstd", "-standalone") ] readFlagAssignents :: [(String,String)] -> [(PackageName,FlagAssignment)] readFlagAssignents xs = [ (fromJust (simpleParse name), readFlagList (words assignments)) | (name,assignments) <- xs ] readFlagList :: [String] -> FlagAssignment readFlagList = mkFlagAssignment . map (tagWithValue . noMinusF) where tagWithValue ('-':fname) = (mkFlagName (lowercase fname), False) tagWithValue fname = (mkFlagName (lowercase fname), True) noMinusF :: String -> String noMinusF ('-':'f':_) = error "don't use '-f' in flag assignments; just use the flag's name" noMinusF x = x ghcCorePackages :: PackageSet ghcCorePackages = [ "array-0.5.4.0" , "base-4.15.0.0" , "binary-0.8.8.0" , "bytestring-0.10.12.1" , "Cabal-3.4.0.0" , "containers-0.6.2.1" , "deepseq-1.4.5.0" , "directory-1.3.6.1" , "exceptions-0.10.4" , "filepath-1.4.2.1" , "ghc-9.0.0.20200925" , "ghc-bignum-1.0" , "ghc-boot-9.0.0.20200925" , "ghc-boot-th-9.0.0.20200925" , "ghc-compact-0.1.0.0" , "ghc-heap-9.0.0.20200925" , "ghc-prim-0.7.0" , "ghci-9.0.0.20200925" , "haskeline-0.8.1.0" , "hpc-0.6.1.0" , "integer-gmp-1.1" -- backward compactibility record, not built anymore , "libiserv-9.0.0.20200925" , "mtl-2.2.2" , "parsec-3.1.14.0" , "pretty-1.1.3.6" , "process-1.6.10.0" , "rts-1.0" , "stm-2.5.0.0" , "template-haskell-2.17.0.0" , "terminfo-0.4.1.4" , "text-1.2.4.1" , "time-1.9.3" , "transformers-0.5.6.2" , "unix-2.7.2.2" , "xhtml-3000.2.2.1" ] checkConsistency :: MonadFail m => PackageSetConfig -> m PackageSetConfig checkConsistency pset@PackageSetConfig {..} = do let corePackagesInPackageSet = Map.keysSet packageSet `Set.intersection` Map.keysSet corePackages unless (Set.null corePackagesInPackageSet) $ fail ("core packages listed in package set: " <> List.intercalate ", " (unPackageName <$> Set.toList corePackagesInPackageSet)) pure pset
opensuse-haskell/configuration
src/cabal2obs/Config/Ghc90x.hs
gpl-3.0
27,178
0
15
13,847
2,651
1,710
941
690
3
module Language.Arith.Eval ( small , multi , big ) where import Language.Arith.Syntax import Control.Monad ((<=<)) -- | small documentation small :: Term -> Maybe Term small t | isVal t = Just t -- E-IfTrue small (TmIf TmTrue t2 _) = Just t2 -- E-IfFalse small (TmIf TmFalse _ t3) = Just t3 -- E-If small (TmIf t1 t2 t3) | not $ isVal t1 = (\t1' -> TmIf t1' t2 t3) <$> small t1 -- E-Succ small (TmSucc t) | not $ isVal t = TmSucc <$> small t -- E-PredZero small (TmPred TmZero) = Just TmZero -- E-PredSucc small (TmPred (TmSucc nv)) | isNumericalVal nv = Just nv -- E-Pred small (TmPred t) | not $ isVal t = TmPred <$> small t -- E-IsZeroZero small (TmIsZero TmZero) = Just TmTrue -- E-IsZeroSucc small (TmIsZero (TmSucc nv)) | isNumericalVal nv = Just TmFalse -- E-IsZero small (TmIsZero t) | not $ isVal t = TmIsZero <$> small t small _ = Nothing -- | multi documentation multi :: Term -> Maybe Term multi t = case small t of Just t' -> if isVal t' then return t' else multi t' Nothing -> Nothing multi2 :: Term -> Maybe Term multi2 = small <=< small -- | big documentation big :: Term -> Maybe Term -- B-IfTrue and B-IfFalse big (TmIf t1 t2 t3) = case big t1 of Just TmTrue -> big t2 Just TmFalse -> big t3 _ -> Nothing -- B-Succ big (TmSucc t1) = do nv1 <- big t1 if isNumericalVal nv1 then return $ TmSucc nv1 else Nothing -- B-PredZero and B-PredSucc big (TmPred t1) = case big t1 of Just TmZero -> Just TmZero Just (TmSucc nv1) -> Just nv1 _ -> Nothing -- B-IsZeroZero and B-IsZeroSucc big (TmIsZero t1) = case big t1 of Just TmZero -> Just TmTrue Just (TmSucc nv1) -> Just TmFalse _ -> Nothing -- B-Value big t | isVal t = Just t | otherwise = Nothing
juanbono/tapl-haskell
arith/src/Language/Arith/Eval.hs
gpl-3.0
1,887
0
10
558
724
349
375
52
8
{-# 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.Compute.TargetVPNGateways.Insert -- 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) -- -- Creates a target VPN gateway in the specified project and region using -- the data included in the request. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.targetVpnGateways.insert@. module Network.Google.Resource.Compute.TargetVPNGateways.Insert ( -- * REST Resource TargetVPNGatewaysInsertResource -- * Creating a Request , targetVPNGatewaysInsert , TargetVPNGatewaysInsert -- * Request Lenses , tvgiProject , tvgiPayload , tvgiRegion ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.targetVpnGateways.insert@ method which the -- 'TargetVPNGatewaysInsert' request conforms to. type TargetVPNGatewaysInsertResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "regions" :> Capture "region" Text :> "targetVpnGateways" :> QueryParam "alt" AltJSON :> ReqBody '[JSON] TargetVPNGateway :> Post '[JSON] Operation -- | Creates a target VPN gateway in the specified project and region using -- the data included in the request. -- -- /See:/ 'targetVPNGatewaysInsert' smart constructor. data TargetVPNGatewaysInsert = TargetVPNGatewaysInsert' { _tvgiProject :: !Text , _tvgiPayload :: !TargetVPNGateway , _tvgiRegion :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'TargetVPNGatewaysInsert' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tvgiProject' -- -- * 'tvgiPayload' -- -- * 'tvgiRegion' targetVPNGatewaysInsert :: Text -- ^ 'tvgiProject' -> TargetVPNGateway -- ^ 'tvgiPayload' -> Text -- ^ 'tvgiRegion' -> TargetVPNGatewaysInsert targetVPNGatewaysInsert pTvgiProject_ pTvgiPayload_ pTvgiRegion_ = TargetVPNGatewaysInsert' { _tvgiProject = pTvgiProject_ , _tvgiPayload = pTvgiPayload_ , _tvgiRegion = pTvgiRegion_ } -- | Project ID for this request. tvgiProject :: Lens' TargetVPNGatewaysInsert Text tvgiProject = lens _tvgiProject (\ s a -> s{_tvgiProject = a}) -- | Multipart request metadata. tvgiPayload :: Lens' TargetVPNGatewaysInsert TargetVPNGateway tvgiPayload = lens _tvgiPayload (\ s a -> s{_tvgiPayload = a}) -- | Name of the region for this request. tvgiRegion :: Lens' TargetVPNGatewaysInsert Text tvgiRegion = lens _tvgiRegion (\ s a -> s{_tvgiRegion = a}) instance GoogleRequest TargetVPNGatewaysInsert where type Rs TargetVPNGatewaysInsert = Operation type Scopes TargetVPNGatewaysInsert = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute"] requestClient TargetVPNGatewaysInsert'{..} = go _tvgiProject _tvgiRegion (Just AltJSON) _tvgiPayload computeService where go = buildClient (Proxy :: Proxy TargetVPNGatewaysInsertResource) mempty
rueshyna/gogol
gogol-compute/gen/Network/Google/Resource/Compute/TargetVPNGateways/Insert.hs
mpl-2.0
3,977
0
16
916
470
281
189
76
1
{-# 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.Content.Reports.Search -- 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 merchant performance mertrics matching the search query and -- optionally segmented by selected dimensions. -- -- /See:/ <https://developers.google.com/shopping-content/v2/ Content API for Shopping Reference> for @content.reports.search@. module Network.Google.Resource.Content.Reports.Search ( -- * REST Resource ReportsSearchResource -- * Creating a Request , reportsSearch , ReportsSearch -- * Request Lenses , rsXgafv , rsMerchantId , rsUploadProtocol , rsAccessToken , rsUploadType , rsPayload , rsCallback ) where import Network.Google.Prelude import Network.Google.ShoppingContent.Types -- | A resource alias for @content.reports.search@ method which the -- 'ReportsSearch' request conforms to. type ReportsSearchResource = "content" :> "v2.1" :> Capture "merchantId" (Textual Int64) :> "reports" :> "search" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] SearchRequest :> Post '[JSON] SearchResponse -- | Retrieves merchant performance mertrics matching the search query and -- optionally segmented by selected dimensions. -- -- /See:/ 'reportsSearch' smart constructor. data ReportsSearch = ReportsSearch' { _rsXgafv :: !(Maybe Xgafv) , _rsMerchantId :: !(Textual Int64) , _rsUploadProtocol :: !(Maybe Text) , _rsAccessToken :: !(Maybe Text) , _rsUploadType :: !(Maybe Text) , _rsPayload :: !SearchRequest , _rsCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ReportsSearch' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rsXgafv' -- -- * 'rsMerchantId' -- -- * 'rsUploadProtocol' -- -- * 'rsAccessToken' -- -- * 'rsUploadType' -- -- * 'rsPayload' -- -- * 'rsCallback' reportsSearch :: Int64 -- ^ 'rsMerchantId' -> SearchRequest -- ^ 'rsPayload' -> ReportsSearch reportsSearch pRsMerchantId_ pRsPayload_ = ReportsSearch' { _rsXgafv = Nothing , _rsMerchantId = _Coerce # pRsMerchantId_ , _rsUploadProtocol = Nothing , _rsAccessToken = Nothing , _rsUploadType = Nothing , _rsPayload = pRsPayload_ , _rsCallback = Nothing } -- | V1 error format. rsXgafv :: Lens' ReportsSearch (Maybe Xgafv) rsXgafv = lens _rsXgafv (\ s a -> s{_rsXgafv = a}) -- | Required. Id of the merchant making the call. Must be a standalone -- account or an MCA subaccount. rsMerchantId :: Lens' ReportsSearch Int64 rsMerchantId = lens _rsMerchantId (\ s a -> s{_rsMerchantId = a}) . _Coerce -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). rsUploadProtocol :: Lens' ReportsSearch (Maybe Text) rsUploadProtocol = lens _rsUploadProtocol (\ s a -> s{_rsUploadProtocol = a}) -- | OAuth access token. rsAccessToken :: Lens' ReportsSearch (Maybe Text) rsAccessToken = lens _rsAccessToken (\ s a -> s{_rsAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). rsUploadType :: Lens' ReportsSearch (Maybe Text) rsUploadType = lens _rsUploadType (\ s a -> s{_rsUploadType = a}) -- | Multipart request metadata. rsPayload :: Lens' ReportsSearch SearchRequest rsPayload = lens _rsPayload (\ s a -> s{_rsPayload = a}) -- | JSONP rsCallback :: Lens' ReportsSearch (Maybe Text) rsCallback = lens _rsCallback (\ s a -> s{_rsCallback = a}) instance GoogleRequest ReportsSearch where type Rs ReportsSearch = SearchResponse type Scopes ReportsSearch = '["https://www.googleapis.com/auth/content"] requestClient ReportsSearch'{..} = go _rsMerchantId _rsXgafv _rsUploadProtocol _rsAccessToken _rsUploadType _rsCallback (Just AltJSON) _rsPayload shoppingContentService where go = buildClient (Proxy :: Proxy ReportsSearchResource) mempty
brendanhay/gogol
gogol-shopping-content/gen/Network/Google/Resource/Content/Reports/Search.hs
mpl-2.0
5,114
0
19
1,251
809
470
339
115
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeFamilies #-} module Marvin.API.Algorithms.LinearRegression ( LinearRegression (..) , defaultLinearRegression , LinearRegressionModel , coefficients , intercept ) where import qualified Numeric.LinearAlgebra as LA import Numeric.LinearAlgebra.HMatrix import qualified Marvin.API.Algorithms.Internal.GradientDescent as GD import Marvin.API.Algorithms.Internal.GradientDescent hiding (learningRate, lambda, addIntercept) import Marvin.API.Meta.Model import Marvin.API.Table.DataType import Marvin.API.Table.Internal import Marvin.API.Fallible import Control.Arrow import Control.Monad.Except import qualified Data.Vector as Vec -- * Parameters -- | Parameters. data LinearRegression = LinearRegression { learningRate :: Double -- ^ Coefficient of the gradient when updating the model. , numberOfIterations :: Int -- ^ Number of iterations. , lambda :: Double -- ^ Regularization coefficient. , addIntercept :: Bool -- ^ Whether to add a constant 1 column before training. } -- | Default parameters. defaultLinearRegression = LinearRegression { learningRate = 0.001 , numberOfIterations = 10 , lambda = 0.1 , addIntercept = True } toGradDesc :: LinearRegression -> GradientDescent toGradDesc linReg = defaultGradientDescent { numIter = numberOfIterations linReg , GD.cost = linearRegressionCost , GD.learningRate = learningRate linReg , GD.addIntercept = addIntercept linReg , GD.lambda = lambda linReg } -- * Model -- | Resulting model. newtype LinearRegressionModel = LinRegModel LinearModel -- | Retrieves a list of the coefficient. coefficients :: LinearRegressionModel -> [Double] coefficients (LinRegModel linearModel) = LA.toList $ coefs linearModel -- | Retrieves the constant to be added. intercept :: LinearRegressionModel -> Double intercept (LinRegModel linearModel) = intercept_ linearModel instance Show LinearRegressionModel where show (LinRegModel linear) = "Linear regression model:\n\n" ++ show linear instance Estimator LinearRegression (NumericTable, NumericColumn) where type ResultingModel LinearRegression (NumericTable, NumericColumn) = LinearRegressionModel fit linReg (train, target) = do ensurePositive (InvalidAlgorithmParameter "LinearRegression" "numberOfIterations must be positive") $ numberOfIterations linReg ensurePositive (InvalidAlgorithmParameter "LinearRegression" "learning rate must be positive") $ learningRate linReg ensureNonNegative (InvalidAlgorithmParameter "LinearRegression" "lambda must be non-negative") $ lambda linReg ensureTableColSizeMatch "while training linear regression" train target let linearModel = fit' (toGradDesc linReg) (train, target) return $ LinRegModel linearModel instance Predictor LinearRegressionModel where type Testing LinearRegressionModel = NumericTable type Prediction LinearRegressionModel = NumericColumn predict (LinRegModel model) = predict' model unsafeFit :: LinearRegression -> FeatureMatrix -> TargetVariable -> ModelParameters unsafeFit linReg = gradientDescent (toGradDesc linReg)
gaborhermann/marvin
src/Marvin/API/Algorithms/LinearRegression.hs
apache-2.0
3,192
0
13
482
600
343
257
66
1
{-| Module : Marvin.API.Meta.Pipeline Description : Chained transformations of training and test data. -} module Marvin.API.Meta.Pipeline ( Pipeline , transform , inject , fitThenRun ) where import Prelude hiding (id, (.)) import Control.Arrow import Control.Monad import Control.Category import Marvin.API.Fallible -- * Pipeline -- Note: Although 'Trainable' could express 'Simple', then the identity property of category -- would not be satisfied because of Fallible side-effect. -- In the composition of 'Trainable's (f x x) might be Left Error, so even if g does not use f x x -- it's going to return Error. -- Furthermore, using 'Simple' might lead to more efficient computation as there's no need -- to compute (f x x). data MonadicPipeline m a b = Trainable (a -> a -> m b) | Simple (a -> m b) -- | A machine learning pipe representing chained transformations from type 'a' to type 'b'. -- The underlying type is (a -> a -> Fallible b). The transformation is fitted by the first argument -- and the second argument is transformed. This is analogous to the fit and transform methods -- in scikit-learn. type Pipeline a b = MonadicPipeline Fallible a b instance (Monad m) => Category (MonadicPipeline m) where id = Simple return -- f :: a -> a -> m b -- g :: b -> b -> m c (Trainable g) . (Trainable f) = Trainable $ \x x' -> do let f' = f x fx' <- f' x' fx <- f' x g fx fx' (Trainable g) . (Simple f') = Trainable $ \x x' -> do fx <- f' x fx' <- f' x' g fx fx' (Simple g') . (Trainable f) = Trainable $ \x x' -> do fx' <- f x x' g' fx' (Simple g') . (Simple f') = Simple $ \x -> do f'x <- f' x g' f'x instance (Monad m) => Arrow (MonadicPipeline m) where arr f = Simple $ return . f first (Trainable f) = Trainable $ \(x,y) (x',y') -> do fxx' <- f x x' return (fxx', y') first (Simple f) = Simple $ \(x,y) -> do fx <- f x return (fx, y) -- | Primary constructor of 'Pipeline'. transform :: (a -> a -> Fallible b) -> Pipeline a b transform = Trainable -- | A pipeline that passes a 'Fallible' value forward and does not modify it. inject :: Pipeline (Fallible a) a inject = Simple id -- | Evaluates a pipeline. fitThenRun :: Pipeline a b -- ^ Pipeline. -> a -- ^ Training data. -> (a -> Fallible b) -- ^ Transformation learned by the training data. fitThenRun (Trainable f) = f fitThenRun (Simple f') = const f'
gaborhermann/marvin
src/Marvin/API/Meta/Pipeline.hs
apache-2.0
2,449
0
13
582
667
349
318
47
1
module BackwardChaining ( resolve ) where import Control.Monad.Trans.State.Lazy as S ( get, modify, runState ) import Control.Monad.Trans.Reader ( ask, runReaderT ) import Control.Monad.Except ( throwError, runExceptT ) import Control.Monad.Trans.Class (lift) import Types as T import Inference import Logic import Prelude hiding(lookup, filter) import Data.Map(insert, lookup, toList, fromList) resolveRules :: Expr -> Resolution T.State resolveRules goal = do rules <- lift ask let concernedRules = inferRules rules goal let evalRule state relation = do s <- state s' <- eval relation return (s @| s') foldl evalRule (return (Unsolved goal)) concernedRules eval :: Relation -> Resolution T.State eval (lhs `Imply` rhs) = do s <- evalExpr resolveFact lhs return (evalImplication rhs s) eval _ = error "Unreachable Code" evalGoal :: Expr -> Resolution T.State evalGoal goal@(Fact c) = do (lift . lift . modify) (insert c (Unsolved goal)) s <- resolveRules goal ns <- resolveRules (Not goal) let resultState = s `combineGoalAndOposite` ns either (throwError) (\s -> do {lift $ lift $ modify (insert c s) ; return s}) resultState resolveFact :: Expr -> Resolution T.State resolveFact fact@(Fact c) = do knowledge <- lift $ lift $ get maybe (evalGoal fact) (return) (lookup c knowledge) getStateOfQueries :: [Expr] -> Resolution [(String, State)] getStateOfQueries queries = do mapM_ resolveFact queries knowledge <- lift $ lift get return $ [ x | x@(f, s) <- toList knowledge, elem (Fact f) queries] --filterWithKey (\fact _ -> elem fact queries) (collectedKnowledge) resolve :: ([Relation], [(String, State)], [Expr]) -> Either String [(String, State)] resolve (rules, init, queries) = let knowledge = fromList init in fst $ runState (runReaderT (runExceptT (getStateOfQueries queries)) rules) knowledge
tmielcza/demiurge
src/BackwardChaining.hs
apache-2.0
1,917
0
15
381
728
381
347
52
1
data Color = Black | Red deriving (Show, Read, Eq, Enum) data Value = A | Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | J | Q | K deriving (Show, Read, Eq, Enum) data Suit = Spades | Clubs | Diamonds | Hearts deriving (Show, Read, Eq, Enum) data Card = Card { val :: Value , suit :: Suit } deriving (Show, Read, Eq) data Move = Draw Card | Discard Card deriving (Show, Read, Eq) type Moves = [Move] type Deck = [Card] cards :: [Card] cards = [ Card Nine Hearts , Card A Spades , Card Two Clubs , Card Three Clubs ] deck :: Deck deck = [Card v s | s <- [Spades .. Hearts] , v <- [A .. K]] showMove :: Move -> String showMove (Draw c) = "drawing " ++ show c showMove (Discard c) = "discarding " ++ show c {- It takes a card and returns its color (spades and clubs are black, diamonds and hearts are red). Note: One case-expression is enough. -} cardColor :: Card -> Color cardColor c = color (suit c) where color s | s == Spades || s == Clubs = Black | otherwise = Red {- It takes a card and returns its value (numbered cards have their number as the value, aces are 11, everything else is 10). -} cardValue :: Card -> Int cardValue c = value (val c) where value v | v == A = 11 | v == J || v == Q || v == K = 10 | otherwise = fromEnum v + 1 deleteCard :: Card -> [Card] -> [Card] deleteCard _ [] = [] deleteCard c' (c:cs) | c == c' = cs | otherwise = c : (deleteCard c' cs) deleteCard' :: Card -> [Card] -> (Bool, [Card]) deleteCard' _ [] = (False, []) deleteCard' c xs = remove False [] xs where remove found acc [] = (found, acc) remove _ acc (y:ys) = if c == y then (remove True (acc ++ ys) []) else (remove False (y:acc) ys) {- It takes a list of cards 'cs', a card 'c', and an exception 'e'. It returns a list that has all the elements of cs except c. If c is in the list more than once, remove only the first one. If c is not in the list, raise the exception e. -} removeCard :: Card -> [Card] -> Either String [Card] removeCard _ [] = Left "Prelude.removeCard: card not found." removeCard c xs = remove False [] xs where remove found acc [] = if found then Right acc else Left "Prelude.removeCard: card not found." remove _ acc (y:ys) = if c == y then (remove True (acc ++ ys) []) else (remove False (y:acc) ys) {- It takes a list of cards and returns true if all the cards in the list are the same color. -} allSameColor :: [Card] -> Bool allSameColor xs = (allColor Black) || (allColor Red) where allColor color = all (sameColor color) xs sameColor color card = (cardColor card) == color {- It takes a list of cards and returns the sum of their values -} sumCards :: [Card] -> Int sumCards cs = sum [cardValue v | v <- cs] {- It takes a card list (the held-cards) and an int (the goal) and computes the score. Let sum be the sum of the values of the held-cards. If sum is greater than goal, the preliminary score is three times (sum − goal), else the preliminary score is (goal − sum). The score is the preliminary score unless all the held-cards are the same color, in which case the score is the preliminary score divided by 2 -} score :: Int -> [Card] -> Int score goal heldCards = let sum = sumCards heldCards prelimScore = if sum > goal then (sum - goal) * 3 else (goal - sum) in prelimScore `div` if allSameColor heldCards then 1 else 2 {- It runs a game. It takes a card list (the card-list) a move list (what the player “does” at each point), and an int (the goal) and returns the score at the end of the game after processing (some or all of) the moves in the move list in order. -} officiate :: Int -> Deck -> Moves -> Either String Int officiate goal cards ms = case applyMoves ms [] cards of Left x -> Left x Right heldCards -> Right $ score goal heldCards applyMoves :: Moves -> [Card] -> [Card] -> Either String [Card] applyMoves [] held cards = Right held applyMoves ((Draw _):_) held [] = Right held applyMoves ((Draw m):ms) held cards = case (removeCard m cards) of Left x -> Left "IllegalMove: card not found (draw)" Right remCards -> applyMoves ms (m:held) remCards applyMoves ((Discard m):ms) held cards = case (removeCard m held) of Left x -> Left "IllegalMove: card not found (discard)" Right remHeld -> applyMoves ms remHeld (m:cards) cardsList :: [Card] cardsList = [ Card Two Spades , Card Four Hearts , Card Seven Clubs , Card A Hearts , Card K Spades ] moves :: Moves moves = [ Draw (Card Two Spades) , Draw (Card A Hearts) , Discard (Card Two Spades) ] errMoves :: Moves errMoves = [ Draw (Card Two Spades) , Draw (Card A Hearts) , Discard (Card Two Spades) , Discard (Card Four Spades) ]
CarloMicieli/fun-with-haskell
src/prog-lang/HsCard.hs
apache-2.0
5,618
129
9
1,987
1,577
839
738
97
4
module Model where import Prelude import Yesod import Data.Text (Text) import Database.Persist.Quasi import Data.Typeable (Typeable) import Data.Time (UTCTime) import Yesod.Markdown (Markdown) -- You can define all of your database entities in the entities file. -- You can find more information on persistent and how to declare entities -- at: -- http://www.yesodweb.com/book/persistent/ share [mkPersist sqlOnlySettings, mkMigrate "migrateAll"] $(persistFileWith upperCaseSettings "config/models")
pbrisbin/devsite
Model.hs
bsd-2-clause
512
0
8
71
89
52
37
-1
-1
{-# language OverloadedStrings #-} {-# language TemplateHaskell #-} -- | Snaplet that serves javascript files compiled with ghcjs -- (<https://github.com/valderman/ghcjs-compiler>). This Snaplet is meant to be -- used for development. You can work on client side Haskell code and -- immedietely test the code with a simple browser reload. It certainly adds -- some overhead and is not meant to be used in production websites. -- -- Usage: -- -- Put haskell source files in the snaplet path (e.g. @$ROOT\/snaplets\/ghcjs@). -- For every such haskell file there will be a new javascript file available via -- http. -- -- * Other files won't be served through http. The snaplet will 'mzero' on .hs, -- .hi, .o and all other files. -- -- * If any haskell file in the snaplet path is newer than the -- requested javascript file, it will be recompiled. The ghcjs -- snaplet does not track haskell import dependencies: recompilation -- happens whether the js file is requested or not. -- -- * If ghcjsc exits with an error code this snaplet will serve a special -- javascript file that contains the error message as a comment and a -- javascript command that will raise the error message as a javascript -- exception. -- -- Please add such a handler to your routes: -- -- [ ... -- , ("" , with ghcjs ghcjsServe) -- ] module Snap.Snaplet.GHCJS ( GHCJS, snapletArgs, initialize, ghcjsServe, ) where import Control.Applicative import Control.Monad import Control.Monad.IO.Class import Control.Monad.State.Class as State import Control.Lens (makeLenses) import Data.List import Data.String.Conversions import Snap.Core import Snap.Snaplet import Snap.Util.FileServe import System.Directory import System.Exit import System.FilePath import System.IO import System.Process import Text.Printf -- | Internal data type for the ghcjs snaplet. data GHCJS = GHCJS { _ghcjsc :: FilePath , _snapletArgs :: [String] } makeLenses ''GHCJS -- | Initializes the ghcjs snaplet. Use it with e.g. 'nestSnaplet'. initialize :: [String] -> SnapletInit app GHCJS initialize args = makeSnaplet "ghcjs" description Nothing $ do cabalPackageDBs <- liftIO parseCabalPackageDBs let packageArgs = cabalPackageDBs >>= (\a -> ["-package-db", a]) liftIO $ mapM_ putStrLn packageArgs return $ GHCJS "ghcjs" (packageArgs ++ args) where description = "handler for delivering javascript files compiled with ghcjs" -- The following is a hack. There is code to parse the cabal config properly -- to find the sandbox, but it is in cabal-install which doesn't export it -- There may also be a few ways of doing this with cabal, but they would -- be even worse than the following: parseCabalPackageDBs :: IO [String] parseCabalPackageDBs = do -- lines not indented are paths -- TODO - validate properly let isPath s = take 2 s /= (" "::String) && take 1 s == ("/" :: String) dir <- getCurrentDirectory writeFile "cabal.snaplet-ghcjs.config" $ unlines [ "-- Automatically generated by snaplet-ghcjs to help determine location of package db" , "compiler: ghcjs" , "-- Thankyou." , ""] (_stdin, Just stdoutH, Just stderrH, processHandle) <- createProcess (proc "cabal" ["--config-file=cabal.snaplet-ghcjs.config", "exec", "ghcjs-pkg", "list"]){ cwd = Just dir, std_out = CreatePipe, std_err = CreatePipe } exitCode <- waitForProcess processHandle stdout <- hGetContents stdoutH stderr <- hGetContents stderrH case exitCode of -- Delete trailing colon ExitSuccess -> return $ map init $ filter isPath $ lines stdout ExitFailure _ -> do putStrLn "snaplet-ghcjs WARNING: dirty hack failed. Please set -package-db yourself." return [] ghcjsServe :: Handler app GHCJS () ghcjsServe = do jsPath <- cs <$> rqPathInfo <$> getRequest ghcjsDir <- getSnapletFilePath if takeExtension jsPath /= ".js" then mzero else deliverJS (dropExtension (ghcjsDir </> jsPath)) deliverJS :: FilePath -> Handler app GHCJS () deliverJS basename = do hsExists <- liftIO $ doesFileExist (basename <.> "hs") unless hsExists mzero let jsFile = jsFileName basename snapletDir <- getSnapletFilePath jsNewer <- liftIO $ isJSNewer jsFile snapletDir if jsNewer then serveFile jsFile else compile basename -- | Returns whether the given javascript file exists and is newer than -- all Haskell files in the given directory. isJSNewer :: FilePath -> FilePath -> IO Bool isJSNewer jsFile dir = do exists <- liftIO $ doesFileExist jsFile if not exists then return False else do hsFiles <- collectAllHsFiles dir hsTimeStamps <- mapM getModificationTime hsFiles jsTimeStamp <- getModificationTime jsFile return (jsTimeStamp > maximum hsTimeStamps) where collectAllHsFiles :: FilePath -> IO [FilePath] collectAllHsFiles dir = do paths <- fmap (dir </>) <$> filter (not . ("." `isPrefixOf`)) <$> getDirectoryContents dir (files, dirs) <- partitionM doesFileExist paths let hsFiles = filter (\ f -> takeExtension f == ".hs") files subHsFiles <- concat <$> mapM collectAllHsFiles dirs return (hsFiles ++ subHsFiles) partitionM :: Monad m => (a -> m Bool) -> [a] -> m ([a], [a]) partitionM pred (a : r) = do is <- pred a (yes, no) <- partitionM pred r return $ if is then (a : yes, no) else (yes, a : no) partitionM pred [] = return ([], []) -- | Recompiles the file and serves it in case of success. compile :: FilePath -> Handler app GHCJS () compile name = do GHCJS ghcjsc snapletArgs <- State.get let args = snapletArgs ++ [name <.> "hs"] outfile = jsFileName name dir <- getSnapletFilePath (exitCode, message) <- liftIO $ do (_stdin, Just stdoutH, Just stderrH, processHandle) <- createProcess (proc ghcjsc args){ cwd = Just dir, std_out = CreatePipe, std_err = CreatePipe } exitCode <- waitForProcess processHandle stdout <- hGetContents stdoutH stderr <- hGetContents stderrH return (exitCode, "\nGHCJS error:\n============\n" ++ stdout ++ stderr) case exitCode of ExitFailure _ -> writeBS $ cs (printf ("/*\n\n%s\n\n*/\n\nthrow %s;") message (show message) :: String) ExitSuccess -> serveFile outfile -- At time of writing, there's no way to include js from packages. -- Just throw everything up onto the frontend without worrying about -- duplicate code etc. jsFileName :: String -> FilePath jsFileName name = name <.> "jsexe" </> "all.js"
johncant/snaplet-ghcjs
Snap/Snaplet/GHCJS.hs
bsd-3-clause
6,958
0
16
1,764
1,419
741
678
121
4
{-# LANGUAGE BangPatterns, CPP, OverloadedStrings #-} -- | -- Module: Data.Aeson.Parser.Internal -- Copyright: (c) 2011-2015 Bryan O'Sullivan -- (c) 2011 MailRank, Inc. -- License: Apache -- Maintainer: Bryan O'Sullivan <[email protected]> -- Stability: experimental -- Portability: portable -- -- Efficiently and correctly parse a JSON string. The string must be -- encoded as UTF-8. module Data.Aeson.Parser.Internal ( -- * Lazy parsers json, jsonEOF , value , jstring -- * Strict parsers , json', jsonEOF' , value' -- * Helpers , decodeWith , decodeStrictWith , eitherDecodeWith , eitherDecodeStrictWith ) where import Control.Applicative ((*>), (<$>), (<*), liftA2, pure) import Control.Monad.IO.Class (liftIO) import Data.Aeson.Types.Internal (IResult(..), JSONPath, Result(..), Value(..)) import Data.Attoparsec.ByteString.Char8 (Parser, char, endOfInput, scientific, skipSpace, string) import Data.Bits ((.|.), shiftL) import Data.ByteString.Internal (ByteString(..)) import Data.Char (chr) import Data.Text (Text) import Data.Text.Encoding (decodeUtf8') import Data.Text.Internal.Encoding.Utf8 (ord2, ord3, ord4) import Data.Text.Internal.Unsafe.Char (ord) import Data.Vector as Vector (Vector, empty, fromList, reverse) import Data.Word (Word8) import Foreign.ForeignPtr (withForeignPtr) import Foreign.Ptr (minusPtr) import Foreign.Ptr (Ptr, plusPtr) import Foreign.Storable (poke) import System.IO.Unsafe (unsafePerformIO) import qualified Data.Attoparsec.ByteString as A import qualified Data.Attoparsec.Lazy as L import qualified Data.Attoparsec.Zepto as Z import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as L import qualified Data.ByteString.Internal as B import qualified Data.ByteString.Unsafe as B import qualified Data.HashMap.Strict as H #define BACKSLASH 92 #define CLOSE_CURLY 125 #define CLOSE_SQUARE 93 #define COMMA 44 #define DOUBLE_QUOTE 34 #define OPEN_CURLY 123 #define OPEN_SQUARE 91 #define C_0 48 #define C_9 57 #define C_A 65 #define C_F 70 #define C_a 97 #define C_f 102 #define C_n 110 #define C_t 116 -- | Parse a top-level JSON value. -- -- The conversion of a parsed value to a Haskell value is deferred -- until the Haskell value is needed. This may improve performance if -- only a subset of the results of conversions are needed, but at a -- cost in thunk allocation. -- -- This function is an alias for 'value'. In aeson 0.8 and earlier, it -- parsed only object or array types, in conformance with the -- now-obsolete RFC 4627. json :: Parser Value json = value -- | Parse a top-level JSON value. -- -- This is a strict version of 'json' which avoids building up thunks -- during parsing; it performs all conversions immediately. Prefer -- this version if most of the JSON data needs to be accessed. -- -- This function is an alias for 'value''. In aeson 0.8 and earlier, it -- parsed only object or array types, in conformance with the -- now-obsolete RFC 4627. json' :: Parser Value json' = value' object_ :: Parser Value object_ = {-# SCC "object_" #-} Object <$> objectValues jstring value object_' :: Parser Value object_' = {-# SCC "object_'" #-} do !vals <- objectValues jstring' value' return (Object vals) where jstring' = do !s <- jstring return s objectValues :: Parser Text -> Parser Value -> Parser (H.HashMap Text Value) objectValues str val = do skipSpace let pair = liftA2 (,) (str <* skipSpace) (char ':' *> val) w <- A.peekWord8' if w == CLOSE_CURLY then A.anyWord8 >> return H.empty else loop H.empty where loop m0 = do k <- str <* skipSpace <* char ':' v <- val <* skipSpace let !m = H.insert k v m0 ch <- A.satisfy $ \w -> w == COMMA || w == CLOSE_CURLY if ch == COMMA then skipSpace >> loop m else return m {-# INLINE objectValues #-} array_ :: Parser Value array_ = {-# SCC "array_" #-} Array <$> arrayValues value array_' :: Parser Value array_' = {-# SCC "array_'" #-} do !vals <- arrayValues value' return (Array vals) arrayValues :: Parser Value -> Parser (Vector Value) arrayValues val = do skipSpace w <- A.peekWord8' if w == CLOSE_SQUARE then A.anyWord8 >> return Vector.empty else loop [] where loop acc = do v <- val <* skipSpace ch <- A.satisfy $ \w -> w == COMMA || w == CLOSE_SQUARE if ch == COMMA then skipSpace >> loop (v:acc) else return (Vector.reverse (Vector.fromList (v:acc))) {-# INLINE arrayValues #-} -- | Parse any JSON value. You should usually 'json' in preference to -- this function, as this function relaxes the object-or-array -- requirement of RFC 4627. -- -- In particular, be careful in using this function if you think your -- code might interoperate with Javascript. A na&#xef;ve Javascript -- library that parses JSON data using @eval@ is vulnerable to attack -- unless the encoded data represents an object or an array. JSON -- implementations in other languages conform to that same restriction -- to preserve interoperability and security. value :: Parser Value value = do skipSpace w <- A.peekWord8' case w of DOUBLE_QUOTE -> A.anyWord8 *> (String <$> jstring_) OPEN_CURLY -> A.anyWord8 *> object_ OPEN_SQUARE -> A.anyWord8 *> array_ C_f -> string "false" *> pure (Bool False) C_t -> string "true" *> pure (Bool True) C_n -> string "null" *> pure Null _ | w >= 48 && w <= 57 || w == 45 -> Number <$> scientific | otherwise -> fail "not a valid json value" -- | Strict version of 'value'. See also 'json''. value' :: Parser Value value' = do skipSpace w <- A.peekWord8' case w of DOUBLE_QUOTE -> do !s <- A.anyWord8 *> jstring_ return (String s) OPEN_CURLY -> A.anyWord8 *> object_' OPEN_SQUARE -> A.anyWord8 *> array_' C_f -> string "false" *> pure (Bool False) C_t -> string "true" *> pure (Bool True) C_n -> string "null" *> pure Null _ | w >= 48 && w <= 57 || w == 45 -> do !n <- scientific return (Number n) | otherwise -> fail "not a valid json value" -- | Parse a quoted JSON string. jstring :: Parser Text jstring = A.word8 DOUBLE_QUOTE *> jstring_ -- | Parse a string without a leading quote. jstring_ :: Parser Text jstring_ = {-# SCC "jstring_" #-} do s <- A.scan False $ \s c -> if s then Just False else if c == DOUBLE_QUOTE then Nothing else Just (c == BACKSLASH) _ <- A.word8 DOUBLE_QUOTE s1 <- if BACKSLASH `B.elem` s then case unescape s of Right r -> return r Left err -> fail err else return s case decodeUtf8' s1 of Right r -> return r Left err -> fail $ show err {-# INLINE jstring_ #-} unescape :: ByteString -> Either String ByteString unescape s = unsafePerformIO $ do let len = B.length s fp <- B.mallocByteString len -- We perform no bounds checking when writing to the destination -- string, as unescaping always makes it shorter than the source. withForeignPtr fp $ \ptr -> do ret <- Z.parseT (go ptr) s case ret of Left err -> return (Left err) Right p -> do let newlen = p `minusPtr` ptr slop = len - newlen Right <$> if slop >= 128 && slop >= len `quot` 4 then B.create newlen $ \np -> B.memcpy np ptr newlen else return (PS fp 0 newlen) where go ptr = do h <- Z.takeWhile (/=BACKSLASH) let rest = do start <- Z.take 2 let !slash = B.unsafeHead start !t = B.unsafeIndex start 1 escape = case B.elemIndex t "\"\\/ntbrfu" of Just i -> i _ -> 255 if slash /= BACKSLASH || escape == 255 then fail "invalid JSON escape sequence" else if t /= 117 -- 'u' then copy h ptr >>= word8 (B.unsafeIndex mapping escape) >>= go else do a <- hexQuad if a < 0xd800 || a > 0xdfff then copy h ptr >>= charUtf8 (chr a) >>= go else do b <- Z.string "\\u" *> hexQuad if a <= 0xdbff && b >= 0xdc00 && b <= 0xdfff then let !c = ((a - 0xd800) `shiftL` 10) + (b - 0xdc00) + 0x10000 in copy h ptr >>= charUtf8 (chr c) >>= go else fail "invalid UTF-16 surrogates" done <- Z.atEnd if done then copy h ptr else rest mapping = "\"\\/\n\t\b\r\f" hexQuad :: Z.ZeptoT IO Int hexQuad = do s <- Z.take 4 let hex n | w >= C_0 && w <= C_9 = w - C_0 | w >= C_a && w <= C_f = w - 87 | w >= C_A && w <= C_F = w - 55 | otherwise = 255 where w = fromIntegral $ B.unsafeIndex s n a = hex 0; b = hex 1; c = hex 2; d = hex 3 if (a .|. b .|. c .|. d) /= 255 then return $! d .|. (c `shiftL` 4) .|. (b `shiftL` 8) .|. (a `shiftL` 12) else fail "invalid hex escape" decodeWith :: Parser Value -> (Value -> Result a) -> L.ByteString -> Maybe a decodeWith p to s = case L.parse p s of L.Done _ v -> case to v of Success a -> Just a _ -> Nothing _ -> Nothing {-# INLINE decodeWith #-} decodeStrictWith :: Parser Value -> (Value -> Result a) -> B.ByteString -> Maybe a decodeStrictWith p to s = case either Error to (A.parseOnly p s) of Success a -> Just a _ -> Nothing {-# INLINE decodeStrictWith #-} eitherDecodeWith :: Parser Value -> (Value -> IResult a) -> L.ByteString -> Either (JSONPath, String) a eitherDecodeWith p to s = case L.parse p s of L.Done _ v -> case to v of ISuccess a -> Right a IError path msg -> Left (path, msg) L.Fail _ _ msg -> Left ([], msg) {-# INLINE eitherDecodeWith #-} eitherDecodeStrictWith :: Parser Value -> (Value -> IResult a) -> B.ByteString -> Either (JSONPath, String) a eitherDecodeStrictWith p to s = case either (IError []) to (A.parseOnly p s) of ISuccess a -> Right a IError path msg -> Left (path, msg) {-# INLINE eitherDecodeStrictWith #-} -- $lazy -- -- The 'json' and 'value' parsers decouple identification from -- conversion. Identification occurs immediately (so that an invalid -- JSON document can be rejected as early as possible), but conversion -- to a Haskell value is deferred until that value is needed. -- -- This decoupling can be time-efficient if only a smallish subset of -- elements in a JSON value need to be inspected, since the cost of -- conversion is zero for uninspected elements. The trade off is an -- increase in memory usage, due to allocation of thunks for values -- that have not yet been converted. -- $strict -- -- The 'json'' and 'value'' parsers combine identification with -- conversion. They consume more CPU cycles up front, but have a -- smaller memory footprint. -- | Parse a top-level JSON value followed by optional whitespace and -- end-of-input. See also: 'json'. jsonEOF :: Parser Value jsonEOF = json <* skipSpace <* endOfInput -- | Parse a top-level JSON value followed by optional whitespace and -- end-of-input. See also: 'json''. jsonEOF' :: Parser Value jsonEOF' = json' <* skipSpace <* endOfInput word8 :: Word8 -> Ptr Word8 -> Z.ZeptoT IO (Ptr Word8) word8 w ptr = do liftIO $ poke ptr w return $! ptr `plusPtr` 1 copy :: ByteString -> Ptr Word8 -> Z.ZeptoT IO (Ptr Word8) copy (PS fp off len) ptr = liftIO . withForeignPtr fp $ \src -> do B.memcpy ptr (src `plusPtr` off) len return $! ptr `plusPtr` len charUtf8 :: Char -> Ptr Word8 -> Z.ZeptoT IO (Ptr Word8) charUtf8 ch ptr | ch < '\x80' = liftIO $ do poke ptr (fromIntegral (ord ch)) return $! ptr `plusPtr` 1 | ch < '\x800' = liftIO $ do let (a,b) = ord2 ch poke ptr a poke (ptr `plusPtr` 1) b return $! ptr `plusPtr` 2 | ch < '\xffff' = liftIO $ do let (a,b,c) = ord3 ch poke ptr a poke (ptr `plusPtr` 1) b poke (ptr `plusPtr` 2) c return $! ptr `plusPtr` 3 | otherwise = liftIO $ do let (a,b,c,d) = ord4 ch poke ptr a poke (ptr `plusPtr` 1) b poke (ptr `plusPtr` 2) c poke (ptr `plusPtr` 3) d return $! ptr `plusPtr` 4
nurpax/aeson
Data/Aeson/Parser/Internal.hs
bsd-3-clause
13,153
0
31
4,044
3,511
1,825
1,686
261
9
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 \section[PatSyntax]{Abstract Haskell syntax---patterns} -} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE UndecidableInstances #-} -- Note [Pass sensitive types] -- in module PlaceHolder {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE TypeFamilies #-} module HsPat ( Pat(..), InPat, OutPat, LPat, HsConPatDetails, hsConPatArgs, HsRecFields(..), HsRecField'(..), LHsRecField', HsRecField, LHsRecField, HsRecUpdField, LHsRecUpdField, hsRecFields, hsRecFieldSel, hsRecFieldId, hsRecFieldsArgs, hsRecUpdFieldId, hsRecUpdFieldOcc, hsRecUpdFieldRdr, mkPrefixConPat, mkCharLitPat, mkNilPat, isUnliftedHsBind, looksLazyPatBind, isUnliftedLPat, isBangedLPat, isBangedPatBind, hsPatNeedsParens, isIrrefutableHsPat, collectEvVarsPats, pprParendLPat, pprConArgs ) where import {-# SOURCE #-} HsExpr (SyntaxExpr, LHsExpr, HsSplice, pprLExpr, pprSplice) -- friends: import HsBinds import HsLit import PlaceHolder -- ( PostRn,PostTc,DataId ) import HsTypes import TcEvidence import BasicTypes -- others: import PprCore ( {- instance OutputableBndr TyVar -} ) import TysWiredIn import Var import RdrName ( RdrName ) import ConLike import DataCon import TyCon import Outputable import Type import SrcLoc import Bag -- collect ev vars from pats import DynFlags( gopt, GeneralFlag(..) ) import Maybes -- libraries: import Data.Data hiding (TyCon,Fixity) type InPat id = LPat id -- No 'Out' constructors type OutPat id = LPat id -- No 'In' constructors type LPat id = Located (Pat id) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnBang' -- For details on above see note [Api annotations] in ApiAnnotation data Pat id = ------------ Simple patterns --------------- WildPat (PostTc id Type) -- Wild card -- The sole reason for a type on a WildPat is to -- support hsPatType :: Pat Id -> Type | VarPat (Located id) -- Variable -- See Note [Located RdrNames] in HsExpr | LazyPat (LPat id) -- Lazy pattern -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnTilde' -- For details on above see note [Api annotations] in ApiAnnotation | AsPat (Located id) (LPat id) -- As pattern -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnAt' -- For details on above see note [Api annotations] in ApiAnnotation | ParPat (LPat id) -- Parenthesised pattern -- See Note [Parens in HsSyn] in HsExpr -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@, -- 'ApiAnnotation.AnnClose' @')'@ -- For details on above see note [Api annotations] in ApiAnnotation | BangPat (LPat id) -- Bang pattern -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnBang' -- For details on above see note [Api annotations] in ApiAnnotation ------------ Lists, tuples, arrays --------------- | ListPat [LPat id] -- Syntactic list (PostTc id Type) -- The type of the elements (Maybe (PostTc id Type, SyntaxExpr id)) -- For rebindable syntax -- For OverloadedLists a Just (ty,fn) gives -- overall type of the pattern, and the toList -- function to convert the scrutinee to a list value -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@, -- 'ApiAnnotation.AnnClose' @']'@ -- For details on above see note [Api annotations] in ApiAnnotation | TuplePat [LPat id] -- Tuple sub-patterns Boxity -- UnitPat is TuplePat [] [PostTc id Type] -- [] before typechecker, filled in afterwards -- with the types of the tuple components -- You might think that the PostTc id Type was redundant, because we can -- get the pattern type by getting the types of the sub-patterns. -- But it's essential -- data T a where -- T1 :: Int -> T Int -- f :: (T a, a) -> Int -- f (T1 x, z) = z -- When desugaring, we must generate -- f = /\a. \v::a. case v of (t::T a, w::a) -> -- case t of (T1 (x::Int)) -> -- Note the (w::a), NOT (w::Int), because we have not yet -- refined 'a' to Int. So we must know that the second component -- of the tuple is of type 'a' not Int. See selectMatchVar -- (June 14: I'm not sure this comment is right; the sub-patterns -- will be wrapped in CoPats, no?) -- ^ - 'ApiAnnotation.AnnKeywordId' : -- 'ApiAnnotation.AnnOpen' @'('@ or @'(#'@, -- 'ApiAnnotation.AnnClose' @')'@ or @'#)'@ -- For details on above see note [Api annotations] in ApiAnnotation | PArrPat [LPat id] -- Syntactic parallel array (PostTc id Type) -- The type of the elements -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@, -- 'ApiAnnotation.AnnClose' @':]'@ -- For details on above see note [Api annotations] in ApiAnnotation ------------ Constructor patterns --------------- | ConPatIn (Located id) (HsConPatDetails id) | ConPatOut { pat_con :: Located ConLike, pat_arg_tys :: [Type], -- The universal arg types, 1-1 with the universal -- tyvars of the constructor/pattern synonym -- Use (conLikeResTy pat_con pat_arg_tys) to get -- the type of the pattern pat_tvs :: [TyVar], -- Existentially bound type variables pat_dicts :: [EvVar], -- Ditto *coercion variables* and *dictionaries* -- One reason for putting coercion variable here, I think, -- is to ensure their kinds are zonked pat_binds :: TcEvBinds, -- Bindings involving those dictionaries pat_args :: HsConPatDetails id, pat_wrap :: HsWrapper -- Extra wrapper to pass to the matcher -- Only relevant for pattern-synonyms; -- ignored for data cons } ------------ View patterns --------------- -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRarrow' -- For details on above see note [Api annotations] in ApiAnnotation | ViewPat (LHsExpr id) (LPat id) (PostTc id Type) -- The overall type of the pattern -- (= the argument type of the view function) -- for hsPatType. ------------ Pattern splices --------------- -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'$('@ -- 'ApiAnnotation.AnnClose' @')'@ -- For details on above see note [Api annotations] in ApiAnnotation | SplicePat (HsSplice id) -- Includes quasi-quotes ------------ Literal and n+k patterns --------------- | LitPat HsLit -- Used for *non-overloaded* literal patterns: -- Int#, Char#, Int, Char, String, etc. | NPat -- Used for all overloaded literals, -- including overloaded strings with -XOverloadedStrings (Located (HsOverLit id)) -- ALWAYS positive (Maybe (SyntaxExpr id)) -- Just (Name of 'negate') for negative -- patterns, Nothing otherwise (SyntaxExpr id) -- Equality checker, of type t->t->Bool (PostTc id Type) -- Overall type of pattern. Might be -- different than the literal's type -- if (==) or negate changes the type -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnVal' @'+'@ -- For details on above see note [Api annotations] in ApiAnnotation | NPlusKPat (Located id) -- n+k pattern (Located (HsOverLit id)) -- It'll always be an HsIntegral (HsOverLit id) -- See Note [NPlusK patterns] in TcPat -- NB: This could be (PostTc ...), but that induced a -- a new hs-boot file. Not worth it. (SyntaxExpr id) -- (>=) function, of type t1->t2->Bool (SyntaxExpr id) -- Name of '-' (see RnEnv.lookupSyntaxName) (PostTc id Type) -- Type of overall pattern ------------ Pattern type signatures --------------- -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon' -- For details on above see note [Api annotations] in ApiAnnotation | SigPatIn (LPat id) -- Pattern with a type signature (LHsSigWcType id) -- Signature can bind both -- kind and type vars | SigPatOut (LPat id) -- Pattern with a type signature Type ------------ Pattern coercions (translation only) --------------- | CoPat HsWrapper -- If co :: t1 ~ t2, p :: t2, -- then (CoPat co p) :: t1 (Pat id) -- Why not LPat? Ans: existing locn will do Type -- Type of whole pattern, t1 -- During desugaring a (CoPat co pat) turns into a cast with 'co' on -- the scrutinee, followed by a match on 'pat' deriving instance (DataId id) => Data (Pat id) type HsConPatDetails id = HsConDetails (LPat id) (HsRecFields id (LPat id)) hsConPatArgs :: HsConPatDetails id -> [LPat id] hsConPatArgs (PrefixCon ps) = ps hsConPatArgs (RecCon fs) = map (hsRecFieldArg . unLoc) (rec_flds fs) hsConPatArgs (InfixCon p1 p2) = [p1,p2] -- HsRecFields is used only for patterns and expressions (not data type -- declarations) data HsRecFields id arg -- A bunch of record fields -- { x = 3, y = True } -- Used for both expressions and patterns = HsRecFields { rec_flds :: [LHsRecField id arg], rec_dotdot :: Maybe Int } -- Note [DotDot fields] deriving (Functor, Foldable, Traversable) deriving instance (DataId id, Data arg) => Data (HsRecFields id arg) -- Note [DotDot fields] -- ~~~~~~~~~~~~~~~~~~~~ -- The rec_dotdot field means this: -- Nothing => the normal case -- Just n => the group uses ".." notation, -- -- In the latter case: -- -- *before* renamer: rec_flds are exactly the n user-written fields -- -- *after* renamer: rec_flds includes *all* fields, with -- the first 'n' being the user-written ones -- and the remainder being 'filled in' implicitly type LHsRecField' id arg = Located (HsRecField' id arg) type LHsRecField id arg = Located (HsRecField id arg) type LHsRecUpdField id = Located (HsRecUpdField id) type HsRecField id arg = HsRecField' (FieldOcc id) arg type HsRecUpdField id = HsRecField' (AmbiguousFieldOcc id) (LHsExpr id) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnEqual', -- -- For details on above see note [Api annotations] in ApiAnnotation data HsRecField' id arg = HsRecField { hsRecFieldLbl :: Located id, hsRecFieldArg :: arg, -- ^ Filled in by renamer when punning hsRecPun :: Bool -- ^ Note [Punning] } deriving (Data, Functor, Foldable, Traversable) -- Note [Punning] -- ~~~~~~~~~~~~~~ -- If you write T { x, y = v+1 }, the HsRecFields will be -- HsRecField x x True ... -- HsRecField y (v+1) False ... -- That is, for "punned" field x is expanded (in the renamer) -- to x=x; but with a punning flag so we can detect it later -- (e.g. when pretty printing) -- -- If the original field was qualified, we un-qualify it, thus -- T { A.x } means T { A.x = x } -- Note [HsRecField and HsRecUpdField] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- A HsRecField (used for record construction and pattern matching) -- contains an unambiguous occurrence of a field (i.e. a FieldOcc). -- We can't just store the Name, because thanks to -- DuplicateRecordFields this may not correspond to the label the user -- wrote. -- -- A HsRecUpdField (used for record update) contains a potentially -- ambiguous occurrence of a field (an AmbiguousFieldOcc). The -- renamer will fill in the selector function if it can, but if the -- selector is ambiguous the renamer will defer to the typechecker. -- After the typechecker, a unique selector will have been determined. -- -- The renamer produces an Unambiguous result if it can, rather than -- just doing the lookup in the typechecker, so that completely -- unambiguous updates can be represented by 'DsMeta.repUpdFields'. -- -- For example, suppose we have: -- -- data S = MkS { x :: Int } -- data T = MkT { x :: Int } -- -- f z = (z { x = 3 }) :: S -- -- The parsed HsRecUpdField corresponding to the record update will have: -- -- hsRecFieldLbl = Unambiguous "x" PlaceHolder :: AmbiguousFieldOcc RdrName -- -- After the renamer, this will become: -- -- hsRecFieldLbl = Ambiguous "x" PlaceHolder :: AmbiguousFieldOcc Name -- -- (note that the Unambiguous constructor is not type-correct here). -- The typechecker will determine the particular selector: -- -- hsRecFieldLbl = Unambiguous "x" $sel:x:MkS :: AmbiguousFieldOcc Id -- -- See also Note [Disambiguating record fields] in TcExpr. hsRecFields :: HsRecFields id arg -> [PostRn id id] hsRecFields rbinds = map (unLoc . hsRecFieldSel . unLoc) (rec_flds rbinds) -- Probably won't typecheck at once, things have changed :/ hsRecFieldsArgs :: HsRecFields id arg -> [arg] hsRecFieldsArgs rbinds = map (hsRecFieldArg . unLoc) (rec_flds rbinds) hsRecFieldSel :: HsRecField name arg -> Located (PostRn name name) hsRecFieldSel = fmap selectorFieldOcc . hsRecFieldLbl hsRecFieldId :: HsRecField Id arg -> Located Id hsRecFieldId = hsRecFieldSel hsRecUpdFieldRdr :: HsRecUpdField id -> Located RdrName hsRecUpdFieldRdr = fmap rdrNameAmbiguousFieldOcc . hsRecFieldLbl hsRecUpdFieldId :: HsRecField' (AmbiguousFieldOcc Id) arg -> Located Id hsRecUpdFieldId = fmap selectorFieldOcc . hsRecUpdFieldOcc hsRecUpdFieldOcc :: HsRecField' (AmbiguousFieldOcc Id) arg -> LFieldOcc Id hsRecUpdFieldOcc = fmap unambiguousFieldOcc . hsRecFieldLbl {- ************************************************************************ * * * Printing patterns * * ************************************************************************ -} instance (OutputableBndr name) => Outputable (Pat name) where ppr = pprPat pprPatBndr :: OutputableBndr name => name -> SDoc pprPatBndr var -- Print with type info if -dppr-debug is on = getPprStyle $ \ sty -> if debugStyle sty then parens (pprBndr LambdaBind var) -- Could pass the site to pprPat -- but is it worth it? else pprPrefixOcc var pprParendLPat :: (OutputableBndr name) => LPat name -> SDoc pprParendLPat (L _ p) = pprParendPat p pprParendPat :: (OutputableBndr name) => Pat name -> SDoc pprParendPat p = sdocWithDynFlags $ \ dflags -> if need_parens dflags p then parens (pprPat p) else pprPat p where need_parens dflags p | CoPat {} <- p = gopt Opt_PrintTypecheckerElaboration dflags | otherwise = hsPatNeedsParens p -- For a CoPat we need parens if we are going to show it, which -- we do if -fprint-typechecker-elaboration is on (c.f. pprHsWrapper) -- But otherwise the CoPat is discarded, so it -- is the pattern inside that matters. Sigh. pprPat :: (OutputableBndr name) => Pat name -> SDoc pprPat (VarPat (L _ var)) = pprPatBndr var pprPat (WildPat _) = char '_' pprPat (LazyPat pat) = char '~' <> pprParendLPat pat pprPat (BangPat pat) = char '!' <> pprParendLPat pat pprPat (AsPat name pat) = hcat [pprPrefixOcc (unLoc name), char '@', pprParendLPat pat] pprPat (ViewPat expr pat _) = hcat [pprLExpr expr, text " -> ", ppr pat] pprPat (ParPat pat) = parens (ppr pat) pprPat (LitPat s) = ppr s pprPat (NPat l Nothing _ _) = ppr l pprPat (NPat l (Just _) _ _) = char '-' <> ppr l pprPat (NPlusKPat n k _ _ _ _)= hcat [ppr n, char '+', ppr k] pprPat (SplicePat splice) = pprSplice splice pprPat (CoPat co pat _) = pprHsWrapper co (\parens -> if parens then pprParendPat pat else pprPat pat) pprPat (SigPatIn pat ty) = ppr pat <+> dcolon <+> ppr ty pprPat (SigPatOut pat ty) = ppr pat <+> dcolon <+> ppr ty pprPat (ListPat pats _ _) = brackets (interpp'SP pats) pprPat (PArrPat pats _) = paBrackets (interpp'SP pats) pprPat (TuplePat pats bx _) = tupleParens (boxityTupleSort bx) (pprWithCommas ppr pats) pprPat (ConPatIn con details) = pprUserCon (unLoc con) details pprPat (ConPatOut { pat_con = con, pat_tvs = tvs, pat_dicts = dicts, pat_binds = binds, pat_args = details }) = sdocWithDynFlags $ \dflags -> -- Tiresome; in TcBinds.tcRhs we print out a -- typechecked Pat in an error message, -- and we want to make sure it prints nicely if gopt Opt_PrintTypecheckerElaboration dflags then ppr con <> braces (sep [ hsep (map pprPatBndr (tvs ++ dicts)) , ppr binds]) <+> pprConArgs details else pprUserCon (unLoc con) details pprUserCon :: (OutputableBndr con, OutputableBndr id) => con -> HsConPatDetails id -> SDoc pprUserCon c (InfixCon p1 p2) = ppr p1 <+> pprInfixOcc c <+> ppr p2 pprUserCon c details = pprPrefixOcc c <+> pprConArgs details pprConArgs :: OutputableBndr id => HsConPatDetails id -> SDoc pprConArgs (PrefixCon pats) = sep (map pprParendLPat pats) pprConArgs (InfixCon p1 p2) = sep [pprParendLPat p1, pprParendLPat p2] pprConArgs (RecCon rpats) = ppr rpats instance (Outputable arg) => Outputable (HsRecFields id arg) where ppr (HsRecFields { rec_flds = flds, rec_dotdot = Nothing }) = braces (fsep (punctuate comma (map ppr flds))) ppr (HsRecFields { rec_flds = flds, rec_dotdot = Just n }) = braces (fsep (punctuate comma (map ppr (take n flds) ++ [dotdot]))) where dotdot = text ".." <+> ifPprDebug (ppr (drop n flds)) instance (Outputable id, Outputable arg) => Outputable (HsRecField' id arg) where ppr (HsRecField { hsRecFieldLbl = f, hsRecFieldArg = arg, hsRecPun = pun }) = ppr f <+> (ppUnless pun $ equals <+> ppr arg) {- ************************************************************************ * * * Building patterns * * ************************************************************************ -} mkPrefixConPat :: DataCon -> [OutPat id] -> [Type] -> OutPat id -- Make a vanilla Prefix constructor pattern mkPrefixConPat dc pats tys = noLoc $ ConPatOut { pat_con = noLoc (RealDataCon dc), pat_tvs = [], pat_dicts = [], pat_binds = emptyTcEvBinds, pat_args = PrefixCon pats, pat_arg_tys = tys, pat_wrap = idHsWrapper } mkNilPat :: Type -> OutPat id mkNilPat ty = mkPrefixConPat nilDataCon [] [ty] mkCharLitPat :: String -> Char -> OutPat id mkCharLitPat src c = mkPrefixConPat charDataCon [noLoc $ LitPat (HsCharPrim src c)] [] {- ************************************************************************ * * * Predicates for checking things about pattern-lists in EquationInfo * * * ************************************************************************ \subsection[Pat-list-predicates]{Look for interesting things in patterns} Unlike in the Wadler chapter, where patterns are either ``variables'' or ``constructors,'' here we distinguish between: \begin{description} \item[unfailable:] Patterns that cannot fail to match: variables, wildcards, and lazy patterns. These are the irrefutable patterns; the two other categories are refutable patterns. \item[constructor:] A non-literal constructor pattern (see next category). \item[literal patterns:] At least the numeric ones may be overloaded. \end{description} A pattern is in {\em exactly one} of the above three categories; `as' patterns are treated specially, of course. The 1.3 report defines what ``irrefutable'' and ``failure-free'' patterns are. -} isUnliftedLPat :: LPat id -> Bool isUnliftedLPat (L _ (ParPat p)) = isUnliftedLPat p isUnliftedLPat (L _ (TuplePat _ Unboxed _)) = True isUnliftedLPat _ = False isUnliftedHsBind :: HsBind id -> Bool -- A pattern binding with an outermost bang or unboxed tuple must be matched strictly -- Defined in this module because HsPat is above HsBinds in the import graph isUnliftedHsBind (PatBind { pat_lhs = p }) = isUnliftedLPat p isUnliftedHsBind _ = False isBangedPatBind :: HsBind id -> Bool isBangedPatBind (PatBind {pat_lhs = pat}) = isBangedLPat pat isBangedPatBind _ = False isBangedLPat :: LPat id -> Bool isBangedLPat (L _ (ParPat p)) = isBangedLPat p isBangedLPat (L _ (BangPat {})) = True isBangedLPat _ = False looksLazyPatBind :: HsBind id -> Bool -- Returns True of anything *except* -- a StrictHsBind (as above) or -- a VarPat -- In particular, returns True of a pattern binding with a compound pattern, like (I# x) looksLazyPatBind (PatBind { pat_lhs = p }) = looksLazyLPat p looksLazyPatBind _ = False looksLazyLPat :: LPat id -> Bool looksLazyLPat (L _ (ParPat p)) = looksLazyLPat p looksLazyLPat (L _ (AsPat _ p)) = looksLazyLPat p looksLazyLPat (L _ (BangPat {})) = False looksLazyLPat (L _ (TuplePat _ Unboxed _)) = False looksLazyLPat (L _ (VarPat {})) = False looksLazyLPat (L _ (WildPat {})) = False looksLazyLPat _ = True isIrrefutableHsPat :: OutputableBndr id => LPat id -> Bool -- (isIrrefutableHsPat p) is true if matching against p cannot fail, -- in the sense of falling through to the next pattern. -- (NB: this is not quite the same as the (silly) defn -- in 3.17.2 of the Haskell 98 report.) -- -- WARNING: isIrrefutableHsPat returns False if it's in doubt. -- Specifically on a ConPatIn, which is what it sees for a -- (LPat Name) in the renamer, it doesn't know the size of the -- constructor family, so it returns False. Result: only -- tuple patterns are considered irrefuable at the renamer stage. -- -- But if it returns True, the pattern is definitely irrefutable isIrrefutableHsPat pat = go pat where go (L _ pat) = go1 pat go1 (WildPat {}) = True go1 (VarPat {}) = True go1 (LazyPat {}) = True go1 (BangPat pat) = go pat go1 (CoPat _ pat _) = go1 pat go1 (ParPat pat) = go pat go1 (AsPat _ pat) = go pat go1 (ViewPat _ pat _) = go pat go1 (SigPatIn pat _) = go pat go1 (SigPatOut pat _) = go pat go1 (TuplePat pats _ _) = all go pats go1 (ListPat {}) = False go1 (PArrPat {}) = False -- ? go1 (ConPatIn {}) = False -- Conservative go1 (ConPatOut{ pat_con = L _ (RealDataCon con), pat_args = details }) = isJust (tyConSingleDataCon_maybe (dataConTyCon con)) -- NB: tyConSingleDataCon_maybe, *not* isProductTyCon, because -- the latter is false of existentials. See Trac #4439 && all go (hsConPatArgs details) go1 (ConPatOut{ pat_con = L _ (PatSynCon _pat) }) = False -- Conservative go1 (LitPat {}) = False go1 (NPat {}) = False go1 (NPlusKPat {}) = False -- Both should be gotten rid of by renamer before -- isIrrefutablePat is called go1 (SplicePat {}) = urk pat urk pat = pprPanic "isIrrefutableHsPat:" (ppr pat) hsPatNeedsParens :: Pat a -> Bool hsPatNeedsParens (NPlusKPat {}) = True hsPatNeedsParens (SplicePat {}) = False hsPatNeedsParens (ConPatIn _ ds) = conPatNeedsParens ds hsPatNeedsParens p@(ConPatOut {}) = conPatNeedsParens (pat_args p) hsPatNeedsParens (SigPatIn {}) = True hsPatNeedsParens (SigPatOut {}) = True hsPatNeedsParens (ViewPat {}) = True hsPatNeedsParens (CoPat _ p _) = hsPatNeedsParens p hsPatNeedsParens (WildPat {}) = False hsPatNeedsParens (VarPat {}) = False hsPatNeedsParens (LazyPat {}) = False hsPatNeedsParens (BangPat {}) = False hsPatNeedsParens (ParPat {}) = False hsPatNeedsParens (AsPat {}) = False hsPatNeedsParens (TuplePat {}) = False hsPatNeedsParens (ListPat {}) = False hsPatNeedsParens (PArrPat {}) = False hsPatNeedsParens (LitPat {}) = False hsPatNeedsParens (NPat {}) = False conPatNeedsParens :: HsConDetails a b -> Bool conPatNeedsParens (PrefixCon args) = not (null args) conPatNeedsParens (InfixCon {}) = True conPatNeedsParens (RecCon {}) = True {- % Collect all EvVars from all constructor patterns -} -- May need to add more cases collectEvVarsPats :: [Pat id] -> Bag EvVar collectEvVarsPats = unionManyBags . map collectEvVarsPat collectEvVarsLPat :: LPat id -> Bag EvVar collectEvVarsLPat (L _ pat) = collectEvVarsPat pat collectEvVarsPat :: Pat id -> Bag EvVar collectEvVarsPat pat = case pat of LazyPat p -> collectEvVarsLPat p AsPat _ p -> collectEvVarsLPat p ParPat p -> collectEvVarsLPat p BangPat p -> collectEvVarsLPat p ListPat ps _ _ -> unionManyBags $ map collectEvVarsLPat ps TuplePat ps _ _ -> unionManyBags $ map collectEvVarsLPat ps PArrPat ps _ -> unionManyBags $ map collectEvVarsLPat ps ConPatOut {pat_dicts = dicts, pat_args = args} -> unionBags (listToBag dicts) $ unionManyBags $ map collectEvVarsLPat $ hsConPatArgs args SigPatOut p _ -> collectEvVarsLPat p CoPat _ p _ -> collectEvVarsPat p ConPatIn _ _ -> panic "foldMapPatBag: ConPatIn" SigPatIn _ _ -> panic "foldMapPatBag: SigPatIn" _other_pat -> emptyBag
vikraman/ghc
compiler/hsSyn/HsPat.hs
bsd-3-clause
27,766
0
18
8,384
4,770
2,585
2,185
310
20
{-# LANGUAGE TemplateHaskell, MultiParamTypeClasses, Rank2Types, FlexibleContexts, FlexibleInstances #-} module Control.Walkable.THExp where import Control.Walkable.TH import Control.Walkable.Class import Language.Haskell.TH import Language.Haskell.TH.Syntax(NameFlavour, OccName) import Data.Word (Word8) data ExpHandler m = ExpHandler { handleExp :: Exp -> m Exp } $(let hasPrefix s p = take (length p) s == p in do ([walkExpImplLambda], instancesInfo) <- makeTraverseInfo False [''Exp] (`elem` [''String, ''Rational, ''Char, ''Integer, ''Int, ''Word8, ''NameFlavour, ''Bool, ''OccName]) (\n -> case nameModule n of {Just s | s `hasPrefix` "Language.Haskell.TH." -> True; _ -> False}) (`elem` [''Exp, ''String]) walkExpImplDec <- [d| walkExpImpl :: Monad m => (ExpHandler m) -> Exp -> m Exp walkExpImpl f = ($(return walkExpImplLambda) :: Monad m => (forall t . Walkable t ExpHandler => t -> m t) -> Exp -> m Exp) (walk f) |] instancesDec <- mapM (\ (tName, tLambda) -> [d| instance Walkable $(conT tName) ExpHandler where walk f = ($(return tLambda) :: Monad m => (forall t . Walkable t ExpHandler => t -> m t) -> $(conT tName) -> m $(conT tName)) (walk f) |]) instancesInfo return (walkExpImplDec ++ concat instancesDec)) instance Walkable Exp ExpHandler where walk f e = handleExp f e
max630/walkable
Control/Walkable/THExp.hs
bsd-3-clause
1,538
0
21
438
338
192
146
26
0
{-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE FlexibleContexts , ScopedTypeVariables , OverloadedStrings , DataKinds #-} module Sigym4.Geometry.BinarySpec (main, spec) where import System.IO hiding (hGetContents) import Data.ByteString.Lazy (hGetContents) import Data.Either (isRight) import Test.Hspec import Test.QuickCheck import Test.Hspec.QuickCheck import Sigym4.Geometry (Geometry, V2, V3) import Sigym4.Geometry.Binary (ByteOrder(..), wkbEncode, wkbDecode) import Arbitrary () main :: IO () main = hspec spec instance Arbitrary ByteOrder where arbitrary = elements [LittleEndian, BigEndian] spec :: Spec spec = do describe "Sigym4.Geometry.Binary" $ do describe "Geometry V2" $ do prop "deserializes the same thing it serializes" $ \(g :: Geometry V2 0, bo) -> (wkbDecode . wkbEncode bo $ g) == Right g describe "Geometry V3" $ do prop "deserializes the same thing it serializes" $ \(g :: Geometry V3 0, bo) -> (wkbDecode . wkbEncode bo $ g) == Right g describe "wkbDecode" $ do it "can decode a postgis wkb dump" $ do bs <- hGetContents =<< openFile "tests/fixtures/big_geom.wkb" ReadMode let rGeom = wkbDecode bs :: Either String (Geometry V2 0) isRight rGeom `shouldBe` True
krisajenkins/sigym4-geometry
tests/Sigym4/Geometry/BinarySpec.hs
bsd-3-clause
1,337
0
21
314
366
193
173
33
1
module System.SGE.ShellCmd where import HSH import System.Exit newtype ShellCmd = Cmd { fromCmd :: String } deriving Show class Shell a where shellCmd :: a -> ShellCmd runShell :: Shell a => a -> IO ExitCode runShell = run . fromCmd . shellCmd
badi/hsge
System/SGE/ShellCmd.hs
bsd-3-clause
254
0
7
53
81
46
35
8
1
-- | -- Module : Main -- Copyright : (c) 2018 Harendra Kumar -- -- License : BSD3 -- Maintainer : [email protected] import Control.Concurrent (threadDelay) import Control.Monad (when) import Control.Monad.IO.Class (liftIO) import Gauge import Streamly import Streamly.Prelude as S import System.Random (randomRIO) -- Note that we should also compare the cpuTime especially when threaded -- runtime is used with this benchmark because thread scheduling is not -- predictable and can add non-deterministic delay to the total time measured. -- -- Also, the worker dispatch depends on the worker dispatch latency which is -- set to fixed 200 us. We need to keep that in mind when designing tests. value :: Int value = 1000 {-# INLINE source #-} source :: IsStream t => (Int, Int) -> t IO Int source range = S.replicateM value $ do r <- randomRIO range when (r /= 0) $ liftIO $ threadDelay r return r {-# INLINE run #-} run :: IsStream t => (Int, Int) -> (Int, Int) -> (t IO Int -> SerialT IO Int) -> IO () run srange crange t = S.drain $ do n <- t $ source srange d <- liftIO (randomRIO crange) when (d /= 0) $ liftIO $ threadDelay d return n low, medium, high :: Int low = 10 medium = 20 high = 30 {-# INLINE noDelay #-} noDelay :: IsStream t => (t IO Int -> SerialT IO Int) -> IO () noDelay = run (0,0) (0,0) {-# INLINE alwaysConstSlowSerial #-} alwaysConstSlowSerial :: IsStream t => (t IO Int -> SerialT IO Int) -> IO () alwaysConstSlowSerial = run (0,0) (medium,medium) {-# INLINE alwaysConstSlow #-} alwaysConstSlow :: IsStream t => (t IO Int -> SerialT IO Int) -> IO () alwaysConstSlow = run (low,low) (medium,medium) {-# INLINE alwaysConstFast #-} alwaysConstFast :: IsStream t => (t IO Int -> SerialT IO Int) -> IO () alwaysConstFast = run (high,high) (medium,medium) {-# INLINE alwaysVarSlow #-} alwaysVarSlow :: IsStream t => (t IO Int -> SerialT IO Int) -> IO () alwaysVarSlow = run (low,low) (low,high) {-# INLINE alwaysVarFast #-} alwaysVarFast :: IsStream t => (t IO Int -> SerialT IO Int) -> IO () alwaysVarFast = run (high,high) (low,high) -- XXX add variable producer tests as well {-# INLINE runVarSometimesFast #-} runVarSometimesFast :: IsStream t => (t IO Int -> SerialT IO Int) -> IO () runVarSometimesFast = run (medium,medium) (low,high) {-# INLINE randomVar #-} randomVar :: IsStream t => (t IO Int -> SerialT IO Int) -> IO () randomVar = run (low,high) (low,high) main :: IO () main = defaultMain [ bgroup "serialConstantSlowConsumer" [ bench "serially" $ nfIO $ alwaysConstSlowSerial serially , bench "wSerially" $ nfIO $ alwaysConstSlowSerial wSerially ] , bgroup "default" [ bench "serially" $ nfIO $ noDelay serially , bench "wSerially" $ nfIO $ noDelay wSerially , bench "aheadly" $ nfIO $ noDelay aheadly , bench "asyncly" $ nfIO $ noDelay asyncly , bench "wAsyncly" $ nfIO $ noDelay wAsyncly , bench "parallely" $ nfIO $ noDelay parallely ] , bgroup "constantSlowConsumer" [ bench "aheadly" $ nfIO $ alwaysConstSlow aheadly , bench "asyncly" $ nfIO $ alwaysConstSlow asyncly , bench "wAsyncly" $ nfIO $ alwaysConstSlow wAsyncly , bench "parallely" $ nfIO $ alwaysConstSlow parallely ] , bgroup "constantFastConsumer" [ bench "aheadly" $ nfIO $ alwaysConstFast aheadly , bench "asyncly" $ nfIO $ alwaysConstFast asyncly , bench "wAsyncly" $ nfIO $ alwaysConstFast wAsyncly , bench "parallely" $ nfIO $ alwaysConstFast parallely ] , bgroup "variableSlowConsumer" [ bench "aheadly" $ nfIO $ alwaysVarSlow aheadly , bench "asyncly" $ nfIO $ alwaysVarSlow asyncly , bench "wAsyncly" $ nfIO $ alwaysVarSlow wAsyncly , bench "parallely" $ nfIO $ alwaysVarSlow parallely ] , bgroup "variableFastConsumer" [ bench "aheadly" $ nfIO $ alwaysVarFast aheadly , bench "asyncly" $ nfIO $ alwaysVarFast asyncly , bench "wAsyncly" $ nfIO $ alwaysVarFast wAsyncly , bench "parallely" $ nfIO $ alwaysVarFast parallely ] , bgroup "variableSometimesFastConsumer" [ bench "aheadly" $ nfIO $ runVarSometimesFast aheadly , bench "asyncly" $ nfIO $ runVarSometimesFast asyncly , bench "wAsyncly" $ nfIO $ runVarSometimesFast wAsyncly , bench "parallely" $ nfIO $ runVarSometimesFast parallely ] , bgroup "variableFullOverlap" [ bench "aheadly" $ nfIO $ randomVar aheadly , bench "asyncly" $ nfIO $ randomVar asyncly , bench "wAsyncly" $ nfIO $ randomVar wAsyncly , bench "parallely" $ nfIO $ randomVar parallely ] ]
harendra-kumar/asyncly
benchmark/Adaptive.hs
bsd-3-clause
4,738
3
12
1,126
1,450
730
720
94
1
module Main where import Control.Monad (unless) import Data.Text (unpack) import Data.Void (Void) import Dhall.DhallToToml (dhallToToml) import Dhall.Parser (Src) import Dhall.Toml.Utils (fileToDhall) import Dhall.TomlToDhall (tomlToDhall) import Test.Tasty (TestTree) import Test.Tasty.HUnit (Assertion, HasCallStack, assertFailure) import Toml.Type.Printer (pretty) import Toml.Type.TOML (TOML, tomlDiff) import qualified Data.Text.IO import qualified Dhall.Core as Core import qualified GHC.IO.Encoding import qualified Test.Tasty import qualified Test.Tasty.HUnit import qualified Toml.Parser main :: IO () main = do GHC.IO.Encoding.setLocaleEncoding GHC.IO.Encoding.utf8 Test.Tasty.defaultMain testTree testTree :: TestTree testTree = Test.Tasty.testGroup "dhall-toml" [ Test.Tasty.testGroup "dhall-to-toml" dhallToTomlTests , Test.Tasty.testGroup "toml-to-dhall" tomlToDhallTests ] where dhallToTomlTests = map testDhallToToml [ "./tasty/data/empty" , "./tasty/data/natural" , "./tasty/data/float" , "./tasty/data/multiple-fields" , "./tasty/data/nested-tables" , "./tasty/data/adjacent-tables" , "./tasty/data/inline-list" , "./tasty/data/record-list" , "./tasty/data/union-empty" , "./tasty/data/union-typed" , "./tasty/data/union-nested" , "./tasty/data/optional" ] tomlToDhallTests = map testTomlToDhall [ "./tasty/data/empty" , "./tasty/data/natural" , "./tasty/data/float" , "./tasty/data/multiple-fields" , "./tasty/data/nested-tables" , "./tasty/data/adjacent-tables" , "./tasty/data/inline-list" , "./tasty/data/record-list" , "./tasty/data/union-empty" , "./tasty/data/union-typed" , "./tasty/data/optional" ] testDhallToToml :: String -> TestTree testDhallToToml prefix = Test.Tasty.HUnit.testCase prefix $ do let inputFile = prefix ++ ".dhall" let outputFile = prefix ++ ".toml" resolvedExpression <- fileToDhall inputFile actualValue <- Core.throws (dhallToToml resolvedExpression) inputText <- Data.Text.IO.readFile outputFile expectedValue <- case Toml.Parser.parse inputText of Left tomlErr -> fail $ show tomlErr Right expectedValue -> return expectedValue let message = "Conversion to TOML did not generate the expected output" assertTomlEq message expectedValue actualValue testTomlToDhall :: String -> TestTree testTomlToDhall prefix = Test.Tasty.HUnit.testCase prefix $ do let inputFile = prefix ++ ".toml" let schemaFile = prefix ++ "-schema.dhall" let outputFile = prefix ++ ".dhall" inputText <- Data.Text.IO.readFile inputFile toml <- case Toml.Parser.parse inputText of Left tomlErr -> fail $ show tomlErr Right toml -> return toml schema <- fileToDhall schemaFile actualValue <- case tomlToDhall schema toml of Left err -> fail $ show err Right val -> return val expectedValue <- fileToDhall outputFile let message = "Conversion to Dhall did not generate the expected output" assertDhallEq message (Core.normalize expectedValue) actualValue assertTomlEq :: HasCallStack => String -> TOML -> TOML -> Assertion assertTomlEq prefix expected actual = unless (expected == actual) (assertFailure msg) where pretty' = unpack . pretty msg = prefix ++ "\nExpected:\n" ++ pretty' expected ++ "\nActual:\n" ++ pretty' actual ++ "Diff:\nMissing:\n" ++ pretty' (tomlDiff expected actual) ++ "\nExtra:\n" ++ pretty' (tomlDiff actual expected) ++ "AST:\nExpected:\n" ++ show expected ++ "\nActual:\n" ++ show actual assertDhallEq :: HasCallStack => String -> Core.Expr Src Void -> Core.Expr Src Void -> Assertion assertDhallEq prefix expected actual = unless (expected == actual) (assertFailure msg) where pretty' = unpack . Core.pretty msg = prefix ++ "\nExpected:\n" ++ pretty' expected ++ "\nActual:\n" ++ pretty' actual ++ "AST:\nExpected:\n" ++ show expected ++ "\nActual:\n" ++ show actual
Gabriel439/Haskell-Dhall-Library
dhall-toml/tasty/Main.hs
bsd-3-clause
4,345
0
18
1,061
992
515
477
-1
-1
{-# Language BangPatterns #-} module InitialConditions {- ( initialConditions ,initializeMolcasOntheFly ,initializeMolcasTinker ,initializeRC ,initializeSystemOnTheFly ,parseConnections ,parseFileInput ,parseInput )-} where import qualified Data.List as DL import qualified Data.Vector.Unboxed as VU import Control.Applicative hiding ((<|>)) import Control.Arrow ((&&&),first) import Control.Lens import Control.Monad ((<=<),liftM,mplus) import Data.Array.Repa as R import Data.Array.Repa.Unsafe as R import qualified Data.Vector as V import Data.Char(toUpper,toLower) import Data.Either (either) import Data.Maybe (fromMaybe) import qualified Data.Map as M import qualified Data.Monoid as DM import Data.Random.Normal import System.Random import Text.Parsec import Text.Parsec.ByteString -- internal modules import APIparser import CommonTypes import Constants import Gaussian import Molcas import ReactionCoordinate import ParsecNumbers import ParsecText import TinkerQMMM -- =====================> <==================== -- =====================> <=================== initializeRC :: Int -> M.Map Int (Int,Internals) initializeRC numat = M.fromList [(i,(0,v0)) | i <- [0..39]] where dim = 3*numat-6 v0 = VU.replicate dim 0.0 -- =========================> <======================== -- | Parser to read the initial conditions declare in the input file parseFileInput :: MyParser () InitialDynamics -> FilePath -> IO InitialDynamics parseFileInput parser fileName = do r <- parseFromFile parser fileName case r of Left msg -> fail $ show msg Right xs -> return xs parseFilePrueba :: Show a => MyParser () a -> FilePath -> IO () parseFilePrueba parser fileName = do r <- parseFromFile parser fileName case r of Left msg -> fail $ show msg Right xs -> print xs parseInput :: MyParser () InitialDynamics parseInput = do elecSt <- parserElectronicState time <- parserTotalTime step <- parserIntegrationStep (theory,basis) <- parserTheory extForce <- parserExtenalforce anchor <- parserAnchor -- atoms on which the external forces are applied project <- parserProject return $ InitialDynamics elecSt time step theory basis extForce anchor project -- | initial Electronic state parserElectronicState :: MyParser () Singlet parserElectronicState = do keyword <- parseKeyword st <- (\x -> read x :: Singlet) <$> manyTill anyChar space anyLine if (keyword) == "initialstate" then return st else fail "An initial electronic state is mandatory" parserTotalTime :: MyParser () Double parserTotalTime = do keyword <- parseKeyword time <- realNumber anyLine if keyword == "time" then return time else fail " The total time of the dynamics is mandatory" parserIntegrationStep :: MyParser () Double parserIntegrationStep = do keyword <- parseKeyword step <- realNumber anyLine if keyword == "step" then return step else fail " The total Integatin step of the dynamics is mandatory" -- | in case of Gaussian Job a level of theory is required parserTheory :: MyParser () (TheoryLevel,String) parserTheory = option (Unspecified,"Unspecified") $ do spaces try (string "Theory") <|> try (string "theory") spaces >> char '=' >> spaces theory <- parseLevel basis <- manyTill anyChar newline return (theory,basis) where parseLevel = try parserCasMolcas <|> try parserHF <?> "theory level" parserHF = do try (string "HF") <|> try (string "hf") return HF parserCasMolcas = do try (string "CASSCF") <|> try (string "casscf") char '(' electrons <- intNumber char ',' orbitals <- intNumber manyTill anyChar (char '=') rlxRoot <- intNumber rest <- manyTill anyChar (char ')') return $ CASSCF (electrons,orbitals) rlxRoot rest funParser s p = case runP p () "" s of Left msg -> error $ show msg Right x -> x parserExtenalforce :: MyParser () Double parserExtenalforce = option 0 $ try $ do spaces try (string "Force") <|> try (string "force") parseEqual force <- realNumber anyLine return force -- | a list of atom numbers where the external force is applied parserAnchor :: MyParser () [Int] parserAnchor = option [] $ try $ do spaces try (string "Anchor") <|> try (string "anchor") parseEqual anchor <- (\xs -> read xs :: [Int]) <$> manyTill anyChar space anyLine return anchor -- | A string which gives name to the job parserProject :: MyParser () String parserProject = option [] $ try $ do spaces try (string "Project") <|> try (string "project") parseEqual project <- try (manyTill anyChar space) <|> manyTill anyChar eof return project parseKeyword :: MyParser () String parseKeyword = do spaces keyword <- manyTill anyChar space parseEqual return $ toLower <$> keyword parseEqual :: MyParser () () parseEqual = spaces *> char '=' *> spaces -- =====================> Initial Conditions <==================== -- function to initialize on the fly molecular dynamics using Molcas initializeMolcasOntheFly :: FilePath -> Singlet -> Temperature -> IO Molecule initializeMolcasOntheFly xyz st temp = do r <- parseFromFile (parseMoleculeXYZ parseAtoms) xyz case r of Left msg -> error $ show msg Right xs -> initializeBaseOnXYZ xs st temp initializeMolcasZeroVel :: FilePath -> IO Vec initializeMolcasZeroVel xyz = do r <- parseFromFile (parseMoleculeXYZ parseAtoms) xyz case r of Left msg -> error $ show msg Right xs -> do let dim = 3 * (length xs) return $ R.fromUnboxed (Z:. dim) $ VU.replicate dim 0 initializeBaseOnXYZ :: [(Label,[Double])] -> Singlet -> Temperature -> IO Molecule initializeBaseOnXYZ xs st temp = do let (labels,coord) = unzip xs f2U (c:cs) = toUpper c : cs numat = DL.length labels dim = 3*numat repaCoord = fromListUnboxed (Z :. dim) . fmap (/a0) $ concat coord masses = fmap (\k -> fromMaybe msg $ M.lookup (f2U k) atom2Mass) labels msg = error "Sorry boy, but I don't know some of your input atoms" aumasses = fromListUnboxed (Z:.numat) $ fmap (*amu) masses forces = R.fromUnboxed (Z:.dim) $ VU.replicate dim 0 velocities <- genMaxwellBoltzmann aumasses temp return $ defaultMol & getCoord .~ repaCoord & getVel .~ velocities & getForce .~ forces & getMass .~ aumasses & getAtoms .~ labels & getElecSt.~ (Left st) initializeMolcasTinker :: FilePath -> Singlet -> Temperature -> Int -> IO (Molecule,[AtomQM]) initializeMolcasTinker molcasInput st temp numat = do molcasQM <- parserInputMolcasQM molcasInput $ parserGatewayQM numat let atoms = takeLabelCoordinates <$> molcasQM mol <- initializeBaseOnXYZ atoms st temp return (mol,molcasQM) where takeLabelCoordinates (AtomQM label xyz _) = (label,xyz) -- |collects the initial required to initialize a dynamic on the fly initializeSystemOnTheFly :: FilePath -> Singlet -> Temperature-> IO Molecule initializeSystemOnTheFly file st temp = do let keywords = ["Coordinates","Masses","Charges"] pairs <- takeInfo keywords <=< parseGaussianCheckpoint $ file let getData = lookupLabel pairs [coord,masses] = fmap ((\ys -> R.fromListUnboxed (Z:. DL.length ys) ys) . getData) ["Coordinates","Masses"] labels = fmap (charge2Label .floor) $ getData "Charges" numat = DL.length labels dim = 3*numat aumasses = computeUnboxedS $ R.map (*amu) masses forces = R.fromUnboxed (Z:.dim) $ VU.replicate dim 0 velocities <- genMaxwellBoltzmann aumasses temp return $ defaultMol & getCoord .~ coord & getVel .~ velocities & getForce .~ forces & getMass .~ aumasses & getAtoms .~ labels & getElecSt.~ (Left st) -- =============> <================ initialConditions :: [Double] -> [Double] -> [EnergyDerivatives] -> Connections -> Temperature -> IO Molecule initialConditions !cartCoord !masses !dervEs !conex !t = do let numat = length masses velocities <- genMaxwellBoltzmann (R.fromListUnboxed (Z:. numat) masses) t let forces = R.fromUnboxed (Z:. numat*3) $ VU.generate (3*numat) (const 0) repaMass = R.fromListUnboxed (Z:. numat) masses repaCoord = R.fromListUnboxed (Z:. numat*3) cartCoord internals = calculateInternals conex (R.toUnboxed repaCoord) initialMol = defaultMol fc = FC internals conex return $ initialMol & getCoord .~ repaCoord & getVel .~ velocities & getForce .~ forces & getMass .~ repaMass & getElecSt.~ (Left S0) & getDervEn.~ dervEs & getFCStruc.~fc parseConnections :: FilePath -> IO Connections parseConnections file = do r <- parseFromFile parseInternals file case r of Left msg -> error $ show msg Right conex -> return conex -- ====================> Initial Velocities <================ genMaxwellBoltzmann :: Array U DIM1 Double -> Temperature -> IO (Array U DIM1 Double) genMaxwellBoltzmann !ms !t = do let stds = fmap (\mi -> sqrt $ (t*kb/mi)) $ R.toList ms xs <- mapM (\std -> (take 3) `liftM` (normalsIO' (0,std))) stds let vs = concat xs return $ R.fromListUnboxed (Z:. length vs) vs readInitialVel :: FilePath -> IO (Array U DIM1 Double) readInitialVel xyz = do r <- parseFromFile (parseMoleculeXYZ parseAtoms) xyz case r of Left msg -> error $ show msg Right xs -> do let dim = 3*(length xs) return $ R.fromListUnboxed (Z:.dim) $ concatMap snd xs -- ===================> <================== -- | String to Nuclear Charge atom2Mass :: M.Map String Double atom2Mass = M.fromList [("H",1.0000000203387491),("C",12.000000244064989),("N",14.000000284742487),("O",16.0)]
felipeZ/Dynamics
src/InitialConditions.hs
bsd-3-clause
11,127
1
21
3,413
3,104
1,547
1,557
229
2
newtype Diag a = MkDiag { unDiag :: [a] } deriving Show instance Monad Diag where return x = MkDiag [x] MkDiag xs >>= f = MkDiag (concat (diag (map (unDiag . f) xs))) diag [] = [] diag (xs:xss) = zipWith (++) [ [x] | x <- xs ] ([] : diag xss)
jystic/QuickSpec
experiment/Diag.hs
bsd-3-clause
247
0
14
58
149
79
70
6
1
{-# LANGUAGE OverloadedStrings #-} module RealWorld.Api.Articles where import RealWorld.Api.Prelude import Control.Monad.Time (currentTime) import qualified RealWorld.DB as DB import RealWorld.Model.Article (Article(..), ArticleBody(..), ArticlesBody(..), Slug) import qualified RealWorld.Model.Article as Article import qualified RealWorld.Model.Errors as Errors import qualified RealWorld.Model.Field as Field type Api = GetArticles :<|> GetArticle :<|> CreateArticle :<|> UpdateArticle :<|> DeleteArticle type GetArticles = Get '[JSON] ArticlesBody type GetArticle = Capture "slug" Slug :> Get '[JSON] ArticleBody type CreateArticle = ReqBody '[JSON] ArticleBody :> Post '[JSON] ArticleBody type UpdateArticle = Capture "slug" Slug :> ReqBody '[JSON] ArticleBody :> Put '[JSON] ArticleBody type DeleteArticle = Capture "slug" Slug :> Delete '[JSON] () server :: ServerT Api RealWorld server = getArticles :<|> getArticle :<|> createArticle :<|> updateArticle :<|> deleteArticle getArticles :: RealWorld ArticlesBody getArticles = do articles <- DB.query DB.GetArticles pure $ ArticlesBody articles createArticle :: ArticleBody -> RealWorld ArticleBody createArticle (ArticleBody a) = ArticleBody <$> do title_ <- Field.require a title desc_ <- Field.require a description body_ <- Field.require a body tags_ <- Field.require a tagList <|> pure mempty slug_ <- Article.sluggify title_ ?? Errors.unprocessable "Unsluggable title" createdAt_ <- currentTime let article = Article { slug = pure slug_ , title = pure title_ , description = pure desc_ , body = pure body_ , tagList = pure tags_ , createdAt = pure createdAt_ , updatedAt = Field.Nil , favorited = Field.Undefined , favoritesCount = pure 0 , author = Field.Undefined -- FIXME: DEFINE } article <$ DB.update (DB.UpsertArticle slug_ article) getArticle :: Slug -> RealWorld ArticleBody getArticle slug = ArticleBody <$> do DB.query (DB.GetArticle slug) !? articleNotFound updateArticle :: Slug -> ArticleBody -> RealWorld ArticleBody updateArticle slug (ArticleBody article') = ArticleBody <$> do ArticleBody article <- getArticle slug let article'' = article { title = title article' <|> title article , description = description article' <|> description article , body = body article' <|> body article , tagList = tagList article' <|> tagList article } DB.update (DB.UpsertArticle slug article'') pure article'' deleteArticle :: Slug -> RealWorld () deleteArticle slug = do _article <- DB.update (DB.DeleteArticle slug) !? articleNotFound pure () articleNotFound :: Errors articleNotFound = Errors.notFound "Requested article doesn't exist."
zudov/servant-realworld-example-app
src/RealWorld/Api/Articles.hs
bsd-3-clause
3,060
0
14
806
822
427
395
-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.Distance.DE.Rules (rules) where import Data.String import Data.Text (Text) import Prelude import Duckling.Dimensions.Types import Duckling.Distance.Helpers import Duckling.Distance.Types (DistanceData(..)) import qualified Duckling.Distance.Types as TDistance import Duckling.Numeral.Helpers import Duckling.Numeral.Types (NumeralData(..)) import qualified Duckling.Numeral.Types as TNumeral import Duckling.Types distances :: [(Text, String, TDistance.Unit)] distances = [ -- Imperial ("miles", "meilen?", TDistance.Mile) , ("inch", "(\"|''|zoll)", TDistance.Inch) -- Metric , ("km", "k(ilo)?m(etern?)?", TDistance.Kilometre) , ("meters", "m(etern?)?", TDistance.Metre) , ("centimeters", "(cm|[zc]entimetern?)", TDistance.Centimetre) , ("millimeters", "(mm|millimetern?)", TDistance.Millimetre) ] rulePrecision :: Rule rulePrecision = Rule { name = "about|exactly <dist>" , pattern = [ regex "genau|exakt|präzise|ungefähr|(in )?etwa|nahe?( an)?|um( die)?|fast|rund|gut" , dimension Distance ] , prod = \case (_:token:_) -> Just token _ -> Nothing } ruleDistances :: [Rule] ruleDistances = map go distances where go :: (Text, String, TDistance.Unit) -> Rule go (name, regexPattern, u) = Rule { name = name , pattern = [ dimension Distance, regex regexPattern ] , prod = \case (Token Distance dd:_) -> Just . Token Distance $ withUnit u dd _ -> Nothing } ruleIntervalBetweenNumeral :: Rule ruleIntervalBetweenNumeral = Rule { name = "between|from <numeral> to|and <dist>" , pattern = [ regex "zwischen|von" , Predicate isPositive , regex "bis|und" , Predicate isSimpleDistance ] , prod = \case (_: Token Numeral NumeralData{TNumeral.value = from}: _: Token Distance DistanceData{TDistance.value = Just to, TDistance.unit = Just u}: _) | from < to -> Just . Token Distance . withInterval (from, to) $ unitOnly u _ -> Nothing } ruleIntervalBetween :: Rule ruleIntervalBetween = Rule { name = "between|from <dist> to|and <dist>" , pattern = [ regex "zwischen|von" , Predicate isSimpleDistance , regex "und|bis" , Predicate isSimpleDistance ] , prod = \case (_: Token Distance DistanceData{TDistance.value = Just from, TDistance.unit = Just u1}: _: Token Distance DistanceData{TDistance.value = Just to, TDistance.unit = Just u2}: _) | from < to && u1 == u2 -> Just . Token Distance . withInterval (from, to) $ unitOnly u1 _ -> Nothing } ruleIntervalNumeralDash :: Rule ruleIntervalNumeralDash = Rule { name = "<numeral> - <dist>" , pattern = [ Predicate isPositive , regex "-" , Predicate isSimpleDistance ] , prod = \case (Token Numeral NumeralData{TNumeral.value = from}: _: Token Distance DistanceData{TDistance.value = Just to, TDistance.unit = Just u}: _) | from < to -> Just . Token Distance . withInterval (from, to) $ unitOnly u _ -> Nothing } ruleIntervalDash :: Rule ruleIntervalDash = Rule { name = "<dist> - <dist>" , pattern = [ Predicate isSimpleDistance , regex "-" , Predicate isSimpleDistance ] , prod = \case (Token Distance DistanceData{TDistance.value = Just from, TDistance.unit = Just u1}: _: Token Distance DistanceData{TDistance.value = Just to, TDistance.unit = Just u2}: _) | from < to && u1 == u2 -> Just . Token Distance . withInterval (from, to) $ unitOnly u1 _ -> Nothing } ruleIntervalMax :: Rule ruleIntervalMax = Rule { name = "under/less/lower/no more than <dist>" , pattern = [ regex "unter|höchstens|maximal|(weniger|nicht mehr) als" , Predicate isSimpleDistance ] , prod = \case (_: Token Distance DistanceData{TDistance.value = Just to, TDistance.unit = Just u}: _) -> Just . Token Distance . withMax to $ unitOnly u _ -> Nothing } ruleIntervalMin :: Rule ruleIntervalMin = Rule { name = "over/above/at least/more than <dist>" , pattern = [ regex "über|(mehr|nicht weniger) als|mindestens|wenigstens|minimal" , Predicate isSimpleDistance ] , prod = \case (_: Token Distance DistanceData{TDistance.value = Just to, TDistance.unit = Just u}: _) -> Just . Token Distance . withMin to $ unitOnly u _ -> Nothing } rules :: [Rule] rules = [ ruleIntervalBetweenNumeral , ruleIntervalBetween , ruleIntervalMax , ruleIntervalMin , ruleIntervalNumeralDash , ruleIntervalDash , rulePrecision ] ++ ruleDistances
facebookincubator/duckling
Duckling/Distance/DE/Rules.hs
bsd-3-clause
4,972
0
19
1,162
1,399
771
628
134
2
{-# LANGUAGE TypeOperators #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleInstances #-} ------------------------------------------------------------------------------- -- | -- Module : Control.Lens.Zipper -- Copyright : (C) 2012 Brandon Simmons -- (C) 2012 Edward Kmett -- License : BSD-style (see the file LICENSE) -- Maintainer : Edward Kmett <[email protected]> -- Stability : provisional -- Portability : non-portable -- -- We provide a simple, heterogenous, fully type-checked, generic zipper -- implementation. This flavor of zipper doesn\'t use \"left\" and \"right\" for -- navigation, and instead relies on lenses to indicate a child type to \"move -- to\". ------------------------------------------------------------------------------- module Control.Lens.Zipper ( -- * Zipper type Zipper(..) -- ** Zipper history -- $history , Top(Top) , (:>)() , Hist(..) -- * Zipper operations -- ** Horizontal Motion , Zipped(..) -- ** Vertical Motion , up , down , move -- ** Starting and Stopping , zipper , close -- ** Internals , Level , closeLevel , level ) where {- TODO - - excellent rewrite rules - - first look at core output of simple example - - add rules one-by-one, looking at core - - consider a newtype-wrapped submodule encapsulating monad return value - what we really want is a notation like: - move x - move y - foc <- move z - moveUp - modf (+foc) - quasiquotation, or can we shoe-horn this into proc notation? - otherwise add those combinators (in notes) - - more advanced motions a.la. pez? - - better demos - - pretty Show instance for Zipper -} import Control.Applicative import Control.Comonad import Control.Lens import Control.Lens.Internal import Control.Monad.Identity import Data.Maybe import Data.Foldable import Data.Traversable class Zipped f where -- | To read the current focus, use @'view' 'focus'@. -- -- You can also @'set' 'focus'@ or @'over' 'focus'@ or use any other lens combinator. focus :: Simple Lens (f a) a -- | Try to move the 'Zipper' 'left' through the current 'Traversal'. left :: f a -> Maybe (f a) -- | Try to move the 'Zipper' 'right' through the current 'Traversal'. right :: f a -> Maybe (f a) -- | A traditional list zipper. The constructor is not exported to preserve the invariant that -- the number of elements in this zipper should not be allowed to change. -- -- /Clowns to the left of me, -- Jokers to the right, here I am, -- Stuck in the middle with you./ data Level a = Level [a] a [a] instance Functor Level where fmap f (Level ls a rs) = Level (f <$> ls) (f a) (f <$> rs) instance Foldable Level where foldMap f = foldMap f . closeLevel instance Traversable Level where traverse f (Level ls a rs) = Level <$> backwards traverse f ls <*> f a <*> traverse f rs closeLevel :: Level a -> [a] closeLevel (Level ls a rs) = reverse ls ++ a : rs instance Comonad Level where extract (Level _ a _) = a extend f w@(Level ls m rs) = Level (gol (m:rs) ls) (f w) (gor (m:ls) rs) where gol zs [] = [] gol zs (y:ys) = f (Level ys y zs) : gol (y:zs) ys gor ys [] = [] gor ys (z:zs) = f (Level ys z zs) : gor (z:ys) zs instance Zipped Level where focus f (Level ls a rs) = (\a' -> Level ls a' rs) <$> f a left (Level [] _ _ ) = Nothing left (Level (l:ls) a rs) = Just (Level ls l (a:rs)) right (Level _ _ [] ) = Nothing right (Level ls a (r:rs)) = Just (Level (a:ls) r rs) -- | Our zipper type, parameterized by a 'focus' and \"history stack\", -- supporting completely type-checked zipper operations. data Zipper h a = Zipper (h a) (Level a) instance Zipped (Zipper h) where focus = level.focus left (Zipper h w) = Zipper h <$> left w right (Zipper h w) = Zipper h <$> right w ------------------------------------------------------------------------------- -- Zipper History ------------------------------------------------------------------------------- -- $zipper -- These three types make up the heterogenous history stack, and the programmer -- should never need to use them directly. They come together with 'Zipper' to -- form types that look like, e.g. -- -- @ -- -- a zipper on a Tree, with focus on a leaf "a" of a 2nd level subtree -- z :: 'Zipper' ('Top' ':>' Tree a ':>' Tree a) a -- @ -- -- This zipper works conceptually like the \"breadcrumbs\" navigation UI design -- pattern, and the types reflect this visually. -- -- Nevertheless user-provided type annotations should almost never be -- necessary, so these will probably never appear in your code. data (:>) h b c = Snoc (h b) [b] ([c] -> b) [b] data Top a = Top level :: Simple Lens (Zipper h a) (Level a) level f (Zipper h w) = Zipper h <$> f w -- | \"enter\" a data type. Move the 'focus' with 'left', 'right', 'down' and 'up'. Exit -- the zipper with 'close'. -- -- @'zipper' = 'Zipper' 'Top'@ zipper :: a -> Zipper Top a zipper a = Zipper Top (Level [] a []) class Hist h a c where runHist :: h c -> [c] -> a -- | Our only use of @TypeFamilies@. Thanks to Daniel Wagner for this trick. instance a ~ b => Hist Top a b where runHist _ = head instance Hist h a b => Hist (h :> b) a c where runHist (Snoc h ls k rs) cs = runHist h (reverse ls ++ k cs : rs) -- | Exit the 'Zipper', rebuilding the structure @a@: close :: Hist h a b => Zipper h b -> a close (Zipper h w) = runHist h (closeLevel w) -- | Navigate up a level in a 'Zipper' not already at 'Top'. up :: Zipper (st :> b) c -> Zipper st b up (Zipper (Snoc h ls k rs) w) = Zipper h (Level ls (k (closeLevel w)) rs) -- | Navigate to the target of the supplied 'Lens' -- -- @'down' :: 'Simple' 'Lens' a b -> 'Zipper' h a -> 'Zipper' (h ':>' a) b@ down :: SimpleLensLike (Context c c) b c -> Zipper h b -> Zipper (h :> b) c down l (Zipper h (Level ls b rs)) = case l (Context id) b of Context k c -> Zipper (Snoc h ls (k . head) rs) (Level [] c []) -- | Navigate to the first element indicated by the passed 'Traversal'. -- -- You can move 'left' and 'right' through the 'Traversal' thereafter. -- -- @'move' :: 'Simple' 'Traversal' a b -> 'Zipper' h a -> 'Maybe' ('Zipper' (h ':>' a) b)@ -- move :: SimpleLensLike (Bazaar c c) b c -> Zipper h b -> Maybe (Zipper (h :> b) c) move l (Zipper h (Level ls b rs)) = case partsOf l (Context id) b of Context _ [] -> Nothing Context k (c:cs) -> Just (Zipper (Snoc h ls k rs) (Level [] c cs))
ekmett/zippo
Control/Lens/Zipper.hs
bsd-3-clause
6,622
0
13
1,513
1,657
884
773
86
2
----------------------------------------------------------------------------- -- | -- Module : Distribution.GetOpt -- Copyright : (c) Sven Panne 2002-2005 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : [email protected] -- Portability : portable -- -- This library provides facilities for parsing the command-line options -- in a standalone program. It is essentially a Haskell port of the GNU -- @getopt@ library. -- ----------------------------------------------------------------------------- {- Sven Panne <[email protected]> Oct. 1996 (small changes Dec. 1997) Two rather obscure features are missing: The Bash 2.0 non-option hack (if you don't already know it, you probably don't want to hear about it...) and the recognition of long options with a single dash (e.g. '-help' is recognised as '--help', as long as there is no short option 'h'). Other differences between GNU's getopt and this implementation: * To enforce a coherent description of options and arguments, there are explanation fields in the option/argument descriptor. * Error messages are now more informative, but no longer POSIX compliant... :-( And a final Haskell advertisement: The GNU C implementation uses well over 1100 lines, we need only 195 here, including a 46 line example! :-) -} -- #hide module Distribution.GetOpt ( -- * GetOpt getOpt, getOpt', usageInfo, ArgOrder(..), OptDescr(..), ArgDescr(..), -- * Example -- $example ) where import Data.List ( isPrefixOf, intersperse, find ) -- |What to do with options following non-options data ArgOrder a = RequireOrder -- ^ no option processing after first non-option | Permute -- ^ freely intersperse options and non-options | ReturnInOrder (String -> a) -- ^ wrap non-options into options {-| Each 'OptDescr' describes a single option. The arguments to 'Option' are: * list of short option characters * list of long option strings (without \"--\") * argument descriptor * explanation of option for user -} data OptDescr a = -- description of a single options: Option [Char] -- list of short option characters [String] -- list of long option strings (without "--") (ArgDescr a) -- argument descriptor String -- explanation of option for user -- |Describes whether an option takes an argument or not, and if so -- how the argument is injected into a value of type @a@. data ArgDescr a = NoArg a -- ^ no argument expected | ReqArg (String -> a) String -- ^ option requires argument | OptArg (Maybe String -> a) String -- ^ optional argument data OptKind a -- kind of cmd line arg (internal use only): = Opt a -- an option | UnreqOpt String -- an un-recognized option | NonOpt String -- a non-option | EndOfOpts -- end-of-options marker (i.e. "--") | OptErr String -- something went wrong... -- | Return a string describing the usage of a command, derived from -- the header (first argument) and the options described by the -- second argument. usageInfo :: String -- header -> [OptDescr a] -- option descriptors -> String -- nicely formatted decription of options usageInfo header optDescr = unlines (header:table) where (ss,ls,ds) = unzip3 [ (sepBy ", " (map (fmtShort ad) sos) ,sepBy ", " (map (fmtLong ad) los) ,d) | Option sos los ad d <- optDescr ] ssWidth = (maximum . map length) ss lsWidth = (maximum . map length) ls dsWidth = 30 `max` (80 - (ssWidth + lsWidth + 3)) table = [ " " ++ padTo ssWidth so' ++ " " ++ padTo lsWidth lo' ++ " " ++ d' | (so,lo,d) <- zip3 ss ls ds , (so',lo',d') <- fmtOpt dsWidth so lo d ] padTo n x = take n (x ++ repeat ' ') sepBy s = concat . intersperse s fmtOpt :: Int -> String -> String -> String -> [(String, String, String)] fmtOpt descrWidth so lo descr = case wrapText descrWidth descr of [] -> [(so,lo,"")] (d:ds) -> (so,lo,d) : [ ("","",d') | d' <- ds ] fmtShort :: ArgDescr a -> Char -> String fmtShort (NoArg _ ) so = "-" ++ [so] fmtShort (ReqArg _ _) so = "-" ++ [so] fmtShort (OptArg _ _) so = "-" ++ [so] fmtLong :: ArgDescr a -> String -> String fmtLong (NoArg _ ) lo = "--" ++ lo fmtLong (ReqArg _ ad) lo = "--" ++ lo ++ "=" ++ ad fmtLong (OptArg _ ad) lo = "--" ++ lo ++ "[=" ++ ad ++ "]" wrapText :: Int -> String -> [String] wrapText width = map unwords . wrap 0 [] . words where wrap :: Int -> [String] -> [String] -> [[String]] wrap 0 [] (w:ws) | length w + 1 > width = wrap (length w) [w] ws wrap col line (w:ws) | col + length w + 1 > width = reverse line : wrap 0 [] (w:ws) wrap col line (w:ws) = let col' = col + length w + 1 in wrap col' (w:line) ws wrap _ [] [] = [] wrap _ line [] = [reverse line] {-| Process the command-line, and return the list of values that matched (and those that didn\'t). The arguments are: * The order requirements (see 'ArgOrder') * The option descriptions (see 'OptDescr') * The actual command line arguments (presumably got from 'System.Environment.getArgs'). 'getOpt' returns a triple consisting of the option arguments, a list of non-options, and a list of error messages. -} getOpt :: ArgOrder a -- non-option handling -> [OptDescr a] -- option descriptors -> [String] -- the command-line arguments -> ([a],[String],[String]) -- (options,non-options,error messages) getOpt ordering optDescr args = (os,xs,es ++ map errUnrec us) where (os,xs,us,es) = getOpt' ordering optDescr args {-| This is almost the same as 'getOpt', but returns a quadruple consisting of the option arguments, a list of non-options, a list of unrecognized options, and a list of error messages. -} getOpt' :: ArgOrder a -- non-option handling -> [OptDescr a] -- option descriptors -> [String] -- the command-line arguments -> ([a],[String], [String] ,[String]) -- (options,non-options,unrecognized,error messages) getOpt' _ _ [] = ([],[],[],[]) getOpt' ordering optDescr (arg:args) = procNextOpt opt ordering where procNextOpt (Opt o) _ = (o:os,xs,us,es) procNextOpt (UnreqOpt u) _ = (os,xs,u:us,es) procNextOpt (NonOpt x) RequireOrder = ([],x:rest,[],[]) procNextOpt (NonOpt x) Permute = (os,x:xs,us,es) procNextOpt (NonOpt x) (ReturnInOrder f) = (f x :os, xs,us,es) procNextOpt EndOfOpts RequireOrder = ([],rest,[],[]) procNextOpt EndOfOpts Permute = ([],rest,[],[]) procNextOpt EndOfOpts (ReturnInOrder f) = (map f rest,[],[],[]) procNextOpt (OptErr e) _ = (os,xs,us,e:es) (opt,rest) = getNext arg args optDescr (os,xs,us,es) = getOpt' ordering optDescr rest -- take a look at the next cmd line arg and decide what to do with it getNext :: String -> [String] -> [OptDescr a] -> (OptKind a,[String]) getNext ('-':'-':[]) rest _ = (EndOfOpts,rest) getNext ('-':'-':xs) rest optDescr = longOpt xs rest optDescr getNext ('-': x :xs) rest optDescr = shortOpt x xs rest optDescr getNext a rest _ = (NonOpt a,rest) -- handle long option longOpt :: String -> [String] -> [OptDescr a] -> (OptKind a,[String]) longOpt ls rs optDescr = long ads arg rs where (opt,arg) = break (=='=') ls getWith p = [ o | o@(Option _ xs _ _) <- optDescr , find (p opt) xs /= Nothing] exact = getWith (==) options = if null exact then getWith isPrefixOf else exact ads = [ ad | Option _ _ ad _ <- options ] optStr = ("--"++opt) long (_:_:_) _ rest = (errAmbig options optStr,rest) long [NoArg a ] [] rest = (Opt a,rest) long [NoArg _ ] ('=':_) rest = (errNoArg optStr,rest) long [ReqArg _ d] [] [] = (errReq d optStr,[]) long [ReqArg f _] [] (r:rest) = (Opt (f r),rest) long [ReqArg f _] ('=':xs) rest = (Opt (f xs),rest) long [OptArg f _] [] rest = (Opt (f Nothing),rest) long [OptArg f _] ('=':xs) rest = (Opt (f (Just xs)),rest) long _ _ rest = (UnreqOpt ("--"++ls),rest) -- handle short option shortOpt :: Char -> String -> [String] -> [OptDescr a] -> (OptKind a,[String]) shortOpt y ys rs optDescr = short ads ys rs where options = [ o | o@(Option ss _ _ _) <- optDescr, s <- ss, y == s ] ads = [ ad | Option _ _ ad _ <- options ] optStr = '-':[y] short (_:_:_) _ rest = (errAmbig options optStr,rest) short (NoArg a :_) [] rest = (Opt a,rest) short (NoArg a :_) xs rest = (Opt a,('-':xs):rest) short (ReqArg _ d:_) [] [] = (errReq d optStr,[]) short (ReqArg f _:_) [] (r:rest) = (Opt (f r),rest) short (ReqArg f _:_) xs rest = (Opt (f xs),rest) short (OptArg f _:_) [] rest = (Opt (f Nothing),rest) short (OptArg f _:_) xs rest = (Opt (f (Just xs)),rest) short [] [] rest = (UnreqOpt optStr,rest) short [] xs rest = (UnreqOpt (optStr++xs),rest) -- miscellaneous error formatting errAmbig :: [OptDescr a] -> String -> OptKind a errAmbig ods optStr = OptErr (usageInfo header ods) where header = "option `" ++ optStr ++ "' is ambiguous; could be one of:" errReq :: String -> String -> OptKind a errReq d optStr = OptErr ("option `" ++ optStr ++ "' requires an argument " ++ d ++ "\n") errUnrec :: String -> String errUnrec optStr = "unrecognized option `" ++ optStr ++ "'\n" errNoArg :: String -> OptKind a errNoArg optStr = OptErr ("option `" ++ optStr ++ "' doesn't allow an argument\n") {- ----------------------------------------------------------------------------------------- -- and here a small and hopefully enlightening example: data Flag = Verbose | Version | Name String | Output String | Arg String deriving Show options :: [OptDescr Flag] options = [Option ['v'] ["verbose"] (NoArg Verbose) "verbosely list files", Option ['V','?'] ["version","release"] (NoArg Version) "show version info", Option ['o'] ["output"] (OptArg out "FILE") "use FILE for dump", Option ['n'] ["name"] (ReqArg Name "USER") "only dump USER's files"] out :: Maybe String -> Flag out Nothing = Output "stdout" out (Just o) = Output o test :: ArgOrder Flag -> [String] -> String test order cmdline = case getOpt order options cmdline of (o,n,[] ) -> "options=" ++ show o ++ " args=" ++ show n ++ "\n" (_,_,errs) -> concat errs ++ usageInfo header options where header = "Usage: foobar [OPTION...] files..." -- example runs: -- putStr (test RequireOrder ["foo","-v"]) -- ==> options=[] args=["foo", "-v"] -- putStr (test Permute ["foo","-v"]) -- ==> options=[Verbose] args=["foo"] -- putStr (test (ReturnInOrder Arg) ["foo","-v"]) -- ==> options=[Arg "foo", Verbose] args=[] -- putStr (test Permute ["foo","--","-v"]) -- ==> options=[] args=["foo", "-v"] -- putStr (test Permute ["-?o","--name","bar","--na=baz"]) -- ==> options=[Version, Output "stdout", Name "bar", Name "baz"] args=[] -- putStr (test Permute ["--ver","foo"]) -- ==> option `--ver' is ambiguous; could be one of: -- -v --verbose verbosely list files -- -V, -? --version, --release show version info -- Usage: foobar [OPTION...] files... -- -v --verbose verbosely list files -- -V, -? --version, --release show version info -- -o[FILE] --output[=FILE] use FILE for dump -- -n USER --name=USER only dump USER's files ----------------------------------------------------------------------------------------- -} {- $example To hopefully illuminate the role of the different data structures, here\'s the command-line options for a (very simple) compiler: > module Opts where > > import Distribution.GetOpt > import Data.Maybe ( fromMaybe ) > > data Flag > = Verbose | Version > | Input String | Output String | LibDir String > deriving Show > > options :: [OptDescr Flag] > options = > [ Option ['v'] ["verbose"] (NoArg Verbose) "chatty output on stderr" > , Option ['V','?'] ["version"] (NoArg Version) "show version number" > , Option ['o'] ["output"] (OptArg outp "FILE") "output FILE" > , Option ['c'] [] (OptArg inp "FILE") "input FILE" > , Option ['L'] ["libdir"] (ReqArg LibDir "DIR") "library directory" > ] > > inp,outp :: Maybe String -> Flag > outp = Output . fromMaybe "stdout" > inp = Input . fromMaybe "stdin" > > compilerOpts :: [String] -> IO ([Flag], [String]) > compilerOpts argv = > case getOpt Permute options argv of > (o,n,[] ) -> return (o,n) > (_,_,errs) -> ioError (userError (concat errs ++ usageInfo header options)) > where header = "Usage: ic [OPTION...] files..." -}
dcreager/cabal
Distribution/GetOpt.hs
bsd-3-clause
13,949
0
14
4,147
3,089
1,671
1,418
141
10
-- | @FilteredComplex a b@ represents a complex of simplices (with -- vertex type @b@) filtered over @a@s. A filtered (simplicial) -- complex is stored as a vector of filtration values and a vector of -- lists of simplices. The @n@'th filtration of the complex is the -- collection of simplices from the lists in positions @0@ through -- @n@. Index @k@ in the first vector represents the value at which -- the simplices at index @k@ in the second vector enter the -- filtration. module Math.Simplicial.FilteredComplex where import qualified Data.Vector as Vect import qualified Math.Simplicial.Simplex as S import qualified Math.Misc.Nat as Nat import Misc.Misc data FilteredComplex a b = C (Vect.Vector a) (Vect.Vector [S.Simplex b]) instance (Show a, Show b) => Show (FilteredComplex a b) where show c@(C fs _) = "### " ++ show (Vect.length fs) ++ " degrees\n" ++ unlines' (map (showDegree c) [0..(Vect.length fs - 1)]) showDegree :: (Show a, Show b) => FilteredComplex a b -> Int -> String showDegree (C fs ss) i = "### " ++ show i ++ ": " ++ show (fs Vect.! i) ++ if null (ss Vect.! i) then "" else "\n" ++ unlines' (map show (ss Vect.! i)) filtrationTimes :: FilteredComplex a b -> Vect.Vector a filtrationTimes (C t _) = t degree :: FilteredComplex a b -> Nat.N -> [S.Simplex b] degree (C _ s) n = s Vect.! (Nat.toInt n) degree' :: FilteredComplex a b -> Int -> [S.Simplex b] degree' (C _ s) n = s Vect.! n degrees :: FilteredComplex a b -> Nat.N degrees = Nat.fromInt . degrees' degrees' :: FilteredComplex a b -> Int degrees' (C fs _) = Vect.length fs toVect :: FilteredComplex a b -> Vect.Vector [S.Simplex b] toVect (C _ s) = s allSimplices :: FilteredComplex a b -> [S.Simplex b] allSimplices = concat . Vect.toList . toVect fromList :: [(a, [S.Simplex b])] -> FilteredComplex a b fromList x = C fs ss where x' = unzip x fs = Vect.fromList (fst x') ss = Vect.fromList (snd x') count :: FilteredComplex a b -> Int count = Vect.sum . (Vect.map length) . toVect toList :: FilteredComplex a b -> [(a, [S.Simplex b])] toList (C fs ss) = zip (Vect.toList fs) (Vect.toList ss) toList' :: FilteredComplex a b -> [(Nat.N, S.Simplex b)] toList' x = concatMap (\ n -> zip (repeat (Nat.fromInt n)) (x `degree'` n)) [0..(degrees' x - 1)] --- TESTING testComplex :: FilteredComplex Nat.N Char testComplex = fromList [ (Nat.zero, [S.s0, S.s1]), (Nat.one, [S.s2, S.s3, S.s4, S.s5]), (Nat.two, [S.s6, S.s7]), (Nat.three, [S.s8]), (Nat.four, [S.s9]), (Nat.five, [S.s10]) ]
michiexile/hplex
pershom/src/Math/Simplicial/FilteredComplex.hs
bsd-3-clause
2,712
0
14
675
1,030
551
479
47
2
module Part2.Problem49 where import qualified Data.Map as Map import Data.List (find, permutations, sort) import Part1.Problem12 (combinations) import Part1.Problem27 (isPrime, primes) import Part1.Problem32 (digits) -- -- Problem 49: Prime permutations -- -- The arithmetic sequence, 1487, 4817, 8147, in which each of the terms -- increases by 3330, is unusual in two ways: -- (i) each of the three terms are prime, and, -- (ii) each of the 4-digit numbers are permutations of one another. -- -- There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, -- exhibiting this property, but there is one other 4-digit increasing sequence. -- -- What 12-digit number do you form by concatenating the three terms in this -- sequence? problem49 :: String problem49 = concatMap show $ solutions !! 1 where fourDigitPrimes = dropWhile (< 10^3) $ takeWhile (< 10^4) primes indexedByDigits = map (\p -> (sort $ digits p, p)) fourDigitPrimes groupedOnDigits = sortAndGroup indexedByDigits enoughPermutations = Map.filter (\xs -> length xs >= 3) groupedOnDigits candidatesList = sort . snd <$> Map.toList enoughPermutations allCombinations = concatMap (combinations 3) candidatesList solutions = filter allDiffsEqual allCombinations allDiffsEqual xs = let d = diffs xs in all (== head d) d diffs xs = tail $ zipWith (-) xs (0:xs) -- https://stackoverflow.com/a/12398993/248948 sortAndGroup assocs = Map.fromListWith (++) [(k, [v]) | (k, v) <- assocs]
c0deaddict/project-euler
src/Part2/Problem49.hs
bsd-3-clause
1,536
0
12
298
348
197
151
18
1
{-| Tick (Time, KeyPresses, KeyReleases, KeyState, ) -> -}
binarin/learnopengl
src/Host.hs
bsd-3-clause
64
0
2
14
3
2
1
1
0
{-# OPTIONS_GHC -fno-warn-orphans #-} module Text.RSS.Equals where import Text.XML.Light (Element(..), Content(..), CData(..)) import Text.RSS.Syntax (RSSCloud(..)) instance Eq Element where (Element name1 attribs1 content1 line1) == (Element name2 attribs2 content2 line2) = (name1 == name2) && (attribs1 == attribs2) && (content1 == content2) && (line1 == line2) instance Eq Content where (Text data1) == (Text data2) = (data1 == data2) (CRef text1) == (CRef text2) = (text1 == text2) (Elem elem1) == (Elem elem2) = (elem1 == elem2) (_) == (_) = False instance Eq CData where (CData verbatim1 data1 line1) == (CData verbatim2 data2 line2) = (verbatim1 == verbatim2) && (data1 == data2) && (line1 == line2) instance Eq RSSCloud where (RSSCloud rssCloudDomain1 rssCloudPort1 rssCloudPath1 rssCloudRegisterProcedure1 rssCloudProtocol1 rssCloudAttrs1) == (RSSCloud rssCloudDomain2 rssCloudPort2 rssCloudPath2 rssCloudRegisterProcedure2 rssCloudProtocol2 rssCloudAttrs2) = (rssCloudDomain1 == rssCloudDomain2) && (rssCloudPort1 == rssCloudPort2) && (rssCloudPath1 == rssCloudPath2) && (rssCloudRegisterProcedure1 == rssCloudRegisterProcedure2) && (rssCloudProtocol1 == rssCloudProtocol2) && (rssCloudAttrs1 == rssCloudAttrs2)
danfran/feed
tests/Text/RSS/Equals.hs
bsd-3-clause
1,328
0
12
255
431
231
200
24
0
-- some tests for behaviors. {-# LANGUAGE TypeOperators #-} module Main ( main ) where import Sirea.Prelude import Sirea.UnsafeLink import Sirea.UnsafeIO import Sirea.Clock import Sirea.Time import Sirea.DemandMonitor import Control.Monad (unless) import qualified Data.Set as S import Debug.Trace main :: IO () main = runSireaApp $ tstCycle |*| (bconst (int 0) >>> bdemand dm) dm :: String dm = "TestCycle" tstCycle :: B (S P0 ()) (S P0 ()) tstCycle = bmonitor dm >>> bdelay 0.1 >>> bfmap addOne >>> bprint >>> bdemand dm where addOne = succ . S.findMax . S.insert (minBound :: Int) -- 'int' is just a type annotation to help inference int :: Int -> Int int = id
dmbarbour/Sirea
tst/Cyc.hs
bsd-3-clause
686
0
10
134
222
122
100
21
1
module P15 ( p15 ) where longList :: [[Int]] longList = [ [a,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17,a18,a19,a20 ,b,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17,b18,b19,b20] | a <- [0,1], a2 <- [0,1], a3 <- [0,1], a4 <- [0,1], a5 <- [0,1], a6 <- [0,1], a17 <- [0,1], a7 <- [0,1], a8 <- [0,1], a9 <- [0,1], a10 <- [0,1], a11 <- [0,1], a18 <- [0,1], a12 <- [0,1], a13 <- [0,1], a14 <- [0,1], a15 <- [0,1], a16 <- [0,1], a19 <- [0,1], a20 <- [0,1], b <- [0,1], b2 <- [0,1], b3 <- [0,1], b4 <- [0,1], b5 <- [0,1], b6 <- [0,1], b17 <- [0,1], b7 <- [0,1], b8 <- [0,1], b9 <- [0,1], b10 <- [0,1], b11 <- [0,1], b18 <- [0,1], b12 <- [0,1], b13 <- [0,1], b14 <- [0,1], b15 <- [0,1], b16 <- [0,1], b19 <- [0,1], b20 <- [0,1]] longList' :: [[Int]] longList' = [[a,b,c,d] | a <- [0,1], b <- [0,1], c <- [0,1], d <- [0,1]] p15 :: Int p15 = length $ filter ((==20) . sum) longList
pyuk/euler2
src/P15.hs
bsd-3-clause
919
0
9
191
825
487
338
18
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE NoImplicitPrelude #-} module System.Command ( -- * Running sub-processes P.createProcess , P.shell , P.proc , P.CreateProcess(..) , P.CmdSpec(..) , P.StdStream(..) , P.ProcessHandle -- * Specific variants of createProcess , readProcessWithExitCode , P.runCommand , P.runProcess , P.runInteractiveCommand , P.runInteractiveProcess , P.readProcess , system , rawSystem -- * Data Type , ExitCode -- * ExitCode combinators , exitCode , success , isSuccess , isFailure , exitWith , exitFailure , exitSuccess -- * Process completion , waitForProcess , getProcessExitCode , P.terminateProcess ) where import qualified System.Exit as E(exitWith, ExitCode(ExitSuccess, ExitFailure)) import qualified System.Process as P(system, rawSystem, ProcessHandle, waitForProcess, getProcessExitCode, readProcessWithExitCode, shell, CreateProcess(..), createProcess, readProcess, terminateProcess, runInteractiveCommand, runInteractiveProcess, runProcess, StdStream(..), CmdSpec(..), runCommand, proc) import Control.Exception(Exception, toException, fromException) import Control.Lens(Iso', iso, (#)) import Data.Bool(Bool, not) import Data.Data(Data, Typeable) import Data.Function((.)) import Data.Functor(Functor(fmap)) import Data.Maybe(Maybe) import Data.Monoid(Monoid(mempty, mappend)) import Data.Semigroup(Semigroup((<>))) import Data.String(String) import System.IO(IO) import System.FilePath(FilePath) import Prelude(Read, Show, Eq((==)), Ord, Int) -- | The result of running a process newtype ExitCode = ExitCode Int deriving (Eq, Ord, Data, Show, Read, Typeable) instance Exception ExitCode where toException = toException . toExitCode fromException = fmap fromExitCode . fromException instance Semigroup ExitCode where (<>) = mappend instance Monoid ExitCode where mempty = success a `mappend` b = if isSuccess a then b else a -- | The isomorphism between an @ExitCode@ and an @Int@. exitCode :: Iso' ExitCode Int exitCode = iso (\(ExitCode n) -> n) ExitCode -- | Construct a process result with the value @0@. success :: ExitCode success = exitCode # 0 -- | Returns true if the given process result was constructed with the value @0@, otherwise false. isSuccess :: ExitCode -> Bool isSuccess (ExitCode n) = n == 0 -- | Returns false if the given process result was constructed with the value @0@, otherwise true. isFailure :: ExitCode -> Bool isFailure = not . isSuccess -- | Computation 'exitWith' @code@ throws 'ExitCode' @code@. -- Normally this terminates the program, returning @code@ to the -- program's caller. Before the program terminates, any open or -- semi-closed handles are first closed. -- -- A program that fails in any other way is treated as if it had -- called 'exitFailure'. -- A program that terminates successfully without calling 'exitWith' -- explicitly is treated as it it had called 'exitWith' 'ExitSuccess'. -- -- As an 'ExitCode' is not an 'IOError', 'exitWith' bypasses -- the error handling in the 'IO' monad and cannot be intercepted by -- 'catch' from the "Prelude". However it is a 'SomeException', and can -- be caught using the functions of "Control.Exception". This means -- that cleanup computations added with 'Control.Exception.bracket' -- (from "Control.Exception") are also executed properly on 'exitWith'. -- -- Note: in GHC, 'exitWith' should be called from the main program -- thread in order to exit the process. When called from another -- thread, 'exitWith' will throw an 'ExitException' as normal, but the -- exception will not cause the process itself to exit. exitWith :: ExitCode -> IO a exitWith = E.exitWith . toExitCode -- | The computation 'exitFailure' is equivalent to -- 'exitWith' @(@'exitCode exitfail'@)@, -- where /exitfail/ is implementation-dependent. exitFailure :: IO a exitFailure = exitWith (exitCode # 1) -- | The computation 'exitSuccess' is equivalent to -- 'exitWith' 'success', It terminates the program -- sucessfully. exitSuccess :: IO a exitSuccess = exitWith success -- | readProcessWithExitCode creates an external process, reads its -- standard output and standard error strictly, waits until the process -- terminates, and then returns the 'ExitCode' of the process, -- the standard output, and the standard error. -- -- 'readProcess' and 'readProcessWithExitCode' are fairly simple wrappers -- around 'createProcess'. Constructing variants of these functions is -- quite easy: follow the link to the source code to see how -- 'readProcess' is implemented. readProcessWithExitCode :: FilePath -> [String] -> String -> IO (ExitCode, String, String) readProcessWithExitCode p args i = fmap (\(e, t, u) -> (fromExitCode e, t, u)) (P.readProcessWithExitCode p args i) -- | Computation @system cmd@ returns the exit code produced when the -- operating system runs the shell command @cmd@. -- -- This computation may fail with -- -- * @PermissionDenied@: The process has insufficient privileges to -- perform the operation. -- -- * @ResourceExhausted@: Insufficient resources are available to -- perform the operation. -- -- * @UnsupportedOperation@: The implementation does not support -- system calls. -- -- On Windows, 'system' passes the command to the Windows command -- interpreter (@CMD.EXE@ or @COMMAND.COM@), hence Unixy shell tricks -- will not work. system :: String -> IO ExitCode system = fmap fromExitCode . P.system -- | The computation @'rawSystem' cmd args@ runs the operating system command -- @cmd@ in such a way that it receives as arguments the @args@ strings -- exactly as given, with no funny escaping or shell meta-syntax expansion. -- It will therefore behave more portably between operating systems than 'system'. -- -- The return codes and possible failures are the same as for 'system'. rawSystem :: String -> [String] -> IO ExitCode rawSystem z = fmap fromExitCode . P.rawSystem z -- | Waits for the specified process to terminate, and returns its exit code. -- GHC Note: in order to call @waitForProcess@ without blocking all the -- other threads in the system, you must compile the program with -- @-threaded@. waitForProcess :: P.ProcessHandle -> IO ExitCode waitForProcess = fmap fromExitCode . P.waitForProcess -- | This is a non-blocking version of 'waitForProcess'. If the process is -- still running, 'Nothing' is returned. If the process has exited, then -- @'Just' e@ is returned where @e@ is the exit code of the process. getProcessExitCode :: P.ProcessHandle -> IO (Maybe ExitCode) getProcessExitCode = (fmap . fmap) fromExitCode . P.getProcessExitCode -- not exported toExitCode :: ExitCode -> E.ExitCode toExitCode (ExitCode n) = if n == 0 then E.ExitSuccess else E.ExitFailure n fromExitCode :: E.ExitCode -> ExitCode fromExitCode E.ExitSuccess = success fromExitCode (E.ExitFailure n) = exitCode # n
tonymorris/system-command
src/System/Command.hs
bsd-3-clause
6,955
0
9
1,174
1,065
651
414
134
2
{-# LANGUAGE RecordWildCards #-} -- | Specification for submodules of Pos.Chain.Update module Test.Pos.Update.PollSpec ( spec ) where import Universum import Control.Lens (at) import qualified Data.HashSet as HS import Test.Hspec (Spec, describe) import Test.Hspec.QuickCheck (modifyMaxSuccess, prop) import Test.QuickCheck (Arbitrary (..), Gen, Property, conjoin, forAll, listOf, suchThat, (===)) import Test.QuickCheck.Arbitrary.Generic (genericArbitrary, genericShrink) import Pos.Chain.Update (ApplicationName, BlockVersion (..), BlockVersionData (..), SoftwareVersion (..), UpId, UpdateProposal (..), applyBVM) import qualified Pos.Chain.Update as Poll import Pos.Core (StakeholderId, addressHash) import Pos.Crypto (hash) import qualified Pos.DB.Update as Poll import Pos.Infra.Slotting.Types (SlottingData) import qualified Pos.Util.Modifier as MM import Test.Pos.Binary.Helpers () import Test.Pos.Chain.Update.Arbitrary () import Test.Pos.DB.Update.Arbitrary () import Test.Pos.Util.QuickCheck.Property (formsMonoid) spec :: Spec spec = describe "Poll" $ do let smaller n = modifyMaxSuccess (const n) describe "modifyPollModifier" $ smaller 30 $ do prop "poll modifiers form a commutative monoid under 'modifyPollModifier'" modifyPollFormsMonoid describe "PollState" $ smaller 30 $ do prop "applying two poll modifiers in sequence to the poll state is equivalent\ \ to combining them and applying the resulting modifier" modifyPollStateWithModifiers describe "PurePoll" $ smaller 30 $ do prop "applying a series of modifications to a modifier and then applying it to\ \ a poll state is the same as applying the modifications directly to the\ \ poll state" applyActions prop "Adding and then deleting a block version's state to 'PollState' is\ \ equivalent to doing nothing" putDelBVState prop "Setting and then deleting the last confirmed version of an application\ \ is equivalent to doing nothing" setDeleteConfirmedSV prop "Adding and then deleting a confirmed proposal is the same as doing\ \ nothing" addDeleteConfirmedProposal prop "Inserting an active proposal and then deleting it is the same as doing\ \ nothing" insertDeleteProposal modifyPollFormsMonoid :: Poll.PollModifier -> Poll.PollModifier -> Poll.PollModifier -> Property modifyPollFormsMonoid = formsMonoid modifyPollStateWithModifiers :: Poll.PollState -> Poll.PollModifier -> Poll.PollModifier -> Property modifyPollStateWithModifiers pst pm1 pm2 = Poll.modifyPollState pm2 (Poll.modifyPollState pm1 pst) === Poll.modifyPollState (pm1 <> pm2) pst data PollAction = PutBVState BlockVersion Poll.BlockVersionState | DelBVState BlockVersion | SetAdoptedBV BlockVersion | SetLastConfirmedSV SoftwareVersion | DelConfirmedSV ApplicationName | AddConfirmedProposal Poll.ConfirmedProposalState | DelConfirmedProposal SoftwareVersion | InsertActiveProposal Poll.ProposalState | DeactivateProposal UpId | SetSlottingData SlottingData | SetEpochProposers (HashSet StakeholderId) deriving (Show, Eq, Generic) instance Arbitrary PollAction where arbitrary = genericArbitrary shrink = genericShrink actionToMonad :: Poll.MonadPoll m => PollAction -> m () actionToMonad (PutBVState bv bvs) = Poll.putBVState bv bvs actionToMonad (DelBVState bv) = Poll.delBVState bv actionToMonad (SetAdoptedBV bv) = Poll.setAdoptedBV bv actionToMonad (SetLastConfirmedSV sv) = Poll.setLastConfirmedSV sv actionToMonad (DelConfirmedSV an) = Poll.delConfirmedSV an actionToMonad (AddConfirmedProposal cps) = Poll.addConfirmedProposal cps actionToMonad (DelConfirmedProposal sv) = Poll.delConfirmedProposal sv actionToMonad (InsertActiveProposal ps) = Poll.insertActiveProposal ps actionToMonad (DeactivateProposal ui) = Poll.deactivateProposal ui actionToMonad (SetSlottingData sd) = Poll.setSlottingData sd actionToMonad (SetEpochProposers hs) = Poll.setEpochProposers hs applyActionToModifier :: PollAction -> Poll.PollState -> Poll.PollModifier -> Poll.PollModifier applyActionToModifier (PutBVState bv bvs) _ = Poll.pmBVsL %~ MM.insert bv bvs applyActionToModifier (DelBVState bv) _ = Poll.pmBVsL %~ MM.delete bv applyActionToModifier (SetAdoptedBV bv) pst = \pm -> do let adoptedBVData = snd $ fromMaybe (pst ^. Poll.psAdoptedBV) (Poll.pmAdoptedBVFull pm) case MM.lookup innerLookupFun bv (Poll.pmBVs pm) of Nothing -> pm Just (Poll.bvsModifier -> bvm) -> pm { Poll.pmAdoptedBVFull = Just (bv, applyBVM bvm adoptedBVData) } where innerLookupFun k = pst ^. Poll.psBlockVersions . at k applyActionToModifier (SetLastConfirmedSV SoftwareVersion {..}) _ = Poll.pmConfirmedL %~ MM.insert svAppName svNumber applyActionToModifier (DelConfirmedSV an) _ = Poll.pmConfirmedL %~ MM.delete an applyActionToModifier (AddConfirmedProposal cps) _ = Poll.pmConfirmedPropsL %~ MM.insert (Poll.cpsSoftwareVersion cps) cps applyActionToModifier (DelConfirmedProposal sv) _ = Poll.pmConfirmedPropsL %~ MM.delete sv applyActionToModifier (InsertActiveProposal ps) pst = \p -> let up@UnsafeUpdateProposal{..} = Poll.psProposal ps upId = hash up p' = case MM.lookup innerLookupFun upId (Poll.pmActiveProps p) of Nothing -> p Just _ -> p & Poll.pmEpochProposersL %~ fmap (HS.insert (addressHash upFrom)) in p' & (Poll.pmActivePropsL %~ MM.insert upId ps) where innerLookupFun k = pst ^. Poll.psActiveProposals . at k applyActionToModifier (DeactivateProposal ui) pst = \p -> let proposal = MM.lookup innerLookupFun ui (Poll.pmActiveProps p) in case proposal of Nothing -> p Just ps -> let up = Poll.psProposal ps upId = hash up in p & (Poll.pmActivePropsL %~ MM.delete upId) where innerLookupFun k = pst ^. Poll.psActiveProposals . at k applyActionToModifier (SetSlottingData sd) _ = Poll.pmSlottingDataL .~ (Just sd) applyActionToModifier (SetEpochProposers hs) _ = Poll.pmEpochProposersL .~ (Just hs) applyActions :: Poll.PollState -> [PollAction] -> Property applyActions ps actionList = let pollSts = fmap (actionToMonad @Poll.PurePoll) actionList -- 'resultModifiers' has a 'mempty' poll modifier up front, so 'newPollStates' -- has two 'ps's in the head of the list. As such another 'ps' is added -- at the head of 'resultPStates' to make up for that. resultModifiers = scanl (\pmod act -> applyActionToModifier act ps pmod) mempty actionList resultPStates = ps : scanl Poll.execPurePollWithLogger ps pollSts newPollStates = scanl (flip Poll.modifyPollState) ps resultModifiers in conjoin $ zipWith (===) resultPStates newPollStates -- | Type synonym used for convenience. type PollStateTestInfo = (BlockVersion, BlockVersionData) -- | Empty 'PollState' to be used in tests. Since all fields of the datatype except -- the second (psAdoptedBV) have an instance for 'Monoid', it is passed as an argument -- that each property will supply. emptyPollSt :: PollStateTestInfo -> Poll.PollState emptyPollSt bvInfo = Poll.PollState mempty bvInfo mempty mempty mempty mempty mempty mempty mempty mempty -- | Apply a sequence of 'PollAction's from left to right. perform :: [PollAction] -> Poll.PurePoll () perform = foldl (>>) (return ()) . map actionToMonad -- | Operational equivalence operator in the 'PurePoll' monad. To be used when -- equivalence between two sequences of actions in 'PurePoll' is to be tested/proved. (==^) :: [PollAction] -> [PollAction] -> Gen PollAction -> PollStateTestInfo -> Property p1 ==^ p2 = \prefixGen bvInfo -> forAll ((listOf prefixGen) :: Gen [PollAction]) $ \prefix -> forAll (arbitrary :: Gen [PollAction]) $ \suffix -> let applyAction x = Poll.execPurePollWithLogger (emptyPollSt bvInfo) (perform $ prefix ++ x ++ suffix) in applyAction p1 === applyAction p2 {- A note on the following tests ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The reason these tests have to pass a custom generator for the prefix of the action list to '(==^)' is that in each case, there is a particular sequence of actions for which the property does not hold. Using the next test as an example: Let 'bvs, bvs´ :: BlockVersionState' such that 'bvs /= bvs´'. This sequence of actions in the 'PurePoll' monad: [PutBVState bv bvs´, PutBVState bv bvs, DelBVState bv] is not, in operational semantics terms, equal to the sequence [PutBVState bv bvs´] It is instead equivalent to [] Because these actions are performed from left to right, performing an insertion with the same key twice in a row without deleting it in between those two insertions means only the last insertion actually matters for these tests. As such, prefixes with an insertion with the same key as the action being tested in the property will cause it to fail. -} putDelBVState :: BlockVersion -> Poll.BlockVersionState -> PollStateTestInfo -> Property putDelBVState bv bvs = let actionPrefixGen = arbitrary `suchThat` (\case PutBVState bv' _ -> bv' /= bv _ -> True) in ([PutBVState bv bvs, DelBVState bv] ==^ []) actionPrefixGen setDeleteConfirmedSV :: SoftwareVersion -> PollStateTestInfo -> Property setDeleteConfirmedSV sv = let appName = svAppName sv actionPrefixGen = arbitrary `suchThat` (\case SetLastConfirmedSV sv' -> svAppName sv' /= appName _ -> True) in ([SetLastConfirmedSV sv, DelConfirmedSV appName] ==^ []) actionPrefixGen addDeleteConfirmedProposal :: Poll.ConfirmedProposalState -> PollStateTestInfo -> Property addDeleteConfirmedProposal cps = let softwareVersion = Poll.cpsSoftwareVersion cps actionPrefixGen = arbitrary `suchThat` (\case AddConfirmedProposal cps' -> Poll.cpsSoftwareVersion cps' /= softwareVersion _ -> True) in ([AddConfirmedProposal cps, DelConfirmedProposal softwareVersion] ==^ []) actionPrefixGen insertDeleteProposal :: Poll.ProposalState -> PollStateTestInfo -> Property insertDeleteProposal ps = let getUpId p = hash $ Poll.psProposal p upId = getUpId ps actionPrefixGen = arbitrary `suchThat` (\case InsertActiveProposal ps' -> upId /= getUpId ps' _ -> True) in ([InsertActiveProposal ps, DeactivateProposal upId] ==^ []) actionPrefixGen
input-output-hk/pos-haskell-prototype
lib/test/Test/Pos/Update/PollSpec.hs
mit
11,333
0
18
2,817
2,380
1,235
1,145
-1
-1
----------------------------------------------------------------------------- -- | -- Module : Database.Muesli.Indexes -- Copyright : (c) 2015-16 Călin Ardelean -- License : MIT -- -- Maintainer : Călin Ardelean <[email protected]> -- Stability : experimental -- Portability : portable -- -- Incremental database index update functions. Except for 'updateMainIndex', -- these functions first search for the previous version for each record and, -- if found, remove the old references from the index, then add the new ones. -- -- Used during loading, query evaluation, and GC. ---------------------------------------------------------------------------- module Database.Muesli.Indexes ( updateMainIndex , updateFilterIndex , updateSortIndex , updateUniqueIndex ) where import qualified Data.IntMap.Strict as Map import qualified Data.IntSet as Set import Data.List (foldl') import Database.Muesli.State -- | Updates the 'MainIndex' (allocation table). updateMainIndex :: MainIndex -> [LogRecord] -> MainIndex updateMainIndex = foldl' f where f idx r = let did = fromIntegral (recDocumentKey r) in let rs' = maybe [r] (r:) (Map.lookup did idx) in Map.insert did rs' idx getPreviousVersion :: MainIndex -> LogRecord -> Maybe LogRecord getPreviousVersion idx r = let did = fromIntegral (recDocumentKey r) in maybe Nothing (\ors -> if null ors then Nothing else Just (head ors) { recDeleted = True }) (Map.lookup did idx) -- | Updates the 'UniqueIndex'. updateUniqueIndex :: MainIndex -> UniqueIndex -> [LogRecord] -> UniqueIndex updateUniqueIndex mIdx = foldl' h where h idx r = f (maybe idx (f idx) (getPreviousVersion mIdx r)) r f idx r = foldl' g idx (recUniques r) where did = fromIntegral (recDocumentKey r) del = recDeleted r g idx' lnk = let rpid = fromIntegral (fst lnk) in let rval = fromIntegral (snd lnk) in case Map.lookup rpid idx' of Nothing -> if del then idx' else Map.insert rpid (Map.singleton rval did) idx' Just is -> Map.insert rpid is' idx' where is' = if del then Map.delete rval is else Map.insert rval did is -- | Updates the main 'SortIndex', and also the 'SortIndex'es inside a 'FilterIndex'. updateSortIndex :: MainIndex -> SortIndex -> [LogRecord] -> SortIndex updateSortIndex mIdx = foldl' h where h idx r = f (maybe idx (f idx) (getPreviousVersion mIdx r)) r f idx r = foldl' g idx (recSortables r) where did = fromIntegral (recDocumentKey r) del = recDeleted r g idx' lnk = let rpid = fromIntegral (fst lnk) in let rval = fromIntegral (snd lnk) in let sng = Set.singleton did in case Map.lookup rpid idx' of Nothing -> if del then idx' else Map.insert rpid (Map.singleton rval sng) idx' Just is -> Map.insert rpid is' idx' where is' = case Map.lookup rval is of Nothing -> if del then is else Map.insert rval sng is Just ss -> if Set.null ss' then Map.delete rval is else Map.insert rval ss' is where ss' = if del then Set.delete did ss else Set.insert did ss -- | Updates the 'FilterIndex'. -- -- Calls 'updateSortIndex' for the internal sorted indexes. updateFilterIndex :: MainIndex -> FilterIndex -> [LogRecord] -> FilterIndex updateFilterIndex mIdx = foldl' h where h idx r = f (maybe idx (f idx) (getPreviousVersion mIdx r)) r f idx r = foldl' g idx (recReferences r) where del = recDeleted r g idx' lnk = let rpid = fromIntegral (fst lnk) in let rval = fromIntegral (snd lnk) in let sng = updateSortIndex mIdx Map.empty [r] in case Map.lookup rpid idx' of Nothing -> if del then idx' else Map.insert rpid (Map.singleton rval sng) idx' Just is -> Map.insert rpid is' idx' where is' = case Map.lookup rval is of Nothing -> if del then is else Map.insert rval sng is Just ss -> Map.insert rval ss' is where ss' = updateSortIndex mIdx ss [r]
clnx/muesli
src/Database/Muesli/Indexes.hs
mit
4,763
0
27
1,684
1,208
614
594
74
7
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE MultiWayIf #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeFamilies #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Dense -- Copyright : (c) Christopher Chalmers -- License : BSD3 -- -- Maintainer : Christopher Chalmers -- Stability : provisional -- Portability : non-portable -- -- This module provides a large subset of the full functionality of -- "dense" without exporting names that conflict with names in prelude, -- so it can often be imported unqualified. It also includes reexported -- classes and data types from other modules. However it does not -- contain much functions necessary to construct arrays, for that see -- "Data.Dense.Generic" or one of the type specific modules intended to -- be imported qualified. Typical imports for shaped will look like -- this: -- -- @ -- import "Data.Dense" -- import qualified "Data.Dense.Unboxed" as U -- @ -- -- For boxed-specific arrays (a la "Data.Vector") see "Data.Dense.Boxed". ----------------------------------------------------------------------------- module Data.Dense ( -- * Array types Array , BArray , UArray , SArray , PArray -- * Indexing , Layout , HasLayout (..) , Shape , extent , size -- ** Folds over indexes , indexes , indexesBetween , indexesFrom -- ** Lenses , vector -- ** Traversals , values , values' , valuesBetween -- * Construction -- ** Flat arrays , flat -- ** Shaped from lists , fromListInto , fromListInto_ -- ** Shaped from vectors , fromVectorInto , fromVectorInto_ -- ** Generating -- | See "Data.Shaped.Generic". -- * Functions on arrays -- ** Empty arrays -- | See 'Control.Lens.Empty.AsEmpty' class or "Data.Shaped.Generic". -- ** Indexing -- | See 'Control.Lens.At.Ixed' class. -- ** Modifying arrays -- | See "Data.Shaped.Generic". -- ** Slices -- *** Matrix , ixRow , rows , ixColumn , columns -- *** 3D , ixPlane , planes , flattenPlane -- * Mutable , MArray , BMArray , UMArray , SMArray , PMArray -- * Delayed , Delayed -- ** Generating delayed , delayed , seqDelayed , delay , manifest , seqManifest , genDelayed , indexDelayed , affirm , seqAffirm -- ** Helpful reexports , (*^) , (^*) , (^/) , Additive (..) , Metric (..) -- * Focused , Focused -- ** Generating focused , focusOn , unfocus , unfocused , extendFocus -- ** Focus location , locale , shiftFocus -- ** Boundary , Boundary (..) , peekB , peeksB , peekRelativeB -- ** Helpful reexports , Comonad (..) , ComonadStore (..) -- * Stencils , Stencil -- ** Constructing stencils , stencil , mkStencil , mkStencilTH -- ** Using stencils , stencilSum -- * Common shapes , V1 (..) , V2 (..) , V3 (..) , V4 (..) , R1 (..) , R2 (..) , R3 (..) , R4 (..) -- ** Extra planes , _xz , _yz , _yx , _zy , _zx ) where import Data.Dense.Generic import Control.Comonad.Store import Linear hiding (vector) import Data.Dense.TH import Data.Dense.Stencil
cchalmers/dense
src/Data/Dense.hs
bsd-3-clause
3,400
0
5
914
410
302
108
93
0
------------------------------------------------------------------------ -- | -- Module : ALife.Realtra.ImageQC -- Copyright : (c) Amy de Buitléir 2013-2014 -- License : BSD-style -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- QuickCheck tests. -- ------------------------------------------------------------------------ module ALife.Realtra.ImageQC ( test ) where import ALife.Realtra.Image import ALife.Realtra.TestUtils (prop_serialize_round_trippable, prop_genetic_round_trippable, prop_diploid_identity) -- import Data.Array.Repa (Array, DIM3, DIM2, Shape, Source, -- toList, listOfShape, extent, shapeOfList, size) -- import Data.Array.Repa.Eval (fromList) -- import Data.Array.Repa.Repr.ForeignPtr (F) -- import Data.Word (Word8) import Test.Framework (Test, testGroup) import Test.Framework.Providers.QuickCheck2 (testProperty) import Test.QuickCheck -- arbShape :: Shape sh => Int -> Gen sh -- arbShape nDims = do -- dims <- vectorOf nDims (choose (0,10)) -- keep the images small for testing -- return $ shapeOfList dims -- arbPixels :: Shape sh => sh -> Gen [Word8] -- arbPixels s = vectorOf (size s) arbitrary -- arbArray :: Shape sh => Int -> Gen (Array F sh Word8) -- arbArray nDims = do -- s <- arbShape nDims -- ps <- arbPixels s -- return $ fromList s ps sizedArbImage :: Int -> Gen Image sizedArbImage n = do w <- choose (0,n) let h = n - w ps <- vectorOf (w*h) arbitrary return $ Image w h ps instance Arbitrary Image where arbitrary = sized sizedArbImage -- instance Arbitrary Image where -- arbitrary = oneof [RGBA <$> arbArray 3, RGB <$> arbArray 3, -- BGRA <$> arbArray 3, BGR <$> arbArray 3, -- Grey <$> arbArray 2] -- showArray :: Shape sh => Array F sh Word8 -> String -- showArray arr = sh ++ " " ++ xs -- where sh = show . listOfShape . extent $ arr -- elems = toList arr :: [Word8] -- xs = show elems -- instance Show (Array F DIM3 Word8) where -- show = showArray -- instance Show (Array F DIM2 Word8) where -- show = showArray -- data ValidImage = ValidImage Image deriving (Eq, Show) -- instance Arbitrary ValidImage where -- arbitrary = ValidImage <$> dimensionedArbImage imageWidth imageHeight -- prop_imageToArray_round_trippable :: Image -> Property -- prop_imageToArray_round_trippable x = property $ x' == x -- where x' = arrayToImage . imageToArray $ x test :: Test test = testGroup "ALife.Realtra.ImageQC" [ -- testProperty "prop_imageToArray_round_trippable" -- prop_imageToArray_round_trippable, testProperty "prop_serialize_round_trippable - Image" (prop_serialize_round_trippable :: Image -> Property), testProperty "prop_genetic_round_trippable - Image" (prop_genetic_round_trippable (==) :: Image -> Property), testProperty "prop_diploid_identity - Image" (prop_diploid_identity (==) :: Image -> Property) -- testProperty "prop_generator_never_fails - Image" -- (prop_generator_never_fails :: ValidImage -> Property) ]
mhwombat/creatur-realtra.OLD
test/ALife/Realtra/ImageQC.hs
bsd-3-clause
3,106
0
10
602
293
184
109
26
1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1993-1998 -} {-# LANGUAGE CPP #-} module IfaceSyn ( module IfaceType, IfaceDecl(..), IfaceFamTyConFlav(..), IfaceClassOp(..), IfaceAT(..), IfaceConDecl(..), IfaceConDecls(..), IfaceEqSpec, IfaceExpr(..), IfaceAlt, IfaceLetBndr(..), IfaceBinding(..), IfaceConAlt(..), IfaceIdInfo(..), IfaceIdDetails(..), IfaceUnfolding(..), IfaceInfoItem(..), IfaceRule(..), IfaceAnnotation(..), IfaceAnnTarget, IfaceClsInst(..), IfaceFamInst(..), IfaceTickish(..), IfaceBang(..), IfaceSrcBang(..), SrcUnpackedness(..), SrcStrictness(..), IfaceAxBranch(..), IfaceTyConParent(..), -- Misc ifaceDeclImplicitBndrs, visibleIfConDecls, ifaceDeclFingerprints, -- Free Names freeNamesIfDecl, freeNamesIfRule, freeNamesIfFamInst, -- Pretty printing pprIfaceExpr, pprIfaceDecl, ShowSub(..), ShowHowMuch(..) ) where #include "HsVersions.h" import IfaceType import PprCore() -- Printing DFunArgs import Demand import Class import NameSet import CoAxiom ( BranchIndex, Role ) import Name import CostCentre import Literal import ForeignCall import Annotations( AnnPayload, AnnTarget ) import BasicTypes import Outputable import FastString import Module import SrcLoc import Fingerprint import Binary import BooleanFormula ( BooleanFormula ) import HsBinds import TyCon (Role (..)) import StaticFlags (opt_PprStyle_Debug) import Util( filterOut ) import InstEnv import DataCon (SrcStrictness(..), SrcUnpackedness(..)) import Control.Monad import System.IO.Unsafe import Data.Maybe (isJust) infixl 3 &&& {- ************************************************************************ * * Declarations * * ************************************************************************ -} type IfaceTopBndr = OccName -- It's convenient to have an OccName in the IfaceSyn, altough in each -- case the namespace is implied by the context. However, having an -- OccNames makes things like ifaceDeclImplicitBndrs and ifaceDeclFingerprints -- very convenient. -- -- We don't serialise the namespace onto the disk though; rather we -- drop it when serialising and add it back in when deserialising. data IfaceDecl = IfaceId { ifName :: IfaceTopBndr, ifType :: IfaceType, ifIdDetails :: IfaceIdDetails, ifIdInfo :: IfaceIdInfo } | IfaceData { ifName :: IfaceTopBndr, -- Type constructor ifCType :: Maybe CType, -- C type for CAPI FFI ifTyVars :: [IfaceTvBndr], -- Type variables ifRoles :: [Role], -- Roles ifCtxt :: IfaceContext, -- The "stupid theta" ifCons :: IfaceConDecls, -- Includes new/data/data family info ifRec :: RecFlag, -- Recursive or not? ifPromotable :: Bool, -- Promotable to kind level? ifGadtSyntax :: Bool, -- True <=> declared using -- GADT syntax ifParent :: IfaceTyConParent -- The axiom, for a newtype, -- or data/newtype family instance } | IfaceSynonym { ifName :: IfaceTopBndr, -- Type constructor ifTyVars :: [IfaceTvBndr], -- Type variables ifRoles :: [Role], -- Roles ifSynKind :: IfaceKind, -- Kind of the *rhs* (not of -- the tycon) ifSynRhs :: IfaceType } | IfaceFamily { ifName :: IfaceTopBndr, -- Type constructor ifTyVars :: [IfaceTvBndr], -- Type variables ifFamKind :: IfaceKind, -- Kind of the *rhs* (not of -- the tycon) ifFamFlav :: IfaceFamTyConFlav } | IfaceClass { ifCtxt :: IfaceContext, -- Superclasses ifName :: IfaceTopBndr, -- Name of the class TyCon ifTyVars :: [IfaceTvBndr], -- Type variables ifRoles :: [Role], -- Roles ifFDs :: [FunDep FastString], -- Functional dependencies ifATs :: [IfaceAT], -- Associated type families ifSigs :: [IfaceClassOp], -- Method signatures ifMinDef :: BooleanFormula IfLclName, -- Minimal complete definition ifRec :: RecFlag -- Is newtype/datatype associated -- with the class recursive? } | IfaceAxiom { ifName :: IfaceTopBndr, -- Axiom name ifTyCon :: IfaceTyCon, -- LHS TyCon ifRole :: Role, -- Role of axiom ifAxBranches :: [IfaceAxBranch] -- Branches } | IfacePatSyn { ifName :: IfaceTopBndr, -- Name of the pattern synonym ifPatIsInfix :: Bool, ifPatMatcher :: (IfExtName, Bool), ifPatBuilder :: Maybe (IfExtName, Bool), -- Everything below is redundant, -- but needed to implement pprIfaceDecl ifPatUnivTvs :: [IfaceTvBndr], ifPatExTvs :: [IfaceTvBndr], ifPatProvCtxt :: IfaceContext, ifPatReqCtxt :: IfaceContext, ifPatArgs :: [IfaceType], ifPatTy :: IfaceType } data IfaceTyConParent = IfNoParent | IfDataInstance IfExtName IfaceTyCon IfaceTcArgs data IfaceFamTyConFlav = IfaceOpenSynFamilyTyCon | IfaceClosedSynFamilyTyCon (Maybe (IfExtName, [IfaceAxBranch])) -- ^ Name of associated axiom and branches for pretty printing purposes, -- or 'Nothing' for an empty closed family without an axiom | IfaceAbstractClosedSynFamilyTyCon | IfaceBuiltInSynFamTyCon -- for pretty printing purposes only data IfaceClassOp = IfaceClassOp IfaceTopBndr DefMethSpec IfaceType -- Nothing => no default method -- Just False => ordinary polymorphic default method -- Just True => generic default method data IfaceAT = IfaceAT -- See Class.ClassATItem IfaceDecl -- The associated type declaration (Maybe IfaceType) -- Default associated type instance, if any -- This is just like CoAxBranch data IfaceAxBranch = IfaceAxBranch { ifaxbTyVars :: [IfaceTvBndr] , ifaxbLHS :: IfaceTcArgs , ifaxbRoles :: [Role] , ifaxbRHS :: IfaceType , ifaxbIncomps :: [BranchIndex] } -- See Note [Storing compatibility] in CoAxiom data IfaceConDecls = IfAbstractTyCon Bool -- c.f TyCon.AbstractTyCon | IfDataFamTyCon -- Data family | IfDataTyCon [IfaceConDecl] -- Data type decls | IfNewTyCon IfaceConDecl -- Newtype decls data IfaceConDecl = IfCon { ifConOcc :: IfaceTopBndr, -- Constructor name ifConWrapper :: Bool, -- True <=> has a wrapper ifConInfix :: Bool, -- True <=> declared infix -- The universal type variables are precisely those -- of the type constructor of this data constructor -- This is *easy* to guarantee when creating the IfCon -- but it's not so easy for the original TyCon/DataCon -- So this guarantee holds for IfaceConDecl, but *not* for DataCon ifConExTvs :: [IfaceTvBndr], -- Existential tyvars ifConEqSpec :: IfaceEqSpec, -- Equality constraints ifConCtxt :: IfaceContext, -- Non-stupid context ifConArgTys :: [IfaceType], -- Arg types ifConFields :: [IfaceTopBndr], -- ...ditto... (field labels) ifConStricts :: [IfaceBang], -- Empty (meaning all lazy), -- or 1-1 corresp with arg tys -- See Note [Bangs on imported data constructors] in MkId ifConSrcStricts :: [IfaceSrcBang] } -- empty meaning no src stricts type IfaceEqSpec = [(IfLclName,IfaceType)] -- | This corresponds to an HsImplBang; that is, the final -- implementation decision about the data constructor arg data IfaceBang = IfNoBang | IfStrict | IfUnpack | IfUnpackCo IfaceCoercion -- | This corresponds to HsSrcBang data IfaceSrcBang = IfSrcBang SrcUnpackedness SrcStrictness data IfaceClsInst = IfaceClsInst { ifInstCls :: IfExtName, -- See comments with ifInstTys :: [Maybe IfaceTyCon], -- the defn of ClsInst ifDFun :: IfExtName, -- The dfun ifOFlag :: OverlapFlag, -- Overlap flag ifInstOrph :: IsOrphan } -- See Note [Orphans] in InstEnv -- There's always a separate IfaceDecl for the DFun, which gives -- its IdInfo with its full type and version number. -- The instance declarations taken together have a version number, -- and we don't want that to wobble gratuitously -- If this instance decl is *used*, we'll record a usage on the dfun; -- and if the head does not change it won't be used if it wasn't before -- The ifFamInstTys field of IfaceFamInst contains a list of the rough -- match types data IfaceFamInst = IfaceFamInst { ifFamInstFam :: IfExtName -- Family name , ifFamInstTys :: [Maybe IfaceTyCon] -- See above , ifFamInstAxiom :: IfExtName -- The axiom , ifFamInstOrph :: IsOrphan -- Just like IfaceClsInst } data IfaceRule = IfaceRule { ifRuleName :: RuleName, ifActivation :: Activation, ifRuleBndrs :: [IfaceBndr], -- Tyvars and term vars ifRuleHead :: IfExtName, -- Head of lhs ifRuleArgs :: [IfaceExpr], -- Args of LHS ifRuleRhs :: IfaceExpr, ifRuleAuto :: Bool, ifRuleOrph :: IsOrphan -- Just like IfaceClsInst } data IfaceAnnotation = IfaceAnnotation { ifAnnotatedTarget :: IfaceAnnTarget, ifAnnotatedValue :: AnnPayload } type IfaceAnnTarget = AnnTarget OccName -- Here's a tricky case: -- * Compile with -O module A, and B which imports A.f -- * Change function f in A, and recompile without -O -- * When we read in old A.hi we read in its IdInfo (as a thunk) -- (In earlier GHCs we used to drop IdInfo immediately on reading, -- but we do not do that now. Instead it's discarded when the -- ModIface is read into the various decl pools.) -- * The version comparison sees that new (=NoInfo) differs from old (=HasInfo *) -- and so gives a new version. data IfaceIdInfo = NoInfo -- When writing interface file without -O | HasInfo [IfaceInfoItem] -- Has info, and here it is data IfaceInfoItem = HsArity Arity | HsStrictness StrictSig | HsInline InlinePragma | HsUnfold Bool -- True <=> isStrongLoopBreaker is true IfaceUnfolding -- See Note [Expose recursive functions] | HsNoCafRefs -- NB: Specialisations and rules come in separately and are -- only later attached to the Id. Partial reason: some are orphans. data IfaceUnfolding = IfCoreUnfold Bool IfaceExpr -- True <=> INLINABLE, False <=> regular unfolding -- Possibly could eliminate the Bool here, the information -- is also in the InlinePragma. | IfCompulsory IfaceExpr -- Only used for default methods, in fact | IfInlineRule Arity -- INLINE pragmas Bool -- OK to inline even if *un*-saturated Bool -- OK to inline even if context is boring IfaceExpr | IfDFunUnfold [IfaceBndr] [IfaceExpr] -- We only serialise the IdDetails of top-level Ids, and even then -- we only need a very limited selection. Notably, none of the -- implicit ones are needed here, because they are not put it -- interface files data IfaceIdDetails = IfVanillaId | IfRecSelId IfaceTyCon Bool | IfDFunId {- Note [Versioning of instances] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ See [http://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/RecompilationAvoidance#Instances] ************************************************************************ * * Functions over declarations * * ************************************************************************ -} visibleIfConDecls :: IfaceConDecls -> [IfaceConDecl] visibleIfConDecls (IfAbstractTyCon {}) = [] visibleIfConDecls IfDataFamTyCon = [] visibleIfConDecls (IfDataTyCon cs) = cs visibleIfConDecls (IfNewTyCon c) = [c] ifaceDeclImplicitBndrs :: IfaceDecl -> [OccName] -- *Excludes* the 'main' name, but *includes* the implicitly-bound names -- Deeply revolting, because it has to predict what gets bound, -- especially the question of whether there's a wrapper for a datacon -- See Note [Implicit TyThings] in HscTypes -- N.B. the set of names returned here *must* match the set of -- TyThings returned by HscTypes.implicitTyThings, in the sense that -- TyThing.getOccName should define a bijection between the two lists. -- This invariant is used in LoadIface.loadDecl (see note [Tricky iface loop]) -- The order of the list does not matter. ifaceDeclImplicitBndrs IfaceData {ifCons = IfAbstractTyCon {}} = [] -- Newtype ifaceDeclImplicitBndrs (IfaceData {ifName = tc_occ, ifCons = IfNewTyCon ( IfCon { ifConOcc = con_occ })}) = -- implicit newtype coercion (mkNewTyCoOcc tc_occ) : -- JPM: newtype coercions shouldn't be implicit -- data constructor and worker (newtypes don't have a wrapper) [con_occ, mkDataConWorkerOcc con_occ] ifaceDeclImplicitBndrs (IfaceData {ifName = _tc_occ, ifCons = IfDataTyCon cons }) = -- for each data constructor in order, -- data constructor, worker, and (possibly) wrapper concatMap dc_occs cons where dc_occs con_decl | has_wrapper = [con_occ, work_occ, wrap_occ] | otherwise = [con_occ, work_occ] where con_occ = ifConOcc con_decl -- DataCon namespace wrap_occ = mkDataConWrapperOcc con_occ -- Id namespace work_occ = mkDataConWorkerOcc con_occ -- Id namespace has_wrapper = ifConWrapper con_decl -- This is the reason for -- having the ifConWrapper field! ifaceDeclImplicitBndrs (IfaceClass {ifCtxt = sc_ctxt, ifName = cls_tc_occ, ifSigs = sigs, ifATs = ats }) = -- (possibly) newtype coercion co_occs ++ -- data constructor (DataCon namespace) -- data worker (Id namespace) -- no wrapper (class dictionaries never have a wrapper) [dc_occ, dcww_occ] ++ -- associated types [ifName at | IfaceAT at _ <- ats ] ++ -- superclass selectors [mkSuperDictSelOcc n cls_tc_occ | n <- [1..n_ctxt]] ++ -- operation selectors [op | IfaceClassOp op _ _ <- sigs] where n_ctxt = length sc_ctxt n_sigs = length sigs co_occs | is_newtype = [mkNewTyCoOcc cls_tc_occ] | otherwise = [] dcww_occ = mkDataConWorkerOcc dc_occ dc_occ = mkClassDataConOcc cls_tc_occ is_newtype = n_sigs + n_ctxt == 1 -- Sigh ifaceDeclImplicitBndrs _ = [] -- ----------------------------------------------------------------------------- -- The fingerprints of an IfaceDecl -- We better give each name bound by the declaration a -- different fingerprint! So we calculate the fingerprint of -- each binder by combining the fingerprint of the whole -- declaration with the name of the binder. (#5614, #7215) ifaceDeclFingerprints :: Fingerprint -> IfaceDecl -> [(OccName,Fingerprint)] ifaceDeclFingerprints hash decl = (ifName decl, hash) : [ (occ, computeFingerprint' (hash,occ)) | occ <- ifaceDeclImplicitBndrs decl ] where computeFingerprint' = unsafeDupablePerformIO . computeFingerprint (panic "ifaceDeclFingerprints") {- ************************************************************************ * * Expressions * * ************************************************************************ -} data IfaceExpr = IfaceLcl IfLclName | IfaceExt IfExtName | IfaceType IfaceType | IfaceCo IfaceCoercion | IfaceTuple TupleSort [IfaceExpr] -- Saturated; type arguments omitted | IfaceLam IfaceLamBndr IfaceExpr | IfaceApp IfaceExpr IfaceExpr | IfaceCase IfaceExpr IfLclName [IfaceAlt] | IfaceECase IfaceExpr IfaceType -- See Note [Empty case alternatives] | IfaceLet IfaceBinding IfaceExpr | IfaceCast IfaceExpr IfaceCoercion | IfaceLit Literal | IfaceFCall ForeignCall IfaceType | IfaceTick IfaceTickish IfaceExpr -- from Tick tickish E data IfaceTickish = IfaceHpcTick Module Int -- from HpcTick x | IfaceSCC CostCentre Bool Bool -- from ProfNote | IfaceSource RealSrcSpan String -- from SourceNote -- no breakpoints: we never export these into interface files type IfaceAlt = (IfaceConAlt, [IfLclName], IfaceExpr) -- Note: IfLclName, not IfaceBndr (and same with the case binder) -- We reconstruct the kind/type of the thing from the context -- thus saving bulk in interface files data IfaceConAlt = IfaceDefault | IfaceDataAlt IfExtName | IfaceLitAlt Literal data IfaceBinding = IfaceNonRec IfaceLetBndr IfaceExpr | IfaceRec [(IfaceLetBndr, IfaceExpr)] -- IfaceLetBndr is like IfaceIdBndr, but has IdInfo too -- It's used for *non-top-level* let/rec binders -- See Note [IdInfo on nested let-bindings] data IfaceLetBndr = IfLetBndr IfLclName IfaceType IfaceIdInfo {- Note [Empty case alternatives] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In IfaceSyn an IfaceCase does not record the types of the alternatives, unlike CorSyn Case. But we need this type if the alternatives are empty. Hence IfaceECase. See Note [Empty case alternatives] in CoreSyn. Note [Expose recursive functions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For supercompilation we want to put *all* unfoldings in the interface file, even for functions that are recursive (or big). So we need to know when an unfolding belongs to a loop-breaker so that we can refrain from inlining it (except during supercompilation). Note [IdInfo on nested let-bindings] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Occasionally we want to preserve IdInfo on nested let bindings. The one that came up was a NOINLINE pragma on a let-binding inside an INLINE function. The user (Duncan Coutts) really wanted the NOINLINE control to cross the separate compilation boundary. In general we retain all info that is left by CoreTidy.tidyLetBndr, since that is what is seen by importing module with --make ************************************************************************ * * Printing IfaceDecl * * ************************************************************************ -} pprAxBranch :: SDoc -> IfaceAxBranch -> SDoc -- The TyCon might be local (just an OccName), or this might -- be a branch for an imported TyCon, so it would be an ExtName -- So it's easier to take an SDoc here pprAxBranch pp_tc (IfaceAxBranch { ifaxbTyVars = tvs , ifaxbLHS = pat_tys , ifaxbRHS = rhs , ifaxbIncomps = incomps }) = hang (pprUserIfaceForAll tvs) 2 (hang pp_lhs 2 (equals <+> ppr rhs)) $+$ nest 2 maybe_incomps where pp_lhs = hang pp_tc 2 (pprParendIfaceTcArgs pat_tys) maybe_incomps = ppUnless (null incomps) $ parens $ ptext (sLit "incompatible indices:") <+> ppr incomps instance Outputable IfaceAnnotation where ppr (IfaceAnnotation target value) = ppr target <+> colon <+> ppr value instance HasOccName IfaceClassOp where occName (IfaceClassOp n _ _) = n instance HasOccName IfaceConDecl where occName = ifConOcc instance HasOccName IfaceDecl where occName = ifName instance Outputable IfaceDecl where ppr = pprIfaceDecl showAll data ShowSub = ShowSub { ss_ppr_bndr :: OccName -> SDoc -- Pretty-printer for binders in IfaceDecl -- See Note [Printing IfaceDecl binders] , ss_how_much :: ShowHowMuch } data ShowHowMuch = ShowHeader -- Header information only, not rhs | ShowSome [OccName] -- [] <=> Print all sub-components -- (n:ns) <=> print sub-component 'n' with ShowSub=ns -- elide other sub-components to "..." -- May 14: the list is max 1 element long at the moment | ShowIface -- Everything including GHC-internal information (used in --show-iface) showAll :: ShowSub showAll = ShowSub { ss_how_much = ShowIface, ss_ppr_bndr = ppr } ppShowIface :: ShowSub -> SDoc -> SDoc ppShowIface (ShowSub { ss_how_much = ShowIface }) doc = doc ppShowIface _ _ = Outputable.empty ppShowRhs :: ShowSub -> SDoc -> SDoc ppShowRhs (ShowSub { ss_how_much = ShowHeader }) _ = Outputable.empty ppShowRhs _ doc = doc showSub :: HasOccName n => ShowSub -> n -> Bool showSub (ShowSub { ss_how_much = ShowHeader }) _ = False showSub (ShowSub { ss_how_much = ShowSome (n:_) }) thing = n == occName thing showSub (ShowSub { ss_how_much = _ }) _ = True {- Note [Printing IfaceDecl binders] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The binders in an IfaceDecl are just OccNames, so we don't know what module they come from. But when we pretty-print a TyThing by converting to an IfaceDecl (see PprTyThing), the TyThing may come from some other module so we really need the module qualifier. We solve this by passing in a pretty-printer for the binders. When printing an interface file (--show-iface), we want to print everything unqualified, so we can just print the OccName directly. -} ppr_trim :: [Maybe SDoc] -> [SDoc] -- Collapse a group of Nothings to a single "..." ppr_trim xs = snd (foldr go (False, []) xs) where go (Just doc) (_, so_far) = (False, doc : so_far) go Nothing (True, so_far) = (True, so_far) go Nothing (False, so_far) = (True, ptext (sLit "...") : so_far) isIfaceDataInstance :: IfaceTyConParent -> Bool isIfaceDataInstance IfNoParent = False isIfaceDataInstance _ = True pprIfaceDecl :: ShowSub -> IfaceDecl -> SDoc -- NB: pprIfaceDecl is also used for pretty-printing TyThings in GHCi -- See Note [Pretty-printing TyThings] in PprTyThing pprIfaceDecl ss (IfaceData { ifName = tycon, ifCType = ctype, ifCtxt = context, ifTyVars = tc_tyvars, ifRoles = roles, ifCons = condecls, ifParent = parent, ifRec = isrec, ifGadtSyntax = gadt, ifPromotable = is_prom }) | gadt_style = vcat [ pp_roles , pp_nd <+> pp_lhs <+> pp_where , nest 2 (vcat pp_cons) , nest 2 $ ppShowIface ss pp_extra ] | otherwise = vcat [ pp_roles , hang (pp_nd <+> pp_lhs) 2 (add_bars pp_cons) , nest 2 $ ppShowIface ss pp_extra ] where is_data_instance = isIfaceDataInstance parent gadt_style = gadt || any (not . isVanillaIfaceConDecl) cons cons = visibleIfConDecls condecls pp_where = ppWhen (gadt_style && not (null cons)) $ ptext (sLit "where") pp_cons = ppr_trim (map show_con cons) :: [SDoc] pp_lhs = case parent of IfNoParent -> pprIfaceDeclHead context ss tycon tc_tyvars _ -> ptext (sLit "instance") <+> pprIfaceTyConParent parent pp_roles | is_data_instance = Outputable.empty | otherwise = pprRoles (== Representational) (pprPrefixIfDeclBndr ss tycon) tc_tyvars roles -- Don't display roles for data family instances (yet) -- See discussion on Trac #8672. add_bars [] = Outputable.empty add_bars (c:cs) = sep ((equals <+> c) : map (char '|' <+>) cs) ok_con dc = showSub ss dc || any (showSub ss) (ifConFields dc) show_con dc | ok_con dc = Just $ pprIfaceConDecl ss gadt_style mk_user_con_res_ty dc | otherwise = Nothing mk_user_con_res_ty :: IfaceEqSpec -> ([IfaceTvBndr], SDoc) -- See Note [Result type of a data family GADT] mk_user_con_res_ty eq_spec | IfDataInstance _ tc tys <- parent = (con_univ_tvs, pprIfaceType (IfaceTyConApp tc (substIfaceTcArgs gadt_subst tys))) | otherwise = (con_univ_tvs, sdocWithDynFlags (ppr_tc_app gadt_subst)) where gadt_subst = mkFsEnv eq_spec done_univ_tv (tv,_) = isJust (lookupFsEnv gadt_subst tv) con_univ_tvs = filterOut done_univ_tv tc_tyvars ppr_tc_app gadt_subst dflags = pprPrefixIfDeclBndr ss tycon <+> sep [ pprParendIfaceType (substIfaceTyVar gadt_subst tv) | (tv,_kind) <- stripIfaceKindVars dflags tc_tyvars ] pp_nd = case condecls of IfAbstractTyCon d -> ptext (sLit "abstract") <> ppShowIface ss (parens (ppr d)) IfDataFamTyCon -> ptext (sLit "data family") IfDataTyCon _ -> ptext (sLit "data") IfNewTyCon _ -> ptext (sLit "newtype") pp_extra = vcat [pprCType ctype, pprRec isrec, pp_prom] pp_prom | is_prom = ptext (sLit "Promotable") | otherwise = Outputable.empty pprIfaceDecl ss (IfaceClass { ifATs = ats, ifSigs = sigs, ifRec = isrec , ifCtxt = context, ifName = clas , ifTyVars = tyvars, ifRoles = roles , ifFDs = fds }) = vcat [ pprRoles (== Nominal) (pprPrefixIfDeclBndr ss clas) tyvars roles , ptext (sLit "class") <+> pprIfaceDeclHead context ss clas tyvars <+> pprFundeps fds <+> pp_where , nest 2 (vcat [vcat asocs, vcat dsigs, pprec])] where pp_where = ppShowRhs ss $ ppUnless (null sigs && null ats) (ptext (sLit "where")) asocs = ppr_trim $ map maybeShowAssoc ats dsigs = ppr_trim $ map maybeShowSig sigs pprec = ppShowIface ss (pprRec isrec) maybeShowAssoc :: IfaceAT -> Maybe SDoc maybeShowAssoc asc@(IfaceAT d _) | showSub ss d = Just $ pprIfaceAT ss asc | otherwise = Nothing maybeShowSig :: IfaceClassOp -> Maybe SDoc maybeShowSig sg | showSub ss sg = Just $ pprIfaceClassOp ss sg | otherwise = Nothing pprIfaceDecl ss (IfaceSynonym { ifName = tc , ifTyVars = tv , ifSynRhs = mono_ty }) = hang (ptext (sLit "type") <+> pprIfaceDeclHead [] ss tc tv <+> equals) 2 (sep [pprIfaceForAll tvs, pprIfaceContextArr theta, ppr tau]) where (tvs, theta, tau) = splitIfaceSigmaTy mono_ty pprIfaceDecl ss (IfaceFamily { ifName = tycon, ifTyVars = tyvars , ifFamFlav = rhs, ifFamKind = kind }) = vcat [ hang (text "type family" <+> pprIfaceDeclHead [] ss tycon tyvars <+> dcolon) 2 (ppr kind <+> ppShowRhs ss (pp_rhs rhs)) , ppShowRhs ss (nest 2 (pp_branches rhs)) ] where pp_rhs IfaceOpenSynFamilyTyCon = ppShowIface ss (ptext (sLit "open")) pp_rhs IfaceAbstractClosedSynFamilyTyCon = ppShowIface ss (ptext (sLit "closed, abstract")) pp_rhs (IfaceClosedSynFamilyTyCon _) = ptext (sLit "where") pp_rhs IfaceBuiltInSynFamTyCon = ppShowIface ss (ptext (sLit "built-in")) pp_branches (IfaceClosedSynFamilyTyCon (Just (ax, brs))) = vcat (map (pprAxBranch (pprPrefixIfDeclBndr ss tycon)) brs) $$ ppShowIface ss (ptext (sLit "axiom") <+> ppr ax) pp_branches _ = Outputable.empty pprIfaceDecl _ (IfacePatSyn { ifName = name, ifPatBuilder = builder, ifPatUnivTvs = univ_tvs, ifPatExTvs = ex_tvs, ifPatProvCtxt = prov_ctxt, ifPatReqCtxt = req_ctxt, ifPatArgs = arg_tys, ifPatTy = pat_ty} ) = pprPatSynSig name is_bidirectional (pprUserIfaceForAll tvs) (pprIfaceContextMaybe prov_ctxt) (pprIfaceContextMaybe req_ctxt) (pprIfaceType ty) where is_bidirectional = isJust builder tvs = univ_tvs ++ ex_tvs ty = foldr IfaceFunTy pat_ty arg_tys pprIfaceDecl ss (IfaceId { ifName = var, ifType = ty, ifIdDetails = details, ifIdInfo = info }) = vcat [ hang (pprPrefixIfDeclBndr ss var <+> dcolon) 2 (pprIfaceSigmaType ty) , ppShowIface ss (ppr details) , ppShowIface ss (ppr info) ] pprIfaceDecl _ (IfaceAxiom { ifName = name, ifTyCon = tycon , ifAxBranches = branches }) = hang (ptext (sLit "axiom") <+> ppr name <> dcolon) 2 (vcat $ map (pprAxBranch (ppr tycon)) branches) pprCType :: Maybe CType -> SDoc pprCType Nothing = Outputable.empty pprCType (Just cType) = ptext (sLit "C type:") <+> ppr cType -- if, for each role, suppress_if role is True, then suppress the role -- output pprRoles :: (Role -> Bool) -> SDoc -> [IfaceTvBndr] -> [Role] -> SDoc pprRoles suppress_if tyCon tyvars roles = sdocWithDynFlags $ \dflags -> let froles = suppressIfaceKinds dflags tyvars roles in ppUnless (all suppress_if roles || null froles) $ ptext (sLit "type role") <+> tyCon <+> hsep (map ppr froles) pprRec :: RecFlag -> SDoc pprRec NonRecursive = Outputable.empty pprRec Recursive = ptext (sLit "RecFlag: Recursive") pprInfixIfDeclBndr, pprPrefixIfDeclBndr :: ShowSub -> OccName -> SDoc pprInfixIfDeclBndr (ShowSub { ss_ppr_bndr = ppr_bndr }) occ = pprInfixVar (isSymOcc occ) (ppr_bndr occ) pprPrefixIfDeclBndr (ShowSub { ss_ppr_bndr = ppr_bndr }) occ = parenSymOcc occ (ppr_bndr occ) instance Outputable IfaceClassOp where ppr = pprIfaceClassOp showAll pprIfaceClassOp :: ShowSub -> IfaceClassOp -> SDoc pprIfaceClassOp ss (IfaceClassOp n dm ty) = hang opHdr 2 (pprIfaceSigmaType ty) where opHdr = pprPrefixIfDeclBndr ss n <+> ppShowIface ss (ppr dm) <+> dcolon instance Outputable IfaceAT where ppr = pprIfaceAT showAll pprIfaceAT :: ShowSub -> IfaceAT -> SDoc pprIfaceAT ss (IfaceAT d mb_def) = vcat [ pprIfaceDecl ss d , case mb_def of Nothing -> Outputable.empty Just rhs -> nest 2 $ ptext (sLit "Default:") <+> ppr rhs ] instance Outputable IfaceTyConParent where ppr p = pprIfaceTyConParent p pprIfaceTyConParent :: IfaceTyConParent -> SDoc pprIfaceTyConParent IfNoParent = Outputable.empty pprIfaceTyConParent (IfDataInstance _ tc tys) = sdocWithDynFlags $ \dflags -> let ftys = stripKindArgs dflags tys in pprIfaceTypeApp tc ftys pprIfaceDeclHead :: IfaceContext -> ShowSub -> OccName -> [IfaceTvBndr] -> SDoc pprIfaceDeclHead context ss tc_occ tv_bndrs = sdocWithDynFlags $ \ dflags -> sep [ pprIfaceContextArr context , pprPrefixIfDeclBndr ss tc_occ <+> pprIfaceTvBndrs (stripIfaceKindVars dflags tv_bndrs) ] isVanillaIfaceConDecl :: IfaceConDecl -> Bool isVanillaIfaceConDecl (IfCon { ifConExTvs = ex_tvs , ifConEqSpec = eq_spec , ifConCtxt = ctxt }) = (null ex_tvs) && (null eq_spec) && (null ctxt) pprIfaceConDecl :: ShowSub -> Bool -> (IfaceEqSpec -> ([IfaceTvBndr], SDoc)) -> IfaceConDecl -> SDoc pprIfaceConDecl ss gadt_style mk_user_con_res_ty (IfCon { ifConOcc = name, ifConInfix = is_infix, ifConExTvs = ex_tvs, ifConEqSpec = eq_spec, ifConCtxt = ctxt, ifConArgTys = arg_tys, ifConStricts = stricts, ifConFields = labels }) | gadt_style = pp_prefix_con <+> dcolon <+> ppr_ty | otherwise = ppr_fields tys_w_strs where tys_w_strs :: [(IfaceBang, IfaceType)] tys_w_strs = zip stricts arg_tys pp_prefix_con = pprPrefixIfDeclBndr ss name (univ_tvs, pp_res_ty) = mk_user_con_res_ty eq_spec ppr_ty = pprIfaceForAllPart (univ_tvs ++ ex_tvs) ctxt pp_tau -- A bit gruesome this, but we can't form the full con_tau, and ppr it, -- because we don't have a Name for the tycon, only an OccName pp_tau = case map pprParendIfaceType arg_tys ++ [pp_res_ty] of (t:ts) -> fsep (t : map (arrow <+>) ts) [] -> panic "pp_con_taus" ppr_bang IfNoBang = ppWhen opt_PprStyle_Debug $ char '_' ppr_bang IfStrict = char '!' ppr_bang IfUnpack = ptext (sLit "{-# UNPACK #-}") ppr_bang (IfUnpackCo co) = ptext (sLit "! {-# UNPACK #-}") <> pprParendIfaceCoercion co pprParendBangTy (bang, ty) = ppr_bang bang <> pprParendIfaceType ty pprBangTy (bang, ty) = ppr_bang bang <> ppr ty maybe_show_label (lbl,bty) | showSub ss lbl = Just (pprPrefixIfDeclBndr ss lbl <+> dcolon <+> pprBangTy bty) | otherwise = Nothing ppr_fields [ty1, ty2] | is_infix && null labels = sep [pprParendBangTy ty1, pprInfixIfDeclBndr ss name, pprParendBangTy ty2] ppr_fields fields | null labels = pp_prefix_con <+> sep (map pprParendBangTy fields) | otherwise = pp_prefix_con <+> (braces $ sep $ punctuate comma $ ppr_trim $ map maybe_show_label (zip labels fields)) instance Outputable IfaceRule where ppr (IfaceRule { ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs, ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs }) = sep [hsep [pprRuleName name, ppr act, ptext (sLit "forall") <+> pprIfaceBndrs bndrs], nest 2 (sep [ppr fn <+> sep (map pprParendIfaceExpr args), ptext (sLit "=") <+> ppr rhs]) ] instance Outputable IfaceClsInst where ppr (IfaceClsInst { ifDFun = dfun_id, ifOFlag = flag , ifInstCls = cls, ifInstTys = mb_tcs}) = hang (ptext (sLit "instance") <+> ppr flag <+> ppr cls <+> brackets (pprWithCommas ppr_rough mb_tcs)) 2 (equals <+> ppr dfun_id) instance Outputable IfaceFamInst where ppr (IfaceFamInst { ifFamInstFam = fam, ifFamInstTys = mb_tcs , ifFamInstAxiom = tycon_ax}) = hang (ptext (sLit "family instance") <+> ppr fam <+> pprWithCommas (brackets . ppr_rough) mb_tcs) 2 (equals <+> ppr tycon_ax) ppr_rough :: Maybe IfaceTyCon -> SDoc ppr_rough Nothing = dot ppr_rough (Just tc) = ppr tc {- Note [Result type of a data family GADT] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider data family T a data instance T (p,q) where T1 :: T (Int, Maybe c) T2 :: T (Bool, q) The IfaceDecl actually looks like data TPr p q where T1 :: forall p q. forall c. (p~Int,q~Maybe c) => TPr p q T2 :: forall p q. (p~Bool) => TPr p q To reconstruct the result types for T1 and T2 that we want to pretty print, we substitute the eq-spec [p->Int, q->Maybe c] in the arg pattern (p,q) to give T (Int, Maybe c) Remember that in IfaceSyn, the TyCon and DataCon share the same universal type variables. ----------------------------- Printing IfaceExpr ------------------------------------ -} instance Outputable IfaceExpr where ppr e = pprIfaceExpr noParens e noParens :: SDoc -> SDoc noParens pp = pp pprParendIfaceExpr :: IfaceExpr -> SDoc pprParendIfaceExpr = pprIfaceExpr parens -- | Pretty Print an IfaceExpre -- -- The first argument should be a function that adds parens in context that need -- an atomic value (e.g. function args) pprIfaceExpr :: (SDoc -> SDoc) -> IfaceExpr -> SDoc pprIfaceExpr _ (IfaceLcl v) = ppr v pprIfaceExpr _ (IfaceExt v) = ppr v pprIfaceExpr _ (IfaceLit l) = ppr l pprIfaceExpr _ (IfaceFCall cc ty) = braces (ppr cc <+> ppr ty) pprIfaceExpr _ (IfaceType ty) = char '@' <+> pprParendIfaceType ty pprIfaceExpr _ (IfaceCo co) = text "@~" <+> pprParendIfaceCoercion co pprIfaceExpr add_par app@(IfaceApp _ _) = add_par (pprIfaceApp app []) pprIfaceExpr _ (IfaceTuple c as) = tupleParens c (pprWithCommas ppr as) pprIfaceExpr add_par i@(IfaceLam _ _) = add_par (sep [char '\\' <+> sep (map pprIfaceLamBndr bndrs) <+> arrow, pprIfaceExpr noParens body]) where (bndrs,body) = collect [] i collect bs (IfaceLam b e) = collect (b:bs) e collect bs e = (reverse bs, e) pprIfaceExpr add_par (IfaceECase scrut ty) = add_par (sep [ ptext (sLit "case") <+> pprIfaceExpr noParens scrut , ptext (sLit "ret_ty") <+> pprParendIfaceType ty , ptext (sLit "of {}") ]) pprIfaceExpr add_par (IfaceCase scrut bndr [(con, bs, rhs)]) = add_par (sep [ptext (sLit "case") <+> pprIfaceExpr noParens scrut <+> ptext (sLit "of") <+> ppr bndr <+> char '{' <+> ppr_con_bs con bs <+> arrow, pprIfaceExpr noParens rhs <+> char '}']) pprIfaceExpr add_par (IfaceCase scrut bndr alts) = add_par (sep [ptext (sLit "case") <+> pprIfaceExpr noParens scrut <+> ptext (sLit "of") <+> ppr bndr <+> char '{', nest 2 (sep (map ppr_alt alts)) <+> char '}']) pprIfaceExpr _ (IfaceCast expr co) = sep [pprParendIfaceExpr expr, nest 2 (ptext (sLit "`cast`")), pprParendIfaceCoercion co] pprIfaceExpr add_par (IfaceLet (IfaceNonRec b rhs) body) = add_par (sep [ptext (sLit "let {"), nest 2 (ppr_bind (b, rhs)), ptext (sLit "} in"), pprIfaceExpr noParens body]) pprIfaceExpr add_par (IfaceLet (IfaceRec pairs) body) = add_par (sep [ptext (sLit "letrec {"), nest 2 (sep (map ppr_bind pairs)), ptext (sLit "} in"), pprIfaceExpr noParens body]) pprIfaceExpr add_par (IfaceTick tickish e) = add_par (pprIfaceTickish tickish <+> pprIfaceExpr noParens e) ppr_alt :: (IfaceConAlt, [IfLclName], IfaceExpr) -> SDoc ppr_alt (con, bs, rhs) = sep [ppr_con_bs con bs, arrow <+> pprIfaceExpr noParens rhs] ppr_con_bs :: IfaceConAlt -> [IfLclName] -> SDoc ppr_con_bs con bs = ppr con <+> hsep (map ppr bs) ppr_bind :: (IfaceLetBndr, IfaceExpr) -> SDoc ppr_bind (IfLetBndr b ty info, rhs) = sep [hang (ppr b <+> dcolon <+> ppr ty) 2 (ppr info), equals <+> pprIfaceExpr noParens rhs] ------------------ pprIfaceTickish :: IfaceTickish -> SDoc pprIfaceTickish (IfaceHpcTick m ix) = braces (text "tick" <+> ppr m <+> ppr ix) pprIfaceTickish (IfaceSCC cc tick scope) = braces (pprCostCentreCore cc <+> ppr tick <+> ppr scope) pprIfaceTickish (IfaceSource src _names) = braces (pprUserRealSpan True src) ------------------ pprIfaceApp :: IfaceExpr -> [SDoc] -> SDoc pprIfaceApp (IfaceApp fun arg) args = pprIfaceApp fun $ nest 2 (pprParendIfaceExpr arg) : args pprIfaceApp fun args = sep (pprParendIfaceExpr fun : args) ------------------ instance Outputable IfaceConAlt where ppr IfaceDefault = text "DEFAULT" ppr (IfaceLitAlt l) = ppr l ppr (IfaceDataAlt d) = ppr d ------------------ instance Outputable IfaceIdDetails where ppr IfVanillaId = Outputable.empty ppr (IfRecSelId tc b) = ptext (sLit "RecSel") <+> ppr tc <+> if b then ptext (sLit "<naughty>") else Outputable.empty ppr IfDFunId = ptext (sLit "DFunId") instance Outputable IfaceIdInfo where ppr NoInfo = Outputable.empty ppr (HasInfo is) = ptext (sLit "{-") <+> pprWithCommas ppr is <+> ptext (sLit "-}") instance Outputable IfaceInfoItem where ppr (HsUnfold lb unf) = ptext (sLit "Unfolding") <> ppWhen lb (ptext (sLit "(loop-breaker)")) <> colon <+> ppr unf ppr (HsInline prag) = ptext (sLit "Inline:") <+> ppr prag ppr (HsArity arity) = ptext (sLit "Arity:") <+> int arity ppr (HsStrictness str) = ptext (sLit "Strictness:") <+> pprIfaceStrictSig str ppr HsNoCafRefs = ptext (sLit "HasNoCafRefs") instance Outputable IfaceUnfolding where ppr (IfCompulsory e) = ptext (sLit "<compulsory>") <+> parens (ppr e) ppr (IfCoreUnfold s e) = (if s then ptext (sLit "<stable>") else Outputable.empty) <+> parens (ppr e) ppr (IfInlineRule a uok bok e) = sep [ptext (sLit "InlineRule") <+> ppr (a,uok,bok), pprParendIfaceExpr e] ppr (IfDFunUnfold bs es) = hang (ptext (sLit "DFun:") <+> sep (map ppr bs) <> dot) 2 (sep (map pprParendIfaceExpr es)) {- ************************************************************************ * * Finding the Names in IfaceSyn * * ************************************************************************ This is used for dependency analysis in MkIface, so that we fingerprint a declaration before the things that depend on it. It is specific to interface-file fingerprinting in the sense that we don't collect *all* Names: for example, the DFun of an instance is recorded textually rather than by its fingerprint when fingerprinting the instance, so DFuns are not dependencies. -} freeNamesIfDecl :: IfaceDecl -> NameSet freeNamesIfDecl (IfaceId _s t d i) = freeNamesIfType t &&& freeNamesIfIdInfo i &&& freeNamesIfIdDetails d freeNamesIfDecl d@IfaceData{} = freeNamesIfTvBndrs (ifTyVars d) &&& freeNamesIfaceTyConParent (ifParent d) &&& freeNamesIfContext (ifCtxt d) &&& freeNamesIfConDecls (ifCons d) freeNamesIfDecl d@IfaceSynonym{} = freeNamesIfTvBndrs (ifTyVars d) &&& freeNamesIfType (ifSynRhs d) &&& freeNamesIfKind (ifSynKind d) -- IA0_NOTE: because of promotion, we -- return names in the kind signature freeNamesIfDecl d@IfaceFamily{} = freeNamesIfTvBndrs (ifTyVars d) &&& freeNamesIfFamFlav (ifFamFlav d) &&& freeNamesIfKind (ifFamKind d) -- IA0_NOTE: because of promotion, we -- return names in the kind signature freeNamesIfDecl d@IfaceClass{} = freeNamesIfTvBndrs (ifTyVars d) &&& freeNamesIfContext (ifCtxt d) &&& fnList freeNamesIfAT (ifATs d) &&& fnList freeNamesIfClsSig (ifSigs d) freeNamesIfDecl d@IfaceAxiom{} = freeNamesIfTc (ifTyCon d) &&& fnList freeNamesIfAxBranch (ifAxBranches d) freeNamesIfDecl d@IfacePatSyn{} = unitNameSet (fst (ifPatMatcher d)) &&& maybe emptyNameSet (unitNameSet . fst) (ifPatBuilder d) &&& freeNamesIfTvBndrs (ifPatUnivTvs d) &&& freeNamesIfTvBndrs (ifPatExTvs d) &&& freeNamesIfContext (ifPatProvCtxt d) &&& freeNamesIfContext (ifPatReqCtxt d) &&& fnList freeNamesIfType (ifPatArgs d) &&& freeNamesIfType (ifPatTy d) freeNamesIfAxBranch :: IfaceAxBranch -> NameSet freeNamesIfAxBranch (IfaceAxBranch { ifaxbTyVars = tyvars , ifaxbLHS = lhs , ifaxbRHS = rhs }) = freeNamesIfTvBndrs tyvars &&& freeNamesIfTcArgs lhs &&& freeNamesIfType rhs freeNamesIfIdDetails :: IfaceIdDetails -> NameSet freeNamesIfIdDetails (IfRecSelId tc _) = freeNamesIfTc tc freeNamesIfIdDetails _ = emptyNameSet -- All other changes are handled via the version info on the tycon freeNamesIfFamFlav :: IfaceFamTyConFlav -> NameSet freeNamesIfFamFlav IfaceOpenSynFamilyTyCon = emptyNameSet freeNamesIfFamFlav (IfaceClosedSynFamilyTyCon (Just (ax, br))) = unitNameSet ax &&& fnList freeNamesIfAxBranch br freeNamesIfFamFlav (IfaceClosedSynFamilyTyCon Nothing) = emptyNameSet freeNamesIfFamFlav IfaceAbstractClosedSynFamilyTyCon = emptyNameSet freeNamesIfFamFlav IfaceBuiltInSynFamTyCon = emptyNameSet freeNamesIfContext :: IfaceContext -> NameSet freeNamesIfContext = fnList freeNamesIfType freeNamesIfAT :: IfaceAT -> NameSet freeNamesIfAT (IfaceAT decl mb_def) = freeNamesIfDecl decl &&& case mb_def of Nothing -> emptyNameSet Just rhs -> freeNamesIfType rhs freeNamesIfClsSig :: IfaceClassOp -> NameSet freeNamesIfClsSig (IfaceClassOp _n _dm ty) = freeNamesIfType ty freeNamesIfConDecls :: IfaceConDecls -> NameSet freeNamesIfConDecls (IfDataTyCon c) = fnList freeNamesIfConDecl c freeNamesIfConDecls (IfNewTyCon c) = freeNamesIfConDecl c freeNamesIfConDecls _ = emptyNameSet freeNamesIfConDecl :: IfaceConDecl -> NameSet freeNamesIfConDecl c = freeNamesIfTvBndrs (ifConExTvs c) &&& freeNamesIfContext (ifConCtxt c) &&& fnList freeNamesIfType (ifConArgTys c) &&& fnList freeNamesIfType (map snd (ifConEqSpec c)) -- equality constraints freeNamesIfKind :: IfaceType -> NameSet freeNamesIfKind = freeNamesIfType freeNamesIfTcArgs :: IfaceTcArgs -> NameSet freeNamesIfTcArgs (ITC_Type t ts) = freeNamesIfType t &&& freeNamesIfTcArgs ts freeNamesIfTcArgs (ITC_Kind k ks) = freeNamesIfKind k &&& freeNamesIfTcArgs ks freeNamesIfTcArgs ITC_Nil = emptyNameSet freeNamesIfType :: IfaceType -> NameSet freeNamesIfType (IfaceTyVar _) = emptyNameSet freeNamesIfType (IfaceAppTy s t) = freeNamesIfType s &&& freeNamesIfType t freeNamesIfType (IfaceTyConApp tc ts) = freeNamesIfTc tc &&& freeNamesIfTcArgs ts freeNamesIfType (IfaceTupleTy _ _ ts) = freeNamesIfTcArgs ts freeNamesIfType (IfaceLitTy _) = emptyNameSet freeNamesIfType (IfaceForAllTy tv t) = freeNamesIfTvBndr tv &&& freeNamesIfType t freeNamesIfType (IfaceFunTy s t) = freeNamesIfType s &&& freeNamesIfType t freeNamesIfType (IfaceDFunTy s t) = freeNamesIfType s &&& freeNamesIfType t freeNamesIfCoercion :: IfaceCoercion -> NameSet freeNamesIfCoercion (IfaceReflCo _ t) = freeNamesIfType t freeNamesIfCoercion (IfaceFunCo _ c1 c2) = freeNamesIfCoercion c1 &&& freeNamesIfCoercion c2 freeNamesIfCoercion (IfaceTyConAppCo _ tc cos) = freeNamesIfTc tc &&& fnList freeNamesIfCoercion cos freeNamesIfCoercion (IfaceAppCo c1 c2) = freeNamesIfCoercion c1 &&& freeNamesIfCoercion c2 freeNamesIfCoercion (IfaceForAllCo tv co) = freeNamesIfTvBndr tv &&& freeNamesIfCoercion co freeNamesIfCoercion (IfaceCoVarCo _) = emptyNameSet freeNamesIfCoercion (IfaceAxiomInstCo ax _ cos) = unitNameSet ax &&& fnList freeNamesIfCoercion cos freeNamesIfCoercion (IfaceUnivCo _ _ t1 t2) = freeNamesIfType t1 &&& freeNamesIfType t2 freeNamesIfCoercion (IfaceSymCo c) = freeNamesIfCoercion c freeNamesIfCoercion (IfaceTransCo c1 c2) = freeNamesIfCoercion c1 &&& freeNamesIfCoercion c2 freeNamesIfCoercion (IfaceNthCo _ co) = freeNamesIfCoercion co freeNamesIfCoercion (IfaceLRCo _ co) = freeNamesIfCoercion co freeNamesIfCoercion (IfaceInstCo co ty) = freeNamesIfCoercion co &&& freeNamesIfType ty freeNamesIfCoercion (IfaceSubCo co) = freeNamesIfCoercion co freeNamesIfCoercion (IfaceAxiomRuleCo _ax tys cos) -- the axiom is just a string, so we don't count it as a name. = fnList freeNamesIfType tys &&& fnList freeNamesIfCoercion cos freeNamesIfTvBndrs :: [IfaceTvBndr] -> NameSet freeNamesIfTvBndrs = fnList freeNamesIfTvBndr freeNamesIfBndr :: IfaceBndr -> NameSet freeNamesIfBndr (IfaceIdBndr b) = freeNamesIfIdBndr b freeNamesIfBndr (IfaceTvBndr b) = freeNamesIfTvBndr b freeNamesIfLetBndr :: IfaceLetBndr -> NameSet -- Remember IfaceLetBndr is used only for *nested* bindings -- The IdInfo can contain an unfolding (in the case of -- local INLINE pragmas), so look there too freeNamesIfLetBndr (IfLetBndr _name ty info) = freeNamesIfType ty &&& freeNamesIfIdInfo info freeNamesIfTvBndr :: IfaceTvBndr -> NameSet freeNamesIfTvBndr (_fs,k) = freeNamesIfKind k -- kinds can have Names inside, because of promotion freeNamesIfIdBndr :: IfaceIdBndr -> NameSet freeNamesIfIdBndr = freeNamesIfTvBndr freeNamesIfIdInfo :: IfaceIdInfo -> NameSet freeNamesIfIdInfo NoInfo = emptyNameSet freeNamesIfIdInfo (HasInfo i) = fnList freeNamesItem i freeNamesItem :: IfaceInfoItem -> NameSet freeNamesItem (HsUnfold _ u) = freeNamesIfUnfold u freeNamesItem _ = emptyNameSet freeNamesIfUnfold :: IfaceUnfolding -> NameSet freeNamesIfUnfold (IfCoreUnfold _ e) = freeNamesIfExpr e freeNamesIfUnfold (IfCompulsory e) = freeNamesIfExpr e freeNamesIfUnfold (IfInlineRule _ _ _ e) = freeNamesIfExpr e freeNamesIfUnfold (IfDFunUnfold bs es) = fnList freeNamesIfBndr bs &&& fnList freeNamesIfExpr es freeNamesIfExpr :: IfaceExpr -> NameSet freeNamesIfExpr (IfaceExt v) = unitNameSet v freeNamesIfExpr (IfaceFCall _ ty) = freeNamesIfType ty freeNamesIfExpr (IfaceType ty) = freeNamesIfType ty freeNamesIfExpr (IfaceCo co) = freeNamesIfCoercion co freeNamesIfExpr (IfaceTuple _ as) = fnList freeNamesIfExpr as freeNamesIfExpr (IfaceLam (b,_) body) = freeNamesIfBndr b &&& freeNamesIfExpr body freeNamesIfExpr (IfaceApp f a) = freeNamesIfExpr f &&& freeNamesIfExpr a freeNamesIfExpr (IfaceCast e co) = freeNamesIfExpr e &&& freeNamesIfCoercion co freeNamesIfExpr (IfaceTick _ e) = freeNamesIfExpr e freeNamesIfExpr (IfaceECase e ty) = freeNamesIfExpr e &&& freeNamesIfType ty freeNamesIfExpr (IfaceCase s _ alts) = freeNamesIfExpr s &&& fnList fn_alt alts &&& fn_cons alts where fn_alt (_con,_bs,r) = freeNamesIfExpr r -- Depend on the data constructors. Just one will do! -- Note [Tracking data constructors] fn_cons [] = emptyNameSet fn_cons ((IfaceDefault ,_,_) : xs) = fn_cons xs fn_cons ((IfaceDataAlt con,_,_) : _ ) = unitNameSet con fn_cons (_ : _ ) = emptyNameSet freeNamesIfExpr (IfaceLet (IfaceNonRec bndr rhs) body) = freeNamesIfLetBndr bndr &&& freeNamesIfExpr rhs &&& freeNamesIfExpr body freeNamesIfExpr (IfaceLet (IfaceRec as) x) = fnList fn_pair as &&& freeNamesIfExpr x where fn_pair (bndr, rhs) = freeNamesIfLetBndr bndr &&& freeNamesIfExpr rhs freeNamesIfExpr _ = emptyNameSet freeNamesIfTc :: IfaceTyCon -> NameSet freeNamesIfTc tc = unitNameSet (ifaceTyConName tc) -- ToDo: shouldn't we include IfaceIntTc & co.? freeNamesIfRule :: IfaceRule -> NameSet freeNamesIfRule (IfaceRule { ifRuleBndrs = bs, ifRuleHead = f , ifRuleArgs = es, ifRuleRhs = rhs }) = unitNameSet f &&& fnList freeNamesIfBndr bs &&& fnList freeNamesIfExpr es &&& freeNamesIfExpr rhs freeNamesIfFamInst :: IfaceFamInst -> NameSet freeNamesIfFamInst (IfaceFamInst { ifFamInstFam = famName , ifFamInstAxiom = axName }) = unitNameSet famName &&& unitNameSet axName freeNamesIfaceTyConParent :: IfaceTyConParent -> NameSet freeNamesIfaceTyConParent IfNoParent = emptyNameSet freeNamesIfaceTyConParent (IfDataInstance ax tc tys) = unitNameSet ax &&& freeNamesIfTc tc &&& freeNamesIfTcArgs tys -- helpers (&&&) :: NameSet -> NameSet -> NameSet (&&&) = unionNameSet fnList :: (a -> NameSet) -> [a] -> NameSet fnList f = foldr (&&&) emptyNameSet . map f {- Note [Tracking data constructors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In a case expression case e of { C a -> ...; ... } You might think that we don't need to include the datacon C in the free names, because its type will probably show up in the free names of 'e'. But in rare circumstances this may not happen. Here's the one that bit me: module DynFlags where import {-# SOURCE #-} Packages( PackageState ) data DynFlags = DF ... PackageState ... module Packages where import DynFlags data PackageState = PS ... lookupModule (df :: DynFlags) = case df of DF ...p... -> case p of PS ... -> ... Now, lookupModule depends on DynFlags, but the transitive dependency on the *locally-defined* type PackageState is not visible. We need to take account of the use of the data constructor PS in the pattern match. ************************************************************************ * * Binary instances * * ************************************************************************ -} instance Binary IfaceDecl where put_ bh (IfaceId name ty details idinfo) = do putByte bh 0 put_ bh (occNameFS name) put_ bh ty put_ bh details put_ bh idinfo put_ bh (IfaceData a1 a2 a3 a4 a5 a6 a7 a8 a9 a10) = do putByte bh 2 put_ bh (occNameFS a1) put_ bh a2 put_ bh a3 put_ bh a4 put_ bh a5 put_ bh a6 put_ bh a7 put_ bh a8 put_ bh a9 put_ bh a10 put_ bh (IfaceSynonym a1 a2 a3 a4 a5) = do putByte bh 3 put_ bh (occNameFS a1) put_ bh a2 put_ bh a3 put_ bh a4 put_ bh a5 put_ bh (IfaceFamily a1 a2 a3 a4) = do putByte bh 4 put_ bh (occNameFS a1) put_ bh a2 put_ bh a3 put_ bh a4 put_ bh (IfaceClass a1 a2 a3 a4 a5 a6 a7 a8 a9) = do putByte bh 5 put_ bh a1 put_ bh (occNameFS a2) put_ bh a3 put_ bh a4 put_ bh a5 put_ bh a6 put_ bh a7 put_ bh a8 put_ bh a9 put_ bh (IfaceAxiom a1 a2 a3 a4) = do putByte bh 6 put_ bh (occNameFS a1) put_ bh a2 put_ bh a3 put_ bh a4 put_ bh (IfacePatSyn name a2 a3 a4 a5 a6 a7 a8 a9 a10) = do putByte bh 7 put_ bh (occNameFS name) put_ bh a2 put_ bh a3 put_ bh a4 put_ bh a5 put_ bh a6 put_ bh a7 put_ bh a8 put_ bh a9 put_ bh a10 get bh = do h <- getByte bh case h of 0 -> do name <- get bh ty <- get bh details <- get bh idinfo <- get bh occ <- return $! mkVarOccFS name return (IfaceId occ ty details idinfo) 1 -> error "Binary.get(TyClDecl): ForeignType" 2 -> do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh a5 <- get bh a6 <- get bh a7 <- get bh a8 <- get bh a9 <- get bh a10 <- get bh occ <- return $! mkTcOccFS a1 return (IfaceData occ a2 a3 a4 a5 a6 a7 a8 a9 a10) 3 -> do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh a5 <- get bh occ <- return $! mkTcOccFS a1 return (IfaceSynonym occ a2 a3 a4 a5) 4 -> do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh occ <- return $! mkTcOccFS a1 return (IfaceFamily occ a2 a3 a4) 5 -> do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh a5 <- get bh a6 <- get bh a7 <- get bh a8 <- get bh a9 <- get bh occ <- return $! mkClsOccFS a2 return (IfaceClass a1 occ a3 a4 a5 a6 a7 a8 a9) 6 -> do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh occ <- return $! mkTcOccFS a1 return (IfaceAxiom occ a2 a3 a4) 7 -> do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh a5 <- get bh a6 <- get bh a7 <- get bh a8 <- get bh a9 <- get bh a10 <- get bh occ <- return $! mkDataOccFS a1 return (IfacePatSyn occ a2 a3 a4 a5 a6 a7 a8 a9 a10) _ -> panic (unwords ["Unknown IfaceDecl tag:", show h]) instance Binary IfaceFamTyConFlav where put_ bh IfaceOpenSynFamilyTyCon = putByte bh 0 put_ bh (IfaceClosedSynFamilyTyCon mb) = putByte bh 1 >> put_ bh mb put_ bh IfaceAbstractClosedSynFamilyTyCon = putByte bh 2 put_ _ IfaceBuiltInSynFamTyCon = pprPanic "Cannot serialize IfaceBuiltInSynFamTyCon, used for pretty-printing only" Outputable.empty get bh = do { h <- getByte bh ; case h of 0 -> return IfaceOpenSynFamilyTyCon 1 -> do { mb <- get bh ; return (IfaceClosedSynFamilyTyCon mb) } _ -> return IfaceAbstractClosedSynFamilyTyCon } instance Binary IfaceClassOp where put_ bh (IfaceClassOp n def ty) = do put_ bh (occNameFS n) put_ bh def put_ bh ty get bh = do n <- get bh def <- get bh ty <- get bh occ <- return $! mkVarOccFS n return (IfaceClassOp occ def ty) instance Binary IfaceAT where put_ bh (IfaceAT dec defs) = do put_ bh dec put_ bh defs get bh = do dec <- get bh defs <- get bh return (IfaceAT dec defs) instance Binary IfaceAxBranch where put_ bh (IfaceAxBranch a1 a2 a3 a4 a5) = do put_ bh a1 put_ bh a2 put_ bh a3 put_ bh a4 put_ bh a5 get bh = do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh a5 <- get bh return (IfaceAxBranch a1 a2 a3 a4 a5) instance Binary IfaceConDecls where put_ bh (IfAbstractTyCon d) = putByte bh 0 >> put_ bh d put_ bh IfDataFamTyCon = putByte bh 1 put_ bh (IfDataTyCon cs) = putByte bh 2 >> put_ bh cs put_ bh (IfNewTyCon c) = putByte bh 3 >> put_ bh c get bh = do h <- getByte bh case h of 0 -> liftM IfAbstractTyCon $ get bh 1 -> return IfDataFamTyCon 2 -> liftM IfDataTyCon $ get bh _ -> liftM IfNewTyCon $ get bh instance Binary IfaceConDecl where put_ bh (IfCon a1 a2 a3 a4 a5 a6 a7 a8 a9 a10) = do put_ bh a1 put_ bh a2 put_ bh a3 put_ bh a4 put_ bh a5 put_ bh a6 put_ bh a7 put_ bh a8 put_ bh a9 put_ bh a10 get bh = do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh a5 <- get bh a6 <- get bh a7 <- get bh a8 <- get bh a9 <- get bh a10 <- get bh return (IfCon a1 a2 a3 a4 a5 a6 a7 a8 a9 a10) instance Binary IfaceBang where put_ bh IfNoBang = putByte bh 0 put_ bh IfStrict = putByte bh 1 put_ bh IfUnpack = putByte bh 2 put_ bh (IfUnpackCo co) = putByte bh 3 >> put_ bh co get bh = do h <- getByte bh case h of 0 -> do return IfNoBang 1 -> do return IfStrict 2 -> do return IfUnpack _ -> do { a <- get bh; return (IfUnpackCo a) } instance Binary IfaceSrcBang where put_ bh (IfSrcBang a1 a2) = do put_ bh a1 put_ bh a2 get bh = do a1 <- get bh a2 <- get bh return (IfSrcBang a1 a2) instance Binary IfaceClsInst where put_ bh (IfaceClsInst cls tys dfun flag orph) = do put_ bh cls put_ bh tys put_ bh dfun put_ bh flag put_ bh orph get bh = do cls <- get bh tys <- get bh dfun <- get bh flag <- get bh orph <- get bh return (IfaceClsInst cls tys dfun flag orph) instance Binary IfaceFamInst where put_ bh (IfaceFamInst fam tys name orph) = do put_ bh fam put_ bh tys put_ bh name put_ bh orph get bh = do fam <- get bh tys <- get bh name <- get bh orph <- get bh return (IfaceFamInst fam tys name orph) instance Binary IfaceRule where put_ bh (IfaceRule a1 a2 a3 a4 a5 a6 a7 a8) = do put_ bh a1 put_ bh a2 put_ bh a3 put_ bh a4 put_ bh a5 put_ bh a6 put_ bh a7 put_ bh a8 get bh = do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh a5 <- get bh a6 <- get bh a7 <- get bh a8 <- get bh return (IfaceRule a1 a2 a3 a4 a5 a6 a7 a8) instance Binary IfaceAnnotation where put_ bh (IfaceAnnotation a1 a2) = do put_ bh a1 put_ bh a2 get bh = do a1 <- get bh a2 <- get bh return (IfaceAnnotation a1 a2) instance Binary IfaceIdDetails where put_ bh IfVanillaId = putByte bh 0 put_ bh (IfRecSelId a b) = putByte bh 1 >> put_ bh a >> put_ bh b put_ bh IfDFunId = putByte bh 2 get bh = do h <- getByte bh case h of 0 -> return IfVanillaId 1 -> do { a <- get bh; b <- get bh; return (IfRecSelId a b) } _ -> return IfDFunId instance Binary IfaceIdInfo where put_ bh NoInfo = putByte bh 0 put_ bh (HasInfo i) = putByte bh 1 >> lazyPut bh i -- NB lazyPut get bh = do h <- getByte bh case h of 0 -> return NoInfo _ -> liftM HasInfo $ lazyGet bh -- NB lazyGet instance Binary IfaceInfoItem where put_ bh (HsArity aa) = putByte bh 0 >> put_ bh aa put_ bh (HsStrictness ab) = putByte bh 1 >> put_ bh ab put_ bh (HsUnfold lb ad) = putByte bh 2 >> put_ bh lb >> put_ bh ad put_ bh (HsInline ad) = putByte bh 3 >> put_ bh ad put_ bh HsNoCafRefs = putByte bh 4 get bh = do h <- getByte bh case h of 0 -> liftM HsArity $ get bh 1 -> liftM HsStrictness $ get bh 2 -> do lb <- get bh ad <- get bh return (HsUnfold lb ad) 3 -> liftM HsInline $ get bh _ -> return HsNoCafRefs instance Binary IfaceUnfolding where put_ bh (IfCoreUnfold s e) = do putByte bh 0 put_ bh s put_ bh e put_ bh (IfInlineRule a b c d) = do putByte bh 1 put_ bh a put_ bh b put_ bh c put_ bh d put_ bh (IfDFunUnfold as bs) = do putByte bh 2 put_ bh as put_ bh bs put_ bh (IfCompulsory e) = do putByte bh 3 put_ bh e get bh = do h <- getByte bh case h of 0 -> do s <- get bh e <- get bh return (IfCoreUnfold s e) 1 -> do a <- get bh b <- get bh c <- get bh d <- get bh return (IfInlineRule a b c d) 2 -> do as <- get bh bs <- get bh return (IfDFunUnfold as bs) _ -> do e <- get bh return (IfCompulsory e) instance Binary IfaceExpr where put_ bh (IfaceLcl aa) = do putByte bh 0 put_ bh aa put_ bh (IfaceType ab) = do putByte bh 1 put_ bh ab put_ bh (IfaceCo ab) = do putByte bh 2 put_ bh ab put_ bh (IfaceTuple ac ad) = do putByte bh 3 put_ bh ac put_ bh ad put_ bh (IfaceLam (ae, os) af) = do putByte bh 4 put_ bh ae put_ bh os put_ bh af put_ bh (IfaceApp ag ah) = do putByte bh 5 put_ bh ag put_ bh ah put_ bh (IfaceCase ai aj ak) = do putByte bh 6 put_ bh ai put_ bh aj put_ bh ak put_ bh (IfaceLet al am) = do putByte bh 7 put_ bh al put_ bh am put_ bh (IfaceTick an ao) = do putByte bh 8 put_ bh an put_ bh ao put_ bh (IfaceLit ap) = do putByte bh 9 put_ bh ap put_ bh (IfaceFCall as at) = do putByte bh 10 put_ bh as put_ bh at put_ bh (IfaceExt aa) = do putByte bh 11 put_ bh aa put_ bh (IfaceCast ie ico) = do putByte bh 12 put_ bh ie put_ bh ico put_ bh (IfaceECase a b) = do putByte bh 13 put_ bh a put_ bh b get bh = do h <- getByte bh case h of 0 -> do aa <- get bh return (IfaceLcl aa) 1 -> do ab <- get bh return (IfaceType ab) 2 -> do ab <- get bh return (IfaceCo ab) 3 -> do ac <- get bh ad <- get bh return (IfaceTuple ac ad) 4 -> do ae <- get bh os <- get bh af <- get bh return (IfaceLam (ae, os) af) 5 -> do ag <- get bh ah <- get bh return (IfaceApp ag ah) 6 -> do ai <- get bh aj <- get bh ak <- get bh return (IfaceCase ai aj ak) 7 -> do al <- get bh am <- get bh return (IfaceLet al am) 8 -> do an <- get bh ao <- get bh return (IfaceTick an ao) 9 -> do ap <- get bh return (IfaceLit ap) 10 -> do as <- get bh at <- get bh return (IfaceFCall as at) 11 -> do aa <- get bh return (IfaceExt aa) 12 -> do ie <- get bh ico <- get bh return (IfaceCast ie ico) 13 -> do a <- get bh b <- get bh return (IfaceECase a b) _ -> panic ("get IfaceExpr " ++ show h) instance Binary IfaceTickish where put_ bh (IfaceHpcTick m ix) = do putByte bh 0 put_ bh m put_ bh ix put_ bh (IfaceSCC cc tick push) = do putByte bh 1 put_ bh cc put_ bh tick put_ bh push put_ bh (IfaceSource src name) = do putByte bh 2 put_ bh (srcSpanFile src) put_ bh (srcSpanStartLine src) put_ bh (srcSpanStartCol src) put_ bh (srcSpanEndLine src) put_ bh (srcSpanEndCol src) put_ bh name get bh = do h <- getByte bh case h of 0 -> do m <- get bh ix <- get bh return (IfaceHpcTick m ix) 1 -> do cc <- get bh tick <- get bh push <- get bh return (IfaceSCC cc tick push) 2 -> do file <- get bh sl <- get bh sc <- get bh el <- get bh ec <- get bh let start = mkRealSrcLoc file sl sc end = mkRealSrcLoc file el ec name <- get bh return (IfaceSource (mkRealSrcSpan start end) name) _ -> panic ("get IfaceTickish " ++ show h) instance Binary IfaceConAlt where put_ bh IfaceDefault = putByte bh 0 put_ bh (IfaceDataAlt aa) = putByte bh 1 >> put_ bh aa put_ bh (IfaceLitAlt ac) = putByte bh 2 >> put_ bh ac get bh = do h <- getByte bh case h of 0 -> return IfaceDefault 1 -> liftM IfaceDataAlt $ get bh _ -> liftM IfaceLitAlt $ get bh instance Binary IfaceBinding where put_ bh (IfaceNonRec aa ab) = putByte bh 0 >> put_ bh aa >> put_ bh ab put_ bh (IfaceRec ac) = putByte bh 1 >> put_ bh ac get bh = do h <- getByte bh case h of 0 -> do { aa <- get bh; ab <- get bh; return (IfaceNonRec aa ab) } _ -> do { ac <- get bh; return (IfaceRec ac) } instance Binary IfaceLetBndr where put_ bh (IfLetBndr a b c) = do put_ bh a put_ bh b put_ bh c get bh = do a <- get bh b <- get bh c <- get bh return (IfLetBndr a b c) instance Binary IfaceTyConParent where put_ bh IfNoParent = putByte bh 0 put_ bh (IfDataInstance ax pr ty) = do putByte bh 1 put_ bh ax put_ bh pr put_ bh ty get bh = do h <- getByte bh case h of 0 -> return IfNoParent _ -> do ax <- get bh pr <- get bh ty <- get bh return $ IfDataInstance ax pr ty
TomMD/ghc
compiler/iface/IfaceSyn.hs
bsd-3-clause
71,006
78
27
23,569
17,523
8,725
8,798
1,359
10
-- Common wrapper for HTML pages module Distribution.Server.Pages.Template ( hackagePage , hackagePageWith , hackagePageWithHead ) where import Text.XHtml.Strict --TODO: replace all this with external templates -- | Create top-level HTML document by wrapping the Html with boilerplate. hackagePage :: String -> [Html] -> Html hackagePage = hackagePageWithHead [] hackagePageWithHead :: [Html] -> String -> [Html] -> Html hackagePageWithHead headExtra docTitle docContent = hackagePageWith headExtra docTitle docSubtitle docContent bodyExtra where docSubtitle = anchor ! [href introductionURL] << "Hackage :: [Package]" bodyExtra = [] hackagePageWith :: [Html] -> String -> Html -> [Html] -> [Html] -> Html hackagePageWith headExtra docTitle docSubtitle docContent bodyExtra = toHtml [ header << (docHead ++ headExtra) , body << (docBody ++ bodyExtra) ] where docHead = [ thetitle << (docTitle ++ " | Hackage") , thelink ! [ rel "stylesheet" , href stylesheetURL , thetype "text/css"] << noHtml -- if Search is enabled , thelink ! [ rel "search", href "/packages/opensearch.xml" , thetype "application/opensearchdescription+xml" , title "Hackage" ] << noHtml ] docBody = [ thediv ! [identifier "page-header"] << docHeader , thediv ! [identifier "content"] << docContent ] docHeader = [ navigationBar , paragraph ! [theclass "caption"] << docSubtitle ] navigationBar :: Html navigationBar = ulist ! [theclass "links", identifier "page-menu"] << map (li <<) [ anchor ! [href introductionURL] << "Home" , form ! [action "/packages/search", theclass "search", method "get"] << [ button ! [thetype "submit"] << "Search", spaceHtml , input ! [thetype "text", name "terms" ] ] , anchor ! [href pkgListURL] << "Browse" , anchor ! [href recentAdditionsURL] << "What's new" , anchor ! [href uploadURL] << "Upload" , anchor ! [href accountsURL] << "User accounts" ] stylesheetURL :: URL stylesheetURL = "/static/hackage.css" -- URL of the package list pkgListURL :: URL pkgListURL = "/packages/" -- URL of the upload form introductionURL :: URL introductionURL = "/" -- URL of the upload form uploadURL :: URL uploadURL = "/upload" -- URL about user accounts, including the form to change passwords accountsURL :: URL accountsURL = "/accounts" -- URL of the admin front end adminURL :: URL adminURL = "/admin" -- URL of the list of recent additions to the database recentAdditionsURL :: URL recentAdditionsURL = "/packages/recent"
mpickering/hackage-server
Distribution/Server/Pages/Template.hs
bsd-3-clause
2,833
0
13
776
627
348
279
53
1