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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
module LispVal (
LispVal(..)
, LispError(..)
, ThrowsError
, IOThrowsError
, Env
, makeFunc
, makeNormalFunc
, makeVarArgs
) where
import Control.Monad.Error
import Data.Ratio
import Data.Complex
import Text.ParserCombinators.Parsec hiding (spaces)
import Data.IORef
data LispVal = Atom String
| List [LispVal]
| DottedList [LispVal] LispVal
| Number Integer
| Complex (Complex Double)
| Float Double
| String String
| Ratio Rational
| Bool Bool
| Character Char
| PrimitiveFunc ([LispVal] -> ThrowsError LispVal)
| Func { params :: [String]
, vararg :: (Maybe String)
, body :: [LispVal]
, closure :: Env }
makeFunc varargs env params body = return $ Func (map showVal params) varargs body env
makeNormalFunc :: Env -> [LispVal] -> [LispVal] -> IOThrowsError LispVal
makeNormalFunc = makeFunc Nothing
makeVarArgs :: LispVal -> Env -> [LispVal] -> [LispVal] -> IOThrowsError LispVal
makeVarArgs = makeFunc . Just . showVal
showVal :: LispVal -> String
showVal (String contents) = "\"" ++ contents ++ "\""
showVal (Atom name) = name
showVal (Number contents) = show contents
showVal (Float a) = show a
showVal (Character a) = "#\\"
++ [a]
showVal (Ratio a) = show (numerator a)
++ "/"
++ show (denominator a)
showVal (Complex (a :+ b)) = show a
++ "+"
++ show b
++ "i"
showVal (Bool True) = "#t"
showVal (Bool False) = "#f"
showVal (List contents) = "("
++ unwordsList contents
++ ")"
showVal (DottedList h t) = "("
++ unwordsList h
++ " . "
++ showVal t
++ ")"
showVal (PrimitiveFunc _) = "<primitive>"
showVal (Func {params = args, vararg = varargs, body = body, closure = env}) =
"(lambda (" ++ unwords (map show args) ++
(case varargs of
Nothing -> ""
Just arg -> " . " ++ arg) ++ ") ...)"
unwordsList :: [LispVal] -> String
unwordsList = unwords . map showVal
instance Show LispVal where show = showVal
data LispError = NumArgs Integer [LispVal]
| TypeMismatch String LispVal
| Parser ParseError
| BadSpecialForm String LispVal
| NotFunction String String
| UnboundVar String String
| Default String
showError :: LispError -> String
showError (UnboundVar message varname) = message ++ ": " ++ varname
showError (BadSpecialForm message form) = message ++ ": " ++ show form
showError (NotFunction message func) = message ++ ": " ++ show func
showError (NumArgs expected found) = "Expected "
++ show expected
++ " args; found values "
++ unwordsList found
showError (TypeMismatch expected found) = "Invalid type: expected "
++ expected
++ ", found " ++ show found
showError (Parser parseErr) = "Parse error at " ++ show parseErr
showError (Default message) = message
instance Show LispError where show = showError
instance Error LispError where
noMsg = Default "An error has occurred"
strMsg = Default
type ThrowsError = Either LispError
type Env = IORef [(String, IORef LispVal)]
type IOThrowsError = ErrorT LispError IO
|
diminishedprime/.org
|
programmey_stuff/write_yourself_a_scheme/ch_08/wyas/app/LispVal.hs
|
mit
| 3,743
| 0
| 11
| 1,387
| 1,032
| 549
| 483
| 94
| 2
|
module Feature.QuerySpec where
import Test.Hspec hiding (pendingWith)
import Test.Hspec.Wai
import Test.Hspec.Wai.JSON
import Network.HTTP.Types
import Network.Wai.Test (SResponse(simpleHeaders))
import SpecHelper
import Text.Heredoc
import Network.Wai (Application)
spec :: SpecWith Application
spec = do
describe "Querying a table with a column called count" $
it "should not confuse count column with pg_catalog.count aggregate" $
get "/has_count_column" `shouldRespondWith` 200
describe "Querying a nonexistent table" $
it "causes a 404" $
get "/faketable" `shouldRespondWith` 404
describe "Filtering response" $ do
it "matches with equality" $
get "/items?id=eq.5"
`shouldRespondWith` ResponseMatcher {
matchBody = Just [json| [{"id":5}] |]
, matchStatus = 200
, matchHeaders = ["Content-Range" <:> "0-0/1"]
}
it "matches with equality using not operator" $
get "/items?id=not.eq.5"
`shouldRespondWith` ResponseMatcher {
matchBody = Just [json| [{"id":1},{"id":2},{"id":3},{"id":4},{"id":6},{"id":7},{"id":8},{"id":9},{"id":10},{"id":11},{"id":12},{"id":13},{"id":14},{"id":15}] |]
, matchStatus = 200
, matchHeaders = ["Content-Range" <:> "0-13/14"]
}
it "matches with more than one condition using not operator" $
get "/simple_pk?k=like.*yx&extra=not.eq.u" `shouldRespondWith` "[]"
it "matches with inequality using not operator" $ do
get "/items?id=not.lt.14&order=id.asc"
`shouldRespondWith` ResponseMatcher {
matchBody = Just [json| [{"id":14},{"id":15}] |]
, matchStatus = 200
, matchHeaders = ["Content-Range" <:> "0-1/2"]
}
get "/items?id=not.gt.2&order=id.asc"
`shouldRespondWith` ResponseMatcher {
matchBody = Just [json| [{"id":1},{"id":2}] |]
, matchStatus = 200
, matchHeaders = ["Content-Range" <:> "0-1/2"]
}
it "matches items IN" $
get "/items?id=in.1,3,5"
`shouldRespondWith` ResponseMatcher {
matchBody = Just [json| [{"id":1},{"id":3},{"id":5}] |]
, matchStatus = 200
, matchHeaders = ["Content-Range" <:> "0-2/3"]
}
it "matches items NOT IN" $
get "/items?id=notin.2,4,6,7,8,9,10,11,12,13,14,15"
`shouldRespondWith` ResponseMatcher {
matchBody = Just [json| [{"id":1},{"id":3},{"id":5}] |]
, matchStatus = 200
, matchHeaders = ["Content-Range" <:> "0-2/3"]
}
it "matches items NOT IN using not operator" $
get "/items?id=not.in.2,4,6,7,8,9,10,11,12,13,14,15"
`shouldRespondWith` ResponseMatcher {
matchBody = Just [json| [{"id":1},{"id":3},{"id":5}] |]
, matchStatus = 200
, matchHeaders = ["Content-Range" <:> "0-2/3"]
}
it "matches nulls using not operator" $
get "/no_pk?a=not.is.null" `shouldRespondWith`
[json| [{"a":"1","b":"0"},{"a":"2","b":"0"}] |]
it "matches nulls in varchar and numeric fields alike" $ do
get "/no_pk?a=is.null" `shouldRespondWith`
[json| [{"a": null, "b": null}] |]
get "/nullable_integer?a=is.null" `shouldRespondWith` [str|[{"a":null}]|]
it "matches with like" $ do
get "/simple_pk?k=like.*yx" `shouldRespondWith`
[str|[{"k":"xyyx","extra":"u"}]|]
get "/simple_pk?k=like.xy*" `shouldRespondWith`
[str|[{"k":"xyyx","extra":"u"}]|]
get "/simple_pk?k=like.*YY*" `shouldRespondWith`
[str|[{"k":"xYYx","extra":"v"}]|]
it "matches with like using not operator" $
get "/simple_pk?k=not.like.*yx" `shouldRespondWith`
[str|[{"k":"xYYx","extra":"v"}]|]
it "matches with ilike" $ do
get "/simple_pk?k=ilike.xy*&order=extra.asc" `shouldRespondWith`
[str|[{"k":"xyyx","extra":"u"},{"k":"xYYx","extra":"v"}]|]
get "/simple_pk?k=ilike.*YY*&order=extra.asc" `shouldRespondWith`
[str|[{"k":"xyyx","extra":"u"},{"k":"xYYx","extra":"v"}]|]
it "matches with ilike using not operator" $
get "/simple_pk?k=not.ilike.xy*&order=extra.asc" `shouldRespondWith` "[]"
it "matches with tsearch @@" $
get "/tsearch?text_search_vector=@@.foo" `shouldRespondWith`
[json| [{"text_search_vector":"'bar':2 'foo':1"}] |]
it "matches with tsearch @@ using not operator" $
get "/tsearch?text_search_vector=not.@@.foo" `shouldRespondWith`
[json| [{"text_search_vector":"'baz':1 'qux':2"}] |]
it "matches with computed column" $
get "/items?always_true=eq.true&order=id.asc" `shouldRespondWith`
[json| [{"id":1},{"id":2},{"id":3},{"id":4},{"id":5},{"id":6},{"id":7},{"id":8},{"id":9},{"id":10},{"id":11},{"id":12},{"id":13},{"id":14},{"id":15}] |]
it "order by computed column" $
get "/items?order=anti_id.desc" `shouldRespondWith`
[json| [{"id":1},{"id":2},{"id":3},{"id":4},{"id":5},{"id":6},{"id":7},{"id":8},{"id":9},{"id":10},{"id":11},{"id":12},{"id":13},{"id":14},{"id":15}] |]
it "matches filtering nested items" $
get "/clients?select=id,projects{id,tasks{id,name}}&projects.tasks.name=like.Design*" `shouldRespondWith`
[str|[{"id":1,"projects":[{"id":1,"tasks":[{"id":1,"name":"Design w7"}]},{"id":2,"tasks":[{"id":3,"name":"Design w10"}]}]},{"id":2,"projects":[{"id":3,"tasks":[{"id":5,"name":"Design IOS"}]},{"id":4,"tasks":[{"id":7,"name":"Design OSX"}]}]}]|]
it "matches with @> operator" $
get "/complex_items?select=id&arr_data=@>.{2}" `shouldRespondWith`
[str|[{"id":2},{"id":3}]|]
it "matches with <@ operator" $
get "/complex_items?select=id&arr_data=<@.{1,2,4}" `shouldRespondWith`
[str|[{"id":1},{"id":2}]|]
describe "Shaping response with select parameter" $ do
it "selectStar works in absense of parameter" $
get "/complex_items?id=eq.3" `shouldRespondWith`
[str|[{"id":3,"name":"Three","settings":{"foo":{"int":1,"bar":"baz"}},"arr_data":[1,2,3],"field-with_sep":1}]|]
it "dash `-` in column names is accepted" $
get "/complex_items?id=eq.3&select=id,field-with_sep" `shouldRespondWith`
[str|[{"id":3,"field-with_sep":1}]|]
it "one simple column" $
get "/complex_items?select=id" `shouldRespondWith`
[json| [{"id":1},{"id":2},{"id":3}] |]
it "rename simple column" $
get "/complex_items?id=eq.1&select=myId:id" `shouldRespondWith`
[json| [{"myId":1}] |]
it "one simple column with casting (text)" $
get "/complex_items?select=id::text" `shouldRespondWith`
[json| [{"id":"1"},{"id":"2"},{"id":"3"}] |]
it "rename simple column with casting" $
get "/complex_items?id=eq.1&select=myId:id::text" `shouldRespondWith`
[json| [{"myId":"1"}] |]
it "json column" $
get "/complex_items?id=eq.1&select=settings" `shouldRespondWith`
[json| [{"settings":{"foo":{"int":1,"bar":"baz"}}}] |]
it "json subfield one level with casting (json)" $
get "/complex_items?id=eq.1&select=settings->>foo::json" `shouldRespondWith`
[json| [{"foo":{"int":1,"bar":"baz"}}] |] -- the value of foo here is of type "text"
it "rename json subfield one level with casting (json)" $
get "/complex_items?id=eq.1&select=myFoo:settings->>foo::json" `shouldRespondWith`
[json| [{"myFoo":{"int":1,"bar":"baz"}}] |] -- the value of foo here is of type "text"
it "fails on bad casting (data of the wrong format)" $
get "/complex_items?select=settings->foo->>bar::integer"
`shouldRespondWith` ResponseMatcher {
matchBody = Just [json| {"hint":null,"details":null,"code":"22P02","message":"invalid input syntax for integer: \"baz\""} |]
, matchStatus = 400
, matchHeaders = []
}
it "fails on bad casting (wrong cast type)" $
get "/complex_items?select=id::fakecolumntype"
`shouldRespondWith` ResponseMatcher {
matchBody = Just [json| {"hint":null,"details":null,"code":"42704","message":"type \"fakecolumntype\" does not exist"} |]
, matchStatus = 400
, matchHeaders = []
}
it "json subfield two levels (string)" $
get "/complex_items?id=eq.1&select=settings->foo->>bar" `shouldRespondWith`
[json| [{"bar":"baz"}] |]
it "rename json subfield two levels (string)" $
get "/complex_items?id=eq.1&select=myBar:settings->foo->>bar" `shouldRespondWith`
[json| [{"myBar":"baz"}] |]
it "json subfield two levels with casting (int)" $
get "/complex_items?id=eq.1&select=settings->foo->>int::integer" `shouldRespondWith`
[json| [{"int":1}] |] -- the value in the db is an int, but here we expect a string for now
it "rename json subfield two levels with casting (int)" $
get "/complex_items?id=eq.1&select=myInt:settings->foo->>int::integer" `shouldRespondWith`
[json| [{"myInt":1}] |] -- the value in the db is an int, but here we expect a string for now
it "requesting parents and children" $
get "/projects?id=eq.1&select=id, name, clients{*}, tasks{id, name}" `shouldRespondWith`
[str|[{"id":1,"name":"Windows 7","clients":{"id":1,"name":"Microsoft"},"tasks":[{"id":1,"name":"Design w7"},{"id":2,"name":"Code w7"}]}]|]
it "embed data with two fk pointing to the same table" $
get "/orders?id=eq.1&select=id, name, billing_address_id{id}, shipping_address_id{id}" `shouldRespondWith`
[str|[{"id":1,"name":"order 1","billing_address_id":{"id":1},"shipping_address_id":{"id":2}}]|]
it "requesting parents and children while renaming them" $
get "/projects?id=eq.1&select=myId:id, name, project_client:client_id{*}, project_tasks:tasks{id, name}" `shouldRespondWith`
[str|[{"myId":1,"name":"Windows 7","project_client":{"id":1,"name":"Microsoft"},"project_tasks":[{"id":1,"name":"Design w7"},{"id":2,"name":"Code w7"}]}]|]
it "requesting parents and filtering parent columns" $
get "/projects?id=eq.1&select=id, name, clients{id}" `shouldRespondWith`
[str|[{"id":1,"name":"Windows 7","clients":{"id":1}}]|]
it "rows with missing parents are included" $
get "/projects?id=in.1,5&select=id,clients{id}" `shouldRespondWith`
[str|[{"id":1,"clients":{"id":1}},{"id":5,"clients":null}]|]
it "rows with no children return [] instead of null" $
get "/projects?id=in.5&select=id,tasks{id}" `shouldRespondWith`
[str|[{"id":5,"tasks":[]}]|]
it "requesting children 2 levels" $
get "/clients?id=eq.1&select=id,projects{id,tasks{id}}" `shouldRespondWith`
[str|[{"id":1,"projects":[{"id":1,"tasks":[{"id":1},{"id":2}]},{"id":2,"tasks":[{"id":3},{"id":4}]}]}]|]
it "requesting many<->many relation" $
get "/tasks?select=id,users{id}" `shouldRespondWith`
[str|[{"id":1,"users":[{"id":1},{"id":3}]},{"id":2,"users":[{"id":1}]},{"id":3,"users":[{"id":1}]},{"id":4,"users":[{"id":1}]},{"id":5,"users":[{"id":2},{"id":3}]},{"id":6,"users":[{"id":2}]},{"id":7,"users":[{"id":2}]},{"id":8,"users":[]}]|]
it "requesting many<->many relation with rename" $
get "/tasks?id=eq.1&select=id,theUsers:users{id}" `shouldRespondWith`
[str|[{"id":1,"theUsers":[{"id":1},{"id":3}]}]|]
it "requesting many<->many relation reverse" $
get "/users?select=id,tasks{id}" `shouldRespondWith`
[str|[{"id":1,"tasks":[{"id":1},{"id":2},{"id":3},{"id":4}]},{"id":2,"tasks":[{"id":5},{"id":6},{"id":7}]},{"id":3,"tasks":[{"id":1},{"id":5}]}]|]
it "requesting parents and children on views" $
get "/projects_view?id=eq.1&select=id, name, clients{*}, tasks{id, name}" `shouldRespondWith`
[str|[{"id":1,"name":"Windows 7","clients":{"id":1,"name":"Microsoft"},"tasks":[{"id":1,"name":"Design w7"},{"id":2,"name":"Code w7"}]}]|]
it "requesting children with composite key" $
get "/users_tasks?user_id=eq.2&task_id=eq.6&select=*, comments{content}" `shouldRespondWith`
[str|[{"user_id":2,"task_id":6,"comments":[{"content":"Needs to be delivered ASAP"}]}]|]
it "detect relations in views from exposed schema that are based on tables in private schema and have columns renames" $
get "/articles?id=eq.1&select=id,articleStars{users{*}}" `shouldRespondWith`
[str|[{"id":1,"articleStars":[{"users":{"id":1,"name":"Angela Martin"}},{"users":{"id":2,"name":"Michael Scott"}},{"users":{"id":3,"name":"Dwight Schrute"}}]}]|]
it "can select by column name" $
get "/projects?id=in.1,3&select=id,name,client_id,client_id{id,name}" `shouldRespondWith`
[str|[{"id":1,"name":"Windows 7","client_id":1,"client_id":{"id":1,"name":"Microsoft"}},{"id":3,"name":"IOS","client_id":2,"client_id":{"id":2,"name":"Apple"}}]|]
it "can select by column name sans id" $
get "/projects?id=in.1,3&select=id,name,client_id,client{id,name}" `shouldRespondWith`
[str|[{"id":1,"name":"Windows 7","client_id":1,"client":{"id":1,"name":"Microsoft"}},{"id":3,"name":"IOS","client_id":2,"client":{"id":2,"name":"Apple"}}]|]
describe "Plurality singular" $ do
it "will select an existing object" $
request methodGet "/items?id=eq.5" [("Prefer","plurality=singular")] ""
`shouldRespondWith` ResponseMatcher {
matchBody = Just [json| {"id":5} |]
, matchStatus = 200
, matchHeaders = []
}
it "can combine multiple prefer values" $
request methodGet "/items?id=eq.5" [("Prefer","plurality=singular ; future=new; count=none")] ""
`shouldRespondWith` ResponseMatcher {
matchBody = Just [json| {"id":5} |]
, matchStatus = 200
, matchHeaders = []
}
it "works in the presence of a range header" $
let headers = ("Prefer","plurality=singular") :
rangeHdrs (ByteRangeFromTo 0 9) in
request methodGet "/items" headers ""
`shouldRespondWith` ResponseMatcher {
matchBody = Just [json| {"id":1} |]
, matchStatus = 200
, matchHeaders = []
}
it "will respond with 404 when not found" $
request methodGet "/items?id=eq.9999" [("Prefer","plurality=singular")] ""
`shouldRespondWith` 404
it "can shape plurality singular object routes" $
request methodGet "/projects_view?id=eq.1&select=id,name,clients{*},tasks{id,name}" [("Prefer","plurality=singular")] ""
`shouldRespondWith`
[str|{"id":1,"name":"Windows 7","clients":{"id":1,"name":"Microsoft"},"tasks":[{"id":1,"name":"Design w7"},{"id":2,"name":"Code w7"}]}|]
describe "ordering response" $ do
it "by a column asc" $
get "/items?id=lte.2&order=id.asc"
`shouldRespondWith` ResponseMatcher {
matchBody = Just [json| [{"id":1},{"id":2}] |]
, matchStatus = 200
, matchHeaders = ["Content-Range" <:> "0-1/2"]
}
it "by a column desc" $
get "/items?id=lte.2&order=id.desc"
`shouldRespondWith` ResponseMatcher {
matchBody = Just [json| [{"id":2},{"id":1}] |]
, matchStatus = 200
, matchHeaders = ["Content-Range" <:> "0-1/2"]
}
it "by a column asc with nulls last" $
get "/no_pk?order=a.asc.nullslast"
`shouldRespondWith` ResponseMatcher {
matchBody = Just [json| [{"a":"1","b":"0"},
{"a":"2","b":"0"},
{"a":null,"b":null}] |]
, matchStatus = 200
, matchHeaders = ["Content-Range" <:> "0-2/3"]
}
it "by a column desc with nulls first" $
get "/no_pk?order=a.desc.nullsfirst"
`shouldRespondWith` ResponseMatcher {
matchBody = Just [json| [{"a":null,"b":null},
{"a":"2","b":"0"},
{"a":"1","b":"0"}] |]
, matchStatus = 200
, matchHeaders = ["Content-Range" <:> "0-2/3"]
}
it "by a column desc with nulls last" $
get "/no_pk?order=a.desc.nullslast"
`shouldRespondWith` ResponseMatcher {
matchBody = Just [json| [{"a":"2","b":"0"},
{"a":"1","b":"0"},
{"a":null,"b":null}] |]
, matchStatus = 200
, matchHeaders = ["Content-Range" <:> "0-2/3"]
}
it "without other constraints" $
get "/items?order=id.asc" `shouldRespondWith` 200
it "ordering embeded entities" $
get "/projects?id=eq.1&select=id, name, tasks{id, name}&tasks.order=name.asc" `shouldRespondWith`
[str|[{"id":1,"name":"Windows 7","tasks":[{"id":2,"name":"Code w7"},{"id":1,"name":"Design w7"}]}]|]
it "ordering embeded entities with alias" $
get "/projects?id=eq.1&select=id, name, the_tasks:tasks{id, name}&tasks.order=name.asc" `shouldRespondWith`
[str|[{"id":1,"name":"Windows 7","the_tasks":[{"id":2,"name":"Code w7"},{"id":1,"name":"Design w7"}]}]|]
it "ordering embeded entities, two levels" $
get "/projects?id=eq.1&select=id, name, tasks{id, name, users{id, name}}&tasks.order=name.asc&tasks.users.order=name.desc" `shouldRespondWith`
[str|[{"id":1,"name":"Windows 7","tasks":[{"id":2,"name":"Code w7","users":[{"id":1,"name":"Angela Martin"}]},{"id":1,"name":"Design w7","users":[{"id":3,"name":"Dwight Schrute"},{"id":1,"name":"Angela Martin"}]}]}]|]
it "ordering embeded parents does not break things" $
get "/projects?id=eq.1&select=id, name, clients{id, name}&clients.order=name.asc" `shouldRespondWith`
[str|[{"id":1,"name":"Windows 7","clients":{"id":1,"name":"Microsoft"}}]|]
it "ordering embeded parents does not break things when using ducktape names" $
get "/projects?id=eq.1&select=id, name, client{id, name}&client.order=name.asc" `shouldRespondWith`
[str|[{"id":1,"name":"Windows 7","client":{"id":1,"name":"Microsoft"}}]|]
describe "Accept headers" $ do
it "should respond an unknown accept type with 415" $
request methodGet "/simple_pk"
(acceptHdrs "text/unknowntype") ""
`shouldRespondWith` 415
it "should respond correctly to */* in accept header" $
request methodGet "/simple_pk"
(acceptHdrs "*/*") ""
`shouldRespondWith` 200
it "should respond correctly to multiple types in accept header" $
request methodGet "/simple_pk"
(acceptHdrs "text/unknowntype, text/csv") ""
`shouldRespondWith` 200
it "should respond with CSV to 'text/csv' request" $
request methodGet "/simple_pk"
(acceptHdrs "text/csv; version=1") ""
`shouldRespondWith` ResponseMatcher {
matchBody = Just "k,extra\nxyyx,u\nxYYx,v"
, matchStatus = 200
, matchHeaders = ["Content-Type" <:> "text/csv; charset=utf-8"]
}
describe "Canonical location" $ do
it "Sets Content-Location with alphabetized params" $
get "/no_pk?b=eq.1&a=eq.1"
`shouldRespondWith` ResponseMatcher {
matchBody = Just "[]"
, matchStatus = 200
, matchHeaders = ["Content-Location" <:> "/no_pk?a=eq.1&b=eq.1"]
}
it "Omits question mark when there are no params" $ do
r <- get "/simple_pk"
liftIO $ do
let respHeaders = simpleHeaders r
respHeaders `shouldSatisfy` matchHeader
"Content-Location" "/simple_pk"
describe "jsonb" $ do
it "can filter by properties inside json column" $ do
get "/json?data->foo->>bar=eq.baz" `shouldRespondWith`
[json| [{"data": {"id": 1, "foo": {"bar": "baz"}}}] |]
get "/json?data->foo->>bar=eq.fake" `shouldRespondWith`
[json| [] |]
it "can filter by properties inside json column using not" $
get "/json?data->foo->>bar=not.eq.baz" `shouldRespondWith`
[json| [] |]
it "can filter by properties inside json column using ->>" $
get "/json?data->>id=eq.1" `shouldRespondWith`
[json| [{"data": {"id": 1, "foo": {"bar": "baz"}}}] |]
describe "remote procedure call" $ do
context "a proc that returns a set" $ do
it "returns paginated results" $
request methodPost "/rpc/getitemrange"
(rangeHdrs (ByteRangeFromTo 0 0)) [json| { "min": 2, "max": 4 } |]
`shouldRespondWith` ResponseMatcher {
matchBody = Just [json| [{"id":3}] |]
, matchStatus = 206
, matchHeaders = ["Content-Range" <:> "0-0/2"]
}
it "returns proper json" $
post "/rpc/getitemrange" [json| { "min": 2, "max": 4 } |] `shouldRespondWith`
[json| [ {"id": 3}, {"id":4} ] |]
context "a proc that returns an empty rowset" $
it "returns empty json array" $
post "/rpc/test_empty_rowset" [json| {} |] `shouldRespondWith`
[json| [] |]
context "a proc that returns plain text" $ do
it "returns proper json" $
post "/rpc/sayhello" [json| { "name": "world" } |] `shouldRespondWith`
[json| [{"sayhello":"Hello, world"}] |]
it "can handle unicode" $
post "/rpc/sayhello" [json| { "name": "¥" } |] `shouldRespondWith`
[json| [{"sayhello":"Hello, ¥"}] |]
context "improper input" $ do
it "rejects unknown content type even if payload is good" $
request methodPost "/rpc/sayhello"
(acceptHdrs "audio/mpeg3") [json| { "name": "world" } |]
`shouldRespondWith` 415
it "rejects malformed json payload" $
request methodPost "/rpc/sayhello"
(acceptHdrs "application/json") "sdfsdf"
`shouldRespondWith` 400
context "unsupported verbs" $ do
it "DELETE fails" $
request methodDelete "/rpc/sayhello" [] ""
`shouldRespondWith` 405
it "PATCH fails" $
request methodPatch "/rpc/sayhello" [] ""
`shouldRespondWith` 405
it "OPTIONS fails" $
-- TODO: should return info about the function
request methodOptions "/rpc/sayhello" [] ""
`shouldRespondWith` 405
it "GET fails with 405 on unknown procs" $
-- TODO: should this be 404?
get "/rpc/fake" `shouldRespondWith` 405
it "GET with 405 on known procs" $
get "/rpc/sayhello" `shouldRespondWith` 405
it "executes the proc exactly once per request" $ do
post "/rpc/callcounter" [json| {} |] `shouldRespondWith`
[json| [{"callcounter":1}] |]
post "/rpc/callcounter" [json| {} |] `shouldRespondWith`
[json| [{"callcounter":2}] |]
describe "weird requests" $ do
it "can query as normal" $ do
get "/Escap3e;" `shouldRespondWith`
[json| [{"so6meIdColumn":1},{"so6meIdColumn":2},{"so6meIdColumn":3},{"so6meIdColumn":4},{"so6meIdColumn":5}] |]
get "/ghostBusters" `shouldRespondWith`
[json| [{"escapeId":1},{"escapeId":3},{"escapeId":5}] |]
it "will embed a collection" $
get "/Escap3e;?select=ghostBusters{*}" `shouldRespondWith`
[json| [{"ghostBusters":[{"escapeId":1}]},{"ghostBusters":[]},{"ghostBusters":[{"escapeId":3}]},{"ghostBusters":[]},{"ghostBusters":[{"escapeId":5}]}] |]
it "will embed using a column" $
get "/ghostBusters?select=escapeId{*}" `shouldRespondWith`
[json| [{"escapeId":{"so6meIdColumn":1}},{"escapeId":{"so6meIdColumn":3}},{"escapeId":{"so6meIdColumn":5}}] |]
|
league/postgrest
|
test/Feature/QuerySpec.hs
|
mit
| 23,375
| 0
| 19
| 5,016
| 3,318
| 1,849
| 1,469
| -1
| -1
|
{-# LANGUAGE OverloadedStrings #-}
module Controllers.HomeSpec ( spec ) where
import qualified Data.ByteString.Lazy as LBS
import Helper
spec :: Spec
spec = do
describe "GET /" $ do
it "should contain 'Scotty Starter' in response body" $ do
app <- getApp
body <- getBody <$> app `get` ""
body `shouldSatisfy` \x -> any (LBS.isPrefixOf "Scotty Starter") $ LBS.tails x
|
slogsdon/url
|
test/Controllers/HomeSpec.hs
|
mit
| 414
| 0
| 19
| 106
| 112
| 60
| 52
| 11
| 1
|
module CIS194.Week06.Fibonacci where
-- | Exercise 01
fib :: Integer -> Integer
fib 0 = 0
fib 1 = 1
fib n = fib (n - 1) + fib (n - 2)
fibs1 :: [Integer]
fibs1 = map fib [0..]
-- | Exercise 02
-- The implementation was borrowed from:
-- https://wiki.haskell.org/The_Fibonacci_sequence
fibs2 :: [Integer]
fibs2 = 0 : 1 : zipWith (+) fibs2 (tail fibs2)
-- | Exercise 03
data Stream a = Cons a (Stream a)
instance Show a => Show (Stream a) where
show = show . take 20 . streamToList
streamToList :: Stream a -> [a]
streamToList (Cons x xs) = x : streamToList xs
-- | Exercise 04
streamRepeat :: a -> Stream a
streamRepeat x = Cons x (streamRepeat x)
streamMap :: (a -> b) -> Stream a -> Stream b
streamMap f (Cons x xs) = Cons (f x) (streamMap f xs)
streamFromSeed :: (a -> a) -> a -> Stream a
streamFromSeed f x = Cons x (streamFromSeed f (f x))
-- | Exercise 05
nats :: Stream Integer
nats = streamFromSeed (+1) 0
ruler :: Stream Integer
ruler = ruler' 0
where
ruler' x = interleave (streamRepeat x) (ruler' (x + 1))
interleave :: Stream a -> Stream a -> Stream a
interleave (Cons x xs) ys = Cons x (interleave ys xs)
|
acamino/cis-194-2013
|
src/CIS194/Week06/Fibonacci.hs
|
mit
| 1,144
| 0
| 11
| 250
| 492
| 254
| 238
| 27
| 1
|
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# OPTIONS_GHC -fno-warn-unused-binds -fno-warn-unused-matches -fno-warn-unused-imports #-}
module Technique.Formatter where
import Core.System.Pretty
import Core.Text.Rope
import Core.Text.Utilities
import Data.Foldable (foldl')
import Data.Int (Int8)
import Technique.Language
import Technique.Quantity
data TechniqueToken
= MagicToken
| ProcedureToken
| TypeToken
| SymbolToken
| OperatorToken
| VariableToken
| ApplicationToken
| LabelToken
| StringToken
| QuantityToken
| RoleToken
| ErrorToken
| FilenameToken
| StepToken
instance Pretty Procedure where
pretty = unAnnotate . highlight
colourizeTechnique :: TechniqueToken -> AnsiColour
colourizeTechnique token = case token of
MagicToken -> brightGrey
ProcedureToken -> bold dullBlue
TypeToken -> dullYellow
SymbolToken -> bold dullCyan
OperatorToken -> bold dullYellow
VariableToken -> brightCyan
ApplicationToken -> bold brightBlue
LabelToken -> brightGreen
StringToken -> bold brightGreen
QuantityToken -> bold brightMagenta
RoleToken -> dullYellow
ErrorToken -> bold pureRed
FilenameToken -> bold brightWhite
StepToken -> bold brightGrey -- for diagnostics in evalutator
instance Render Procedure where
type Token Procedure = TechniqueToken
colourize = colourizeTechnique
highlight proc =
let name = highlight . procedureName $ proc
params = case procedureParams proc of
[] -> emptyDoc
xs -> commaCat xs <> " "
from = commaCat . procedureInput $ proc
into = highlight . procedureOutput $ proc
block = highlight . procedureBlock $ proc
description = case procedureDescription proc of
Nothing -> emptyDoc
Just text -> highlight text
in description
<> ( indent
4
( annotate ProcedureToken name
<+> params
<> annotate SymbolToken ":"
<+> annotate TypeToken from
<+> annotate SymbolToken "->"
<+> annotate TypeToken into
<> line
<> block
)
)
-- |
-- Punctuate a list with commas annotated with Symbol highlighting.
commaCat :: (Render a, Token a ~ TechniqueToken) => [a] -> Doc (Token a)
commaCat = hcat . punctuate (annotate SymbolToken comma) . fmap (annotate VariableToken . highlight)
instance Render Type where
type Token Type = TechniqueToken
colourize = colourizeTechnique
highlight (Type name) = annotate TypeToken (pretty name)
instance Render Markdown where
type Token Markdown = TechniqueToken
colourize = colourizeTechnique
highlight (Markdown text) = pretty text
instance Render Block where
type Token Block = TechniqueToken
colourize = colourizeTechnique
highlight (Block statements) =
nest
4
( annotate SymbolToken lbrace
<> go statements
)
<> line
<> annotate SymbolToken rbrace
where
go :: [Statement] -> Doc TechniqueToken
go [] = emptyDoc
go (x@(Series _) : x1 : xs) = highlight x <> highlight x1 <> go xs
go (x : xs) = line <> highlight x <> go xs
instance Render Statement where
type Token Statement = TechniqueToken
colourize = colourizeTechnique
highlight statement = case statement of
Assignment _ vars expr ->
commaCat vars <+> annotate SymbolToken "=" <+> highlight expr
Execute _ expr ->
highlight expr
Comment _ text ->
"-- " <> pretty text -- TODO what about multiple lines?
Declaration _ proc ->
highlight proc
Blank _ ->
emptyDoc
Series _ ->
annotate SymbolToken " ; "
instance Render Attribute where
type Token Attribute = TechniqueToken
colourize = colourizeTechnique
highlight role = case role of
Role name -> annotate RoleToken ("@" <> pretty name)
Place name -> annotate RoleToken ("#" <> pretty name)
Inherit -> annotate ErrorToken "Inherit"
instance Render Expression where
type Token Expression = TechniqueToken
colourize = colourizeTechnique
highlight expr = case expr of
Application _ name subexpr ->
annotate ApplicationToken (highlight name) <+> highlight subexpr
None _ ->
annotate SymbolToken ("()")
Undefined _ ->
annotate ErrorToken "?"
Amount _ qty ->
highlight qty
Text _ text ->
annotate SymbolToken dquote
<> annotate StringToken (pretty text)
<> annotate SymbolToken dquote
Object _ tablet ->
highlight tablet
Variable _ vars ->
commaCat vars
Operation _ operator subexpr1 subexpr2 ->
highlight subexpr1 <+> highlight operator <+> highlight subexpr2
Grouping _ subexpr ->
annotate SymbolToken lparen
<> highlight subexpr
<> annotate SymbolToken rparen
Restriction _ attribute block ->
highlight attribute
<> line
<> highlight block -- TODO some nesting?
instance Render Identifier where
type Token Identifier = TechniqueToken
colourize = colourizeTechnique
highlight (Identifier name) = pretty name
instance Pretty Identifier where
pretty = unAnnotate . highlight
instance Render Decimal where
type Token Decimal = TechniqueToken
colourize = colourizeTechnique
highlight = pretty . decimalToRope
instance Render Quantity where
type Token Quantity = TechniqueToken
colourize = colourizeTechnique
highlight qty = case qty of
Number i ->
annotate QuantityToken (pretty i)
Quantity i u m unit ->
let measurement =
highlight i <> " "
uncertainty =
if isZeroDecimal u
then emptyDoc
else "± " <> highlight u <> " "
magnitude =
if m == 0
then emptyDoc
else "× 10" <> numberToSuperscript m <> " "
in annotate QuantityToken (measurement <> uncertainty <> magnitude <> pretty unit)
numberToSuperscript :: Int8 -> Doc ann
numberToSuperscript number =
let digits = show number
digits' = fmap toSuperscript digits
in pretty digits'
toSuperscript :: Char -> Char
toSuperscript c = case c of
'0' -> '⁰' -- U+2070
'1' -> '¹' -- U+00B9
'2' -> '²' -- U+00B2
'3' -> '³' -- U+00B3
'4' -> '⁴' -- U+2074
'5' -> '⁵' -- U+2075
'6' -> '⁶' -- U+2076
'7' -> '⁷' -- U+2077
'8' -> '⁸' -- U+2078
'9' -> '⁹' -- U+2079
'-' -> '⁻' -- U+207B
_ -> error "Invalid, digit expected"
instance Pretty Quantity where
pretty = unAnnotate . highlight
instance Render Tablet where
type Token Tablet = TechniqueToken
colourize = colourizeTechnique
highlight (Tablet bindings) =
nest
4
( annotate SymbolToken lbracket
<> foldl' g emptyDoc bindings
)
<> line
<> annotate SymbolToken rbracket
where
g :: Doc TechniqueToken -> Binding -> Doc TechniqueToken
g built binding = built <> line <> highlight binding
instance Render Label where
type Token Label = TechniqueToken
colourize = colourizeTechnique
highlight (Label text) =
annotate SymbolToken dquote
<> annotate LabelToken (pretty text)
<> annotate SymbolToken dquote
instance Pretty Label where
pretty = unAnnotate . highlight
-- the annotation for the label duplicates the code Quantity's Text
-- constructor, but for the LabelToken token. This distinction may not be
-- necessary (at present we have the same colouring for both).
instance Render Binding where
type Token Binding = TechniqueToken
colourize = colourizeTechnique
highlight (Binding label subexpr) =
highlight label
<+> annotate SymbolToken "~"
<+> highlight subexpr
instance Render Operator where
type Token Operator = TechniqueToken
colourize = colourizeTechnique
highlight operator =
annotate OperatorToken $ case operator of
WaitBoth -> pretty '&'
WaitEither -> pretty '|'
Combine -> pretty '+'
instance Render Technique where
type Token Technique = TechniqueToken
colourize = colourizeTechnique
highlight technique =
let version = pretty . techniqueVersion $ technique
license = pretty . techniqueLicense $ technique
copyright = case techniqueCopyright technique of
Just owner -> "; ©" <+> pretty owner
Nothing -> emptyDoc
body = fmap highlight . techniqueBody $ technique
in annotate MagicToken ("%" <+> "technique" <+> "v" <> version) <> line
<> annotate MagicToken ("!" <+> license <> copyright)
<> line
<> line
<> vsep (punctuate line body)
|
oprdyn/technique
|
lib/Technique/Formatter.hs
|
mit
| 8,742
| 0
| 19
| 2,297
| 2,236
| 1,117
| 1,119
| 248
| 14
|
module Ch16.Lifting where
a :: [Int]
a = (+1) <$> read "[1]"
b :: Maybe [String]
b = (fmap . fmap) (++ "lol") $ Just ["Hi,", "Hello"]
c :: Int -> Int
c = (*2) . (\x -> x - 2)
d :: Int -> String
d = (return '1' ++) . show . (\x -> [x, 1..3])
e :: IO Integer
e = let ioi = readIO "1" :: IO Integer
changed = read <$> ("123" ++) <$> show <$> ioi
in
(*3) <$> changed
|
andrewMacmurray/haskell-book-solutions
|
src/ch16/Lifting.hs
|
mit
| 387
| 0
| 12
| 110
| 214
| 121
| 93
| 13
| 1
|
module KillRing where
data KillRing = KR { ring :: [String],
seen :: [String]}
mkKillRing :: KillRing
mkKillRing = KR [] []
addToKillRing :: String -> KillRing -> KillRing
addToKillRing st (KR r s) = KR (st:r) s
yank :: KillRing -> (String, KillRing)
yank (KR (x : xs) s) = (x, (KR (s ++ xs) [x]))
yank (KR [] _) = ("", mkKillRing)
yankNext :: KillRing -> (String, KillRing)
yankNext (KR (x : xs) s) = (x, KR xs (x:s))
yankNext (KR [] [] ) = ("", mkKillRing)
yankNext (KR [] s ) = yankNext (KR s [])
|
awbraunstein/emonad
|
src/KillRing.hs
|
mit
| 525
| 0
| 9
| 124
| 292
| 160
| 132
| 14
| 1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE GADTs #-}
-- |
-- Module: Utils
-- Copyright: Copyright © 2014 AlephCloud Systems, Inc.
-- License: MIT
-- Maintainer: Lars Kuhtz <lars@alephcloud.com>
-- Stability: experimental
--
-- Utils for Tests for Haskell AWS bindints
--
module Utils
(
-- * Parameters
testRegion
, testDataPrefix
-- * General Utils
, sshow
, tryT
, retryT
, testData
, evalTestT
, evalTestTM
, eitherTOnceTest0
, eitherTOnceTest1
, eitherTOnceTest2
-- * Generic Tests
, test_jsonRoundtrip
, prop_jsonRoundtrip
) where
import Aws
import Aws.General
import Control.Concurrent (threadDelay)
import Control.Error
import Control.Exception
import Control.Monad
import Control.Monad.Identity
import Control.Monad.IO.Class
import Data.Aeson (FromJSON, ToJSON, encode, eitherDecode)
import qualified Data.ByteString as B
import qualified Data.List as L
import Data.Monoid
import Data.Proxy
import Data.String
import qualified Data.Text as T
import Data.Typeable
import Test.QuickCheck.Property
import Test.QuickCheck.Monadic
import Test.Tasty
import Test.Tasty.QuickCheck
import System.IO
import System.Exit
import System.Environment
-- -------------------------------------------------------------------------- --
-- Static Test parameters
--
-- TODO make these configurable
testRegion :: Region
testRegion = UsWest2
-- | This prefix is used for the IDs and names of all entities that are
-- created in the AWS account.
--
testDataPrefix :: IsString a => a
testDataPrefix = "__TEST_AWSHASKELLBINDINGS__"
-- -------------------------------------------------------------------------- --
-- General Utils
tryT :: MonadIO m => IO a -> EitherT T.Text m a
tryT = fmapLT (T.pack . show) . syncIO
testData :: (IsString a, Monoid a) => a -> a
testData a = testDataPrefix <> a
retryT :: MonadIO m => Int -> EitherT T.Text m a -> EitherT T.Text m a
retryT i f = go 1
where
go x
| x >= i = fmapLT (\e -> "error after " <> sshow x <> " retries: " <> e) f
| otherwise = f `catchT` \_ -> do
liftIO $ threadDelay (1000000 * min 60 (2^(x-1)))
go (succ x)
sshow :: (Show a, IsString b) => a -> b
sshow = fromString . show
evalTestTM
:: Functor f
=> String -- ^ test name
-> f (EitherT T.Text IO a) -- ^ test
-> f (IO Bool)
evalTestTM name = fmap $
runEitherT >=> \r -> case r of
Left e -> do
hPutStrLn stderr $ "failed to run stream test \"" <> name <> "\": " <> show e
return False
Right _ -> return True
evalTestT
:: String -- ^ test name
-> EitherT T.Text IO a -- ^ test
-> IO Bool
evalTestT name = runIdentity . evalTestTM name . Identity
eitherTOnceTest0
:: String -- ^ test name
-> EitherT T.Text IO a -- ^ test
-> TestTree
eitherTOnceTest0 name = testProperty name . once . ioProperty . evalTestT name
eitherTOnceTest1
:: (Arbitrary a, Show a)
=> String -- ^ test name
-> (a -> EitherT T.Text IO b)
-> TestTree
eitherTOnceTest1 name test = testProperty name . once $ monadicIO . liftIO
. evalTestTM name test
eitherTOnceTest2
:: (Arbitrary a, Show a, Arbitrary b, Show b)
=> String -- ^ test name
-> (a -> b -> EitherT T.Text IO c)
-> TestTree
eitherTOnceTest2 name test = testProperty name . once $ \a b -> monadicIO . liftIO
$ (evalTestTM name $ uncurry test) (a, b)
-- -------------------------------------------------------------------------- --
-- Generic Tests
test_jsonRoundtrip
:: forall a . (Eq a, Show a, FromJSON a, ToJSON a, Typeable a, Arbitrary a)
=> Proxy a
-> TestTree
test_jsonRoundtrip proxy = testProperty msg (prop_jsonRoundtrip :: a -> Property)
where
msg = "JSON roundtrip for " <> show (typeRep proxy)
prop_jsonRoundtrip :: forall a . (Eq a, Show a, FromJSON a, ToJSON a) => a -> Property
prop_jsonRoundtrip a = either (const $ property False) (\(b :: [a]) -> [a] === b) $
eitherDecode $ encode [a]
|
alephcloud/hs-aws-general
|
tests/Utils.hs
|
mit
| 3,984
| 0
| 20
| 832
| 1,149
| 621
| 528
| 102
| 2
|
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE UnboxedTuples #-}
{-# LANGUAGE BangPatterns #-}
module Ternary.Compiler.ArrayState (
MulStateAL(MulStateAL),
MulStateAS(MulStateAS),
arrayLookup, arrayState) where
import Data.Array.Base (unsafeAt)
import Data.Array.Unboxed
import Data.Array.ST
import Control.Monad.ST
import GHC.Arr (inRange)
import GHC.Int (Int16)
import Ternary.Core.Digit (T2(..))
import Ternary.Core.Kernel (Kernel)
-- notice the thin interface here
import Ternary.Core.Multiplication (
TriangleParam (TriangleParam),
MultiplicationState (kernel, initialMultiplicationState))
-- notice the thin interface here
import Ternary.Compiler.ArrayLookup (
mixIn, splitOut, lookupArray, lookupInitial,
-- the following we only need to assert an invariant
initialPoints, normalPointBounds, secondPointBounds)
-- Unboxed universal applied triangle
type UUAppliedTriangle = T2 -> Int16 -> (# T2, Int16 #)
-- We want to construct an array without building an assoc list first.
-- We rely on mutability for the construction phase only.
type ArrayConstruction s = ST s (STUArray s Int Int16)
uuAppliedTriangle :: UArray Int Int16 -> UUAppliedTriangle
uuAppliedTriangle array a i =
let !ix = mixIn a (fromIntegral i)
in splitOut (array `unsafeAt` ix)
lookupTriangle :: (T2,T2) -> UUAppliedTriangle
lookupTriangle ab = uuAppliedTriangle $! lookupArray ab
-- We now develop two variations of the inner loop of the algorithm.
-- The first one uses lists, and is therefor easier to understand but
-- not very efficient. The second approach uses mutable arrays for
-- efficiency. So the list variation is a stepping stone towards the
-- array version. We shall alternate between the two approaches, to
-- emphasize the similarity and clarify the difference. Both methods
-- use arrays for lookup, but only the second one uses arrays to hold
-- the state of the multiplication kernel. This explains the names
-- and their abbreviations: ArrayLookup (AL) versus ArrayState (AS).
-- Because triangle parametrization has been absorbed in the state, we
-- can now simplify Ternary.Core.Kernel (chain). It also seems faster
-- when we avoid polymorphic types inside unboxed tuples.
chainAL :: UUAppliedTriangle -> Kernel T2 T2 [Int16]
chainAL f a (u:us) =
let (# !b, !v #) = f a u
(c, vs) = chainAL f b us
in (c, v:vs)
chainAL _ a [] = (a,[])
-- The arrays going in and out are zero-indexed. The new array has
-- one more element than the old array, and the two arrays relate to
-- each other by a shift: with the exclusion of position zero, the new
-- array is completely populated. Thus we anticipate the "final cons"
-- that will set the initial state for the next round.
chainAS :: forall s . UUAppliedTriangle -> T2 ->
UArray Int Int16 -> (T2, ArrayConstruction s)
chainAS f start old = (x,y)
where
(#x,y#) = loop 0 start new
hi = snd (bounds old)
new = newArray_ (0, hi+1)
-- the inner loop needs an explicit type
loop :: Int -> T2 -> ArrayConstruction s -> (# T2, ArrayConstruction s #)
loop i x construction
| i > hi = (# x, construction #)
| otherwise = let !u = unsafeAt old i -- assume zero-indexed array!
(# !b, !v #) = f x u
j = i+1 -- shift to the right
in loop j b (write j v construction)
{-# INLINE write #-} -- important
write :: Int -> Int16 -> ArrayConstruction s -> ArrayConstruction s
write i e st = do a <- st
writeArray a i e
return a
stepInvariant :: [Int16] -> Bool
stepInvariant (u:v:vs) = elem u initialPoints &&
inRange secondPointBounds v &&
all (inRange normalPointBounds) vs
stepInvariant [u] = elem u initialPoints
checkStepInvariant :: [Int16] -> [Int16]
checkStepInvariant us
| stepInvariant us = us
| otherwise = error "checkStepInvariant"
stepAL :: (T2,T2) -> [Int16] -> (T2, [Int16])
stepAL ab = chainAL triangle O0 . checkStepInvariant -- O0 instead of undefined
where !triangle = lookupTriangle ab -- important strictness
-- The arrays going in an out are zero-indexed.
stepAS :: (T2,T2) -> UArray Int Int16 -> (T2, ArrayConstruction s)
stepAS ab = chainAS triangle O0
where !triangle = lookupTriangle ab
newtype MulStateAL = MulStateAL [Int16] deriving Show
newtype MulStateAS = MulStateAS (UArray Int Int16) deriving Eq
multKernelAL :: Kernel (T2,T2) T2 MulStateAL
multKernelAL ab (MulStateAL us) =
let (out, vs) = stepAL ab us
in (out, MulStateAL (lookupInitial ab:vs))
-- The construction of a new state array is finished by setting a new
-- initial state at the beginning of the chain. Strictness makes a
-- noticeable difference on small multiplications, which is just as
-- important as the asymptotic behavior.
multKernelAS :: Kernel (T2,T2) T2 MulStateAS
multKernelAS ab (MulStateAS us) =
let (!out, !construction) = stepAS ab us
!init = lookupInitial ab
finish = write 0 init construction
in (out, MulStateAS (runSTUArray finish))
instance MultiplicationState MulStateAL where
kernel = multKernelAL
initialMultiplicationState (TriangleParam a b) =
MulStateAL [lookupInitial (a,b)] -- singleton list
-- The construction of a new state array is finished by setting a new
-- initial state at the beginning of the chain.
instance MultiplicationState MulStateAS where
kernel = multKernelAS
initialMultiplicationState (TriangleParam a b) =
MulStateAS $ array (0,0) [(0,init)]
where init = lookupInitial (a,b) -- singleton array
instance Show MulStateAS where
show (MulStateAS array) = "MulStateAS " ++ show (b-a+1)
where (a,b) = bounds array
-- algorithm selector
arrayLookup :: MulStateAL
arrayLookup = undefined
arrayState :: MulStateAS
arrayState = undefined
|
jeroennoels/exact-real
|
src/Ternary/Compiler/ArrayState.hs
|
mit
| 5,849
| 3
| 13
| 1,208
| 1,374
| 744
| 630
| 101
| 1
|
module Carbon.DataStructures.Trees.NaturalTree (index, naturals) where
import qualified Carbon.DataStructures.Trees.GenericBinaryTree as GenericBinaryTree
instance Functor GenericBinaryTree.Tree where
fmap f (GenericBinaryTree.Branch left node right) = GenericBinaryTree.Branch (fmap f left) (f node) (fmap f right)
index :: GenericBinaryTree.Tree a -> Integer -> a
index (GenericBinaryTree.Branch _ node _) 0 = node
index (GenericBinaryTree.Branch left _ right) n = case (divMod (n - 1) 2) of
(quotient, 0) -> index left quotient
(quotient, 1) -> index right quotient
-- naturals = GenericBinaryTree.Branch (fmap ((+ 1) . (* 2)) naturals) 0 (fmap ((* 2) . (+ 1)) naturals)
naturals :: GenericBinaryTree.Tree Integer
naturals = create 0 1 where
create n step = let
step' = step * 2
in seq n $ seq step $ GenericBinaryTree.Branch (create (n + step) step') n (create (n + step') step')
|
Raekye/Carbon
|
haskell/src/Carbon/DataStructures/Trees/NaturalTree.hs
|
mit
| 895
| 0
| 14
| 141
| 305
| 159
| 146
| 14
| 2
|
module Domains.English where
import Instances
import Test.QuickCheck
nounS = ["Alice","Bob"] -- ,"John","George","Paul","David"]
nounP = ["Cars","Houses"]
verbS = ["runs","plays"] -- ,"walks","takes"]
verbP = ["move","hide"]
pronounS = ["He","She"]
pronounP = ["We","They"]
adverb = ["slowly","suddenly"]
templates2 = [ (nounS,verbS),
(nounP,verbP),
(pronounS,verbS),
(pronounP,verbP) ]
templates3 = [ (nounS,verbS,adverb),
(nounP,verbP,adverb),
(pronounS,verbS,adverb),
(pronounP,verbP,adverb)
]
words' = nounS ++ nounP ++ verbS ++ verbP ++ pronounS ++ pronounP ++ adverb
sentence2 = do
template <- oneof $ map return templates2
x <- oneof . map return $ fst template
y <- oneof . map return $ snd template
let sentence = Binary (Oper "#") (Root x) (Root y)
return sentence
sentence3 = do
template <- oneof $ map return templates3
x <- oneof . map return $ fst' template
y <- oneof . map return $ snd' template
z <- oneof . map return $ thd' template
let sentence = Binary (Oper "#") (Binary (Oper "#") (Root x) (Root y)) (Root z)
return sentence
nonSentences =
[Root w | w <- words']
++
[Binary (Oper "#") (Root v) (Root n) | n <- nounS, v <- verbS]
++
[Binary (Oper "#") (Root v) (Root p) | p <- pronounS, v <- verbS]
++
[Binary (Oper "#") (Root v) (Root p) | p <- pronounP, v <- verbP]
++
[Binary (Oper "#") (Root v) (Root p) | p <- pronounP, v <- pronounS]
++
[Binary (Oper "#") (Root v) (Root p) | p <- verbP, v <- verbS]
-- random Item for addition facts
langItem :: Int -> Gen Item
langItem s = do
positive <- oneof [return True, return False]
correct <- oneof [return True , return False]
-- ok <- frequency [(9,return (Root "OK")),(1,return (Binary "#" (Root "OK") (Root "OK")))]
let ok = Root "OK"
size' <- oneof [return 2,return 3]
correctLhs <- case size' of
2 -> sentence2
3 -> sentence3
wrongLhs <- elements nonSentences
if positive
then do
if correct -- correct item with positive viability
then do
let item = Item correctLhs ok (size correctLhs)
return item
else do -- wrong item with positive viability
let item = Item wrongLhs (Root "*OK") (size wrongLhs)
return item
else do
if correct -- correct item with negative viability
then do
let item = Item correctLhs (Root "*OK") (0 - (size correctLhs))
return item
else do
let item = Item wrongLhs ok (0 - size wrongLhs)
return item
|
arnizamani/aiw
|
Domains/English.hs
|
gpl-2.0
| 2,845
| 0
| 20
| 939
| 1,028
| 522
| 506
| 71
| 5
|
module HEP.Automation.MadGraph.Dataset.Set20110413set4 where
import HEP.Storage.WebDAV
import HEP.Automation.MadGraph.Model
import HEP.Automation.MadGraph.Machine
import HEP.Automation.MadGraph.UserCut
import HEP.Automation.MadGraph.SetupType
import HEP.Automation.MadGraph.Model.ZpHFull
import HEP.Automation.MadGraph.Dataset.Common
import qualified Data.ByteString as B
{-
ucut :: UserCut
ucut = UserCut {
uc_metcut = 15.0
, uc_etacutlep = 1.2
, uc_etcutlep = 18.0
, uc_etacutjet = 2.5
, uc_etcutjet = 15.0
} -}
processTTBarSemiZp :: [Char]
processTTBarSemiZp =
"\ngenerate P P > t t~ QED=99, ( t > b w+, w+ > l+ vl ), (t~ > u~ zput, zput > b~ d ) @1 \nadd process P P > t t~ QED=99, (t > u zptu, zptu > b d~ ), (t~ > b~ w-, w- > l- vl~ ) @2 \n"
psetup_zphfull_TTSemiZp :: ProcessSetup ZpHFull
psetup_zphfull_TTSemiZp = PS {
mversion = MadGraph4
, model = ZpHFull
, process = processTTBarSemiZp
, processBrief = "TTSemiZp"
, workname = "414ZpH_TTBarSemiZp"
}
zpHFullParamSet :: [ModelParam ZpHFull]
zpHFullParamSet = [ ZpHFullParam m g (0.28)
| m <-[150.0]
, g <- [1.0] ]
psetuplist :: [ProcessSetup ZpHFull]
psetuplist = [ psetup_zphfull_TTSemiZp ]
sets :: [Int]
sets = [1..10]
zptasklist :: ScriptSetup -> ClusterSetup ZpHFull -> [WorkSetup ZpHFull]
zptasklist ssetup csetup =
[ WS ssetup (psetup_zphfull_TTSemiZp)
(rsetupGen p NoMatch NoUserCutDef RunPGS 50000 num)
csetup
(WebDAVRemoteDir "mc/TeVatronFor3/ZpHFull0414BigTTBarSemiZp")
| p <- zpHFullParamSet , num <- sets ]
totaltasklist :: ScriptSetup -> ClusterSetup ZpHFull -> [WorkSetup ZpHFull]
totaltasklist = zptasklist
|
wavewave/madgraph-auto-dataset
|
src/HEP/Automation/MadGraph/Dataset/Set20110413set4.hs
|
gpl-3.0
| 1,745
| 0
| 8
| 384
| 328
| 194
| 134
| 36
| 1
|
-- These problems from projecteuler.net
--
-- Problem 9
-- A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
--
-- a^2 + b^2 = c^2
-- For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
--
-- There exists exactly one Pythagorean triplet for which a + b + c = 1000.
-- Find the product abc.
-- NOT TESTED
{- TODO needs some (math based) optimization
pithag :: (Num a, Eq a, Ord a) => [a] -> [(a,a,a)]
pithag xs = [ (a,b,c) | a <- xs,
b <- xs,
c <- xs,
a + b + c == 1000,
a^2 + b^2 == c^2 ]
solution = head $ pithag [1..1000]
-}
|
susu/haskell-problems
|
ProjectEuler/problem9.hs
|
gpl-3.0
| 632
| 0
| 2
| 211
| 14
| 13
| 1
| 1
| 0
|
{-# LANGUAGE Arrows #-}
module PrisonersDilemma.Agent (
pdAgentBehaviour
) where
import PrisonersDilemma.Model
import FRP.FrABS
import FRP.Yampa
------------------------------------------------------------------------------------------------------------------------
-- Non-Reactive functions
------------------------------------------------------------------------------------------------------------------------
payoff :: PDAction -> PDAction -> Double
payoff Defector Defector = pParam
payoff Cooperator Defector = sParam
payoff Defector Cooperator = bParam
payoff Cooperator Cooperator = rParam
broadcastLocalAction :: PDEnvironment -> PDAgentOut -> PDAgentOut
broadcastLocalAction e ao = broadcastMessage (NeighbourAction curr) ns ao
where
s = agentState ao
coord = pdCoord s
curr = pdCurrAction s
ns = neighbourCells coord True e -- NOTE: include self, otherwise will lead to wrong results
broadcastLocalPayoff :: PDEnvironment -> PDAgentOut -> PDAgentOut
broadcastLocalPayoff e ao = broadcastMessage (NeighbourPayoff (currAct, currPo)) ns ao
where
s = agentState ao
coord = pdCoord s
currAct = pdCurrAction s
currPo = pdLocalPo s
ns = neighbourCells coord True e -- NOTE: include self, otherwise will lead to wrong results
handleNeighbourAction :: PDAgentIn -> PDAgentOut -> PDAgentOut
handleNeighbourAction ain ao = onMessage handleNeighbourActionAux ain ao
where
handleNeighbourActionAux :: AgentMessage PDMsg -> PDAgentOut -> PDAgentOut
handleNeighbourActionAux (_, NeighbourAction act) ao = updateAgentState (\s -> s { pdLocalPo = pdLocalPo s + po }) ao
where
curr = pdCurrAction $ agentState ao
po = payoff curr act
handleNeighbourActionAux _ ao = ao
handleNeighbourPayoff :: PDAgentIn -> PDAgentOut -> PDAgentOut
handleNeighbourPayoff ain ao = onMessage handleNeighbourPayoffAux ain ao
where
handleNeighbourPayoffAux :: AgentMessage PDMsg -> PDAgentOut -> PDAgentOut
handleNeighbourPayoffAux (_, NeighbourPayoff po@(poAct, poValue)) ao
| poValue > localBestPoValue = updateAgentState (\s -> s { pdBestPo = po }) ao
| otherwise = ao
where
s = agentState ao
(_, localBestPoValue) = pdBestPo s
handleNeighbourPayoffAux _ ao = ao
switchToBestPayoff :: PDAgentOut -> PDAgentOut
switchToBestPayoff ao =
updateAgentState (\s -> s {
pdCurrAction = bestAction,
pdPrevAction = oldAction,
pdLocalPo = 0.0,
pdBestPo = (bestAction, 0.0)})
ao
where
s = agentState ao
oldAction = pdCurrAction s
(bestAction, _) = pdBestPo s
------------------------------------------------------------------------------------------------------------------------
-- Reactive Functions
------------------------------------------------------------------------------------------------------------------------
pdAgentAwaitingNeighbourPayoffs :: PDEnvironment -> PDAgentBehaviourIgnoreEnv
pdAgentAwaitingNeighbourPayoffs e = proc ain ->
do
let ao = agentOutFromIn ain
let ao0 = handleNeighbourPayoff ain ao
ao1 <- doOnce (broadcastLocalPayoff e) -< ao0
returnA -< ao1
pdAgentAwaitingNeighbourActions :: PDEnvironment -> PDAgentBehaviourIgnoreEnv
pdAgentAwaitingNeighbourActions e = proc ain ->
do
let ao = agentOutFromIn ain
let ao0 = handleNeighbourAction ain ao
ao1 <- doOnce ((broadcastLocalAction e) . switchToBestPayoff) -< ao0
returnA -< ao1
pdAgentWaitForActions :: PDEnvironment -> PDAgentBehaviour
pdAgentWaitForActions e = transitionAfter
halfRoundTripTime
(ignoreEnv (pdAgentAwaitingNeighbourActions e))
(pdAgentWaitForPayoffs e)
pdAgentWaitForPayoffs :: PDEnvironment -> PDAgentBehaviour
pdAgentWaitForPayoffs e = transitionAfter
halfRoundTripTime
(ignoreEnv (pdAgentAwaitingNeighbourPayoffs e))
(pdAgentWaitForActions e)
pdAgentBehaviour :: PDEnvironment -> PDAgentBehaviour
pdAgentBehaviour = pdAgentWaitForActions
------------------------------------------------------------------------------------------------------------------------
|
thalerjonathan/phd
|
coding/libraries/chimera/examples/ABS/PrisonersDilemma/Agent.hs
|
gpl-3.0
| 4,007
| 30
| 14
| 603
| 914
| 472
| 442
| 77
| 2
|
module Infsabot.RobotAction.Interface (
RobotProgram, RobotProgramResult,
KnownState(KnownState),
peekAtSpot, material, stateLocation, stateAge, stateMemory, stateMessages,
RobotAction(Die, Noop, MoveIn, Dig, Spawn, Fire, Send),
SpawnAction(SpawnAction), SendAction(SendAction), FireAction(FireAction),
newProgram, newAppearance, newMaterial, newMemory, newDirection,
fireDirection, materialExpended,
messageToSend, sendDirection,
orderOfOperations,
actionCost,
robActChecks
) where
import Infsabot.RobotAction.Logic
import Infsabot.RobotAction.Tests
|
kavigupta/Infsabot
|
Infsabot/RobotAction/Interface.hs
|
gpl-3.0
| 664
| 0
| 5
| 153
| 128
| 91
| 37
| 24
| 0
|
{-# LANGUAGE ScopedTypeVariables #-}
module Handlers.Categories (categoryHandlers) where
import Import
categoryHandlers :: OM a
categoryHandlers = categoryListHandlers >> categoryDetailHandlers
categoryListHandlers :: OM a
categoryListHandlers = do
get root $ listAndWrap [Asc CategoryName]
post root $ do
JSONObject (newCategory :: Category) <- jsonBody'
category <- runSQL $ insertEntity newCategory
json $ JSONList [category]
categoryDetailHandlers :: OM a
categoryDetailHandlers = do
get var $ \catId -> getAndWrap (toSqlKey catId :: Key Category)
put var $ \catId -> updateAndWrap (toSqlKey catId :: Key Category)
delete var $ \catId -> deleteAndReturn (toSqlKey catId :: Key Category)
|
Southern-Exposure-Seed-Exchange/Order-Manager-Prototypes
|
spock/src/Handlers/Categories.hs
|
gpl-3.0
| 742
| 0
| 13
| 143
| 221
| 107
| 114
| 17
| 1
|
import Control.Monad
import Data.IORef
import Data.StateVar
import Graphics.Rendering.OpenGL as GL
import Graphics.UI.GLUT as GLUT
import Lens.Micro
import Foreign.Marshal.Alloc as Ptr
import Foreign.Marshal.Array (mallocArray, peekArray)
import Foreign.Ptr (Ptr)
import App
import Camera
import Command
import Editor
import GLUtils
import Model
import ModelRender
import Primitive (Prim)
import Types
import qualified Primitive
--------------------------------------------------------------------------------
logInfo = putStrLn
backgroundColor = Color4 0.64 0.8 1.0 1
--------------------------------------------------------------------------------
main :: IO ()
main = do
GLUT.getArgsAndInitialize
app <- newDefaultApp
GLUT.initialDisplayMode $= [GLUT.RGBAMode, GLUT.DoubleBuffered, GLUT.WithDepthBuffer]
GLUT.createWindow "glbrix"
logInfo =<< get GLUT.glutVersion
-- This must be located *after* the call to createWindow.
GL.depthFunc $= Just Less
GLUT.reshapeCallback $= Just (reshape app)
GLUT.displayCallback $= display app
mousePosRef <- newIORef Nothing
camRef <- newIORef (undefined :: Camera)
keysRef <- newIORef []
GLUT.motionCallback $=
(Just $ \(Position x y) -> do
refPosition <- get mousePosRef
case refPosition of
Nothing -> return ()
Just (Position x' y') -> do
cam <- get camRef
-- arbitrary factor to make motion less sensitive
let dx = 0.5 * fromIntegral (x - x')
let dy = 0.5 * fromIntegral (y - y')
let newCam = ((camElevation %~ \e -> e - dy) .
(camAzimuth %~ \a -> a + dx)) cam
_appCamera app $=! newCam
GLUT.postRedisplay Nothing
)
GLUT.passiveMotionCallback $= Just (handleMouseMove app)
GLUT.keyboardMouseCallback $= Just
(\ key keyState modifiers mousePos ->
case key of
MouseButton btn -> do
when (btn == RightButton) $
case keyState of
Down -> do
mousePosRef $=! Just mousePos
(camRef $=!) =<< get (_appCamera app)
Up ->
mousePosRef $=! Nothing
handleMouse app btn keyState mousePos
SpecialKey key | keyState == Down -> do
case key of
KeyUp -> _appEditor app $~ Editor.moveSelectedParts (Vector3 0 1 0)
KeyDown -> _appEditor app $~ Editor.moveSelectedParts (Vector3 0 (-1) 0)
KeyLeft -> _appEditor app $~ Editor.moveSelectedParts (Vector3 (-1) 0 0)
KeyRight -> _appEditor app $~ Editor.moveSelectedParts (Vector3 1 0 0)
otherwise -> return ()
GLUT.postRedisplay Nothing
Char char | keyState == Down -> do
case char of
'\b' -> keysRef $~ drop 1
'\ESC' -> do
keysRef $= []
_appEditor app $~ Editor.escapeEdit
GLUT.postRedisplay Nothing
'\r' -> do
-- When RETURN is pressed, just place parts
keysRef $= []
_appEditor app $~ Editor.placeParts
GLUT.postRedisplay Nothing
'?' -> do
editor <- get (_appEditor app)
let n = length $ concatMap flattenPartTree $ allParts editor
logInfo $ "Number of pieces: " ++ show n
'\SOH' | GLUT.ctrl modifiers == Down -> do
-- X reports character of Ctrl+a as \SOH
_appEditor app $~ Editor.selectAll
GLUT.postRedisplay Nothing
_ -> do
-- When keys are pressed, their characters are accumulated into
-- commands than can be executed.
keysRef $~ (char :)
keys <- get keysRef
case Command.readCommand (reverse keys) of
Nothing -> return ()
Just cmd -> do
logInfo $ show cmd
App.execCommand app cmd
keysRef $= []
GLUT.postRedisplay Nothing
cmdBuf <- get keysRef
logInfo $ "Command buffer: " ++ cmdBuf
_ -> return ()
) -- end keyboardMouseCallback
GLUT.mainLoop
reshape :: App -> GLUT.Size -> IO ()
reshape app (Size w h) = do
GL.viewport $= (Position 0 0, Size w h)
GL.matrixMode $= Projection
GL.loadIdentity
let w' = fromIntegral w
let h' = fromIntegral h
let h_model = 25
let scale = h_model / h'
let w_model = w' * scale
let w2 = w_model / 2
let h2 = h_model / 2
-- GL.ortho (-w2) w2 (-h2) h2 1 500
GL.frustum (-w2) w2 (-h2) h2 20 800
GL.matrixMode $= Modelview 0
display :: App -> IO ()
display app = do
GL.clearColor $= backgroundColor
GL.clear [GL.ColorBuffer, GL.DepthBuffer]
applyCamera =<< get (_appCamera app)
GL.cullFace $= Just (GL.Back)
editor <- get (_appEditor app)
renderAxis 2
renderModel $ editor ^. lnonSelectedParts
-- Render "invisible" plane for picking
renderBackgroundPlane (-500, -500) (500, 500)
-- TODO: Save the depth buffer at this point for later picking
renderModelWireframe $ editor ^. lselectedParts
GLUT.swapBuffers
renderBackgroundPlane :: (GLint, GLint) -> (GLint, GLint) -> IO ()
renderBackgroundPlane (xMin, yMin) (xMax, yMax) = do
GL.color backgroundColor
GL.polygonMode $= (GL.Fill, GL.Fill)
GL.polygonOffsetFill $= Enabled
GL.renderPrimitive GL.Quads $ do
GL.vertex $ GL.Vertex2 xMin yMin
GL.vertex $ GL.Vertex2 xMax yMin
GL.vertex $ GL.Vertex2 xMax yMax
GL.vertex $ GL.Vertex2 xMin yMax
GL.polygonOffsetFill $= Disabled
--------------------------------------------------------------------------------
handleMouse :: App -> MouseCallback
handleMouse app LeftButton Down mousePos = do
applyCamera =<< get (_appCamera app)
editor <- get (_appEditor app)
case editor of
Place {} ->
_appEditor app $= Editor.placeParts editor
Pick {} -> do
let placed = editor ^. lnonSelectedParts
partMaybe <- pickPlacedPart mousePos (Editor.allParts editor)
case partMaybe of
Nothing ->
_appEditor app $= Editor.unselectAll editor
Just partIndex ->
_appEditor app $= Editor.toggleSelected partIndex editor
GLUT.postRedisplay Nothing
handleMouse app WheelUp Down mousePos = do
_appCamera app $~ (camDistance %~ (\d -> d - 5))
GLUT.postRedisplay Nothing
handleMouse app WheelDown Down mousePos = do
_appCamera app $~ (camDistance %~ (\d -> d + 5))
GLUT.postRedisplay Nothing
handleMouse _ _ _ _ =
return ()
--------------------------------------------------------------------------------
handleMouseMove :: App -> MotionCallback
handleMouseMove app mousePos = do
modelPos <- GLUtils.getModelPosition mousePos
-- logInfo $ "Pos: " ++ show modelPos
editor <- get (_appEditor app)
case editor of
Place {} -> do
_appEditor app $= Editor.moveParts modelPos editor
GLUT.postRedisplay Nothing
_other ->
return ()
--------------------------------------------------------------------------------
-- | Return the index of the placed part under given position, or
-- Nothing if there is no part under position.
pickPlacedPart :: Position -> [PlacedPart] -> IO (Maybe Int)
pickPlacedPart = pickPart ModelRender.renderPart
pickPart :: Renderer a -> Position -> [a] -> IO (Maybe Int)
pickPart renderer pos parts = do
GL.clearColor $= Color4 1 1 1 (1 :: GLfloat)
GL.clear [GL.ColorBuffer, GL.DepthBuffer]
renderWithUniqColors renderer parts
GL.flush
color <- getColorAtPosition pos
let partIndex = if color < maxBound then Just (fromEnum $ looseAlpha color) else Nothing
logInfo $ show pos ++ "\t" ++ show color ++ "\t (part " ++ show partIndex ++ ")"
return partIndex
getColorAtPosition :: Position -> IO (Color4 GLubyte)
getColorAtPosition pos@(Position posX posY) = do
-- glFlush()
-- glFinish()
GL.readBuffer $= BackBuffers
GL.rowAlignment Unpack $= 1
-- Flip y coordinate
(Size w h) <- get GLUT.windowSize
let flippedPos = Position posX (fromIntegral h - posY)
ptr <- mallocArray 4 :: IO (Ptr GLubyte)
GL.readPixels flippedPos (Size 1 1) (PixelData RGBA UnsignedByte ptr)
[r,g,b,a] <- peekArray 4 ptr
-- TODO: force arr before freeing?
Ptr.free ptr
return (Color4 r g b a)
--------------------------------------------------------------------------------
looseAlpha :: Color4 a -> Color3 a
looseAlpha (Color4 r g b a) = Color3 r g b
|
holmisen/glbrix
|
src/Main.hs
|
gpl-3.0
| 8,996
| 0
| 28
| 2,754
| 2,550
| 1,218
| 1,332
| 196
| 16
|
{-# 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.MachineLearning.DeleteEvaluation
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Assigns the 'DELETED' status to an 'Evaluation', rendering it unusable.
--
-- After invoking the 'DeleteEvaluation' operation, you can use the
-- GetEvaluation operation to verify that the status of the 'Evaluation'
-- changed to 'DELETED'.
--
-- __Caution:__ The results of the 'DeleteEvaluation' operation are
-- irreversible.
--
-- /See:/ <http://http://docs.aws.amazon.com/machine-learning/latest/APIReference/API_DeleteEvaluation.html AWS API Reference> for DeleteEvaluation.
module Network.AWS.MachineLearning.DeleteEvaluation
(
-- * Creating a Request
deleteEvaluation
, DeleteEvaluation
-- * Request Lenses
, deEvaluationId
-- * Destructuring the Response
, deleteEvaluationResponse
, DeleteEvaluationResponse
-- * Response Lenses
, dersEvaluationId
, dersResponseStatus
) where
import Network.AWS.MachineLearning.Types
import Network.AWS.MachineLearning.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'deleteEvaluation' smart constructor.
newtype DeleteEvaluation = DeleteEvaluation'
{ _deEvaluationId :: Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DeleteEvaluation' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'deEvaluationId'
deleteEvaluation
:: Text -- ^ 'deEvaluationId'
-> DeleteEvaluation
deleteEvaluation pEvaluationId_ =
DeleteEvaluation'
{ _deEvaluationId = pEvaluationId_
}
-- | A user-supplied ID that uniquely identifies the 'Evaluation' to delete.
deEvaluationId :: Lens' DeleteEvaluation Text
deEvaluationId = lens _deEvaluationId (\ s a -> s{_deEvaluationId = a});
instance AWSRequest DeleteEvaluation where
type Rs DeleteEvaluation = DeleteEvaluationResponse
request = postJSON machineLearning
response
= receiveJSON
(\ s h x ->
DeleteEvaluationResponse' <$>
(x .?> "EvaluationId") <*> (pure (fromEnum s)))
instance ToHeaders DeleteEvaluation where
toHeaders
= const
(mconcat
["X-Amz-Target" =#
("AmazonML_20141212.DeleteEvaluation" :: ByteString),
"Content-Type" =#
("application/x-amz-json-1.1" :: ByteString)])
instance ToJSON DeleteEvaluation where
toJSON DeleteEvaluation'{..}
= object
(catMaybes
[Just ("EvaluationId" .= _deEvaluationId)])
instance ToPath DeleteEvaluation where
toPath = const "/"
instance ToQuery DeleteEvaluation where
toQuery = const mempty
-- | Represents the output of a DeleteEvaluation operation. The output
-- indicates that Amazon Machine Learning (Amazon ML) received the request.
--
-- You can use the GetEvaluation operation and check the value of the
-- 'Status' parameter to see whether an 'Evaluation' is marked as
-- 'DELETED'.
--
-- /See:/ 'deleteEvaluationResponse' smart constructor.
data DeleteEvaluationResponse = DeleteEvaluationResponse'
{ _dersEvaluationId :: !(Maybe Text)
, _dersResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DeleteEvaluationResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dersEvaluationId'
--
-- * 'dersResponseStatus'
deleteEvaluationResponse
:: Int -- ^ 'dersResponseStatus'
-> DeleteEvaluationResponse
deleteEvaluationResponse pResponseStatus_ =
DeleteEvaluationResponse'
{ _dersEvaluationId = Nothing
, _dersResponseStatus = pResponseStatus_
}
-- | A user-supplied ID that uniquely identifies the 'Evaluation'. This value
-- should be identical to the value of the 'EvaluationId' in the request.
dersEvaluationId :: Lens' DeleteEvaluationResponse (Maybe Text)
dersEvaluationId = lens _dersEvaluationId (\ s a -> s{_dersEvaluationId = a});
-- | The response status code.
dersResponseStatus :: Lens' DeleteEvaluationResponse Int
dersResponseStatus = lens _dersResponseStatus (\ s a -> s{_dersResponseStatus = a});
|
olorin/amazonka
|
amazonka-ml/gen/Network/AWS/MachineLearning/DeleteEvaluation.hs
|
mpl-2.0
| 4,963
| 0
| 13
| 1,025
| 593
| 359
| 234
| 77
| 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.People.People.ListDirectoryPeople
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Provides a list of domain profiles and domain contacts in the
-- authenticated user\'s domain directory. When the \`sync_token\` is
-- specified, resources deleted since the last sync will be returned as a
-- person with \`PersonMetadata.deleted\` set to true. When the
-- \`page_token\` or \`sync_token\` is specified, all other request
-- parameters must match the first call. Writes may have a propagation
-- delay of several minutes for sync requests. Incremental syncs are not
-- intended for read-after-write use cases. See example usage at [List the
-- directory people that have
-- changed](\/people\/v1\/directory#list_the_directory_people_that_have_changed).
--
-- /See:/ <https://developers.google.com/people/ People API Reference> for @people.people.listDirectoryPeople@.
module Network.Google.Resource.People.People.ListDirectoryPeople
(
-- * REST Resource
PeopleListDirectoryPeopleResource
-- * Creating a Request
, peopleListDirectoryPeople
, PeopleListDirectoryPeople
-- * Request Lenses
, pldpSyncToken
, pldpXgafv
, pldpUploadProtocol
, pldpRequestSyncToken
, pldpAccessToken
, pldpUploadType
, pldpReadMask
, pldpSources
, pldpPageToken
, pldpPageSize
, pldpMergeSources
, pldpCallback
) where
import Network.Google.People.Types
import Network.Google.Prelude
-- | A resource alias for @people.people.listDirectoryPeople@ method which the
-- 'PeopleListDirectoryPeople' request conforms to.
type PeopleListDirectoryPeopleResource =
"v1" :>
"people:listDirectoryPeople" :>
QueryParam "syncToken" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "requestSyncToken" Bool :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "readMask" GFieldMask :>
QueryParams "sources"
PeopleListDirectoryPeopleSources
:>
QueryParam "pageToken" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParams "mergeSources"
PeopleListDirectoryPeopleMergeSources
:>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListDirectoryPeopleResponse
-- | Provides a list of domain profiles and domain contacts in the
-- authenticated user\'s domain directory. When the \`sync_token\` is
-- specified, resources deleted since the last sync will be returned as a
-- person with \`PersonMetadata.deleted\` set to true. When the
-- \`page_token\` or \`sync_token\` is specified, all other request
-- parameters must match the first call. Writes may have a propagation
-- delay of several minutes for sync requests. Incremental syncs are not
-- intended for read-after-write use cases. See example usage at [List the
-- directory people that have
-- changed](\/people\/v1\/directory#list_the_directory_people_that_have_changed).
--
-- /See:/ 'peopleListDirectoryPeople' smart constructor.
data PeopleListDirectoryPeople =
PeopleListDirectoryPeople'
{ _pldpSyncToken :: !(Maybe Text)
, _pldpXgafv :: !(Maybe Xgafv)
, _pldpUploadProtocol :: !(Maybe Text)
, _pldpRequestSyncToken :: !(Maybe Bool)
, _pldpAccessToken :: !(Maybe Text)
, _pldpUploadType :: !(Maybe Text)
, _pldpReadMask :: !(Maybe GFieldMask)
, _pldpSources :: !(Maybe [PeopleListDirectoryPeopleSources])
, _pldpPageToken :: !(Maybe Text)
, _pldpPageSize :: !(Maybe (Textual Int32))
, _pldpMergeSources :: !(Maybe [PeopleListDirectoryPeopleMergeSources])
, _pldpCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PeopleListDirectoryPeople' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pldpSyncToken'
--
-- * 'pldpXgafv'
--
-- * 'pldpUploadProtocol'
--
-- * 'pldpRequestSyncToken'
--
-- * 'pldpAccessToken'
--
-- * 'pldpUploadType'
--
-- * 'pldpReadMask'
--
-- * 'pldpSources'
--
-- * 'pldpPageToken'
--
-- * 'pldpPageSize'
--
-- * 'pldpMergeSources'
--
-- * 'pldpCallback'
peopleListDirectoryPeople
:: PeopleListDirectoryPeople
peopleListDirectoryPeople =
PeopleListDirectoryPeople'
{ _pldpSyncToken = Nothing
, _pldpXgafv = Nothing
, _pldpUploadProtocol = Nothing
, _pldpRequestSyncToken = Nothing
, _pldpAccessToken = Nothing
, _pldpUploadType = Nothing
, _pldpReadMask = Nothing
, _pldpSources = Nothing
, _pldpPageToken = Nothing
, _pldpPageSize = Nothing
, _pldpMergeSources = Nothing
, _pldpCallback = Nothing
}
-- | Optional. A sync token, received from a previous response
-- \`next_sync_token\` Provide this to retrieve only the resources changed
-- since the last request. When syncing, all other parameters provided to
-- \`people.listDirectoryPeople\` must match the first call that provided
-- the sync token. More details about sync behavior at
-- \`people.listDirectoryPeople\`.
pldpSyncToken :: Lens' PeopleListDirectoryPeople (Maybe Text)
pldpSyncToken
= lens _pldpSyncToken
(\ s a -> s{_pldpSyncToken = a})
-- | V1 error format.
pldpXgafv :: Lens' PeopleListDirectoryPeople (Maybe Xgafv)
pldpXgafv
= lens _pldpXgafv (\ s a -> s{_pldpXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pldpUploadProtocol :: Lens' PeopleListDirectoryPeople (Maybe Text)
pldpUploadProtocol
= lens _pldpUploadProtocol
(\ s a -> s{_pldpUploadProtocol = a})
-- | Optional. Whether the response should return \`next_sync_token\`. It can
-- be used to get incremental changes since the last request by setting it
-- on the request \`sync_token\`. More details about sync behavior at
-- \`people.listDirectoryPeople\`.
pldpRequestSyncToken :: Lens' PeopleListDirectoryPeople (Maybe Bool)
pldpRequestSyncToken
= lens _pldpRequestSyncToken
(\ s a -> s{_pldpRequestSyncToken = a})
-- | OAuth access token.
pldpAccessToken :: Lens' PeopleListDirectoryPeople (Maybe Text)
pldpAccessToken
= lens _pldpAccessToken
(\ s a -> s{_pldpAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pldpUploadType :: Lens' PeopleListDirectoryPeople (Maybe Text)
pldpUploadType
= lens _pldpUploadType
(\ s a -> s{_pldpUploadType = a})
-- | Required. A field mask to restrict which fields on each person are
-- returned. Multiple fields can be specified by separating them with
-- commas. Valid values are: * addresses * ageRanges * biographies *
-- birthdays * calendarUrls * clientData * coverPhotos * emailAddresses *
-- events * externalIds * genders * imClients * interests * locales *
-- locations * memberships * metadata * miscKeywords * names * nicknames *
-- occupations * organizations * phoneNumbers * photos * relations *
-- sipAddresses * skills * urls * userDefined
pldpReadMask :: Lens' PeopleListDirectoryPeople (Maybe GFieldMask)
pldpReadMask
= lens _pldpReadMask (\ s a -> s{_pldpReadMask = a})
-- | Required. Directory sources to return.
pldpSources :: Lens' PeopleListDirectoryPeople [PeopleListDirectoryPeopleSources]
pldpSources
= lens _pldpSources (\ s a -> s{_pldpSources = a}) .
_Default
. _Coerce
-- | Optional. A page token, received from a previous response
-- \`next_page_token\`. Provide this to retrieve the subsequent page. When
-- paginating, all other parameters provided to
-- \`people.listDirectoryPeople\` must match the first call that provided
-- the page token.
pldpPageToken :: Lens' PeopleListDirectoryPeople (Maybe Text)
pldpPageToken
= lens _pldpPageToken
(\ s a -> s{_pldpPageToken = a})
-- | Optional. The number of people to include in the response. Valid values
-- are between 1 and 1000, inclusive. Defaults to 100 if not set or set to
-- 0.
pldpPageSize :: Lens' PeopleListDirectoryPeople (Maybe Int32)
pldpPageSize
= lens _pldpPageSize (\ s a -> s{_pldpPageSize = a})
. mapping _Coerce
-- | Optional. Additional data to merge into the directory sources if they
-- are connected through verified join keys such as email addresses or
-- phone numbers.
pldpMergeSources :: Lens' PeopleListDirectoryPeople [PeopleListDirectoryPeopleMergeSources]
pldpMergeSources
= lens _pldpMergeSources
(\ s a -> s{_pldpMergeSources = a})
. _Default
. _Coerce
-- | JSONP
pldpCallback :: Lens' PeopleListDirectoryPeople (Maybe Text)
pldpCallback
= lens _pldpCallback (\ s a -> s{_pldpCallback = a})
instance GoogleRequest PeopleListDirectoryPeople
where
type Rs PeopleListDirectoryPeople =
ListDirectoryPeopleResponse
type Scopes PeopleListDirectoryPeople =
'["https://www.googleapis.com/auth/directory.readonly"]
requestClient PeopleListDirectoryPeople'{..}
= go _pldpSyncToken _pldpXgafv _pldpUploadProtocol
_pldpRequestSyncToken
_pldpAccessToken
_pldpUploadType
_pldpReadMask
(_pldpSources ^. _Default)
_pldpPageToken
_pldpPageSize
(_pldpMergeSources ^. _Default)
_pldpCallback
(Just AltJSON)
peopleService
where go
= buildClient
(Proxy :: Proxy PeopleListDirectoryPeopleResource)
mempty
|
brendanhay/gogol
|
gogol-people/gen/Network/Google/Resource/People/People/ListDirectoryPeople.hs
|
mpl-2.0
| 10,438
| 0
| 22
| 2,305
| 1,272
| 747
| 525
| 177
| 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.Logging.Projects.Sinks.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Lists sinks.
--
-- /See:/ <https://cloud.google.com/logging/docs/ Cloud Logging API Reference> for @logging.projects.sinks.list@.
module Network.Google.Resource.Logging.Projects.Sinks.List
(
-- * REST Resource
ProjectsSinksListResource
-- * Creating a Request
, projectsSinksList
, ProjectsSinksList
-- * Request Lenses
, pslParent
, pslXgafv
, pslUploadProtocol
, pslAccessToken
, pslUploadType
, pslPageToken
, pslPageSize
, pslCallback
) where
import Network.Google.Logging.Types
import Network.Google.Prelude
-- | A resource alias for @logging.projects.sinks.list@ method which the
-- 'ProjectsSinksList' request conforms to.
type ProjectsSinksListResource =
"v2" :>
Capture "parent" Text :>
"sinks" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "pageToken" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListSinksResponse
-- | Lists sinks.
--
-- /See:/ 'projectsSinksList' smart constructor.
data ProjectsSinksList =
ProjectsSinksList'
{ _pslParent :: !Text
, _pslXgafv :: !(Maybe Xgafv)
, _pslUploadProtocol :: !(Maybe Text)
, _pslAccessToken :: !(Maybe Text)
, _pslUploadType :: !(Maybe Text)
, _pslPageToken :: !(Maybe Text)
, _pslPageSize :: !(Maybe (Textual Int32))
, _pslCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsSinksList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pslParent'
--
-- * 'pslXgafv'
--
-- * 'pslUploadProtocol'
--
-- * 'pslAccessToken'
--
-- * 'pslUploadType'
--
-- * 'pslPageToken'
--
-- * 'pslPageSize'
--
-- * 'pslCallback'
projectsSinksList
:: Text -- ^ 'pslParent'
-> ProjectsSinksList
projectsSinksList pPslParent_ =
ProjectsSinksList'
{ _pslParent = pPslParent_
, _pslXgafv = Nothing
, _pslUploadProtocol = Nothing
, _pslAccessToken = Nothing
, _pslUploadType = Nothing
, _pslPageToken = Nothing
, _pslPageSize = Nothing
, _pslCallback = Nothing
}
-- | Required. The parent resource whose sinks are to be listed:
-- \"projects\/[PROJECT_ID]\" \"organizations\/[ORGANIZATION_ID]\"
-- \"billingAccounts\/[BILLING_ACCOUNT_ID]\" \"folders\/[FOLDER_ID]\"
pslParent :: Lens' ProjectsSinksList Text
pslParent
= lens _pslParent (\ s a -> s{_pslParent = a})
-- | V1 error format.
pslXgafv :: Lens' ProjectsSinksList (Maybe Xgafv)
pslXgafv = lens _pslXgafv (\ s a -> s{_pslXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pslUploadProtocol :: Lens' ProjectsSinksList (Maybe Text)
pslUploadProtocol
= lens _pslUploadProtocol
(\ s a -> s{_pslUploadProtocol = a})
-- | OAuth access token.
pslAccessToken :: Lens' ProjectsSinksList (Maybe Text)
pslAccessToken
= lens _pslAccessToken
(\ s a -> s{_pslAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pslUploadType :: Lens' ProjectsSinksList (Maybe Text)
pslUploadType
= lens _pslUploadType
(\ s a -> s{_pslUploadType = a})
-- | Optional. If present, then retrieve the next batch of results from the
-- preceding call to this method. pageToken must be the value of
-- nextPageToken from the previous response. The values of other method
-- parameters should be identical to those in the previous call.
pslPageToken :: Lens' ProjectsSinksList (Maybe Text)
pslPageToken
= lens _pslPageToken (\ s a -> s{_pslPageToken = a})
-- | Optional. The maximum number of results to return from this request.
-- Non-positive values are ignored. The presence of nextPageToken in the
-- response indicates that more results might be available.
pslPageSize :: Lens' ProjectsSinksList (Maybe Int32)
pslPageSize
= lens _pslPageSize (\ s a -> s{_pslPageSize = a}) .
mapping _Coerce
-- | JSONP
pslCallback :: Lens' ProjectsSinksList (Maybe Text)
pslCallback
= lens _pslCallback (\ s a -> s{_pslCallback = a})
instance GoogleRequest ProjectsSinksList where
type Rs ProjectsSinksList = ListSinksResponse
type Scopes ProjectsSinksList =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only",
"https://www.googleapis.com/auth/logging.admin",
"https://www.googleapis.com/auth/logging.read"]
requestClient ProjectsSinksList'{..}
= go _pslParent _pslXgafv _pslUploadProtocol
_pslAccessToken
_pslUploadType
_pslPageToken
_pslPageSize
_pslCallback
(Just AltJSON)
loggingService
where go
= buildClient
(Proxy :: Proxy ProjectsSinksListResource)
mempty
|
brendanhay/gogol
|
gogol-logging/gen/Network/Google/Resource/Logging/Projects/Sinks/List.hs
|
mpl-2.0
| 5,973
| 0
| 18
| 1,398
| 894
| 520
| 374
| 127
| 1
|
{-# LANGUAGE OverloadedStrings #-}
import Prelude hiding (lookup)
import Test.HUnit
import Cortex.Common.Testing
import Cortex.Miranda.ValueTree
import qualified Cortex.Miranda.Commit as C
-----
-- Insert/delete tests.
test0 :: Test
test0 = runInIOStateError $ do
a <- C.delete "moo"
return $ assertBool "" $ (==)
empty
(delete "a" $ insert "a" a empty)
test1 :: Test
test1 = runInIOStateError $ do
a <- C.delete "moo"
b <- C.delete "moo"
return $ assertBool "" $ (==)
empty
(delete "a" $ delete "a::b" $ insert "a::b" a $ insert "a" b empty)
test2 :: Test
test2 = runInIOStateError $ do
a <- C.delete "moo"
b <- C.delete "moo"
return $ assertBool "" $ (==)
empty
(delete "a::b" $ delete "a" $ insert "a::b" a $ insert "a" b empty)
test3 :: Test
test3 = runInIOStateError $ do
a <- C.delete "moo"
b <- C.delete "moo"
return $ assertBool "" $ (==)
(insert "a" b empty)
(delete "a::b" $ insert "a::b" a $ insert "a" b empty)
test4 :: Test
test4 = runInIOStateError $ do
a <- C.delete "moo"
b <- C.delete "moo"
return $ assertBool "" $ (==)
(insert "a::b" a empty)
(delete "a" $ insert "a::b" a $ insert "a" b empty)
-----
-----
-- Lookup tests.
test5 :: Test
test5 = runInIOStateError $ do
a <- C.set "a" "b"
v <- lookup "a" $ insert "a::b" a empty
return $ assertBool "" $ (==) Nothing v
test6 :: Test
test6 = runInIOStateError $ do
a <- C.set "a" "b"
v <- lookup "a::b::c" $ insert "a::b" a empty
return $ assertBool "" $ (==) Nothing v
test7 :: Test
test7 = runInIOStateError $ do
a <- C.set "a" "b"
v <- lookup "a::b" $ insert "a::b" a empty
return $ assertBool "" $ (==) (Just "b") v
test8 :: Test
test8 = runInIOStateError $ do
a <- C.set "a" "b"
b <- C.set "b" "c"
v <- lookup "a:b" $ insert "a::b" a $ insert "a:b" b empty
return $ assertBool "" $ (==) (Just "c") v
test9 :: Test
test9 = runInIOStateError $ do
a <- C.set "a" "b"
b <- C.set "b" "c"
v <- lookupAll "x" $ insert "x::a:b" a $ insert "a::b" b empty
return $ assertBool "" $ (==) [("a:b", "b")] v
test10 :: Test
test10 = runInIOStateError $ do
a <- C.set "a" "b"
v <- lookup "" $ insert "" a empty
return $ assertBool "" $ (==) (Just "b") v
test11 :: Test
test11 = runInIOStateError $ do
a <- C.set "a" "b"
b <- C.set "b" "c"
v <- lookupAllWhere "x" (\_ v -> v == "b") $
insert "x::a:b" a $ insert "x::b" b empty
return $ assertBool "" $ (==) [("a:b", "b")] v
test12 :: Test
test12 = runInIOStateError $ do
a <- C.set "a" "b"
b <- C.set "b" "c"
v <- lookupAllWhere "x" (\k _ -> k == "a:b") $
insert "x::a:b" a $ insert "x::b" b empty
return $ assertBool "" $ (==) [("a:b", "b")] v
test13 :: Test
test13 = runInIOStateError $ do
a <- C.set "a" "b"
v <- lookupHash "a" $ insert "a" a empty
return $ assertBool "" $ (==)
(Just "e9d71f5ee7c92d6dc9e92ffdad17b8bd49418f98")
v
test14 :: Test
test14 = runInIOStateError $ do
a <- C.set "ala::ma" "kota"
b <- C.set "host::is" "online"
c <- C.delete "ala::ma"
let vt = apply c $ apply b $ apply a $ empty
v <- lookupAll "" vt
return $ assertBool "" $ (==) 1 (length v)
-----
-----
-- Commit application tests.
test15 :: Test
test15 = runInIOStateError $ do
a <- C.set "a" "a"
b <- C.set "b" "b"
c <- C.delete "b"
return $ assertBool "" $ (==)
(insert "a" a empty)
(apply c $ apply b $ apply a empty)
-----
tests :: Test
tests = TestList
[ test0
, test1
, test2
, test3
, test4
, test5
, test6
, test7
, test8
, test9
, test10
, test11
, test12
, test13
, test14
, test15
]
main :: IO Counts
main = runTestTT tests
|
maarons/Cortex
|
Miranda/test/ValueTree_Test.hs
|
agpl-3.0
| 3,864
| 0
| 14
| 1,113
| 1,596
| 779
| 817
| 129
| 1
|
module Tests.HighHock.Inst where
import qualified Network.HighHock.Controller as C
import Control.Exception (SomeException)
instance Show C.Controller where
show c = "Controller _"
instance Eq SomeException where
(==) a b = show a == show b
|
bluepeppers/highhockwho
|
tests/Tests/HighHock/Inst.hs
|
agpl-3.0
| 249
| 0
| 7
| 41
| 74
| 42
| 32
| 7
| 0
|
data Foo = Bar
{ fooz :: Baz
, bar :: Bizzz
}
deriving Show
|
lspitzner/brittany
|
data/Test49.hs
|
agpl-3.0
| 69
| 0
| 8
| 24
| 25
| 15
| 10
| 4
| 0
|
-- stolen from http://www.haskell.org/haskellwiki/The_Fibonacci_sequence
fib 0 = 0
fib 1 = 1
fib n | even n = f1 * (f1 + 2 * f2)
| n `mod` 4 == 1 = (2 * f1 + f2) * (2 * f1 - f2) + 2
| otherwise = (2 * f1 + f2) * (2 * f1 - f2) - 2
where k = n `div` 2
f1 = fib k
f2 = fib (k-1)
-- stolen from http://projecteuler.net/index.php?section=forum&id=20
countDigits :: Integer -> Integer
countDigits 0 = 0
countDigits n = 1 + countDigits (n `div` 10)
--tec 517-721-2837
-- We are one off because testLT only graps the one just before it
-- finds the number of digits
problem25 n = (1 +) $ length $ takeWhile (testLT (n - 1)) $ map (fib ) [ 1..]
where testLT = (\ n x -> ( (countDigits x) <= n ))
|
nmarshall23/Programming-Challenges
|
project-euler/025/25.hs
|
unlicense
| 745
| 0
| 12
| 208
| 300
| 160
| 140
| 13
| 1
|
{- Copyright 2014 David Farrell <shokku.ra@gmail.com>
- 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 IRC.Server.Client where
import System.IO (Handle)
data Client = Client
{ uid :: Maybe Int
, handle :: Maybe Handle
, nick :: Maybe String
, user :: Maybe String
, realName :: Maybe String
, host :: Maybe String
, channels :: [String]
, registered :: Bool
, quitReason :: Maybe String
} deriving (Show)
defaultClient :: Client
defaultClient = Client
{ uid = Nothing
, handle = Nothing
, nick = Nothing
, user = Nothing
, realName = Nothing
, host = Nothing
, channels = []
, registered = False
, quitReason = Nothing
}
|
shockkolate/lambdircd
|
src.old/IRC/Server/Client.hs
|
apache-2.0
| 1,335
| 0
| 9
| 410
| 180
| 110
| 70
| 24
| 1
|
module Stampede.Router where
import Control.Distributed.Process
import Control.Monad.State
import Control.Monad
import qualified Data.Map as M
import Stampede.Types
import Stampede.Utils
import Stampede.SubscriptionNode
-- Process that routes requests to a given node
router :: Process ()
router = do
getSelfPid >>= register "stampede.router"
go (RoutingTable $ M.fromList [])
where go :: RoutingTable -> Process ()
go state = do
newState <- receiveWait [ matchState state handleLookup
]
go newState
handleLookup :: (Destination, ProcessId) -> Action RoutingTable
handleLookup (dst, req) = do
(RoutingTable rt) <- get
let node = M.lookup dst rt
maybe spawnAndForwardToNode forwardToNode node
where spawnAndForwardToNode :: Action RoutingTable
spawnAndForwardToNode = do
sub <- lift $ do
pid <- spawnLocal $ subscriptionNode dst
monitor pid
send req pid
return pid
modify (\(RoutingTable rt) -> (RoutingTable $ M.insert dst sub rt))
forwardToNode :: SubscriptionNodeId -> Action RoutingTable
forwardToNode pid = lift $ send req pid
|
lucasdicioccio/stampede
|
Stampede/Router.hs
|
apache-2.0
| 1,307
| 0
| 15
| 418
| 336
| 167
| 169
| 31
| 1
|
module External.A059450 (a059450) where
import Helpers.ChessSequences (chessMoveCounter, queenN, queenSW)
import Helpers.Table (tableByAntidiagonals)
a059450 :: Integer -> Integer
a059450 n = a059450T (n' + 1) (k' + 1) where
(n', k') = tableByAntidiagonals n
-- Longest chain is given by A094727.
-- King analog: A009766
a059450T :: Integer -> Integer -> Integer
a059450T = chessMoveCounter visibleCells where
visibleCells n k = concatMap (\f -> f n k) [queenN, queenSW]
|
peterokagey/haskellOEIS
|
src/External/A059450.hs
|
apache-2.0
| 482
| 0
| 10
| 79
| 149
| 83
| 66
| 9
| 1
|
module Staircase.A282574Spec (main, spec) where
import Test.Hspec
import Staircase.A282574 (a282574)
main :: IO ()
main = hspec spec
spec :: Spec
spec = describe "A282574" $
it "correctly computes the first 20 elements" $
take 20 (map a282574 [1..]) `shouldBe` expectedValue where
expectedValue = [1,0,1,3,5,2,3,0,1,7,9,2,3,0,1,6,11,17,1,15]
|
peterokagey/haskellOEIS
|
test/Staircase/A282574Spec.hs
|
apache-2.0
| 356
| 0
| 10
| 59
| 160
| 95
| 65
| 10
| 1
|
module Week1 where
f [] = []
f (x:xs) = f ys ++ [x] ++ f zs
where
ys = [a | a <- xs, a <= x]
zs = [b | b <- xs, b > x]
main :: IO ()
main = putStrLn "Week1"
|
dnvriend/study-category-theory
|
funprog/C9_Functional_Programming_Fundamentals/Week1/quicksort.hs
|
apache-2.0
| 208
| 0
| 9
| 97
| 116
| 61
| 55
| 7
| 1
|
module Problem33 where
import Data.List
main :: IO ()
main =
print
. (\(a, b) -> b `div` gcd a b)
. foldl1 (\(a, b) (c, d) -> (a * c, b * d))
$ [ (a, b) | a <- [10 .. 99], b <- [10 .. 99], a < b, special a b ]
special :: Int -> Int -> Bool
-- a/b = a''/b''
special a b = (length c == 1) && a * b'' == b * a'' && a `mod` 10 /= 0 && b `mod` 10 /= 0
where
a' = show a
b' = show b
c = a' `intersect` b'
a'' = read $ a' \\ c
b'' = read $ b' \\ c
|
adityagupta1089/Project-Euler-Haskell
|
src/problems/Problem33.hs
|
bsd-3-clause
| 498
| 0
| 17
| 180
| 287
| 160
| 127
| 15
| 1
|
module Problems.Problem5 where
import qualified Data.HashMap.Strict as HashMap
import Data.Maybe
getSolution :: Int
getSolution = HashMap.foldlWithKey' (\t p c -> t * (p ^ c)) 1 m
where
m = requiredPrimes [2 .. 20]
requiredPrimes :: [Int] -> HashMap.HashMap Int Int
requiredPrimes l = foldr (HashMap.unionWith max) HashMap.empty maps
where
maps = map requiredPrimesImpl l
requiredPrimesImpl :: Int -> HashMap.HashMap Int Int
requiredPrimesImpl n = HashMap.fromListWith (+) [ (p, 1) | p <- primes ]
where
primes = findPrimeFactors n
findPrimeFactors :: Int -> [Int]
findPrimeFactors n = case firstDivisor n of
Nothing -> [n]
Just d -> concat $ map findPrimeFactors [d, n `quot` d]
firstDivisor :: Int -> Maybe Int
firstDivisor n = listToMaybe $ filter f [2 .. maxVal]
where
maxVal = (floor . sqrt . fromIntegral) n
f :: Int -> Bool
f d = n `mod` d == 0
|
sarangj/eulerhs
|
src/Problems/Problem5.hs
|
bsd-3-clause
| 902
| 0
| 11
| 194
| 343
| 185
| 158
| 21
| 2
|
--------------------------------------------------------------------------------
-- |
-- Module : Data.BitVector.BitVector3
-- Copyright : (c) 2010 Philip Weaver
-- License : BSD3
--
-- Maintainer : philip.weaver@gmail.com
-- Stability : provisional
-- Portability : Haskell 98
--
-- (Description)
--------------------------------------------------------------------------------
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ViewPatterns #-}
module Data.BitVector.BitVector3 where
import Prelude hiding (replicate, not, (&&), (||), Eq, Ord, and, or,
(==), (/=), (>), (<), (>=), (<=), min, max, length)
import qualified Prelude
import Data.Bits hiding (setBit)
import qualified Data.Bits as Bits
import Data.Generics ( Data, Typeable )
import Data.Bit as Bit
import Data.BitVector.Util
import Data.BitVector.UtilBE
import Data.Boolean as Boolean
import Data.Compare
----------------------------------------
{- TODO
- support range instead of width
- check for invalid inputs to some functions
- hide internal representation (do not export it)
-}
{-
abit | bbit | value
0 | 0 | 0
1 | 0 | 1
1 | 1 | X
0 | 1 | Z
-}
-- using Integer as the type for abits and bbits means
-- that BitVector widths are unbounded, yay!
type BV_Word = Integer
-- index of MSB, index of LSB, a-bits, b-bits.
data BitVector
= Bits !Int ![Bit]
| BV !Int !BV_Word !BV_Word
deriving (Prelude.Ord, Data, Typeable)
instance Show BitVector where
show = showBitVector showBit
showBit :: Bit -> Char
showBit F = '0'
showBit T = '1'
showBit U = 'X'
showBit Z = 'Z'
showBitVector :: (Bit -> Char) -> BitVector -> String
showBitVector f bv
| w == 0 = [f F]
| otherwise = [ f (bv ! i) | i <- [w-1, w-2..0] ]
where
w = length bv
----------------------------------------
-- internal utility functions
-- {-# INLINE convertToBit #-}
convertToBit :: (Bool, Bool) -> Bit
convertToBit (False, False) = F
convertToBit (True, False) = T
convertToBit (True, True) = U
convertToBit (False, True) = Z
{-# INLINE isKnown #-}
isKnown :: BitVector -> Bool
isKnown (Bits _ xs) = all Bit.isKnown xs
isKnown (BV _ _ b) = b == 0
-- {-# INLINE setBit #-}
setBit :: BitVector -> Int -> Bit -> BitVector
setBit (Bits w zs) i x
= let (as, _:bs) = splitAt (w-i) zs
in Bits w (as Prelude.++ [x] Prelude.++ bs)
setBit (BV w a b) i x
= BV w (setBitA a i x) (setBitB b i x)
-- {-# INLINE setBitA #-}
setBitA :: BV_Word -> Int -> Bit -> BV_Word
setBitA a i x
= if a_bit x then Bits.setBit a i else Bits.clearBit a i
-- {-# INLINE setBitB #-}
setBitB :: BV_Word -> Int -> Bit -> BV_Word
setBitB b i x
= if b_bit x then Bits.setBit b i else Bits.clearBit b i
-- {-# INLINE a_bit #-}
a_bit :: Bit -> Bool
a_bit = flip elem [T, U]
-- a_bit b = b == T || b == U
-- a_bit = flip testBit 0 . fromEnum
-- {-# INLINE b_bit #-}
b_bit :: Bit -> Bool
b_bit = flip elem [Z, U]
-- b_bit b = b == Z || b == U
-- b_bit = flip testBit 1 . fromEnum
----------------------------------------
-- initialization
empty :: BitVector
empty = BV 0 0 0
singleton :: Bit -> BitVector
--singleton b = Bits [b]
singleton F = BV 1 0 0
singleton T = BV 1 1 0
singleton U = BV 1 1 1
singleton Z = BV 1 0 1
replicate :: Int -> Bit -> BitVector
replicate n F = BV n 0 0
replicate n T = BV n (2^n-1) 0
replicate n U = BV n (2^n-1) (2^n-1)
replicate n Z = BV n 0 (2^n-1)
low, high, unknown :: Int -> BitVector
low = flip replicate F
high = flip replicate T
unknown = flip replicate U
----------------------------------------
-- conversion
fromBits, fromBitsBE, fromBitsLE :: [Bit] -> BitVector
fromBits xs = Bits (Prelude.length xs) xs
fromBitsBE = fromBits
fromBitsLE = fromBits . Prelude.reverse
toBits, toBitsBE, toBitsLE :: BitVector -> [Bit]
toBits = toBitsBE
toBitsBE (Bits _ xs) = xs
toBitsBE (BV w a b) = [ convertToBit (testBit a i, testBit b i)
| i <- [w-1, w-2..0]
]
toBitsLE (Bits _ xs) = Prelude.reverse xs
toBitsLE (BV w a b) = [ convertToBit (testBit a i, testBit b i)
| i <- [0..w-1]
]
toNum :: (Num a, Bits a) => BitVector -> Maybe a
toNum (Bits _ zs)
= bitsToNum zs
toNum (BV _ a b)
= if b == 0
then Just (fromIntegral a) -- (maskWidth w a)
else Nothing
-- maskWidth makes this pretty slow
fromNum :: (Integral a) => Int -> a -> BitVector
fromNum w x
-- = BV w (fromIntegral x) 0
| w <= 0 = BV 0 0 0
| otherwise = BV w (maskWidth w (fromIntegral x)) 0
coerceToWord :: BitVector -> BitVector
coerceToWord v@BV {} = v
coerceToWord (Bits w xs)
= BV w a'' b''
where
(a'', b'') = f (w - 1) 0 0 xs
f _ a b [] = (a, b)
f i a b (y:ys) = let a' = setBitA (a*2) 0 y
b' = setBitB (b*2) 0 y
in a' `seq` b' `seq` f (i-1) a' b' ys
coerceToBits :: BitVector -> BitVector
coerceToBits v = Bits (length v) (toBits v)
----------------------------------------
-- length information
{-# INLINE length #-}
length :: BitVector -> Int
length (Bits w _) = w
length (BV w _ _) = w
{-# INLINE null #-}
null :: BitVector -> Bool
null = (==0) . length
----------------------------------------
-- map and fold functions
-- these have pretty terrible performance,
-- and should be avoided whenever possible.
-- for example, bv_and is ridiculously faster than bv_map2 (&&)
{-
bv_map :: (Bit -> Bit) -> BitVector -> BitVector
bv_map f v
= BV (length v) a b
where
w = length v
(a, b) = foldl' g (0, 0) [0..w-1]
g (a, b) i = let x = f (indexR v i)
a' = if a_bit x then Bits.setBit a i else a
b' = if b_bit x then Bits.setBit b i else b
in (a', b')
bv_map2 :: (Bit -> Bit -> Bit) -> BitVector -> BitVector -> BitVector
bv_map2 f v0 v1
= BV w a b
where
w = max (length v0) (length v1)
(a, b) = foldl' g (0, 0) [0..w-1]
g (a, b) i = let x = f (indexR v0 i) (indexR v1 i)
a' = if a_bit x then Bits.setBit a i else a
b' = if b_bit x then Bits.setBit b i else b
in (a', b')
bv_foldl :: (a -> Bit -> a) -> a -> BitVector -> a
bv_foldl f x v
= g x 0
where
w = length v
g y i | i == w = y
| otherwise = g (f y (indexR v i)) (i+1)
-}
----------------------------------------
-- structural operations
-- index, resizing, concatenation, shift, rotate
resize :: Int -> BitVector -> BitVector
resize n (Bits w xs)
| n < w = Bits n (drop (w-n) xs)
| otherwise = Bits n (Prelude.replicate (n-w) F Prelude.++ xs)
resize n (BV w a b)
| n < w = BV n (maskWidth n a) (maskWidth n b)
| otherwise = BV n a b
-- = BV n (maskWidth w a) (maskWidth w b)
-- = BV n a b
-- = BV n (maskWidth i a) (maskWidth i b)
-- where
-- i = min n w
-- sign-extend out to 'n' bits.
-- note that this will fail if n < w
signExtend :: Int -> BitVector -> BitVector
signExtend n (Bits w xs)
= Bits n (Prelude.replicate (n-w) msb Prelude.++ xs)
where
msb = case xs of
[] -> F
(x:_) -> noZ x
signExtend n (BV w a b)
= BV n (signExtend' w n a) (signExtend' w n b)
signExtend' :: Int -> Int -> BV_Word -> BV_Word
signExtend' n n' x
= if testBit x (n-1)
then x .|. Bits.shiftL (2^(n'-n)-1) n
else x
reverse :: BitVector -> BitVector
reverse (Bits w xs) = Bits w (Prelude.reverse xs)
reverse (BV w a b) = BV w a' b'
where
a' = f (w-1) a 0
b' = f (w-1) b 0
f 0 x y = if testBit x (w-1) then Bits.setBit y 0 else y
f n x y = let y' = if testBit x (w-n-1) then Bits.setBit y n else y
in y' `seq` f (n-1) x y'
(++), append :: BitVector -> BitVector -> BitVector
(++) = append
append (BV w0 a0 b0) (BV w1 a1 b1)
= BV (w0 + w1) (Bits.shiftL a0 w1 .|. a1) (Bits.shiftL b0 w1 .|. b1)
append v0 v1
= Bits w (xs0 Prelude.++ xs1)
where
w = length v0 + length v1
xs0 = toBits v0
xs1 = toBits v1
concat :: [BitVector] -> BitVector
concat = foldr append empty
(!), indexR, indexL :: BitVector -> Int -> Bit
(!) = indexR
indexR (Bits w xs) i = xs !! (w-i-1)
indexR (BV _ a b) i = convertToBit (testBit a i, testBit b i)
indexL v i = indexR v (length v - i - 1)
takeL :: Int -> BitVector -> BitVector
takeL i (Bits _ xs)
= Bits i (take i xs)
takeL i (BV w a b)
= BV i (Bits.shiftR a (w-i)) (Bits.shiftR b (w-i))
takeR :: Int -> BitVector -> BitVector
takeR i (Bits w xs)
= Bits i (drop (w-i) xs)
takeR i (BV _ a b)
= BV i (maskWidth i a) (maskWidth i b)
dropL :: Int -> BitVector -> BitVector
dropL i (Bits w xs)
= Bits (w-i) (drop i xs)
dropL i (BV w a b)
= BV (w-i) (maskWidth (w-i) a) (maskWidth (w-i) b)
dropR :: Int -> BitVector -> BitVector
dropR i (Bits w xs)
= Bits (w-i) (take (w-i) xs)
dropR i (BV w a b)
= BV (w-i) (Bits.shiftR a i) (Bits.shiftR b i)
-- start at index 'start' and count down for 'len' total bits.
slice :: Int -> Int -> BitVector -> BitVector
slice start len (Bits w xs)
= Bits len (take len $ drop (w - start - 1) xs)
slice start len (BV _ a b)
= BV len (Bits.shiftR a (start - len + 1))
(Bits.shiftR b (start - len + 1))
shiftL :: BitVector -> Int -> BitVector
shiftL (Bits w xs) i
= Bits w (drop i xs Prelude.++ Prelude.replicate (min i w) F)
shiftL (BV w a b) i
= BV w (maskWidth w a') (maskWidth w b')
where
a' = Bits.shiftL a i
b' = Bits.shiftL b i
shiftR :: BitVector -> Int -> BitVector
shiftR (Bits w xs) i
= Bits w (Prelude.replicate (min i w) F Prelude.++ take (w-i) xs)
shiftR (BV w a b) i
= BV w a' b'
where
a' = Bits.shiftR a i
b' = Bits.shiftR b i
-- we can't use Bits.rotate to implement rotate because we use unbounded
-- Integer to represent the bitvector, so rotate just behaves like a shift
rotateL :: BitVector -> Int -> BitVector
rotateL (Bits w xs) (flip mod w -> i)
= Bits w (drop i xs Prelude.++ take i xs)
rotateL (BV w a b) (flip mod w -> i)
= BV w (maskWidth w a') (maskWidth w b')
where
a' = (a `Bits.shiftR` (w-i)) .|. (a `Bits.shiftL` i)
b' = (b `Bits.shiftR` (w-i)) .|. (b `Bits.shiftL` i)
rotateR :: BitVector -> Int -> BitVector
rotateR (Bits w xs) (flip mod w -> i)
= Bits w (drop (w-i) xs Prelude.++ take (w-i) xs)
rotateR (BV w a b) (flip mod w -> i)
= BV w (maskWidth w a') (maskWidth w b')
where
a' = (a `Bits.shiftR` i) .|. (a `Bits.shiftL` (w-i))
b' = (b `Bits.shiftR` i) .|. (b `Bits.shiftL` (w-i))
----------------------------------------
-- bitwise boolean operations, both binary and unary
-- these functions can all be defined in terms of bv_map, bv_map2 or bv_fold,
-- but the specialized versions below are ridiculously faster.
-- some functions perform operations (like complement) that can cause
-- bits beyond the MSB to be set. in those cases, we must call maskWidth
-- to set those bits back to 0.
-- it would be cool if we had a function written in Template Haskell
-- that took a truth table and synthesized a function that used Data.Bits,
-- and then use that to define all of the functions below.
-- for the bitwise binary operators, if one argument is in bits form and the
-- other is in words form, then which one should we coerce to?
instance Boolean BitVector where
false = singleton false
true = singleton true
isTrue = isTrue . flip indexR 0
isFalse = isFalse . flip indexR 0
not = bv_not
(&&) = bv_and
(||) = bv_or
xor = bv_xor
nor = bv_nor
xnor = bv_xnor
nand = bv_nand
bv_not :: BitVector -> BitVector
bv_not (Bits w xs)
= Bits w (map not xs)
bv_not (BV w a b)
= BV w (maskWidth w a') b
where
a' = complement a .|. b
bv_and :: BitVector -> BitVector -> BitVector
bv_and (BV w0 a0 b0) (BV w1 a1 b1)
= BV w a b
where
w = max w0 w1
a = (a0 .|. b0) .&. (a1 .|. b1)
-- b = (b0 .&. (a1 .|. b1)) .|. (b1 .&. (a0 .|. b0))
b = (b0 .|. b1) .&. (a0 .|. b0) .&. (a1 .|. b1)
bv_and (coerceToBits -> Bits w0 xs0) (coerceToBits -> Bits w1 xs1)
= Bits w (zipWith (&&) xs0' xs1')
where
w = max w0 w1
xs0' = Prelude.replicate (w - w0) F Prelude.++ xs0
xs1' = Prelude.replicate (w - w1) F Prelude.++ xs1
bv_and _ _
= error "bv_and"
bv_or :: BitVector -> BitVector -> BitVector
bv_or (BV w0 a0 b0) (BV w1 a1 b1)
= BV w a (maskWidth w b)
where
w = max w0 w1
a = a0 .|. b0 .|. a1 .|. b1
b = (b0 .&. (complement a1 .|. b1)) .|. (b1 .&. (complement a0 .|. b0))
bv_or (coerceToBits -> Bits w0 xs0) (coerceToBits -> Bits w1 xs1)
= Bits w (zipWith (||) xs0' xs1')
where
w = max w0 w1
xs0' = Prelude.replicate (w - w0) F Prelude.++ xs0
xs1' = Prelude.replicate (w - w1) F Prelude.++ xs1
bv_or _ _
= error "bv_or"
bv_nor :: BitVector -> BitVector -> BitVector
bv_nor (BV w0 a0 b0) (BV w1 a1 b1)
= BV w (maskWidth w a) (maskWidth w b)
where
w = max w0 w1
a = b .|. (complement a0 .&. complement a1 .&.
complement b0 .&. complement b1)
b = (b0 .&. (complement a1 .|. b1)) .|.
(b1 .&. (complement a0 .|. b0))
bv_nor (coerceToBits -> Bits w0 xs0) (coerceToBits -> Bits w1 xs1)
= Bits w (zipWith nor xs0' xs1')
where
w = max w0 w1
xs0' = Prelude.replicate (w - w0) F Prelude.++ xs0
xs1' = Prelude.replicate (w - w1) F Prelude.++ xs1
bv_nor _ _
= error "bv_nor"
bv_xor :: BitVector -> BitVector -> BitVector
bv_xor (BV w0 a0 b0) (BV w1 a1 b1)
= BV w a b
where
w = max w0 w1
a = (a0 `Bits.xor` a1) .|. b0 .|. b1
b = b0 .|. b1
bv_xor (coerceToBits -> Bits w0 xs0) (coerceToBits -> Bits w1 xs1)
= Bits w (zipWith Boolean.xor xs0' xs1')
where
w = max w0 w1
xs0' = Prelude.replicate (w - w0) F Prelude.++ xs0
xs1' = Prelude.replicate (w - w1) F Prelude.++ xs1
bv_xor _ _
= error "bv_xor"
bv_xnor :: BitVector -> BitVector -> BitVector
bv_xnor (BV w0 a0 b0) (BV w1 a1 b1)
= BV w (maskWidth w a) b
where
w = max w0 w1
a = (complement (a0 `Bits.xor` a1)) .|. b0 .|. b1
b = b0 .|. b1
bv_xnor (coerceToBits -> Bits w0 xs0) (coerceToBits -> Bits w1 xs1)
= Bits w (zipWith xnor xs0' xs1')
where
w = max w0 w1
xs0' = Prelude.replicate (w - w0) F Prelude.++ xs0
xs1' = Prelude.replicate (w - w1) F Prelude.++ xs1
bv_xnor _ _
= error "bv_xnor"
bv_nand :: BitVector -> BitVector -> BitVector
bv_nand (BV w0 a0 b0) (BV w1 a1 b1)
= BV w (maskWidth w a) b
where
w = max w0 w1
a = complement a0 .|. complement a1 .|. b0 .|. b1
b = (b0 .&. (a1 .|. b1)) .|. (b1 .&. (a0 .|. b0))
bv_nand (coerceToBits -> Bits w0 xs0) (coerceToBits -> Bits w1 xs1)
= Bits w (zipWith nand xs0' xs1')
where
w = max w0 w1
xs0' = Prelude.replicate (w - w0) F Prelude.++ xs0
xs1' = Prelude.replicate (w - w1) F Prelude.++ xs1
bv_nand _ _
= error "bv_nand"
bv_unary_and :: BitVector -> Bit
bv_unary_and (Bits _ xs)
= foldl (&&) T xs
bv_unary_and (BV w a b)
= if b == 0 then fromBool (a == 2^w-1)
else if (maskWidth w (complement a .&. complement b)) /= 0 then F
else U
bv_unary_or :: BitVector -> Bit
bv_unary_or (Bits _ xs)
= foldl (||) F xs
bv_unary_or (BV w a b)
= if b == 0 then fromBool (a /= 0)
else if (maskWidth w (a .&. complement b)) /= 0 then T
else U
bv_unary_nor :: BitVector -> Bit
bv_unary_nor (Bits _ []) = T
bv_unary_nor (Bits _ (x:xs))
= foldl nor x xs
bv_unary_nor (BV w a b)
= if b == 0 then fromBool (a == 0)
else if (maskWidth w (a .&. complement b)) /= 0 then F
else U
bv_unary_xor :: BitVector -> Bit
bv_unary_xor (Bits _ xs)
= foldl Boolean.xor F xs
-- this implementation isn't very efficient, but it's not as bad
-- as just folding xor over 'a':
bv_unary_xor (BV _ a b)
= if b == 0 then fromBool (f a False) else U
where
f 0 r = r
f n r = f (n .&. (n - 1)) (not r)
-- unary_xnor means "all true or all false"
-- if all bits are known and all T or all F, then T.
-- if there are more than one known bit that don't match, then F.
-- FIXME this implementation is inefficient when any bits are unknown
bv_unary_xnor :: BitVector -> Bit
bv_unary_xnor (BV w a b)
| b == 0 = fromBool (a == 0 || a == 2^w-1)
bv_unary_xnor v
= and xs || not (or xs)
where
xs = toBits v
bv_unary_nand :: BitVector -> Bit
bv_unary_nand (Bits _ xs)
= not (foldl (&&) T xs)
bv_unary_nand (BV w a b)
= if b == 0 then fromBool (a /= 2^w-1)
else if (maskWidth w (complement a .&. complement b)) /= 0 then T
else U
----------------------------------------
-- comparision operations
instance Eq BitVector Bit where
(==) = bv_eq
(/=) = bv_neq
instance Eq BitVector BitVector where
(==) x y = singleton (bv_eq x y)
(/=) x y = singleton (bv_neq x y)
instance Prelude.Eq BitVector where
(==) x y = bv_eq_xz x y
(/=) x y = not (bv_eq_xz x y)
instance Compare BitVector where
min = error "TODO min"
max = error "TODO max"
instance Ord BitVector Bit where
(>) = bv_gt
(<) = bv_lt
(>=) = bv_gte
(<=) = bv_lte
instance Ord BitVector BitVector where
(>) x y = singleton (bv_gt x y)
(<) x y = singleton (bv_lt x y)
(>=) x y = singleton (bv_gte x y)
(<=) x y = singleton (bv_lte x y)
bv_eq :: BitVector -> BitVector -> Bit
bv_eq (BV w0 a0 b0) (BV w1 a1 b1)
-- if all bits are known, then a0 == a1
-- else if there are any known bits that are unequal, then False
-- else Unknown.
= if b0 == 0 && b1 == 0 then fromBool (a0 == a1)
else if (maskWidth w (complement b0 .&. complement b1 .&. (Bits.xor a0 a1))) /= 0
then F
else U
where
w = max w0 w1
bv_eq (coerceToBits -> Bits w0 xs0) (coerceToBits -> Bits w1 xs1)
= and (zipWith (==) xs0' xs1')
where
w = max w0 w1
xs0' = Prelude.replicate (w - w0) F Prelude.++ xs0
xs1' = Prelude.replicate (w - w1) F Prelude.++ xs1
bv_eq _ _
= error "bv_eq"
bv_neq :: BitVector -> BitVector -> Bit
bv_neq (BV w0 a0 b0) (BV w1 a1 b1)
-- if all bits are known, then a0 /= a1
-- else if there are any known bits that are not equal, then T
-- else Unknown.
= if b0 == 0 && b1 == 0 then fromBool (a0 /= a1)
else if (maskWidth w (complement b0 .&. complement b1 .&. (Bits.xor a0 a1))) /= 0
then T
else U
where
w = max w0 w1
bv_neq (coerceToBits -> Bits w0 xs0) (coerceToBits -> Bits w1 xs1)
= or (zipWith (/=) xs0' xs1')
where
w = max w0 w1
xs0' = Prelude.replicate (w - w0) F Prelude.++ xs0
xs1' = Prelude.replicate (w - w1) F Prelude.++ xs1
bv_neq _ _
= error "bv_neq"
bv_eq_xz :: BitVector -> BitVector -> Bool
bv_eq_xz (BV _w0 a0 b0) (BV _w1 a1 b1)
= a0 == a1 && b0 == b1
bv_eq_xz (coerceToBits -> Bits w0 xs0) (coerceToBits -> Bits w1 xs1)
= xs0' == xs1'
where
w = max w0 w1
xs0' = Prelude.replicate (w - w0) F Prelude.++ xs0
xs1' = Prelude.replicate (w - w1) F Prelude.++ xs1
bv_eq_xz _ _
= error "bv_eq_xz"
bv_lt :: BitVector -> BitVector -> Bit
bv_lt (BV _ a0 b0) (BV _ a1 b1)
| b0 == 0 && b1 == 0 = fromBool (a0 < a1)
bv_lt v0 v1
= f xs0 xs1
where
w = max (length v0) (length v1)
xs0 = toBits (resize w v0)
xs1 = toBits (resize w v1)
f [] [] = F
f (y:ys) (z:zs) = case (y, z) of
(F, T) -> T
(T, F) -> F
(T, T) -> f ys zs
(F, F) -> f ys zs
_ -> U
f _ _ = error "bv_lt"
bv_lte :: BitVector -> BitVector -> Bit
bv_lte (BV _ a0 b0) (BV _ a1 b1)
| b0 == 0 && b1 == 0 = fromBool (a0 <= a1)
bv_lte v0 v1
= f xs0 xs1
where
w = max (length v0) (length v1)
xs0 = toBits (resize w v0)
xs1 = toBits (resize w v1)
f [] [] = T
f (y:ys) (z:zs) = case (y, z) of
(F, T) -> T
(T, F) -> F
(T, T) -> f ys zs
(F, F) -> f ys zs
_ -> U
f _ _ = error "bv_lte"
bv_gt :: BitVector -> BitVector -> Bit
bv_gt (BV _ a0 b0) (BV _ a1 b1)
| b0 == 0 && b1 == 0 = fromBool (a0 > a1)
bv_gt v0 v1
= f xs0 xs1
where
w = max (length v0) (length v1)
xs0 = toBits (resize w v0)
xs1 = toBits (resize w v1)
f [] [] = F
f (y:ys) (z:zs) = case (y, z) of
(T, F) -> T
(F, T) -> F
(T, T) -> f ys zs
(F, F) -> f ys zs
_ -> U
f _ _ = error "bv_gt"
bv_gte :: BitVector -> BitVector -> Bit
bv_gte (BV _ a0 b0) (BV _ a1 b1)
| b0 == 0 && b1 == 0 = fromBool (a0 >= a1)
bv_gte v0 v1
= f xs0 xs1
where
w = max (length v0) (length v1)
xs0 = toBits (resize w v0)
xs1 = toBits (resize w v1)
f [] [] = T
f (y:ys) (z:zs) = case (y, z) of
(T, F) -> T
(F, T) -> F
(T, T) -> f ys zs
(F, F) -> f ys zs
_ -> U
f _ _ = error "bv_gte"
----------------------------------------
-- arithmetic functions
-- we have three main choices for handling unknowns in arithmetic operations:
-- * yield all unknown (this is what we do now)
-- * perform the operation on the lower known bits,
-- and yield unknown for the upper bits (iverilog does this, so do we)
-- * manually fold a bitwise function across the vector
{-# INLINE arithOp #-}
arithOp :: (BV_Word -> BV_Word -> BV_Word)
-> Int -> Bool -> BitVector -> BitVector -> BitVector
arithOp f w signed v0 v1 = BV w a b
where
n = min (msbIndex w b0) (msbIndex w b1)
b = Bits.shiftL (2^(w-n)-1) n
a = f a0 a1 .&. (2^w-1) .|. b
BV _ a0 b0 = coerceToWord $ if signed then signExtend w v0 else v0
BV _ a1 b1 = coerceToWord $ if signed then signExtend w v1 else v1
instance Num BitVector where
(+) = plus' True
(*) = times' True
(-) = minus' True
-- abs -- TODO
signum v = replicate (length v) $ noZ $ indexL v 0
negate v = bv_not v + 1
fromInteger n
| n < 0 = negate (fromInteger (-n))
| otherwise = BV (neededBits n + 1) n 0
neg :: Int -> BitVector -> BitVector
neg w v
= plus w True (bv_not v) 1
plus' :: Bool -> BitVector -> BitVector -> BitVector
plus' signed v0 v1
= plus w signed v0 v1
where
w = 1 + max (length v0) (length v1)
plus :: Int -> Bool -> BitVector -> BitVector -> BitVector
plus = arithOp (+)
minus' :: Bool -> BitVector -> BitVector -> BitVector
minus' signed v0 v1
= minus w signed v0 v1
where
w = 1 + max (length v0) (length v1)
minus :: Int -> Bool -> BitVector -> BitVector -> BitVector
minus = arithOp (-)
times' :: Bool -> BitVector -> BitVector -> BitVector
times' signed v0 v1
= times w signed v0 v1
where
w = length v0 + length v1
times :: Int -> Bool -> BitVector -> BitVector -> BitVector
times = arithOp (*)
----------------------------------------
|
pheaver/BitVector
|
Data/BitVector/BitVector3.hs
|
bsd-3-clause
| 22,946
| 0
| 15
| 6,529
| 9,027
| 4,719
| 4,308
| 525
| 7
|
{-# LANGUAGE ScopedTypeVariables, OverloadedStrings, FlexibleContexts #-}
module Rubik.Test where
import Control.Applicative
import Data.Text(Text,pack)
import Rubik.Shape
import Rubik.Face
import Rubik.Turn
import Rubik.D3
import Rubik.Cube
import Rubik.Color
import Rubik.Axis
import Rubik.Sign
import Rubik.Key
import Rubik.V2
import Rubik.V3
import Rubik.Abs
import Rubik.Negate as N
import Rubik.Puzzle
import Graphics.Blank (blankCanvas, send, events,wait, eType, eWhich)
import qualified Data.Char as Char
drawCube :: Puzzle Shape -> Shape
drawCube = borderShape 0.1
. drawMap cubePlacement
. fmap (borderShape 0.01)
. drawFace
-- fold a puzzle into a cube of shapes
drawFace :: Puzzle Shape -> Cube Shape
drawFace (Puzzle pz) sd
= background "#202020" 0.01 0.1
$ drawMap (facePlacement sd)
$ fmap (borderShape 0.05)
$ pz sd
facePlacement :: Cube (Face (Int, Int))
facePlacement ax sq@(V2 x0 y0) = case ax of
(Axis X Plus) -> (ny,nx)
(Axis X Minus) -> (y,nx)
(Axis Y Plus) -> (x,y)
(Axis Y Minus) -> (x,ny)
(Axis Z Plus) -> (x,ny)
(Axis Z Minus) -> (nx,ny)
where
nx = loc $ N.negate x0
ny = loc $ N.negate y0
x = loc x0
y = loc y0
loc MinusOne = 0
loc Zero = 1
loc PlusOne = 2
{-
drawFace' :: Cube (Face Shape -> Shape)
drawFace' sd face = background "#202020" 0.01 0.1
$ drawMap (facePlacement'' sd) $
fmap (borderShape 0.05) $ face
drawCube :: Cube Shape -> Shape
drawCube = borderShape 0.1
. drawMap cubePlacement
. fmap (borderShape 0.01)
-}
face' :: Text -> Face Shape
face' col k = tile col `overlay` (text 5 $ show k) `overlay` (case k of
V2 PlusOne PlusOne -> triangle
V2 PlusOne Zero -> circle
_ -> emptyShape)
cube :: Puzzle Shape
cube = f <$> rubik <*> puzzleSide <*> puzzleSquare
where f col sd sq = tile (pack $ showColor $ col)
`overlay`
text 7 (s (mega sd sq))
s (V3 a b c) = show a ++ "\n" ++ show b ++ "\n" ++ show c
rubik :: Puzzle Color
rubik = Puzzle (fmap pure start)
--- blank cube
cube' :: Puzzle Shape
cube' = Puzzle
$ fmap face'
$ fmap (pack . showColor)
$ start
--main = shape (drawFace $ face)
--main = shape (drawFace $ rotateBy Clock $ face "red")
--main = shape (drawCube $ fmap drawFace cube)
main' = shape $ packShapes
[ [ drawCube $ cube ]
, [ drawCube $ rotate (Turn3D t Z) $ cube | t <- universe ]
]
main = blankCanvas 3000 { events = ["keypress"] } $ \ context ->
let loop cube' = do
send context $ drawShape context
$ borderShape 0.1
$ packShapes [ [ drawCube $ cube, drawCube $ cube' ] ]
e <- wait context
print e
if eType e == "keypress"
then case eWhich e of
Just ch -> loop $ keypress (Char.chr ch) cube' cube
_ -> loop cube'
else loop cube'
in loop cube
-- keypress :: a -> a ->
keypress :: Char -> Puzzle a -> Puzzle a -> Puzzle a
keypress 'x' = const . rotate (Turn3D Clock X)
keypress 'y' = const . rotate (Turn3D Clock Y)
keypress 'z' = const . rotate (Turn3D Clock Z)
keypress 'X' = const . rotate (Turn3D CounterClock X)
keypress 'Y' = const . rotate (Turn3D CounterClock Y)
keypress 'Z' = const . rotate (Turn3D CounterClock Z)
keypress ' ' = flip const -- restore original
keypress _ = const -- do nothing
---------------------------------------------------------------------------
-- twist ::
--twist :: Turn3D -> Puzzle a -> Puzzle a
--twist turn@(Turn3d t d) cube =
side :: Turn3D -> Puzzle Bool
side turn@(Turn3D t d) = fmap (\ (V3 x y z) -> True) coord
where coord :: Puzzle Mega
coord = mega <$> puzzleSide <*> puzzleSquare
class Crown c where
crown :: c -> Bool
instance (Negate c, Crown c) => Crown (Axis c) where
crown (Axis c Plus) = crown c
crown (Axis c Minus) = crown (N.negate c)
instance Crown Sign where
crown Plus = True
crown Minus = False
instance Crown Abs where
crown PlusOne = True
crown _ = False
instance Crown Layer where
crown (E sgn) = crown sgn
crown (I abs) = crown abs
crown3D :: Axis D3 -> (Mega -> Bool)
crown3D (Axis X sgn) (V3 x _ _) = crown (Axis x sgn)
crown3D (Axis Y sgn) (V3 _ y _) = crown (Axis y sgn)
crown3D (Axis Z sgn) (V3 _ _ z) = crown (Axis z sgn)
{-
crown :: Sign -> Layer -> Bool
crown sgn (E sgn') = sgn == sgn'
crown sgn (I abs') =
data Layer = E Sign -- -2 or 2
| I Abs -- -1 | 0 | 1
deriving (Eq, Ord, Show)
Minus | Plus
-}
|
andygill/rubik-solver
|
src/Rubik/Test.hs
|
bsd-3-clause
| 5,082
| 0
| 21
| 1,728
| 1,566
| 802
| 764
| 111
| 8
|
module Language.Swift.Quote.Syntax where
data Module = Module [Statement]
deriving (Show, Eq)
data Expression
= Expression (Maybe String) PrefixExpression [BinaryExpression]
deriving (Show, Eq)
data PrefixExpression
= PrefixExpression (Maybe String) {- prefixOperator -} PostfixExpression
| InOutExpression String -- identifier
deriving (Show, Eq)
data IdG = IdG
{ idgIdentifier :: String
, idgGenericArgs :: [Type]
}
deriving (Show, Eq)
data PostfixExpression
= PostfixPrimary PrimaryExpression
| PostfixOperator PostfixExpression String -- postfix-operator
| ExplicitMemberExpressionDigits PostfixExpression String -- digits
| ExplicitMemberExpressionIdentifier PostfixExpression IdG
| FunctionCallE FunctionCall
| PostfixExpression4Initalizer PostfixExpression
| PostfixSelf PostfixExpression
| PostfixDynamicType PostfixExpression
| PostfixForcedValue PostfixExpression
| PostfixOptionChaining PostfixExpression
| Subscript PostfixExpression [Expression]
deriving (Show, Eq)
data ExpressionElement = ExpressionElement (Maybe String) Expression
deriving (Show, Eq)
data FunctionCall = FunctionCall PostfixExpression [ExpressionElement] (Maybe Closure)
deriving (Show, Eq)
type ParamClause = [Parameter]
data CaptureSpecifier = Weak | Unowned | UnownedSafe | UnownedUnsafe
deriving (Show, Eq)
data Capture = Capture (Maybe CaptureSpecifier) Expression
deriving (Show, Eq)
data CaptureList = CaptureList [Capture]
deriving (Show, Eq)
data ClosureSig
= ClosureSigParam (Maybe CaptureList) ParamClause {- optResult -}(Maybe FunctionResult)
| ClosureSigIdents (Maybe CaptureList) [Identifier] {- optResult -}(Maybe FunctionResult)
deriving (Show, Eq)
data Closure = Closure (Maybe ClosureSig) [Statement]
deriving (Show, Eq)
data PrimaryExpression
= PrimaryExpression1 IdG
| PrimaryLiteral LiteralExpression
| PrimarySelf SelfExpression
| PrimarySuper SuperclassExpression
| PrimaryClosure Closure
| PrimaryParenthesized [ExpressionElement] -- parenthesized-expression
| PrimaryImplicitMember Identifier
| PrimaryWildcard -- wildcard-expression
deriving (Show, Eq)
data SelfExpression
= Self
| SelfMethod Identifier
| SelfSubscript [Expression]
| SelfInit
deriving (Show, Eq)
data SuperclassExpression
= SuperMethod Identifier
| SuperSubscript [Expression]
| SuperInit
deriving (Show, Eq)
data Literal
= NumericLiteral String
| StringLiteral StringLiteral
| BooleanLiteral Bool
| NilLiteral
deriving (Show, Eq)
data StringLiteral
= StaticStringLiteral String
| InterpolatedStringLiteral [InterpolatedTextItem]
deriving (Show, Eq)
data InterpolatedTextItem
= TextItemString String
| TextItemExpr Expression
deriving (Show, Eq)
data LiteralExpression
= RegularLiteral Literal
| ArrayLiteral [Expression]
| DictionaryLiteral [(Expression, Expression)]
| SpecialLiteral String
deriving (Show, Eq)
data BinaryExpression
= BinaryExpression1
{ beOperator :: String
, bePrefixExpression :: PrefixExpression
}
| BinaryAssignmentExpression
{ beTryOperator :: Maybe String
, bePrefixExpression :: PrefixExpression
}
| BinaryConditional (Maybe TryOp, Expression) (Maybe TryOp) PrefixExpression
| BinaryExpression4 String Type
deriving (Show, Eq)
type TryOp = String
data Statement
= ExpressionStatement Expression
| ForStatement
{ forInitE :: Maybe ForInit
, forCondE :: Maybe Expression
, forNextE :: Maybe Expression
, forBlock :: CodeBlock
}
| ForInStatement
{ fiPattern :: Pattern
, fiExpression :: Expression
, fiWhereClause :: Maybe WhereClause
, fiBlock :: CodeBlock
}
| DeclarationStatement Declaration
| ReturnStatement (Maybe Expression)
| WhileStatement ConditionClause CodeBlock
| RepeatWhileStatement CodeBlock Expression
| GuardStatement ConditionClause CodeBlock
| SwitchStatement Expression [Case]
| IfStatement ConditionClause CodeBlock (Maybe (Either CodeBlock {- if -}Statement))
| LabelelStatement LabelName Statement
| BreakStatement (Maybe LabelName)
| ContinueStatement (Maybe LabelName)
| FallthroughStatement
| ThrowStatement Expression
| DeferStatement CodeBlock
| DoStatement CodeBlock [CatchClause]
| LineControlLine
| LineControlSpecified {- lineNum -} Integer {- fileName -} String
| BuildConfigurationStatement BuildConfiguration [Statement] [BuildConfigurationElseifClause]
(Maybe BuildConfigurationElseClause)
deriving (Show, Eq)
type PatternWhere = (Pattern, Maybe WhereClause)
data Case
= CaseLabel [PatternWhere] [Statement]
| CaseDefault [Statement]
deriving (Show, Eq)
data CatchClause = CatchClause (Maybe Pattern) (Maybe WhereClause) CodeBlock
deriving (Show, Eq)
data WhereClause = WhereClause Expression
deriving (Show, Eq)
type LabelName = String
data PlatformName
= IOS
| IOSApplicationExtension
| OSX
| OSXApplicationExtension
| WatchOS
deriving (Show, Eq)
data AvailabilityArgument
= PlatformAvailabilityArgument PlatformName PlatformVersion
| PlatformWildcard
deriving (Show, Eq)
data PlatformVersion = PlatformVersion String
deriving (Show, Eq)
data Condition
= CaseCondition Pattern Initializer (Maybe WhereClause)
| AvailabilityCondition [AvailabilityArgument]
| OptionalBindingCondition
OptionalBindingContinuationHead
OptionalBindingContinuations
(Maybe WhereClause)
deriving (Show, Eq)
data ConditionList = ConditionList [Condition]
deriving (Show, Eq)
data ConditionClause = ConditionClause (Maybe Expression) ConditionList
deriving (Show, Eq)
data ForInit
= FiDeclaration Declaration
| FiExpressionList [Expression]
deriving (Show, Eq)
data CodeBlock = CodeBlock [Statement]
deriving (Show, Eq)
type Identifier = String
type Name = Identifier
type TypeAliasName = Name
type StructName = Name
type ClassName = Name
type ProtocolName = Name
type VariableName = Name
type EnumCaseName = Name
data StructType = Struct | Class
deriving (Show, Eq)
data ProtocolMembers = ProtocolMembers [ProtocolMember]
deriving (Show, Eq)
data ProtocolMember
= ProtocolPropertyDeclaration [Attribute] [DeclarationModifier] VariableName TypeAnnotation {- gskb -} GetSetBlock
| ProtocolMethodDeclaration
[Attribute]
[DeclarationModifier]
FunctionName
(Maybe GenericParameterClause)
[[Parameter]]
(Maybe String) -- "throws" or "rethrows" -- FIXME
(Maybe FunctionResult)
| ProtocolInitializerDeclaration
[Attribute]
[DeclarationModifier]
InitKind
(Maybe GenericParameterClause)
[Parameter]
String -- throwsDecl
| ProtocolSubscriptDeclaration
[Attribute]
[DeclarationModifier]
[Parameter] -- ParameterClause
[Attribute] -- Result attributes
Type -- result type
GetSetBlock -- gskb
| ProtocolAssociatedTypeDeclaration
[Attribute]
(Maybe DeclarationModifier)
TypeAliasName
(Maybe TypeInheritanceClause)
(Maybe Type)
deriving (Show, Eq)
data Declaration
= ImportDeclaration [Attribute] (Maybe ImportKind) ImportPath
| DeclVariableDeclaration VariableDeclaration
| ConstantDeclaration [Attribute] [DeclarationModifier] [PatternInitializer]
| TypeAlias [Attribute] (Maybe DeclarationModifier) TypeAliasName Type
| FunctionDeclaration
{ funAttrs :: [Attribute]
, funDecls :: [DeclarationModifier]
, funName :: FunctionName
, funGenericParamClause :: Maybe GenericParameterClause
, funParameterClauses :: [[Parameter]]
, funThrowDecl :: Maybe String -- "throws" or "rethrows" -- FIXME
, funResult :: Maybe FunctionResult
, funBody :: Maybe CodeBlock
}
| EnumDeclaration EnumDeclaration
| StructDeclaration
StructType
[Attribute]
(Maybe DeclarationModifier)
StructName
(Maybe GenericParameterClause)
(Maybe TypeInheritanceClause)
[Declaration]
| InitializerDeclaration
[Attribute]
[DeclarationModifier]
InitKind
(Maybe GenericParameterClause)
[Parameter]
String -- throwsDecl
CodeBlock
| DeinitializerDeclaration
[Attribute]
CodeBlock
| ExtensionDeclaration
(Maybe DeclarationModifier)
TypeIdentifier
(Maybe TypeInheritanceClause)
ExtensionBody
| SubscriptDeclaration
[Attribute]
[DeclarationModifier]
[Parameter] -- ParameterClause
[Attribute] -- Result attributes
Type -- result type
SubscriptBlock
| OperatorDeclaration OperatorDecl
| ProtocolDeclaration
[Attribute]
(Maybe DeclarationModifier)
ProtocolName
(Maybe TypeInheritanceClause)
ProtocolMembers
deriving (Show, Eq)
data SubscriptBlock
= SubscriptCodeBlock CodeBlock
| SubscriptGetSetBlock GetSetBlock
deriving (Show, Eq)
data ExtensionBody = ExtensionBody [Declaration]
deriving (Show, Eq)
data VariableDeclaration
= VarDeclPattern [Attribute] [DeclarationModifier] [PatternInitializer]
| VarDeclReadOnly [Attribute] [DeclarationModifier] VarName TypeAnnotation CodeBlock
| VarDeclGetSet [Attribute] [DeclarationModifier] VarName TypeAnnotation GetSetBlock
| VarDeclObserved [Attribute] [DeclarationModifier] VarName (Maybe TypeAnnotation) (Maybe Initializer) ObservedBlock
deriving (Show, Eq)
data ObservedBlock = ObservedBlock -- aka WillSetDidSetBlock
deriving (Show, Eq)
type IsIndirect = Bool
type EnumName = Identifier
type VarName = Identifier
type AttributeName = Identifier
type ClassRequirement = Bool
data TypeInheritanceClause = TypeInheritanceClause ClassRequirement [TypeIdentifier]
deriving (Show, Eq)
data EnumDeclaration
= UnionEnum
[Attribute]
(Maybe DeclarationModifier)
IsIndirect
EnumName
(Maybe GenericParameterClause)
(Maybe TypeInheritanceClause)
[UnionStyleEnumMember]
| RawEnumDeclaration
[Attribute]
(Maybe DeclarationModifier)
EnumName
(Maybe GenericParameterClause)
TypeInheritanceClause
RawValueEnumMembers
deriving (Show, Eq)
type CaseName = String
data UnionStyleEnumMember
= EnumMemberDeclaration Declaration
| EnumMemberCase [Attribute] IsIndirect [(CaseName, Maybe {-Tuple-} Type)]
deriving (Show, Eq)
data DeclarationModifier
= Modifier String
| AccessLevelModifier String
deriving (Show, Eq)
type Throws = String -- "throws", "rethrows", "" -- FIXME
data InOut = InOut
deriving (Show, Eq)
type ElementName = Name
data TupleElementType
= TupleElementTypeAnon [Attribute] (Maybe InOut) Type
| TupleElementTypeNamed (Maybe InOut) ElementName TypeAnnotation
deriving (Show, Eq)
data TupleTypeBody = TupleTypeBody [TupleElementType] Bool
deriving (Show, Eq)
data Type
= TypeIdentifierType TypeIdentifier
| TypeOpt Type
| ImplicitlyUnwrappedOptType Type
| ArrayType Type
| DictionaryType Type Type
| FunctionType Throws Type Type
| TypeMetaType Type
| ProtocolMetaType Type
| ProtocolCompositionType [ProtocolIdentifier]
| TupleType (Maybe TupleTypeBody)
deriving (Show, Eq)
type ProtocolIdentifier = TypeIdentifier
type ImportPath = [ImportPathIdentifier]
type ImportKind = String
data ImportPathIdentifier
= ImportIdentifier String
| ImportOperator String
deriving (Show, Eq)
data PatternInitializer = PatternInitializer Pattern (Maybe Initializer)
deriving (Show, Eq)
type OptTypeAnnotation = Maybe TypeAnnotation
data Pattern
= WildcardPattern OptTypeAnnotation
| IdentifierPattern Identifier OptTypeAnnotation
| OptionalPattern Identifier -- id?
| TuplePattern [Pattern] OptTypeAnnotation
| ExpressionPattern Expression
| VarPattern Pattern
| LetPattern Pattern
| IsPattern Type
| AsPattern Type
deriving (Show, Eq)
data FunctionResult = FunctionResult [Attribute] Type
deriving (Show, Eq)
data FunctionName
= FunctionNameIdent String
| FunctionNameOp String
deriving (Show, Eq)
data GenericParameterClause = GenericParameterClause [GenericParameter] (Maybe GenericRequirementClause)
deriving (Show, Eq)
data GenericParameter
= GenericParamName TypeName
| GenericParamTypeId TypeName TypeIdentifier
| GenericParamProtocol TypeName {- protocol-composition-type -} Type
deriving (Show, Eq)
data TypeRequirement
= ConformanceRequirementRegular TypeIdentifier TypeIdentifier
| ConformanceRequirementProtocol TypeIdentifier {- protocol-composition-type -} Type
| SameTypeRequirement TypeIdentifier Type
deriving (Show, Eq)
data GenericRequirementClause = GenericRequirementClause [TypeRequirement]
deriving (Show, Eq)
data Parameter
= ParameterLet (Maybe String) String TypeAnnotation (Maybe Expression)
| ParameterVar (Maybe String) String TypeAnnotation (Maybe Expression)
| ParameterInOut (Maybe String) String TypeAnnotation
| ParameterDots (Maybe String) String TypeAnnotation
deriving (Show, Eq)
data TypeAnnotation = TypeAnnotation [Attribute] Type
deriving (Show, Eq)
data BuildConfigurationElseifClause = BuildConfigurationElseifClause BuildConfiguration [Statement]
deriving (Show, Eq)
data BuildConfigurationElseClause = BuildConfigurationElseClause [Statement]
deriving (Show, Eq)
data BuildConfiguration
= OperatingSystemTest String
| ArchitectureTest String
| BuildConfigurationId String
| BuildConfigurationBool Literal
| BuildConfigurationNegate BuildConfiguration
| BuildConfigurationOr BuildConfiguration BuildConfiguration
| BuildConfigurationAnd BuildConfiguration BuildConfiguration
deriving (Show, Eq)
data InitKind
= Init
| InitOption
| InitForce
deriving (Show, Eq)
data TypeIdentifier = TypeIdentifier [(TypeName, [Type])]
deriving (Show, Eq)
type TypeName = Identifier
data GetterClause = GetterClause [Attribute] CodeBlock
deriving (Show, Eq)
data SetterClause = SetterClause [Attribute] (Maybe Identifier) CodeBlock
deriving (Show, Eq)
data GetSetBlock
= GetSetBlock CodeBlock
| GetSet (Maybe GetterClause) (Maybe SetterClause)
deriving (Show, Eq)
type Op = String
type PrecedenceLevel = Int
data Associativity = AssocLeft | AssocRight | AssocNone
deriving (Show, Eq)
data OperatorDecl
= PrefixOperatorDecl Op
| PostfixOperatorDecl Op
| InfixOperatorDecl Op (Maybe PrecedenceLevel) (Maybe Associativity)
deriving (Show, Eq)
data Attribute = Attribute AttributeName (Maybe String)
deriving (Show, Eq)
data Initializer = Initializer Expression
deriving (Show, Eq)
data OptionalBindingContinuationHead
= LetOptionalBinding Pattern Initializer
| VarOptionalBinding Pattern Initializer
deriving (Show, Eq)
data OptionalBindingContinuations = OptionalBindingContinuations [OptionalBindingContinuation]
deriving (Show, Eq)
data OptionalBindingContinuation
= OptionalBindingContinuationPattern Pattern Initializer
| OptionalBindingContinuationHead OptionalBindingContinuationHead
deriving (Show, Eq)
data RawValueEnumCase = RawValueEnumCase EnumCaseName (Maybe Literal)
deriving (Show, Eq)
data RawValueEnumCases = RawValueEnumCases [RawValueEnumCase]
deriving (Show, Eq)
data RawValueEnumMember
= RawValueEnumCaseClause [Attribute] RawValueEnumCases
| RawValueEnumDeclaration Declaration
deriving (Show, Eq)
data RawValueEnumMembers = RawValueEnumMembers [RawValueEnumMember]
deriving (Show, Eq)
|
steshaw/language-swift-quote
|
Language/Swift/Quote/Syntax.hs
|
bsd-3-clause
| 15,365
| 0
| 10
| 2,675
| 3,583
| 2,048
| 1,535
| 445
| 0
|
module Substitution where
import Syntax
-- Substitute variables by expressions in a given expression
substitute :: [(String,Expr)] -> Expr -> Expr
substitute _ e@(Const _) = e
substitute m (Var s)
= case (lookup s m) of
(Just e') -> e'
Nothing -> Var s
substitute m (Binary op e1 e2) = Binary op (substitute m e1) (substitute m e2)
substitute m (IfZero e1 e2 e3) = IfZero (substitute m e1) (substitute m e2) (substitute m e3)
substitute m (Apply s es) = Apply s (map (substitute m) es)
|
grammarware/slps
|
topics/partial-evaluation/simplepe/Substitution.hs
|
bsd-3-clause
| 501
| 0
| 9
| 104
| 229
| 117
| 112
| 11
| 2
|
{-# LANGUAGE CPP #-}
module Network.Sendfile.Types where
#ifdef VERSION_unix
import qualified Data.ByteString as B
import qualified System.Posix.IO as P
import qualified System.Posix.IO.ByteString as PB
import qualified System.Posix.Types as P
#endif
-- |
-- File range for 'sendfile'.
data FileRange = EntireFile
| PartOfFile {
rangeOffset :: Integer
, rangeLength :: Integer
}
-- To avoid build error in windows
#ifdef VERSION_unix
-- | 'openFd's signature changed in @unix-2.8@. This is a portable wrapper.
openFd :: FilePath -> P.OpenMode -> P.OpenFileFlags -> IO P.Fd
#if MIN_VERSION_unix(2,8,0)
openFd path mode flags = P.openFd path mode flags
#else
openFd path mode flags = P.openFd path mode Nothing flags
#endif
-- | 'openFd's signature changed in @unix-2.8@. This is a portable wrapper.
openFdBS :: B.ByteString -> P.OpenMode -> P.OpenFileFlags -> IO P.Fd
#if MIN_VERSION_unix(2,8,0)
openFdBS path mode flags = PB.openFd path mode flags
#else
openFdBS path mode flags = PB.openFd path mode Nothing flags
#endif
#endif
|
kazu-yamamoto/simple-sendfile
|
Network/Sendfile/Types.hs
|
bsd-3-clause
| 1,126
| 0
| 9
| 249
| 179
| 111
| 68
| 6
| 0
|
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
module IIRCC.IRC.Session (
Session (..),
EventReport (..),
Command (..),
IRCPipes.IrcMessage (..),
start
) where
import Control.Concurrent.Async
import Control.Exception
import Control.Monad.Catch as C
import Control.Monad.State.Lazy
import Data.Either.Combinators (leftToMaybe)
import Data.Functor.Contravariant
import Data.Maybe (isNothing)
import Data.Text
import GHC.IO.Exception
import qualified Irc.Message as IrcMsg
import Irc.RawIrcMsg (RawIrcMsg)
import qualified Irc.RawIrcMsg as IrcRawMsg
import qualified Irc.Commands as IrcCmd
import Pipes
import Pipes.Prelude as PP
import Pipes.Concurrent as PC
import Pipes.Exhaustion
import Pipes.Safe as PS
import Network.Simple.TCP (Socket, HostName, ServiceName)
import qualified Network.Simple.TCP as TCP
import qualified IIRCC.IRC.Pipes as IRCPipes
data Session =
Session {
task :: Async (),
commandSink :: Output Command
}
data EventReport =
Connecting HostName ServiceName |
Connected |
FailedToConnect IOError |
ReceivedMessage IRCPipes.IrcMessage |
SentMessage RawIrcMsg |
UnableTo Command Text |
Disconnected |
LostConnection (Maybe IOError) |
Ended
deriving (Show)
data Command =
Connect |
Disconnect |
Close |
SendMessage RawIrcMsg
deriving (Show)
data Message =
Command Command |
IrcMessage IRCPipes.IrcMessage |
MessageReceiverEnded (Maybe IOError)
deriving (Show)
start :: HostName -> ServiceName -> Output EventReport -> IO Session
start hostName serviceName eventSink = do
(messageSink, messageSource, sealMailbox) <- spawn' unbounded
sessionTask <- async $ do
runEffect $ inexhaustible (fromInput messageSource) >-> sessionPipe (inexhaustible $ toOutput messageSink) >-> toOutput eventSink
runEffect $ toOutput eventSink <-< yield Ended
atomically sealMailbox
return $ Session sessionTask (contramap Command messageSink)
where
sessionPipe :: Consumer Message IO () -> Pipe Message EventReport IO ()
sessionPipe toMailbox = fix $ \sessionPipe' -> await >>= \case
Command Connect -> do
yield $ Connecting hostName serviceName
C.try (TCP.connectSock hostName serviceName) >>= \case
Left ioe -> do
yield $ FailedToConnect ioe
sessionPipe'
Right (socket, _) ->
(
do
yield Connected
msgReceiver <- liftIO $ async $ do
runEffect $
toMailbox <-< (
C.try (IRCPipes.receiver 4096 socket) >-> PP.map IrcMessage
>>= yield . MessageReceiverEnded . leftToMaybe
)
endReason <- runEffect $ connectedSessionPipe >-> IRCPipes.sender socket
liftIO $ do
TCP.closeSock socket
wait msgReceiver
return endReason
`C.onException`
liftIO (TCP.closeSock socket)
) >>= \case
Command Close -> return ()
Command Disconnect -> do
yield Disconnected
sessionPipe'
MessageReceiverEnded ioe -> do
yield $ LostConnection ioe
sessionPipe'
Command Close -> return ()
Command Disconnect -> do
yield $ UnableTo Disconnect "Not connected."
sessionPipe'
Command c@(SendMessage _) -> do
yield $ UnableTo c "Not connected."
sessionPipe'
MessageReceiverEnded _ -> sessionPipe' -- End of message receiver from last connection.
-- Returns event that prompted termination.
connectedSessionPipe :: Producer RawIrcMsg (Pipe Message EventReport IO) Message
connectedSessionPipe = awaitMessage >>= \case
IrcMessage m -> do
yieldEventReport $ ReceivedMessage m
connectedSessionPipe
Command (SendMessage m) -> do
yieldRawIrcMsg m
yieldEventReport $ SentMessage m
connectedSessionPipe
c@(Command Disconnect) -> return c
c@(Command Close) -> return c
c@(MessageReceiverEnded _) -> return c
Command Connect -> do
yieldEventReport $ UnableTo Connect "Already connected."
connectedSessionPipe
where
awaitMessage = lift await
yieldRawIrcMsg = yield
yieldEventReport = lift . yield
|
Rotaerk/iircc
|
src/daemon/IIRCC/IRC/Session.hs
|
bsd-3-clause
| 4,400
| 0
| 37
| 1,217
| 1,113
| 576
| 537
| 121
| 13
|
module Macro where
import Parser2
import qualified Data.Map as M
import Data.Maybe (catMaybes)
import Control.Applicative (liftA2)
-- | Convert an expression to pure datum. TODO: change the name of this
-- function.
--
convMacro :: GenExpr () -> GenDatum ()
convMacro (Var s ()) = SimpleDatum (Var s ())
convMacro (Literal (LitQuote x)) =
CompoundDatum $ (SimpleDatum $ Var "quote" ()) : [x]
convMacro (Literal x) = SimpleDatum (Literal x)
convMacro (Call x xs) = CompoundDatum $ convMacro x : map convMacro xs
convMacro (Lambda vs b) =
let bs = convMacroBody b
in CompoundDatum $ SimpleDatum (Var "lambda" ())
: CompoundDatum (map convMacro vs) : bs
convMacro (Cond a b c) = CompoundDatum $ SimpleDatum (Var "if" ())
: convMacro a : convMacro b : [convMacro c]
convMacro (Assign a b) = CompoundDatum $ SimpleDatum (Var "set!" ())
: convMacro a : [convMacro b]
convMacroBody :: GenBody () -> [GenDatum ()]
convMacroBody (Body ds es) = map convMacroDef ds ++ map convMacro es
convMacroDef :: GenDef () -> GenDatum ()
convMacroDef (Def1 x y) = CompoundDatum $ [ SimpleDatum (Var "define" ())
, SimpleDatum x
, convMacro y
]
convMacroDef (Def2 x ys b) = CompoundDatum $ [ SimpleDatum (Var "define" ())
, CompoundDatum $ SimpleDatum x :
map SimpleDatum ys
] ++ convMacroBody b
convMacroDef (Def3 ds) = CompoundDatum $ SimpleDatum (Var "begin" ()) :
map convMacroDef ds
-- | Result of matching a pattern with a datum. If a variable appears without
-- in ellipses in the pattern it will show up in the map with the datum it
-- matched against. If a variable has ellipses it will show up in the lists with
-- each datum it matched with.
--
data Matched a = Matched (M.Map String (GenDatum a)) [Matched a]
deriving (Eq, Show)
-- | zipWith, but we take values from the longer list after the shorter list has
-- ended.
--
extZipWith :: (a -> a -> a) -> [a] -> [a] -> [a]
extZipWith f (b:bs) (c:cs) = f b c : extZipWith f bs cs
extZipWith f [] cs = cs
extZipWith f bs [] = bs
-- | Combine two match results
--
combine :: Matched a -> Matched a -> Matched a
combine (Matched m1 l1) (Matched m2 l2) =
Matched (M.union m1 m2) (extZipWith combine l1 l2)
-- | Fills in a pattern from a GenDatum that matches it
--
match :: Pattern -> GenDatum a -> Maybe (Matched a)
match (PatEllipses patterns pattern) (CompoundDatum ds) =
let n = length patterns
in if length ds < n
then Nothing
else do
a <- (match (PatternComp patterns) (CompoundDatum (take n ds)))
b <- Matched M.empty <$> (traverse (match pattern) (drop n ds))
return $ combine a b
match (PatternComp (x:xs)) (CompoundDatum (d:ds)) =
combine <$> (match x d) <*> (match (PatternComp xs) (CompoundDatum ds))
match (PatternComp []) (CompoundDatum []) = Just $ Matched M.empty []
match (PatternComp []) _ = Nothing
match (PatternDat x) (SimpleDatum (Literal y)) =
if x == y
then Just $ Matched M.empty []
else Nothing
match (PatternId s) x = Just $ Matched (M.singleton s x) []
match (PatternLit s) (SimpleDatum (Var x _)) = if x == s
then Just $ Matched M.empty []
else Nothing
match _ _ = Nothing
-- | Fill in template Element with matched data. If it is an ellipses element,
-- fill in with each Matched in the list and take all the results that worked.
--
useTemplateElem :: TempElement -> Matched () -> Maybe [GenDatum ()]
useTemplateElem (PureTemp t) m = pure <$> useTemplate t m
useTemplateElem (TempEllipses t) (Matched _ ls) =
Just . catMaybes $ map (useTemplate t) ls
-- | fill in template with Matched data.
useTemplate :: Template -> Matched () -> Maybe (GenDatum ())
useTemplate (TemplateComp xs) m =
CompoundDatum . concat <$> mapM (flip useTemplateElem m) xs
useTemplate (TemplateDat x) _ = Just $ SimpleDatum (Literal x)
useTemplate (TemplateId s) (Matched m l) = M.lookup s m
useTemplate (TemplateLit s) _ = Just $ SimpleDatum (Var s ())
-- | Match against the pattern in the SyntaxRule and then fill in the template
-- from the match.
--
applyMacro :: SyntaxRule -> GenDatum () -> Maybe (GenDatum ())
applyMacro s dat = match (pat s) dat >>= useTemplate (temp s)
type MacroList = [SyntaxRule]
-- | Try to appyl multiple SyntaxRules and when one fails, recursively apply
-- them to the children in the AST.
--
applyMacros :: MacroList -> GenDatum () -> GenDatum ()
applyMacros ms ex =
let conversions = map (flip applyMacro ex) ms
in case take 1 $ catMaybes conversions of
[x] -> applyMacros ms x
[] -> case ex of
CompoundDatum ds -> CompoundDatum $ map (applyMacros ms) ds
SimpleDatum y -> SimpleDatum y
convDatum :: GenDatum () -> GenExpr ()
convDatum (SimpleDatum x) = x
convDatum (CompoundDatum (SimpleDatum (Var "if" ()) : [a,b,c])) =
Cond (convDatum a) (convDatum b) (convDatum c)
convDatum (CompoundDatum (SimpleDatum (Var "lambda" ())
: (CompoundDatum xs) : ys)) =
Lambda (map convDatum xs) (convDatumBody ys)
convDatum (CompoundDatum ( SimpleDatum (Var "set!" ())
: SimpleDatum (Var x ())
: [y])) =
Assign (Var x ()) (convDatum y)
convDatum (CompoundDatum (SimpleDatum (Var "quote" ()) : [x])) =
Literal $ LitQuote x
convDatum (CompoundDatum (x: xs)) =
Call (convDatum x) (map convDatum xs)
isDef :: GenDatum a -> Bool
isDef (CompoundDatum (SimpleDatum (Var "define" _) : _)) = True
isDef (CompoundDatum (SimpleDatum (Var "begin" _ ) : xs)) = and $ map isDef xs
isDef _ = False
convDatumDef :: GenDatum () -> GenDef ()
convDatumDef (CompoundDatum (SimpleDatum (Var "begin" ()) : xs)) =
Def3 $ map convDatumDef xs
convDatumDef (CompoundDatum (SimpleDatum (Var "define" ()) :
CompoundDatum (SimpleDatum (Var x ()) : vs) :
b)) =
Def2 (Var x ()) (map convDatum vs) (convDatumBody b)
convDatumDef (CompoundDatum (SimpleDatum (Var "define" ()) : x : [y])) =
Def1 (convDatum x) (convDatum y)
convDatumBody :: [GenDatum ()] -> GenBody ()
convDatumBody [] = Body [] []
convDatumBody (x:xs) =
let Body ds es = convDatumBody xs
in if isDef x
then Body (convDatumDef x:ds) es
else Body ds (convDatum x:es)
applyMacrosExpr :: MacroList -> GenExpr () -> GenExpr ()
applyMacrosExpr ms = convDatum . applyMacros ms . convMacro
applyMacrosDef :: MacroList -> GenDef () -> GenDef ()
applyMacrosDef ms = convDatumDef . applyMacros ms . convMacroDef
applyMacrosProgram :: MacroList -> [CommOrDef] -> [CommOrDef]
applyMacrosProgram ms xs = map (\x ->
case x of
Comm y -> Comm $ applyMacrosExpr (ms ++ newMacros) y
Def y -> Def $ applyMacrosDef (ms ++ newMacros) y) $ filter notDef xs
where
getSynRule (DefSyn rs) = rs
getSynRule _ = []
newMacros = concatMap getSynRule xs
notDef (DefSyn _) = False
notDef _ = True
defaultMacros :: MacroList
defaultMacros =
[ SyntaxRule { --convert `let` to a lambda application
pat =
PatEllipses
[ PatternLit "let"
, PatEllipses []
(PatternComp [ PatternId "a"
, PatternId "b"
])
, PatternId "c"]
(PatternId "d")
, temp =
TemplateComp
[ PureTemp $ TemplateComp
[ PureTemp $ TemplateLit "lambda"
, PureTemp $ TemplateComp $ [TempEllipses $ TemplateId "a"]
, PureTemp $ TemplateId "c"
, TempEllipses $ TemplateId "d"
]
, TempEllipses $ TemplateId "b"
]
}
, SyntaxRule { -- convert `delay` to a lambda
pat =
PatternComp [ PatternLit "delay"
, PatternId "a"
]
, temp =
TemplateComp [ PureTemp $ TemplateLit "lambda"
, PureTemp $ TemplateComp []
, PureTemp $ TemplateId "a"
]
}
]
|
adamrk/scheme2luac
|
src/Macro.hs
|
bsd-3-clause
| 8,234
| 0
| 17
| 2,328
| 2,952
| 1,474
| 1,478
| 159
| 4
|
module Sklite.Boot
( generateBootScripts
)
where
import Control.Applicative
import Data.List
import System.FilePath
import Sklite.Types
import Sklite.Layout.Validation
import qualified Sklite.Paths as Paths
crossBootScriptFilename :: FilePath
crossBootScriptFilename = "boot.sh"
hostBootScriptFilename :: FilePath
hostBootScriptFilename = "host-boot.sh"
generateBootScripts :: FilePath -> ExplodedLayout -> IO ()
generateBootScripts outputDir (ExplodedLayout (ValidatedLayout layout)) = do
writeCrossBootScript (outputDir </> crossBootScriptFilename) layout
writeHostBootScript (outputDir </> hostBootScriptFilename) layout
writeCrossBootScript :: FilePath -> Layout -> IO ()
writeCrossBootScript scriptPath layout =
writeFile scriptPath $ bootScript True layout
writeHostBootScript :: FilePath -> Layout -> IO ()
writeHostBootScript scriptPath layout =
writeFile scriptPath $ bootScript False layout
-- 1s
globalPeriod :: Double
globalPeriod = 1000000
bootScript :: Bool -> Layout -> String
bootScript doScheduling layout =
unlines $ concat [ headerLines
, [""]
, startupLines
, [""]
, if doScheduling then schedulerLines else []
, [""]
, shmemLines
, [""]
, if doScheduling then ["restorecon -R /sk"] else []
, [""]
, launchLines
]
where
logMsg = ("echo " ++) . show
headerLines = [ "#!/bin/sh"
, "set -e"
, ""
]
startupLines = [ logMsg ">> Separation kernel development platform startup"
, logMsg $ " Global bandwidth: " ++ (show $ layoutBandwidth layout) ++ "%"
]
schedulerLines = [ logMsg "Setting scheduling parameters:"
, logMsg " Reducing root task group real-time bandwidth allocation"
, "echo 0 > /cgroup/cpu/cpu.rt_runtime_us"
, logMsg " Reducing global real-time bandwidth allocation"
, "echo 0 > /proc/sys/kernel/sched_rt_runtime_us"
, logMsg " Setting global deadline bandwidth allocation"
, "echo " ++ show ((truncate $ (layoutBandwidth layout / 100.0) * globalPeriod) :: Integer) ++
" > /proc/sys/kernel/sched_dl_runtime_us"
, logMsg " Setting global deadline period"
, "echo " ++ show ((truncate globalPeriod) :: Integer) ++
" > /proc/sys/kernel/sched_dl_period_us"
]
shmemLines = concat $ shmemCommand <$> sharedMemoryRegions layout
shmemCommand region =
[ logMsg $ concat [ "Creating shared memory region "
, show $ regionName region
, " (" ++ (show $ regionSize region) ++ " bytes)"
]
, concat [ "dd if=/dev/zero of="
, Paths.regionFilename region
, " bs=1 count=" ++ (show $ regionSize region)
]
]
launchLines = concat $ launchCommand <$> layoutCells layout
cellProgString cell =
concat [ "./"
, intercalate " " $ cellProgram cell : cellArguments cell
]
launchCommand cell =
[ logMsg $ "Starting cell: " ++ show (cellName cell)
, logMsg $ " Program: " ++ (show $ cellProgram cell)
, logMsg $ " Runtime: " ++ (show $ cellScheduleRuntime cell)
, logMsg $ " Period: " ++ (show $ cellSchedulePeriod cell)
, if doScheduling
then concat [ "nohup schedtool -E -t "
, concat [ show ((truncate $ cellScheduleRuntime cell) :: Integer)
, ":"
, show ((truncate $ cellSchedulePeriod cell) :: Integer)
, ":"
, show ((truncate $ cellSchedulePeriod cell) :: Integer)
]
, " -e "
, cellProgString cell
, " > "
, cellName cell ++ ".log"
, " &"
]
else concat [ cellProgString cell
, " > "
, cellName cell ++ ".log"
, " &"
]
, ""
]
|
GaloisInc/sk-dev-platform
|
user/sklite/src/Sklite/Boot.hs
|
bsd-3-clause
| 4,707
| 0
| 17
| 1,964
| 891
| 482
| 409
| 88
| 4
|
-- 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. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
module Duckling.Dimensions.Common
( allDimensions
) where
import Duckling.Dimensions.Types
allDimensions :: [Some Dimension]
allDimensions =
[ This Email
, This AmountOfMoney
, This PhoneNumber
, This Url
]
|
rfranek/duckling
|
Duckling/Dimensions/Common.hs
|
bsd-3-clause
| 526
| 0
| 6
| 98
| 64
| 39
| 25
| 9
| 1
|
import "hint" HLint.HLint
ignore "Use camelCase"
ignore "Use section"
ignore "Use infix"
ignore "Use unless"
|
listx/syscfg
|
xmonad/HLint.hs
|
bsd-3-clause
| 110
| 0
| 5
| 16
| 31
| 12
| 19
| -1
| -1
|
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ExistentialQuantification #-}
-- |
-- Module : Streamly.Memory.Ring
-- Copyright : (c) 2019 Composewell Technologies
-- License : BSD3
-- Maintainer : streamly@composewell.com
-- Stability : experimental
-- Portability : GHC
--
module Streamly.Memory.Ring
( Ring(..)
-- * Construction
, new
-- * Modification
, unsafeInsert
-- * Folds
, unsafeFoldRing
, unsafeFoldRingM
, unsafeFoldRingFullM
-- * Fast Byte Comparisons
, unsafeEqArray
, unsafeEqArrayN
) where
import Control.Exception (assert)
import Foreign.ForeignPtr (ForeignPtr, withForeignPtr)
import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
import Foreign.Ptr (plusPtr, minusPtr, castPtr)
import Foreign.Storable (Storable(..))
import GHC.ForeignPtr (mallocPlainForeignPtrAlignedBytes)
import GHC.Ptr (Ptr(..))
import Prelude hiding (length, concat)
import qualified Streamly.Internal.Memory.Array.Types as A
-- | A ring buffer is a mutable array of fixed size. Initially the array is
-- empty, with ringStart pointing at the start of allocated memory. We call the
-- next location to be written in the ring as ringHead. Initially ringHead ==
-- ringStart. When the first item is added, ringHead points to ringStart +
-- sizeof item. When the buffer becomes full ringHead would wrap around to
-- ringStart. When the buffer is full, ringHead always points at the oldest
-- item in the ring and the newest item added always overwrites the oldest
-- item.
--
-- When using it we should keep in mind that a ringBuffer is a mutable data
-- structure. We should not leak out references to it for immutable use.
--
data Ring a = Ring
{ ringStart :: !(ForeignPtr a) -- first address
, ringBound :: !(Ptr a) -- first address beyond allocated memory
}
-- | Create a new ringbuffer and return the ring buffer and the ringHead.
-- Returns the ring and the ringHead, the ringHead is same as ringStart.
{-# INLINE new #-}
new :: forall a. Storable a => Int -> IO (Ring a, Ptr a)
new count = do
let size = count * sizeOf (undefined :: a)
fptr <- mallocPlainForeignPtrAlignedBytes size (alignment (undefined :: a))
let p = unsafeForeignPtrToPtr fptr
return $ (Ring
{ ringStart = fptr
, ringBound = p `plusPtr` size
}, p)
-- | Advance the ringHead by 1 item, wrap around if we hit the end of the
-- array.
{-# INLINE advance #-}
advance :: forall a. Storable a => Ring a -> Ptr a -> Ptr a
advance Ring{..} ringHead =
let ptr = ringHead `plusPtr` sizeOf (undefined :: a)
in if ptr < ringBound
then ptr
else unsafeForeignPtrToPtr ringStart
-- | Insert an item at the head of the ring, when the ring is full this
-- replaces the oldest item in the ring with the new item. This is unsafe
-- beause ringHead supplied is not verified to be within the Ring. Also,
-- the ringStart foreignPtr must be guaranteed to be alive by the caller.
{-# INLINE unsafeInsert #-}
unsafeInsert :: Storable a => Ring a -> Ptr a -> a -> IO (Ptr a)
unsafeInsert rb ringHead newVal = do
poke ringHead newVal
-- touchForeignPtr (ringStart rb)
return $ advance rb ringHead
-- XXX remove all usage of A.unsafeInlineIO
--
-- | Like 'unsafeEqArray' but compares only N bytes instead of entire length of
-- the ring buffer. This is unsafe because the ringHead Ptr is not checked to
-- be in range.
{-# INLINE unsafeEqArrayN #-}
unsafeEqArrayN :: Ring a -> Ptr a -> A.Array a -> Int -> Bool
unsafeEqArrayN Ring{..} rh A.Array{..} n =
let !res = A.unsafeInlineIO $ do
let rs = unsafeForeignPtrToPtr ringStart
let as = unsafeForeignPtrToPtr aStart
assert (aBound `minusPtr` as >= ringBound `minusPtr` rs) (return ())
let len = ringBound `minusPtr` rh
r1 <- A.memcmp (castPtr rh) (castPtr as) (min len n)
r2 <- if n > len
then A.memcmp (castPtr rs) (castPtr (as `plusPtr` len))
(min (rh `minusPtr` rs) (n - len))
else return True
-- XXX enable these, check perf impact
-- touchForeignPtr ringStart
-- touchForeignPtr aStart
return (r1 && r2)
in res
-- | Byte compare the entire length of ringBuffer with the given array,
-- starting at the supplied ringHead pointer. Returns true if the Array and
-- the ringBuffer have identical contents.
--
-- This is unsafe because the ringHead Ptr is not checked to be in range. The
-- supplied array must be equal to or bigger than the ringBuffer, ARRAY BOUNDS
-- ARE NOT CHECKED.
{-# INLINE unsafeEqArray #-}
unsafeEqArray :: Ring a -> Ptr a -> A.Array a -> Bool
unsafeEqArray Ring{..} rh A.Array{..} =
let !res = A.unsafeInlineIO $ do
let rs = unsafeForeignPtrToPtr ringStart
let as = unsafeForeignPtrToPtr aStart
assert (aBound `minusPtr` as >= ringBound `minusPtr` rs)
(return ())
let len = ringBound `minusPtr` rh
r1 <- A.memcmp (castPtr rh) (castPtr as) len
r2 <- A.memcmp (castPtr rs) (castPtr (as `plusPtr` len))
(rh `minusPtr` rs)
-- XXX enable these, check perf impact
-- touchForeignPtr ringStart
-- touchForeignPtr aStart
return (r1 && r2)
in res
-- XXX use MonadIO
--
-- | Fold the buffer starting from ringStart up to the given 'Ptr' using a pure
-- step function. This is useful to fold the items in the ring when the ring is
-- not full. The supplied pointer is usually the end of the ring.
--
-- Unsafe because the supplied Ptr is not checked to be in range.
{-# INLINE unsafeFoldRing #-}
unsafeFoldRing :: forall a b. Storable a
=> Ptr a -> (b -> a -> b) -> b -> Ring a -> b
unsafeFoldRing ptr f z Ring{..} =
let !res = A.unsafeInlineIO $ withForeignPtr ringStart $ \p ->
go z p ptr
in res
where
go !acc !p !q
| p == q = return acc
| otherwise = do
x <- peek p
go (f acc x) (p `plusPtr` sizeOf (undefined :: a)) q
-- | Like unsafeFoldRing but with a monadic step function.
{-# INLINE unsafeFoldRingM #-}
unsafeFoldRingM :: forall m a b. (Monad m, Storable a)
=> Ptr a -> (b -> a -> m b) -> b -> Ring a -> m b
unsafeFoldRingM ptr f z Ring{..} = go z (unsafeForeignPtrToPtr ringStart) ptr
where
go !acc !start !end
| start == end = return acc
| otherwise = do
let !x = A.unsafeInlineIO $ peek start
acc' <- f acc x
go acc' (start `plusPtr` sizeOf (undefined :: a)) end
-- | Fold the entire length of a ring buffer starting at the supplied ringHead
-- pointer. Assuming the supplied ringHead pointer points to the oldest item,
-- this would fold the ring starting from the oldest item to the newest item in
-- the ring.
{-# INLINE unsafeFoldRingFullM #-}
unsafeFoldRingFullM :: forall m a b. (Monad m, Storable a)
=> Ptr a -> (b -> a -> m b) -> b -> Ring a -> m b
unsafeFoldRingFullM rh f z rb@Ring{..} = go z rh
where
go !acc !start = do
let !x = A.unsafeInlineIO $ peek start
acc' <- f acc x
let ptr = advance rb start
if ptr == rh
then return acc'
else go acc' ptr
|
harendra-kumar/asyncly
|
src/Streamly/Memory/Ring.hs
|
bsd-3-clause
| 7,424
| 0
| 18
| 1,955
| 1,639
| 865
| 774
| 113
| 2
|
{-|
'Snap.Extension.Timer' exports the 'MonadTimer' interface which allows you to
keep track of the time at which your application was started. The interface's
only operation is 'startTime'.
Two splices, 'startTimeSplice' and 'currentTimeSplice' are also provided, for
your convenience.
'Snap.Extension.Timer.Timer' contains the only implementation of this
interface and can be used to turn your application's monad into a
'MonadTimer'.
More than anything else, this is intended to serve as an example Snap
Extension to any developer wishing to write their own Snap Extension.
-}
module Snap.Extension.Timer
( MonadTimer(..)
, startTimeSplice
, currentTimeSplice
) where
import Control.Monad.Trans
import qualified Data.ByteString.UTF8 as U
import Data.Time.Clock
import Snap.Types
import Text.Templating.Heist
import Text.XML.Expat.Tree hiding (Node)
------------------------------------------------------------------------------
-- | The 'MonadTimer' type class. Minimal complete definition: 'startTime'.
class MonadSnap m => MonadTimer m where
-- | The time at which your application was last loaded.
startTime :: m UTCTime
------------------------------------------------------------------------------
-- | For your convenience, a splice which shows the start time.
startTimeSplice :: MonadTimer m => Splice m
startTimeSplice = do
time <- lift startTime
return $ [mkText $ U.fromString $ show $ time]
------------------------------------------------------------------------------
-- | For your convenience, a splice which shows the current time.
currentTimeSplice :: MonadTimer m => Splice m
currentTimeSplice = do
time <- lift $ liftIO getCurrentTime
return $ [mkText $ U.fromString $ show $ time]
|
duairc/snap-extensions
|
src/Snap/Extension/Timer.hs
|
bsd-3-clause
| 1,798
| 0
| 12
| 312
| 211
| 119
| 92
| 20
| 1
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable,DeriveAnyClass #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE TypeOperators#-}
module Juno.Hoplite.Types where
import Numeric.Natural
import Data.Typeable
import Data.Data
import Data.Text (Text)
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.Foldable
import Prelude.Extras
import GHC.Generics (Generic)
import Data.Word
import qualified Data.Vector as V
import Bound
import Control.Monad
import Data.Traversable
data Literal = LInteger !Integer
| LRational !Rational
| LNatural !Natural
| LText !Text
deriving(Eq,Ord,Show,Read,Data,Typeable)
newtype ConstrId = ConstrId { unConstrId :: Text }
deriving (Eq, Show,Data,Typeable,Ord,Read)
newtype PrimOpId = PrimopId {unPrimopId :: Text}
deriving (Eq,Show,Data,Typeable,Ord,Read)
data RigModel = Zero | One | Omega
deriving (Eq,Ord,Show,Read,Data,Typeable,Generic)
data Kind = Star | KArr Kind Kind | LiftedPubKey
deriving (Eq,Ord,Read,Show,Data,Typeable,Generic)
data TCon {-a -}= TInteger | TNatural | TRational | TUnit | TArrow RigModel
| EncryptedFor | SignedBy
| PubKey String {- this is not how it'll work :) -}
-- | Linear
deriving (Eq,Ord,Read,Show ,Data,Typeable,Generic)
data Type ty {-a -}= Tapp (Type ty) (Type ty) | TLit (TCon) | TVar ty
deriving (Eq1,Ord1,Show1,Read1,Eq,Ord,Read,Show,Data,Typeable,Functor,Foldable,Traversable,Generic)
-- | current theres no pointer tagging in 'Ref' but eventually that will
-- probably change
newtype Ref = Ref {refPointer :: Word64} deriving (Eq,Show,Ord,Data,Typeable,Generic,Bounded)
refRepLens :: Functor f =>(Word64 -> f a) -> Ref -> f a
refRepLens = \ f (Ref r) -> f r
-- | interface for doing bitwise transformations that yield a new ref
refTransform :: Functor f => (Word64 -> f Word64) -> Ref -> f Ref
refTransform = \ f (Ref r) -> Ref <$> f r
absoluteDistance :: Ref -> Ref -> Word64
absoluteDistance = \(Ref a) (Ref b) -> if a > b then a - b else b - a
instance Enum Ref where
succ rf@(Ref w) | rf < maxBound = Ref (1+ w)
| otherwise = error $ "succ: Ref overflow"
pred rf@(Ref w) | rf > minBound = Ref (w - 1)
| otherwise = error $ "pred: Ref underflow"
fromEnum (Ref w)
| w < fromIntegral (maxBound :: Int) = fromIntegral w
| otherwise =
error "fromEnum: any Ref that is larger than 2^63 -1 is unrepresentable as Int64"
toEnum n | n >= 0 = Ref $ fromIntegral n
| otherwise = error "toEnum: Cant represent negative locations in a Ref"
-- | 'Tag' is a constructor tag sum
newtype Tag = Tag { unTag :: Text {-Word64-} } deriving (Eq,Read, Show,Ord,Data,Typeable,Generic)
-- type ValRec ty = Free (ValueF ty Ref) Ref
type HeapVal ast = ValueF ast Ref -- ValueF ty Ref (ValRec ty)
data ValueF ast v = VLitF !Literal
| ConstructorF !Tag (WrappedVector v)
| ThunkF (ast v )
-- should this be a heap ref to
-- closure to have the right sharing ?
| DirectClosureF (Closure ast v) -- heap ref?
| BlackHoleF
| IndirectionF v
--- in the types are calling conventions paper,
--- indirections can point at pointer sized literals, or heap references (or tuples thereof???)
-- | VRefF !Ref --- refs are so we can have exlpicit sharing
--- in a manner thats parametric in the choice
-- of execution semantics
deriving
(Typeable
,Functor
,Foldable
,Traversable
,Generic
--,Data
,Eq
,Ord
,Show
,Read
--,Eq1
--,Ord1
--,Show1
--,Read1
)
deriving instance (Data a,Data (ast a),Monad ast,Data (ast (Var Text (ast a))), Typeable ast,Typeable a)
=> Data (ValueF ast a )
instance (Eq1 ast,Monad ast) => Eq1 (ValueF ast) where
(==#) (VLitF a) (VLitF b) = a == b
(==#) (VLitF _) _ = False
(==#) (ConstructorF tga va) (ConstructorF tgb vb) = tga == tgb && va == vb
(==#) (ConstructorF _ _) _ = False
(==#) (ThunkF a) (ThunkF b) = a ==# b
(==#) (ThunkF _) _ = False
(==#) (DirectClosureF c1) (DirectClosureF c2) = c1 ==# c2
(==#) (DirectClosureF _ ) _ = False
(==#) BlackHoleF BlackHoleF = True
(==#) BlackHoleF _ = False
(==#) (IndirectionF v) (IndirectionF v2) = v == v2
(==#) (IndirectionF _) _ = False
-- this is a trick to make defining the ord1 instance sane but total
codeValueF :: ValueF a b -> Int
codeValueF (VLitF _) = 1
codeValueF (ConstructorF _ _ ) = 2
codeValueF (ThunkF _) = 3
codeValueF (DirectClosureF _) = 4
codeValueF (BlackHoleF) = 5
codeValueF (IndirectionF _) = 6
instance (Ord1 ast,Monad ast) => Ord1 (ValueF ast) where
compare1 (VLitF a) (VLitF b) = compare a b
compare1 a@(VLitF _) b = compare (codeValueF a) (codeValueF b)
compare1 (ConstructorF ta va) (ConstructorF tb vb) =
let tcomp = compare ta tb in if tcomp == EQ then compare va vb else tcomp
compare1 a@(ConstructorF _ _) b = compare (codeValueF a) (codeValueF b)
compare1 (ThunkF e1) (ThunkF e2) = compare1 e1 e2
compare1 a@(ThunkF _) b = compare (codeValueF a) (codeValueF b)
compare1 (DirectClosureF a) (DirectClosureF b) = compare1 a b
compare1 a@(DirectClosureF _) b = compare (codeValueF a) (codeValueF b)
compare1 BlackHoleF BlackHoleF = EQ
compare1 a@(BlackHoleF) b = compare (codeValueF a) (codeValueF b)
compare1 (IndirectionF a) (IndirectionF b) = compare a b --- this is spiritually evil :))))
compare1 a@(IndirectionF _ ) b = compare (codeValueF a) (codeValueF b)
newtype WrappedVector a = WrappedVector { unWrappedVector :: V.Vector a }
deriving (Eq, Show,Ord,Read,Data,Typeable,Functor,Foldable,Traversable)
instance Show1 WrappedVector
instance Eq1 WrappedVector
instance Ord1 WrappedVector
instance Read1 WrappedVector
data Arity = ArityBoxed {_extractArityInfo :: !Text} --- for now our model of arity is boring and simple
-- for now lets keep the variable names?
-- it'll keep the debugging simpler (maybe?)
deriving (Eq,Ord,Show,Read,Typeable,Data,Generic)
--- | 'Closure' may need some rethinking ... later
--- they're kinda the erasure of a lambda ... for now
data Closure ast a = MkClosure ![Arity] !(Scope Text ast a)
deriving (Eq,Ord,Show,Read,Functor,Foldable,Traversable,Generic,Typeable)
deriving instance (Typeable ast,Typeable a,Data (Scope Text ast a))=> Data (Closure ast a)
instance (Monad ast, Eq1 ast) => Eq1 (Closure ast)
instance (Monad ast, Ord1 ast) => Ord1 (Closure ast)
instance (Monad ast, Read1 ast) => Read1 (Closure ast)
instance (Monad ast, Show1 ast) => Show1 (Closure ast)
deduceLitKind :: TCon -> Kind
deduceLitKind tc = case tc of
TUnit -> Star
TInteger -> Star
TNatural -> Star
TRational -> Star
-- Linear -> KArr Star Star
TArrow _ -> KArr Star (KArr Star Star)
PubKey _s -> LiftedPubKey
EncryptedFor -> KArr LiftedPubKey (KArr Star Star)
SignedBy -> KArr LiftedPubKey (KArr Star Star)
wellKindedType ::(Show ty, Ord ty ) => Map.Map ty Kind -> Type ty -> Either String Kind
wellKindedType kenv tau = case tau of
TLit tc -> Right $ deduceLitKind tc
TVar tv -> maybe (Left $ "free type variable " ++ show tv) Right $ Map.lookup tv kenv
Tapp tarr tinput ->
do (KArr a b) <- wellKindedType kenv tarr ; c <- wellKindedType kenv tinput ;
if a == c {- this part will get tricky later :) -}
then Right b
else Left $ "Woops, kind mismatch " ++ show (a,c)
collectFreeVars :: (Ord a, Traversable f) => f a -> Set.Set a
collectFreeVars = Set.fromList . foldl' (flip (:)) []
data Exp ty a
= V a
| ELit Literal
-- | PrimApp Text [a]
| Force (Exp ty a) --- Force is a Noop on evaluate values,
--- otherwise reduces expression to applicable normal form
-- should force be more like seq a b, cause pure
| Delay (Exp ty a) --- Delay is a Noop on Thunked values, otherwise creates a thunk
--- note: may need to change their semantics later?!
| Exp ty a :@ [Exp ty a]
| PrimApp PrimOpId [Exp ty a] -- not sure if this is needed, but lets go with it for now
| Lam [(Text,Type ty,RigModel)]
(Scope Text (Exp ty) a)
| Let (Maybe Text) (Maybe (Type ty,RigModel)) (Exp ty a) (Scope (Maybe Text) (Exp ty) a) -- [Scope Int Exp a] (Scope Int Exp a)
deriving (Typeable,Data,Generic)
deriving instance (Read a, Read ty) => Read (Exp ty a)
deriving instance (Read ty) => Read1 (Exp ty)
deriving instance (Show a, Show ty) => Show (Exp ty a)
deriving instance (Show ty) => Show1 (Exp ty)
deriving instance (Ord ty) => Ord1 (Exp ty)
deriving instance (Ord ty,Ord a) => Ord (Exp ty a)
deriving instance (Eq ty) => Eq1 (Exp ty)
deriving instance (Eq a,Eq ty) => Eq (Exp ty a)
instance Functor (Exp ty) where fmap = fmapDefault
instance Foldable (Exp ty) where foldMap = foldMapDefault
instance Applicative (Exp ty) where
pure = V
(<*>) = ap
instance Traversable (Exp ty) where
traverse f (V a) = V <$> f a
traverse _f (ELit e) = pure $ ELit e
-- traverse f (PrimApp nm ls) = PrimApp nm <$> traverse f ls
traverse f (Force e) = Force <$> traverse f e
traverse f (Delay e) = Delay <$> traverse f e
traverse f (PrimApp nm args) = PrimApp nm <$> traverse (traverse f) args
traverse f (x :@ ys) = (:@) <$> traverse f x <*> traverse (traverse f) ys
traverse f (Lam t e) = Lam t <$> traverse f e
traverse f (Let mname mtype bs b) = Let mname mtype <$> (traverse f) bs <*> traverse f b
instance Monad (Exp ty) where
-- return = V
V a >>= f = f a
-- PrimApp nm ls >>= f = PrimApp nm (map f ls)
Delay e >>= f = Delay $ e >>= f
Force e >>= f = Force $ e >>= f
ELit e >>= _f = ELit e -- this could also safely be a coerce?
(x :@ y) >>= f = (x >>= f) :@ (map (>>= f) y )
(PrimApp name args) >>= f = PrimApp name (map (>>= f) args )
Lam t e >>= f = Lam t (e >>>= f)
Let mname mtype bs b >>= f = Let mname mtype ( bs >>= f) (b >>>= f)
-- Smart constructors
type DummyType = Int
abstract' :: (Eq b, Monad f) => [b] -> f b -> Scope b f b
abstract' vs b = abstract (\v' -> if v' `elem` vs
then Just v'
else Nothing)
b
lam :: [Text] -> Exp DummyType Text -> Exp DummyType Text
lam vs b = Lam (zipWith (\v n -> (v, TVar n, Omega)) vs [0..])
(abstract' vs b)
-- | A smart constructor for Lam with one variable
--
-- >>> lam1 "y" (lam1 "x" (V "x" :@ [V "y"]))
-- Lam [("y",TVar 0,Omega)]
-- (Scope (Lam [("x",TVar 0,Omega)]
-- (Scope (V (B "x") :@ [V (F (V (B "y")))]))))
lam1 :: Text -> Exp DummyType Text -> Exp DummyType Text
lam1 v b = lam [v] b
let_ :: Text -> Exp DummyType Text -> Exp DummyType Text -> Exp DummyType Text
let_ v rhs bod = Let (Just v)
(Just (TVar 0, Omega))
rhs
(abstract (\var -> if var == v
then Just (Just v)
else Nothing)
bod)
callPrim :: Text -> [Exp ty a] -> Exp ty a
callPrim name = PrimApp (PrimopId name)
infixr 0 !
(!) :: Text -> Exp DummyType Text -> Exp DummyType Text
(!) = lam1
-- let_ "False" ("f" ! "t" ! V"f") (V "False")
-- let_ "True" ("f" ! "t" ! V"t") (V "True")
-- let_ "if" ("b" ! "t" ! "f" ! V"b" :@ [V"f"] :@ [V"t"]) (V "if")
-- let_ "Zero" ("z" ! "s" ! V"z") (V "Zero")
-- let_ "Succ" ("n" ! "z" ! "s" ! V"s" :@ [V"n"]) (V "Succ")
-- let_ "Zero" ("z" ! "s" ! V"z") $
-- let_ "Succ" ("n" ! "z" ! "s" ! V"s" :@ [V"n"]) $
-- let_ "one" (V"Succ" :@ [V"Zero"]) $
-- V "one"
data a :+ b = InL a | InR b
deriving (Eq,Ord,Show,Typeable,Data,Generic)
infixl 7 :+
|
buckie/juno
|
src/Juno/Hoplite/Types.hs
|
bsd-3-clause
| 12,536
| 0
| 13
| 3,467
| 4,161
| 2,181
| 1,980
| 240
| 8
|
{-# LANGUAGE Rank2Types #-}
module Control.Lens.Monadic where
import Control.Applicative ((<$>))
import Data.Functor.Identity (Identity(Identity),runIdentity)
import Data.Traversable (Traversable,mapM)
import Prelude hiding (mapM)
type MLens m s t a b
= forall f. (Traversable f) => (a -> f b) -> (s -> m (f t))
type MLens' m s a
= MLens m s s a a
mkMLens :: (Monad m) => (s -> m a) -> (s -> b -> m t)
-> MLens m s t a b
mkMLens g s f x = g x >>= mapM (s x) . f
overM :: (Functor m) => MLens m s t a b -> (a -> b) -> (s -> m t)
overM l f s = runIdentity <$> l (Identity . f) s
|
ariep/TCache
|
src/Control/Lens/Monadic.hs
|
bsd-3-clause
| 595
| 0
| 12
| 142
| 304
| 169
| 135
| 15
| 1
|
module Benches where
import Data.List ( isPrefixOf )
import System.FilePath ( (</>) )
type BenchSize = [Int]
toExamplePath :: String -> FilePath
toExamplePath f = "examples" </> (f ++ ".netdecomp")
goodSizes :: [BenchSize]
goodSizes = map (return . (2^)) ([1,3,5,9,12,15] :: [Int])
badSizes :: [BenchSize]
badSizes = map return [2, 4, 8, 10, 13, 16]
conTreeSizes :: [BenchSize]
conTreeSizes = disTreeSizes ++ [[7, 7]]
disTreeSizes :: [BenchSize]
disTreeSizes = map (\x -> [x,x]) [1..6]
nfaBenches :: [((String, Bool), ([BenchSize], Bool))]
nfaBenches = [ (("over", True), (goodSizes, False))
, (("dac", False), (goodSizes, False))
, (("philo", False), (goodSizes, True))
, (("buffer", False), (goodSizes, True))
, (("replicator", False), (goodSizes, True))
, (("iterated_choice", False), (goodSizes, True))
, (("hartstone", False), (badSizes, False))
, (("token_ring", False), (badSizes, False))
, (("cyclic", False), (badSizes, True))
, (("counter", True), (badSizes, True))
, (("conjunction_tree", False), (conTreeSizes, True))
, (("disjunction_tree", False), (disTreeSizes, True))
-- , ("rw", ([1,2..10], False))
]
doFilter :: [String] -> [((String, a), b)] -> [((String, a), b)]
doFilter [] benches = benches
doFilter wanted benches = filter (filterBench wanted) benches
where
filterBench names cand = any (`isPrefixOf` (fst . fst) cand) names
|
owst/Penrose
|
bench/Benches.hs
|
bsd-3-clause
| 1,617
| 0
| 11
| 453
| 617
| 387
| 230
| 31
| 1
|
-- http://www.reddit.com/r/dailyprogrammer/comments/21kqjq/4282014_challenge_154_hard_wumpus_cave_game/
module Main where
import Control.Applicative ((<$>))
import Control.Lens (view, ix, contains)
import Control.Lens.Fold (preuse)
import Control.Lens.Getter (to, use)
import Control.Lens.Indexed (imap)
import Control.Lens.Operators
import Control.Monad (when, unless)
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Random
import Control.Monad.State.Strict (evalStateT)
import Data.Char (toUpper)
import Data.List (intercalate, delete)
import qualified Data.Map as Map
import Data.Maybe (fromMaybe)
import qualified Data.Set as Set
import Data.Traversable (traverse)
import System.Random.Shuffle (shuffleM)
import Types
import Lenses
createRooms :: Int -> SpawnRate -> Room -> [Room]
createRooms roomNumber rate = replicate num
where num = floor $ rate * fromIntegral roomNumber
divideUp :: Int -> [a] -> [[a]]
divideUp n = take n . map (take n) . iterate (drop n)
buildCave :: (Functor m, MonadRandom m) => Int -> SpawnRates -> m Cave
buildCave n rates = do
createdRooms <- shuffleM . take nRooms $ Entrance : specialRooms ++ repeat Empty
return . Cave n . Map.fromList $ imap (\i r -> (to2d i, r)) createdRooms
where
to2d :: Int -> (Int,Int)
to2d i = (i `mod` n, i `div` n)
nRooms :: Int
nRooms = n*n
specialRooms :: [Room]
specialRooms = createRooms nRooms (view wumpusRate rates) Wumpus
++ createRooms nRooms (view trapRate rates) Trap
++ createRooms nRooms (view goldRate rates) Gold
++ createRooms nRooms (view weaponRate rates) Weapon
environment :: (Int,Int) -> [(Int,Int)]
environment (x,y) = [ (x-1,y-1)
, (x,y-1)
, (x+1,y-1)
, (x-1,y)
, (x,y)
, (x+1,y)
, (x-1,y+1)
, (x,y+1)
, (x+1,y+1)
]
environment4 :: (Int, Int) -> [(Int, Int)]
environment4 (x,y) = [ (x,y-1)
, (x-1,y)
, (x,y)
, (x+1,y)
, (x,y+1)
]
safeLookup :: (Int, Int) -> Game Room
safeLookup coord = do
exploredRooms <- use explored
if not $ coord `Set.member` exploredRooms
then return Unknown
else fromMaybe Blocked <$> preuse (cave . atCoord coord)
movePlayer :: Direction -> Game Directive
movePlayer dir = do
oldPlayerPos <- use playerCoord
let newPlayerPos = calculateNewPosition dir oldPlayerPos
roomAtPos <- safeLookup newPlayerPos
performTransition newPlayerPos roomAtPos
message :: String -> Game ()
message = liftIO . putStrLn
calculateNewPosition :: Direction -> (Int,Int) -> (Int,Int)
calculateNewPosition North (x,y) = (x,y-1)
calculateNewPosition South (x,y) = (x,y+1)
calculateNewPosition West (x,y) = (x-1,y)
calculateNewPosition East (x,y) = (x+1,y)
initializeGame :: Cave -> GameState
initializeGame c = GameState newPlayer c Set.empty initialScoreBoard
where newPlayer = Player entrancePos 0 False
entrancePos = findEntrance c
main :: IO ()
main = do
let sizeOfCave = 10
builtCave <- buildCave sizeOfCave defaultSpawnRates
let initGame = initializeGame builtCave
playerStart = initGame ^. playerCoord
evalStateT (exploreRoom playerStart >> gameLoop) initGame
gameLoop :: Game ()
gameLoop = do
message . replicate 30 $ '-'
environmentWarnings
printEnv
gameStatus
liftIO . putStr $ "Your move (? for help): "
input <- toUpper . head <$> liftIO getLine
message ""
message . replicate 30 $ '-'
executeCommand input
executeCommand :: Char -> Game ()
executeCommand c = do
directive <- case c of
'N' -> movePlayer North
'S' -> movePlayer South
'E' -> movePlayer East
'W' -> movePlayer West
'?' -> message helpText >> return Continue
'L' -> loot
'R' -> escape
'X' -> message "Goodbye." >> return Stop
_ -> message ("Unknown command:" ++ [c] ++ ".") >> return Continue
case directive of
Continue -> gameLoop
GameOver -> gameOver
GameWon -> gameWon
Stop -> return ()
escape :: Game Directive
escape = do
curRoom <- use playerRoom
if curRoom == Entrance
then return GameWon
else message "No entrance here." >> return Continue
loot :: Game Directive
loot = do
curRoom <- use playerRoom
if curRoom `notElem` [Weapon, Gold]
then message "Nothing to loot." >> return Continue
else pickup curRoom >> return Continue
pickup :: Room -> Game ()
pickup Gold = do
message "You pick up the coins."
scores . purse += 1
playerRoom .= Empty
pickup Weapon = do
message "You pick up the weapon."
playerHasWeapon .= True
playerRoom .= Empty
cave . weaponRooms .= Gold
pickup _ = message "Nothing to pickup here."
helpText :: String
helpText = intercalate "\n" [ "? - Show this help"
, "N - Go north if possible"
, "S - Go south if possible"
, "W - Go west if possible"
, "E - Go east if possible"
, "L - Loot either gold or weapon"
, "R - run of the cave (only at entrance)"
, "X - quit game"
]
withDirective :: Directive -> Game ()
withDirective Continue = gameLoop
withDirective GameOver = gameOver
withDirective GameWon = gameWon
withDirective Stop = return ()
gameStatus :: Game ()
gameStatus = do
hasWeapon <- use playerHasWeapon
gold <- use $ scores . purse
let weaponStr = if hasWeapon
then "You have a weapon."
else "You are not armed."
goldStr = "Gold: " ++ show gold
pts <- show <$> calculateScore
message $ weaponStr ++ " " ++ goldStr ++ " Score: " ++ pts
environmentWarnings :: Game ()
environmentWarnings = do
pos <- use playerCoord
env <- delete pos . environment4 <$> use playerCoord
c <- use cave
let nbs = concatMap (\coord -> c ^.. atCoord coord) env
when (Wumpus `elem` nbs) $ message "You smell a foul stench."
when (Trap `elem` nbs) $ message "You hear a howling wind."
gameOver :: Game ()
gameOver = message "Game over." >> gameEvaluation
calculateScore :: Game Int
calculateScore = do
monsters <- use $ scores . slayedMonsters
gold <- use $ scores . purse
hasWeapon <- use playerHasWeapon
roomPts <- use $ scores . exploredEmptyRooms
let monstertPts = monsters * 10
goldPts = gold * 5
weaponPts = if hasWeapon then 5 else 0
return $ monstertPts + goldPts + weaponPts + roomPts
gameEvaluation :: Game ()
gameEvaluation = do
pts <- calculateScore
message $ "You earned " ++ show pts ++ " points."
gameWon :: Game ()
gameWon = message "You win!" >> gameEvaluation
printEnv :: Game ()
printEnv = do
pos <- use playerCoord
let env = environment pos
rs <- divideUp 3 <$> traverse safeLookup env
let showed = map (view (traverse . to showRoom)) rs
message $ intercalate "\n" (showed & ix 1 . ix 1 .~ '@')
showRoom :: Room -> String
showRoom Entrance = "^"
showRoom Empty = "."
showRoom Blocked = "#"
showRoom Weapon = "W"
showRoom Gold = "$"
showRoom Trap = "%"
showRoom Wumpus = "!"
showRoom Unknown = "?"
findEntrance :: Cave -> (Int,Int)
findEntrance c = fst
. head
. Map.toList
. Map.filter (== Entrance) $ roomMap
where roomMap = view rooms c
exploreRoom :: (Int,Int) -> Game ()
exploreRoom pos = explored . contains pos .= True
performTransition :: (Int,Int) -> Room -> Game Directive
performTransition _ Blocked = do
message "Gmpft. There's a wall."
return Continue
performTransition _ Trap = do
message "Omg is it dark in here, wait whats there? AAAAAAAAAAAAHhhhh SPLAT."
return GameOver
performTransition newPos Unknown = do
message "You feel around..."
exploreRoom newPos
r <- safeLookup newPos
performTransition newPos r
performTransition newPos Empty = do
message "There is nothing."
curPos <- use playerCoord
alreadySeen <- use $ explored . contains curPos
unless alreadySeen $ scores . exploredEmptyRooms += 1
playerCoord .= newPos
return Continue
performTransition newPos Wumpus = do
hasWeapon <- use playerHasWeapon
if hasWeapon
then do
message "A wild wumpus appears!"
message "You use your weapon to slay it."
playerCoord .= newPos
playerRoom .= Empty
scores . slayedMonsters += 1
return Continue
else message "Oh no the Wumpus eats you." >> return GameOver
performTransition newPos Weapon = do
message "There is a sword on the floor."
playerCoord .= newPos
return Continue
performTransition newPos Gold = do
message "Gold is shimmering in a corner of the room."
playerCoord .= newPos
return Continue
performTransition newPos Entrance = do
message "There is the exit!"
playerCoord .= newPos
return Continue
|
markus1189/wumpus-cave
|
Wumpus.hs
|
bsd-3-clause
| 9,121
| 0
| 16
| 2,471
| 2,905
| 1,470
| 1,435
| -1
| -1
|
{-# OPTIONS_GHC -Wall #-}
module AST.Expression.Optimized
( Def(..), Facts(..), dummyFacts
, Expr(..), Jump(..), Branch(..)
) where
import qualified AST.Expression.General as General
import qualified AST.Literal as Literal
import qualified AST.Module.Name as ModuleName
import qualified AST.Type as Type
import qualified AST.Variable as Var
import qualified Optimize.Patterns.DecisionTree as DT
import qualified Reporting.Region as R
-- DEFINITIONS
data Def
= Def Facts String Expr
| TailDef Facts String [String] Expr
deriving (Eq)
data Facts = Facts
{ home :: Maybe ModuleName.Canonical
, dependencies :: [Var.TopLevel]
}
deriving (Eq)
dummyFacts :: Facts
dummyFacts =
Facts Nothing []
-- EXPRESSIONS
data Expr
= Literal Literal.Literal
| Var Var.Canonical
| Range Expr Expr
| ExplicitList [Expr]
| Binop Var.Canonical Expr Expr
| Function [String] Expr
| Call Expr [Expr]
| TailCall String [String] [Expr]
| If [(Expr, Expr)] Expr
| Let [Def] Expr
| Case String (DT.DecisionTree Jump) [(Int, Branch)]
| Data String [Expr]
| DataAccess Expr Int
| Access Expr String
| Update Expr [(String, Expr)]
| Record [(String, Expr)]
| Port (General.PortImpl Expr Type.Canonical)
| GLShader String String Literal.GLShaderTipe
| Crash R.Region (Maybe String)
deriving (Eq)
data Jump
= Inline Branch
| Jump Int
deriving (Eq)
data Branch = Branch
{ _substitutions :: [(String, DT.Path)]
, _branch :: Expr
}
deriving (Eq)
|
Axure/elm-compiler
|
src/AST/Expression/Optimized.hs
|
bsd-3-clause
| 1,574
| 0
| 11
| 372
| 493
| 304
| 189
| 51
| 1
|
-- |Parser module for 6502 assembly files
module AsmParser
( Statement(..)
, Value(..)
, Operand(..)
, parseAssembler
)
where
import Arch6502
import Data.Char
import Error
import Numeric
import System.FilePath
import Text.Parsec.Char
import Text.ParserCombinators.Parsec
-- |Statements for assembly programs
data Statement = Data Int [Value] -- ^ Data definitions
| Equ String Value -- ^ Defines a symbolic name as alias for a constant value
| Include String -- ^ Insert data from referenced file into assembler output
| Instruction Mnemonic Operand -- ^ A 6502 instruction with operand
| Label String -- ^ Define a new label
| Org Value -- ^ Defines the target address assembling will write its output
deriving (Eq,Show)
-- |Instruction operands bundle an addressing mode and a value
data Operand = Operand AddressingMode Value
deriving (Eq,Show)
-- |Constant values or symbolic values with constant offset
data Value = Constant Int -- ^ Immediate constants
| Symbol String Int -- ^ Symbolic references with constant byte-offset
deriving (Eq,Show)
-- |The main parser function
parseAssembler :: String -> IO [Statement]
parseAssembler filename =
parseFromFile asmProgram filename >>= either (exitWithError . ("Error: "++) . show) return
-- |Parser for assembler programs
asmProgram :: Parser [Statement]
asmProgram = do
p <- endBy (whiteSpace *> line) endOfLine <* eof
return $ concat p
where
line = do
l <- asmLabels
s <- option [] asmStatement
_ <- option () comment
return $ l++s
-- |Parser for assembler labels
asmLabels :: Parser [Statement]
asmLabels = many (try oneLabel)
where
oneLabel = do
l <- lexeme identifier
_ <- lexeme (char ':') <?> "label designator"
return $ Label (map toLower l)
-- |Parser for assembler statements which may be directives or instructions
asmStatement :: Parser [Statement]
asmStatement = try equ
<|> try org
<|> try hex
<|> try ascii
<|> try cbm
<|> try byte
<|> try word
<|> try include
<|> instruction
<?> "assembler directive/instruction"
where
equ = do
k <- lexeme identifier
_ <- lexeme $ caseString "equ"
v <- asmValue
return $ [Equ (map toLower k) v]
org = do
_ <- lexeme $ caseString "org"
v <- asmValue
return $ [Org v]
hex = do
_ <- lexeme $ caseString "hexdata"
s <- many1 (lexeme $ char '$' *> many1 hexDigit)
return $ [Data 1 $ map (\v -> Constant $ fromBase 16 v) s]
ascii = do
_ <- lexeme $ caseString "string"
s <- lexeme stringLiteral
return $ [Data 1 $ map (\v -> Constant $ ord v) s]
cbm = do
_ <- lexeme $ caseString "cbmstring"
s <- lexeme stringLiteral
return $ [Data 1 $ map (\v -> Constant $ ord v - if isAsciiLower v then 96 else 0) s]
byte = do
_ <- lexeme $ caseString "byte"
v <- asmValueOrSymbol
return $ [Data 1 [v]]
word = do
_ <- lexeme $ caseString "word"
v <- asmValueOrSymbol
return $ [Data 2 [v]]
include = do
_ <- lexeme $ caseString "include-prg"
f <- lexeme stringLiteral
return $ [Include $ makeValid f]
instruction = do
m <- asmMnemonic
p <- option (Operand Implied $ Constant 0) asmOperand
return $ [Instruction m $ refineOp m p]
refineOp m p | isShiftRotate m, Operand Implied v <- p = Operand Accumulator v
| isBranch m, Operand Absolute v <- p = Operand Relative v
| otherwise = p
-- |Parser for instruction mnemonics
asmMnemonic :: Parser Mnemonic
asmMnemonic = do w <- try (lexeme asmMnemonic') <?> "instruction mnemonic"
return $ read $ map toUpper w
where
asmMnemonic' = (choice $ map (caseString . show) allMnemonics) <* notFollowedBy identLetter
-- |Parser for instruction operands with constant or symbolic offsets for all addressing modes
asmOperand :: Parser Operand
asmOperand = try accumulator
<|> try absoluteX
<|> try absoluteY
<|> try absolute
<|> try indexedIndirect
<|> try indirectIndexed
<|> try indirectMode
<|> immediate
<?> "instruction operand"
where
absolute = do
v <- asmValueOrSymbol
return $ Operand (if isZeroPage v then ZeroPage else Absolute) v
absoluteX = do
v <- asmValueOrSymbol <* index "xX"
return $ Operand (if isZeroPage v then ZeroPageX else AbsoluteX) v
absoluteY = do
v <- asmValueOrSymbol <* index "yY"
return $ Operand (if isZeroPage v then ZeroPageY else AbsoluteY) v
accumulator = do
_ <- lexeme $ oneOf "aA" <* notFollowedBy identLetter
return $ Operand Accumulator (Constant 0)
immediate = do
v <- char '#' *> asmValueOrSymbol
return $ Operand Immediate v
indirectMode = do
v <- parens asmValueOrSymbol
return $ Operand Indirect v
indexedIndirect = do
v <- parens (asmValueOrSymbol <* index "xX")
return $ Operand IndexedIndirect v
indirectIndexed = do
v <- parens asmValueOrSymbol <* index "yY"
return $ Operand IndirectIndexed v
parens p = between (lexeme $ char '(') (lexeme $ char ')') p
index i = lexeme (char ',') <* lexeme (oneOf i)
isZeroPage p | Constant c <- p, c < 256 = True
| otherwise = False
-- |Parser for binary, octal, decimal, or hexadecimal values
asmValue :: Parser Value
asmValue = try binValue
<|> try octValue
<|> try decValue
<|> try hexValue
<?> "integer constant"
where
binValue = do
v <- lexeme $ char '%' *> many1 (oneOf "01")
return $ Constant $ fromBase 2 v
octValue = do
v <- lexeme $ char '0' *> many1 octDigit
return $ Constant $ fromBase 8 v
decValue = do
v <- lexeme $ many1 digit
return $ Constant $ fromBase 10 v
hexValue = do
v <- lexeme $ char '$' *> many1 hexDigit
return $ Constant $ fromBase 16 v
-- |Parser for binary, octal, decimal, or hexadecimal values or symbols
asmValueOrSymbol :: Parser Value
asmValueOrSymbol = try asmValue
<|> symbol
<?> "integer constant or symbolic value"
where
symbol = do
s <- lexeme identifier
o <- option 0 (try offset)
return $ Symbol (map toLower s) o
offset = do
s <- lexeme $ oneOf "+-"
Constant o <- asmValue <?> "integer offset"
return $ if s=='+' then o else -o
-- |Convert digit strings of a given base to an integer value.
fromBase :: Int -> String -> Int
fromBase b = fst . head . readInt b ((<b) . digitToInt) digitToInt
-- |Parser for line based comments
comment :: Parser ()
comment = char ';' *> (skipMany $ noneOf "\r\n")
-- |Parser for identifiers
identStart :: Parser Char
identStart = letter <|> char '_' <?> ""
identLetter :: Parser Char
identLetter = alphaNum <|> char '_' <?> ""
identifier :: Parser String
identifier = do
p <- identStart
q <- many identLetter
return $ p:q
-- |Parser for string literals
stringLiteral :: Parser String
stringLiteral = between (char '"') (char '"') (many $ noneOf "\"\n\r")
-- |Parser for case insensitive strings
caseString :: String -> Parser String
caseString s = try (mapM (\c -> char (toLower c) <|> char (toUpper c)) s)
-- |Parser that skips any whitespace except newline characters
whiteSpace :: Parser ()
whiteSpace = skipMany $ oneOf " \t\v"
-- |Parser generator that applies a parser and the whiteSpace parser after that
lexeme :: Parser a -> Parser a
lexeme p = p <* whiteSpace
|
m-schmidt/Asm6502
|
src/AsmParser.hs
|
bsd-3-clause
| 7,982
| 0
| 17
| 2,409
| 2,319
| 1,131
| 1,188
| 186
| 4
|
--
-- (c) The University of Glasgow 2002-2006
--
-- Functions over HsSyn specialised to RdrName.
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
module RdrHsSyn (
mkHsOpApp,
mkHsIntegral, mkHsFractional, mkHsIsString,
mkHsDo, mkSpliceDecl,
mkRoleAnnotDecl,
mkClassDecl,
mkTyData, mkDataFamInst,
mkTySynonym, mkTyFamInstEqn,
mkTyFamInst,
mkFamDecl,
splitCon, mkInlinePragma,
mkPatSynMatchGroup,
mkRecConstrOrUpdate, -- HsExp -> [HsFieldUpdate] -> P HsExp
mkTyClD, mkInstD,
cvBindGroup,
cvBindsAndSigs,
cvTopDecls,
placeHolderPunRhs,
-- Stuff to do with Foreign declarations
mkImport,
parseCImport,
mkExport,
mkExtName, -- RdrName -> CLabelString
mkGadtDecl, -- [Located RdrName] -> LHsType RdrName -> ConDecl RdrName
mkSimpleConDecl,
mkDeprecatedGadtRecordDecl,
mkATDefault,
-- Bunch of functions in the parser monad for
-- checking and constructing values
checkPrecP, -- Int -> P Int
checkContext, -- HsType -> P HsContext
checkPattern, -- HsExp -> P HsPat
bang_RDR,
checkPatterns, -- SrcLoc -> [HsExp] -> P [HsPat]
checkMonadComp, -- P (HsStmtContext RdrName)
checkCommand, -- LHsExpr RdrName -> P (LHsCmd RdrName)
checkValDef, -- (SrcLoc, HsExp, HsRhs, [HsDecl]) -> P HsDecl
checkValSig, -- (SrcLoc, HsExp, HsRhs, [HsDecl]) -> P HsDecl
checkPartialTypeSignature,
checkNoPartialType,
checkValidPatSynSig,
checkDoAndIfThenElse,
checkRecordSyntax,
checkValidDefaults,
parseErrorSDoc,
-- Help with processing exports
ImpExpSubSpec(..),
mkModuleImpExp,
mkTypeImpExp
) where
import HsSyn -- Lots of it
import Class ( FunDep )
import CoAxiom ( Role, fsFromRole )
import RdrName ( RdrName, isRdrTyVar, isRdrTc, mkUnqual, rdrNameOcc,
isRdrDataCon, isUnqual, getRdrName, setRdrNameSpace,
rdrNameSpace )
import OccName ( tcClsName, isVarNameSpace )
import Name ( Name )
import BasicTypes ( maxPrecedence, Activation(..), RuleMatchInfo,
InlinePragma(..), InlineSpec(..), Origin(..),
SourceText )
import TcEvidence ( idHsWrapper )
import Lexer
import TysWiredIn ( unitTyCon, unitDataCon )
import ForeignCall
import OccName ( srcDataName, varName, isDataOcc, isTcOcc,
occNameString )
import PrelNames ( forall_tv_RDR, allNameStrings )
import DynFlags
import SrcLoc
import OrdList ( OrdList, fromOL )
import Bag ( emptyBag, consBag )
import Outputable
import FastString
import Maybes
import Util
import ApiAnnotation
import Control.Applicative ((<$>))
import Control.Monad
import Text.ParserCombinators.ReadP as ReadP
import Data.Char
import Data.Data ( dataTypeOf, fromConstr, dataTypeConstrs )
import Data.List ( partition )
import qualified Data.Set as Set ( fromList, difference, member )
#include "HsVersions.h"
{- **********************************************************************
Construction functions for Rdr stuff
********************************************************************* -}
-- | mkClassDecl builds a RdrClassDecl, filling in the names for tycon and
-- datacon by deriving them from the name of the class. We fill in the names
-- for the tycon and datacon corresponding to the class, by deriving them
-- from the name of the class itself. This saves recording the names in the
-- interface file (which would be equally good).
-- Similarly for mkConDecl, mkClassOpSig and default-method names.
-- *** See "THE NAMING STORY" in HsDecls ****
mkTyClD :: LTyClDecl n -> LHsDecl n
mkTyClD (L loc d) = L loc (TyClD d)
mkInstD :: LInstDecl n -> LHsDecl n
mkInstD (L loc d) = L loc (InstD d)
mkClassDecl :: SrcSpan
-> Located (Maybe (LHsContext RdrName), LHsType RdrName)
-> Located (a,[Located (FunDep (Located RdrName))])
-> OrdList (LHsDecl RdrName)
-> P (LTyClDecl RdrName)
mkClassDecl loc (L _ (mcxt, tycl_hdr)) fds where_cls
= do { (binds, sigs, ats, at_insts, _, docs) <- cvBindsAndSigs where_cls
; let cxt = fromMaybe (noLoc []) mcxt
; (cls, tparams,ann) <- checkTyClHdr tycl_hdr
; mapM_ (\a -> a loc) ann -- Add any API Annotations to the top SrcSpan
-- Partial type signatures are not allowed in a class definition
; checkNoPartialSigs sigs cls
; tyvars <- checkTyVarsP (ptext (sLit "class")) whereDots cls tparams
; at_defs <- mapM (eitherToP . mkATDefault) at_insts
; return (L loc (ClassDecl { tcdCtxt = cxt, tcdLName = cls, tcdTyVars = tyvars,
tcdFDs = snd (unLoc fds), tcdSigs = sigs,
tcdMeths = binds,
tcdATs = ats, tcdATDefs = at_defs, tcdDocs = docs,
tcdFVs = placeHolderNames })) }
mkATDefault :: LTyFamInstDecl RdrName
-> Either (SrcSpan, SDoc) (LTyFamDefltEqn RdrName)
-- Take a type-family instance declaration and turn it into
-- a type-family default equation for a class declaration
-- We parse things as the former and use this function to convert to the latter
--
-- We use the Either monad because this also called
-- from Convert.hs
mkATDefault (L loc (TyFamInstDecl { tfid_eqn = L _ e }))
| TyFamEqn { tfe_tycon = tc, tfe_pats = pats, tfe_rhs = rhs } <- e
= do { tvs <- checkTyVars (ptext (sLit "default")) equalsDots tc (hswb_cts pats)
; return (L loc (TyFamEqn { tfe_tycon = tc
, tfe_pats = tvs
, tfe_rhs = rhs })) }
-- | Check that none of the given type signatures of the class definition
-- ('Located RdrName') are partial type signatures. An error will be reported
-- for each wildcard found in a (partial) type signature. We do this check
-- because we want the signatures in a class definition to be fully specified.
checkNoPartialSigs :: [LSig RdrName] -> Located RdrName -> P ()
checkNoPartialSigs sigs cls_name =
sequence_ [ whenIsJust mb_loc $ \loc -> parseErrorSDoc loc $ err sig
| L _ sig@(TypeSig _ ty _) <- sigs
, let mb_loc = maybeLocation $ findWildcards ty ]
where err sig =
vcat [ text "The type signature of a class method cannot be partial:"
, ppr sig
, text "In the class declaration for " <> quotes (ppr cls_name) ]
-- | Check that none of the given constructors contain a wildcard (like in a
-- partial type signature). An error will be reported for each wildcard found
-- in a (partial) constructor definition. We do this check because we want the
-- type of a constructor to be fully specified.
checkNoPartialCon :: [LConDecl RdrName] -> P ()
checkNoPartialCon con_decls =
sequence_ [ whenIsJust mb_loc $ \loc -> parseErrorSDoc loc $ err cd
| L _ cd@(ConDecl { con_cxt = cxt, con_res = res,
con_details = details }) <- con_decls
, let mb_loc = maybeLocation $
concatMap findWildcards (unLoc cxt) ++
containsWildcardRes res ++
concatMap findWildcards
(hsConDeclArgTys details) ]
where err con_decl = text "A constructor cannot have a partial type:" $$
ppr con_decl
containsWildcardRes (ResTyGADT _ ty) = findWildcards ty
containsWildcardRes ResTyH98 = notFound
-- | Check that the given type does not contain wildcards, and is thus not a
-- partial type. If it contains wildcards, report an error with the given
-- message.
checkNoPartialType :: SDoc -> LHsType RdrName -> P ()
checkNoPartialType context_msg ty =
whenFound (findWildcards ty) $ \loc -> parseErrorSDoc loc err
where err = text "Wildcard not allowed" $$ context_msg
-- | Represent wildcards found in a type. Used for reporting errors for types
-- that mustn't contain wildcards.
data FoundWildcard = Found { location :: SrcSpan }
| FoundNamed { location :: SrcSpan, _name :: RdrName }
-- | Indicate that no wildcards were found.
notFound :: [FoundWildcard]
notFound = []
-- | Call the function (second argument), accepting the location of the
-- wildcard, on the first wildcard that was found, if any.
whenFound :: [FoundWildcard] -> (SrcSpan -> P ()) -> P ()
whenFound (Found loc:_) f = f loc
whenFound (FoundNamed loc _:_) f = f loc
whenFound _ _ = return ()
-- | Extract the location of the first wildcard, if any.
maybeLocation :: [FoundWildcard] -> Maybe SrcSpan
maybeLocation fws = location <$> listToMaybe fws
-- | Extract the named wildcards from the wildcards that were found.
namedWildcards :: [FoundWildcard] -> [RdrName]
namedWildcards fws = [name | FoundNamed _ name <- fws]
-- | Split the found wildcards into a list of found unnamed wildcard and found
-- named wildcards.
splitUnnamedNamed :: [FoundWildcard] -> ([FoundWildcard], [FoundWildcard])
splitUnnamedNamed = partition (\f -> case f of { Found _ -> True ; _ -> False})
-- | Return a list of the wildcards found while traversing the given type.
findWildcards :: LHsType RdrName -> [FoundWildcard]
findWildcards (L l ty) = case ty of
(HsForAllTy _ xtr _ (L _ ctxt) x) -> (map Found $ maybeToList xtr) ++
concatMap go ctxt ++ go x
(HsAppTy x y) -> go x ++ go y
(HsFunTy x y) -> go x ++ go y
(HsListTy x) -> go x
(HsPArrTy x) -> go x
(HsTupleTy _ xs) -> concatMap go xs
(HsOpTy x _ y) -> go x ++ go y
(HsParTy x) -> go x
(HsIParamTy _ x) -> go x
(HsEqTy x y) -> go x ++ go y
(HsKindSig x y) -> go x ++ go y
(HsDocTy x _) -> go x
(HsBangTy _ x) -> go x
(HsRecTy xs) ->
concatMap (go . getBangType . cd_fld_type . unLoc) xs
(HsExplicitListTy _ xs) -> concatMap go xs
(HsExplicitTupleTy _ xs) -> concatMap go xs
(HsWrapTy _ x) -> go (noLoc x)
HsWildcardTy -> [Found l]
(HsNamedWildcardTy n) -> [FoundNamed l n]
-- HsTyVar, HsQuasiQuoteTy, HsSpliceTy, HsCoreTy, HsTyLit
_ -> notFound
where go = findWildcards
mkTyData :: SrcSpan
-> NewOrData
-> Maybe (Located CType)
-> Located (Maybe (LHsContext RdrName), LHsType RdrName)
-> Maybe (LHsKind RdrName)
-> [LConDecl RdrName]
-> Maybe (Located [LHsType RdrName])
-> P (LTyClDecl RdrName)
mkTyData loc new_or_data cType (L _ (mcxt, tycl_hdr)) ksig data_cons maybe_deriv
= do { (tc, tparams,ann) <- checkTyClHdr tycl_hdr
; mapM_ (\a -> a loc) ann -- Add any API Annotations to the top SrcSpan
; tyvars <- checkTyVarsP (ppr new_or_data) equalsDots tc tparams
; defn <- mkDataDefn new_or_data cType mcxt ksig data_cons maybe_deriv
; return (L loc (DataDecl { tcdLName = tc, tcdTyVars = tyvars,
tcdDataDefn = defn,
tcdFVs = placeHolderNames })) }
mkDataDefn :: NewOrData
-> Maybe (Located CType)
-> Maybe (LHsContext RdrName)
-> Maybe (LHsKind RdrName)
-> [LConDecl RdrName]
-> Maybe (Located [LHsType RdrName])
-> P (HsDataDefn RdrName)
mkDataDefn new_or_data cType mcxt ksig data_cons maybe_deriv
= do { checkDatatypeContext mcxt
; checkNoPartialCon data_cons
; whenIsJust maybe_deriv $
\(L _ deriv) -> mapM_ (checkNoPartialType (errDeriv deriv)) deriv
; let cxt = fromMaybe (noLoc []) mcxt
; return (HsDataDefn { dd_ND = new_or_data, dd_cType = cType
, dd_ctxt = cxt
, dd_cons = data_cons
, dd_kindSig = ksig
, dd_derivs = maybe_deriv }) }
where errDeriv deriv = text "In the deriving items:" <+>
pprHsContextNoArrow deriv
mkTySynonym :: SrcSpan
-> LHsType RdrName -- LHS
-> LHsType RdrName -- RHS
-> P (LTyClDecl RdrName)
mkTySynonym loc lhs rhs
= do { (tc, tparams,ann) <- checkTyClHdr lhs
; mapM_ (\a -> a loc) ann -- Add any API Annotations to the top SrcSpan
; tyvars <- checkTyVarsP (ptext (sLit "type")) equalsDots tc tparams
; let err = text "In type synonym" <+> quotes (ppr tc) <>
colon <+> ppr rhs
; checkNoPartialType err rhs
; return (L loc (SynDecl { tcdLName = tc, tcdTyVars = tyvars
, tcdRhs = rhs, tcdFVs = placeHolderNames })) }
mkTyFamInstEqn :: LHsType RdrName
-> LHsType RdrName
-> P (TyFamInstEqn RdrName,[AddAnn])
mkTyFamInstEqn lhs rhs
= do { (tc, tparams,ann) <- checkTyClHdr lhs
; let err xhs = hang (text "In type family instance equation of" <+>
quotes (ppr tc) <> colon)
2 (ppr xhs)
; checkNoPartialType (err lhs) lhs
; checkNoPartialType (err rhs) rhs
; return (TyFamEqn { tfe_tycon = tc
, tfe_pats = mkHsWithBndrs tparams
, tfe_rhs = rhs },
ann) }
mkDataFamInst :: SrcSpan
-> NewOrData
-> Maybe (Located CType)
-> Located (Maybe (LHsContext RdrName), LHsType RdrName)
-> Maybe (LHsKind RdrName)
-> [LConDecl RdrName]
-> Maybe (Located [LHsType RdrName])
-> P (LInstDecl RdrName)
mkDataFamInst loc new_or_data cType (L _ (mcxt, tycl_hdr)) ksig data_cons maybe_deriv
= do { (tc, tparams,ann) <- checkTyClHdr tycl_hdr
; mapM_ (\a -> a loc) ann -- Add any API Annotations to the top SrcSpan
; defn <- mkDataDefn new_or_data cType mcxt ksig data_cons maybe_deriv
; return (L loc (DataFamInstD (
DataFamInstDecl { dfid_tycon = tc, dfid_pats = mkHsWithBndrs tparams
, dfid_defn = defn, dfid_fvs = placeHolderNames }))) }
mkTyFamInst :: SrcSpan
-> LTyFamInstEqn RdrName
-> P (LInstDecl RdrName)
mkTyFamInst loc eqn
= return (L loc (TyFamInstD (TyFamInstDecl { tfid_eqn = eqn
, tfid_fvs = placeHolderNames })))
mkFamDecl :: SrcSpan
-> FamilyInfo RdrName
-> LHsType RdrName -- LHS
-> Maybe (LHsKind RdrName) -- Optional kind signature
-> P (LTyClDecl RdrName)
mkFamDecl loc info lhs ksig
= do { (tc, tparams,ann) <- checkTyClHdr lhs
; mapM_ (\a -> a loc) ann -- Add any API Annotations to the top SrcSpan
; tyvars <- checkTyVarsP (ppr info) equals_or_where tc tparams
; return (L loc (FamDecl (FamilyDecl { fdInfo = info, fdLName = tc
, fdTyVars = tyvars, fdKindSig = ksig }))) }
where
equals_or_where = case info of
DataFamily -> empty
OpenTypeFamily -> empty
ClosedTypeFamily {} -> whereDots
mkSpliceDecl :: LHsExpr RdrName -> HsDecl RdrName
-- If the user wrote
-- [pads| ... ] then return a QuasiQuoteD
-- $(e) then return a SpliceD
-- but if she wrote, say,
-- f x then behave as if she'd written $(f x)
-- ie a SpliceD
mkSpliceDecl lexpr@(L loc expr)
| HsQuasiQuoteE qq <- expr = QuasiQuoteD qq
| HsSpliceE is_typed splice <- expr = ASSERT( not is_typed )
SpliceD (SpliceDecl (L loc splice) ExplicitSplice)
| otherwise = SpliceD (SpliceDecl (L loc splice) ImplicitSplice)
where
splice = mkHsSplice lexpr
mkRoleAnnotDecl :: SrcSpan
-> Located RdrName -- type being annotated
-> [Located (Maybe FastString)] -- roles
-> P (LRoleAnnotDecl RdrName)
mkRoleAnnotDecl loc tycon roles
= do { roles' <- mapM parse_role roles
; return $ L loc $ RoleAnnotDecl tycon roles' }
where
role_data_type = dataTypeOf (undefined :: Role)
all_roles = map fromConstr $ dataTypeConstrs role_data_type
possible_roles = [(fsFromRole role, role) | role <- all_roles]
parse_role (L loc_role Nothing) = return $ L loc_role Nothing
parse_role (L loc_role (Just role))
= case lookup role possible_roles of
Just found_role -> return $ L loc_role $ Just found_role
Nothing ->
let nearby = fuzzyLookup (unpackFS role) (mapFst unpackFS possible_roles) in
parseErrorSDoc loc_role
(text "Illegal role name" <+> quotes (ppr role) $$
suggestions nearby)
suggestions [] = empty
suggestions [r] = text "Perhaps you meant" <+> quotes (ppr r)
-- will this last case ever happen??
suggestions list = hang (text "Perhaps you meant one of these:")
2 (pprWithCommas (quotes . ppr) list)
{- **********************************************************************
#cvBinds-etc# Converting to @HsBinds@, etc.
********************************************************************* -}
-- | Function definitions are restructured here. Each is assumed to be recursive
-- initially, and non recursive definitions are discovered by the dependency
-- analyser.
-- | Groups together bindings for a single function
cvTopDecls :: OrdList (LHsDecl RdrName) -> [LHsDecl RdrName]
cvTopDecls decls = go (fromOL decls)
where
go :: [LHsDecl RdrName] -> [LHsDecl RdrName]
go [] = []
go (L l (ValD b) : ds) = L l' (ValD b') : go ds'
where (L l' b', ds') = getMonoBind (L l b) ds
go (d : ds) = d : go ds
-- Declaration list may only contain value bindings and signatures.
cvBindGroup :: OrdList (LHsDecl RdrName) -> P (HsValBinds RdrName)
cvBindGroup binding
= do { (mbs, sigs, fam_ds, tfam_insts, dfam_insts, _) <- cvBindsAndSigs binding
; ASSERT( null fam_ds && null tfam_insts && null dfam_insts)
return $ ValBindsIn mbs sigs }
cvBindsAndSigs :: OrdList (LHsDecl RdrName)
-> P (LHsBinds RdrName, [LSig RdrName], [LFamilyDecl RdrName]
, [LTyFamInstDecl RdrName], [LDataFamInstDecl RdrName], [LDocDecl])
-- Input decls contain just value bindings and signatures
-- and in case of class or instance declarations also
-- associated type declarations. They might also contain Haddock comments.
cvBindsAndSigs fb = go (fromOL fb)
where
go [] = return (emptyBag, [], [], [], [], [])
go (L l (ValD b) : ds)
= do { (bs, ss, ts, tfis, dfis, docs) <- go ds'
; return (b' `consBag` bs, ss, ts, tfis, dfis, docs) }
where
(b', ds') = getMonoBind (L l b) ds
go (L l decl : ds)
= do { (bs, ss, ts, tfis, dfis, docs) <- go ds
; case decl of
SigD s
-> return (bs, L l s : ss, ts, tfis, dfis, docs)
TyClD (FamDecl t)
-> return (bs, ss, L l t : ts, tfis, dfis, docs)
InstD (TyFamInstD { tfid_inst = tfi })
-> return (bs, ss, ts, L l tfi : tfis, dfis, docs)
InstD (DataFamInstD { dfid_inst = dfi })
-> return (bs, ss, ts, tfis, L l dfi : dfis, docs)
DocD d
-> return (bs, ss, ts, tfis, dfis, L l d : docs)
SpliceD d
-> parseErrorSDoc l $
hang (text "Declaration splices are allowed only" <+>
text "at the top level:")
2 (ppr d)
_ -> pprPanic "cvBindsAndSigs" (ppr decl) }
-----------------------------------------------------------------------------
-- Group function bindings into equation groups
getMonoBind :: LHsBind RdrName -> [LHsDecl RdrName]
-> (LHsBind RdrName, [LHsDecl RdrName])
-- Suppose (b',ds') = getMonoBind b ds
-- ds is a list of parsed bindings
-- b is a MonoBinds that has just been read off the front
-- Then b' is the result of grouping more equations from ds that
-- belong with b into a single MonoBinds, and ds' is the depleted
-- list of parsed bindings.
--
-- All Haddock comments between equations inside the group are
-- discarded.
--
-- No AndMonoBinds or EmptyMonoBinds here; just single equations
getMonoBind (L loc1 (FunBind { fun_id = fun_id1@(L _ f1), fun_infix = is_infix1,
fun_matches = MG { mg_alts = mtchs1 } })) binds
| has_args mtchs1
= go is_infix1 mtchs1 loc1 binds []
where
go is_infix mtchs loc
(L loc2 (ValD (FunBind { fun_id = L _ f2, fun_infix = is_infix2,
fun_matches = MG { mg_alts = mtchs2 } })) : binds) _
| f1 == f2 = go (is_infix || is_infix2) (mtchs2 ++ mtchs)
(combineSrcSpans loc loc2) binds []
go is_infix mtchs loc (doc_decl@(L loc2 (DocD _)) : binds) doc_decls
= let doc_decls' = doc_decl : doc_decls
in go is_infix mtchs (combineSrcSpans loc loc2) binds doc_decls'
go is_infix mtchs loc binds doc_decls
= (L loc (makeFunBind fun_id1 is_infix (reverse mtchs)), (reverse doc_decls) ++ binds)
-- Reverse the final matches, to get it back in the right order
-- Do the same thing with the trailing doc comments
getMonoBind bind binds = (bind, binds)
has_args :: [LMatch RdrName (LHsExpr RdrName)] -> Bool
has_args [] = panic "RdrHsSyn:has_args"
has_args ((L _ (Match _ args _ _)) : _) = not (null args)
-- Don't group together FunBinds if they have
-- no arguments. This is necessary now that variable bindings
-- with no arguments are now treated as FunBinds rather
-- than pattern bindings (tests/rename/should_fail/rnfail002).
{- **********************************************************************
#PrefixToHS-utils# Utilities for conversion
********************************************************************* -}
-----------------------------------------------------------------------------
-- splitCon
-- When parsing data declarations, we sometimes inadvertently parse
-- a constructor application as a type (eg. in data T a b = C a b `D` E a b)
-- This function splits up the type application, adds any pending
-- arguments, and converts the type constructor back into a data constructor.
splitCon :: LHsType RdrName
-> P (Located RdrName, HsConDeclDetails RdrName)
-- This gets given a "type" that should look like
-- C Int Bool
-- or C { x::Int, y::Bool }
-- and returns the pieces
splitCon ty
= split ty []
where
split (L _ (HsAppTy t u)) ts = split t (u : ts)
split (L l (HsTyVar tc)) ts = do data_con <- tyConToDataCon l tc
return (data_con, mk_rest ts)
split (L l (HsTupleTy _ [])) [] = return (L l (getRdrName unitDataCon), PrefixCon [])
-- See Note [Unit tuples] in HsTypes
split (L l _) _ = parseErrorSDoc l (text "Cannot parse data constructor in a data/newtype declaration:" <+> ppr ty)
mk_rest [L l (HsRecTy flds)] = RecCon (L l flds)
mk_rest ts = PrefixCon ts
recordPatSynErr :: SrcSpan -> LPat RdrName -> P a
recordPatSynErr loc pat =
parseErrorSDoc loc $
text "record syntax not supported for pattern synonym declarations:" $$
ppr pat
mkPatSynMatchGroup :: Located RdrName
-> Located (OrdList (LHsDecl RdrName))
-> P (MatchGroup RdrName (LHsExpr RdrName))
mkPatSynMatchGroup (L _ patsyn_name) (L _ decls) =
do { matches <- mapM fromDecl (fromOL decls)
; return $ mkMatchGroup FromSource matches }
where
fromDecl (L loc decl@(ValD (PatBind pat@(L _ (ConPatIn (L _ name) details)) rhs _ _ _))) =
do { unless (name == patsyn_name) $
wrongNameBindingErr loc decl
; match <- case details of
PrefixCon pats -> return $ Match Nothing pats Nothing rhs
InfixCon pat1 pat2 ->
return $ Match Nothing [pat1, pat2] Nothing rhs
RecCon{} -> recordPatSynErr loc pat
; return $ L loc match }
fromDecl (L loc decl) = extraDeclErr loc decl
extraDeclErr loc decl =
parseErrorSDoc loc $
text "pattern synonym 'where' clause must contain a single binding:" $$
ppr decl
wrongNameBindingErr loc decl =
parseErrorSDoc loc $
text "pattern synonym 'where' clause must bind the pattern synonym's name" <+>
quotes (ppr patsyn_name) $$ ppr decl
mkDeprecatedGadtRecordDecl :: SrcSpan
-> Located RdrName
-> Located [LConDeclField RdrName]
-> LHsType RdrName
-> P (LConDecl RdrName)
-- This one uses the deprecated syntax
-- C { x,y ::Int } :: T a b
-- We give it a RecCon details right away
mkDeprecatedGadtRecordDecl loc (L con_loc con) flds res_ty
= do { data_con <- tyConToDataCon con_loc con
; return (L loc (ConDecl { con_old_rec = True
, con_names = [data_con]
, con_explicit = Implicit
, con_qvars = mkHsQTvs []
, con_cxt = noLoc []
, con_details = RecCon flds
, con_res = ResTyGADT loc res_ty
, con_doc = Nothing })) }
mkSimpleConDecl :: Located RdrName -> [LHsTyVarBndr RdrName]
-> LHsContext RdrName -> HsConDeclDetails RdrName
-> ConDecl RdrName
mkSimpleConDecl name qvars cxt details
= ConDecl { con_old_rec = False
, con_names = [name]
, con_explicit = Explicit
, con_qvars = mkHsQTvs qvars
, con_cxt = cxt
, con_details = details
, con_res = ResTyH98
, con_doc = Nothing }
mkGadtDecl :: [Located RdrName]
-> LHsType RdrName -- Always a HsForAllTy
-> P (ConDecl RdrName)
-- We allow C,D :: ty
-- and expand it as if it had been
-- C :: ty; D :: ty
-- (Just like type signatures in general.)
mkGadtDecl _ ty@(L _ (HsForAllTy _ (Just l) _ _ _))
= parseErrorSDoc l $
text "A constructor cannot have a partial type:" $$
ppr ty
mkGadtDecl names (L ls (HsForAllTy imp Nothing qvars cxt tau))
= return $ mk_gadt_con names
where
(details, res_ty) -- See Note [Sorting out the result type]
= case tau of
L _ (HsFunTy (L l (HsRecTy flds)) res_ty)
-> (RecCon (L l flds), res_ty)
_other -> (PrefixCon [], tau)
mk_gadt_con names
= ConDecl { con_old_rec = False
, con_names = names
, con_explicit = imp
, con_qvars = qvars
, con_cxt = cxt
, con_details = details
, con_res = ResTyGADT ls res_ty
, con_doc = Nothing }
mkGadtDecl _ other_ty = pprPanic "mkGadtDecl" (ppr other_ty)
tyConToDataCon :: SrcSpan -> RdrName -> P (Located RdrName)
tyConToDataCon loc tc
| isTcOcc (rdrNameOcc tc)
= return (L loc (setRdrNameSpace tc srcDataName))
| otherwise
= parseErrorSDoc loc (msg $$ extra)
where
msg = text "Not a data constructor:" <+> quotes (ppr tc)
extra | tc == forall_tv_RDR
= text "Perhaps you intended to use ExistentialQuantification"
| otherwise = empty
-- | Note [Sorting out the result type]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- In a GADT declaration which is not a record, we put the whole constr
-- type into the ResTyGADT for now; the renamer will unravel it once it
-- has sorted out operator fixities. Consider for example
-- C :: a :*: b -> a :*: b -> a :+: b
-- Initially this type will parse as
-- a :*: (b -> (a :*: (b -> (a :+: b))))
-- so it's hard to split up the arguments until we've done the precedence
-- resolution (in the renamer) On the other hand, for a record
-- { x,y :: Int } -> a :*: b
-- there is no doubt. AND we need to sort records out so that
-- we can bring x,y into scope. So:
-- * For PrefixCon we keep all the args in the ResTyGADT
-- * For RecCon we do not
checkTyVarsP :: SDoc -> SDoc -> Located RdrName -> [LHsType RdrName] -> P (LHsTyVarBndrs RdrName)
-- Same as checkTyVars, but in the P monad
checkTyVarsP pp_what equals_or_where tc tparms
= eitherToP $ checkTyVars pp_what equals_or_where tc tparms
eitherToP :: Either (SrcSpan, SDoc) a -> P a
-- Adapts the Either monad to the P monad
eitherToP (Left (loc, doc)) = parseErrorSDoc loc doc
eitherToP (Right thing) = return thing
checkTyVars :: SDoc -> SDoc -> Located RdrName -> [LHsType RdrName]
-> Either (SrcSpan, SDoc) (LHsTyVarBndrs RdrName)
-- Check whether the given list of type parameters are all type variables
-- (possibly with a kind signature)
-- We use the Either monad because it's also called (via mkATDefault) from
-- Convert.hs
checkTyVars pp_what equals_or_where tc tparms
= do { tvs <- mapM chk tparms
; return (mkHsQTvs tvs) }
where
-- Check that the name space is correct!
chk (L l (HsKindSig (L lv (HsTyVar tv)) k))
| isRdrTyVar tv = return (L l (KindedTyVar (L lv tv) k))
chk (L l (HsTyVar tv))
| isRdrTyVar tv = return (L l (UserTyVar tv))
chk t@(L loc _)
= Left (loc,
vcat [ ptext (sLit "Unexpected type") <+> quotes (ppr t)
, ptext (sLit "In the") <+> pp_what <+> ptext (sLit "declaration for") <+> quotes (ppr tc)
, vcat[ (ptext (sLit "A") <+> pp_what <+> ptext (sLit "declaration should have form"))
, nest 2 (pp_what <+> ppr tc
<+> hsep (map text (takeList tparms allNameStrings))
<+> equals_or_where) ] ])
whereDots, equalsDots :: SDoc
-- Second argument to checkTyVars
whereDots = ptext (sLit "where ...")
equalsDots = ptext (sLit "= ...")
checkDatatypeContext :: Maybe (LHsContext RdrName) -> P ()
checkDatatypeContext Nothing = return ()
checkDatatypeContext (Just (L loc c))
= do allowed <- extension datatypeContextsEnabled
unless allowed $
parseErrorSDoc loc
(text "Illegal datatype context (use DatatypeContexts):" <+>
pprHsContext c)
mapM_ (checkNoPartialType err) c
where err = text "In the context:" <+> pprHsContextNoArrow c
checkRecordSyntax :: Outputable a => Located a -> P (Located a)
checkRecordSyntax lr@(L loc r)
= do allowed <- extension traditionalRecordSyntaxEnabled
if allowed
then return lr
else parseErrorSDoc loc
(text "Illegal record syntax (use TraditionalRecordSyntax):" <+>
ppr r)
checkTyClHdr :: LHsType RdrName
-> P (Located RdrName, -- the head symbol (type or class name)
[LHsType RdrName], -- parameters of head symbol
[AddAnn]) -- API Annotation for HsParTy when stripping parens
-- Well-formedness check and decomposition of type and class heads.
-- Decomposes T ty1 .. tyn into (T, [ty1, ..., tyn])
-- Int :*: Bool into (:*:, [Int, Bool])
-- returning the pieces
checkTyClHdr ty
= goL ty [] []
where
goL (L l ty) acc ann = go l ty acc ann
go l (HsTyVar tc) acc ann
| isRdrTc tc = return (L l tc, acc, ann)
go _ (HsOpTy t1 (_, ltc@(L _ tc)) t2) acc ann
| isRdrTc tc = return (ltc, t1:t2:acc, ann)
go l (HsParTy ty) acc ann = goL ty acc (ann ++ mkParensApiAnn l)
go _ (HsAppTy t1 t2) acc ann = goL t1 (t2:acc) ann
go l (HsTupleTy _ []) [] ann = return (L l (getRdrName unitTyCon), [],ann)
-- See Note [Unit tuples] in HsTypes
go l _ _ _
= parseErrorSDoc l (text "Malformed head of type or class declaration:"
<+> ppr ty)
checkContext :: LHsType RdrName -> P (LHsContext RdrName)
checkContext (L l orig_t)
= check orig_t
where
check (HsTupleTy _ ts) -- (Eq a, Ord b) shows up as a tuple type
= return (L l ts) -- Ditto ()
check (HsParTy ty) -- to be sure HsParTy doesn't get into the way
= check (unLoc ty)
check _
= return (L l [L l orig_t])
-- -------------------------------------------------------------------------
-- Checking Patterns.
-- We parse patterns as expressions and check for valid patterns below,
-- converting the expression into a pattern at the same time.
checkPattern :: SDoc -> LHsExpr RdrName -> P (LPat RdrName)
checkPattern msg e = checkLPat msg e
checkPatterns :: SDoc -> [LHsExpr RdrName] -> P [LPat RdrName]
checkPatterns msg es = mapM (checkPattern msg) es
checkLPat :: SDoc -> LHsExpr RdrName -> P (LPat RdrName)
checkLPat msg e@(L l _) = checkPat msg l e []
checkPat :: SDoc -> SrcSpan -> LHsExpr RdrName -> [LPat RdrName]
-> P (LPat RdrName)
checkPat _ loc (L l (HsVar c)) args
| isRdrDataCon c = return (L loc (ConPatIn (L l c) (PrefixCon args)))
checkPat msg loc e args -- OK to let this happen even if bang-patterns
-- are not enabled, because there is no valid
-- non-bang-pattern parse of (C ! e)
| Just (e', args') <- splitBang e
= do { args'' <- checkPatterns msg args'
; checkPat msg loc e' (args'' ++ args) }
checkPat msg loc (L _ (HsApp f e)) args
= do p <- checkLPat msg e
checkPat msg loc f (p : args)
checkPat msg loc (L _ e) []
= do p <- checkAPat msg loc e
return (L loc p)
checkPat msg loc e _
= patFail msg loc (unLoc e)
checkAPat :: SDoc -> SrcSpan -> HsExpr RdrName -> P (Pat RdrName)
checkAPat msg loc e0 = do
pState <- getPState
let dynflags = dflags pState
case e0 of
EWildPat -> return (WildPat placeHolderType)
HsVar x -> return (VarPat x)
HsLit l -> return (LitPat l)
-- Overloaded numeric patterns (e.g. f 0 x = x)
-- Negation is recorded separately, so that the literal is zero or +ve
-- NB. Negative *primitive* literals are already handled by the lexer
HsOverLit pos_lit -> return (mkNPat (L loc pos_lit) Nothing)
NegApp (L l (HsOverLit pos_lit)) _
-> return (mkNPat (L l pos_lit) (Just noSyntaxExpr))
SectionR (L lb (HsVar bang)) e -- (! x)
| bang == bang_RDR
-> do { bang_on <- extension bangPatEnabled
; if bang_on then do { e' <- checkLPat msg e
; addAnnotation loc AnnBang lb
; return (BangPat e') }
else parseErrorSDoc loc (text "Illegal bang-pattern (use BangPatterns):" $$ ppr e0) }
ELazyPat e -> checkLPat msg e >>= (return . LazyPat)
EAsPat n e -> checkLPat msg e >>= (return . AsPat n)
-- view pattern is well-formed if the pattern is
EViewPat expr patE -> checkLPat msg patE >>=
(return . (\p -> ViewPat expr p placeHolderType))
ExprWithTySig e t _ -> do e <- checkLPat msg e
-- Pattern signatures are parsed as sigtypes,
-- but they aren't explicit forall points. Hence
-- we have to remove the implicit forall here.
let t' = case t of
L _ (HsForAllTy Implicit _ _
(L _ []) ty) -> ty
other -> other
return (SigPatIn e (mkHsWithBndrs t'))
-- n+k patterns
OpApp (L nloc (HsVar n)) (L _ (HsVar plus)) _
(L lloc (HsOverLit lit@(OverLit {ol_val = HsIntegral {}})))
| xopt Opt_NPlusKPatterns dynflags && (plus == plus_RDR)
-> return (mkNPlusKPat (L nloc n) (L lloc lit))
OpApp l op _fix r -> do l <- checkLPat msg l
r <- checkLPat msg r
case op of
L cl (HsVar c) | isDataOcc (rdrNameOcc c)
-> return (ConPatIn (L cl c) (InfixCon l r))
_ -> patFail msg loc e0
HsPar e -> checkLPat msg e >>= (return . ParPat)
ExplicitList _ _ es -> do ps <- mapM (checkLPat msg) es
return (ListPat ps placeHolderType Nothing)
ExplicitPArr _ es -> do ps <- mapM (checkLPat msg) es
return (PArrPat ps placeHolderType)
ExplicitTuple es b
| all tupArgPresent es -> do ps <- mapM (checkLPat msg)
[e | L _ (Present e) <- es]
return (TuplePat ps b [])
| otherwise -> parseErrorSDoc loc (text "Illegal tuple section in pattern:" $$ ppr e0)
RecordCon c _ (HsRecFields fs dd)
-> do fs <- mapM (checkPatField msg) fs
return (ConPatIn c (RecCon (HsRecFields fs dd)))
HsSpliceE is_typed s | not is_typed
-> return (SplicePat s)
HsQuasiQuoteE q -> return (QuasiQuotePat q)
_ -> patFail msg loc e0
placeHolderPunRhs :: LHsExpr RdrName
-- The RHS of a punned record field will be filled in by the renamer
-- It's better not to make it an error, in case we want to print it when debugging
placeHolderPunRhs = noLoc (HsVar pun_RDR)
plus_RDR, bang_RDR, pun_RDR :: RdrName
plus_RDR = mkUnqual varName (fsLit "+") -- Hack
bang_RDR = mkUnqual varName (fsLit "!") -- Hack
pun_RDR = mkUnqual varName (fsLit "pun-right-hand-side")
checkPatField :: SDoc -> LHsRecField RdrName (LHsExpr RdrName)
-> P (LHsRecField RdrName (LPat RdrName))
checkPatField msg (L l fld) = do p <- checkLPat msg (hsRecFieldArg fld)
return (L l (fld { hsRecFieldArg = p }))
patFail :: SDoc -> SrcSpan -> HsExpr RdrName -> P a
patFail msg loc e = parseErrorSDoc loc err
where err = text "Parse error in pattern:" <+> ppr e
$$ msg
---------------------------------------------------------------------------
-- Check Equation Syntax
checkValDef :: SDoc
-> LHsExpr RdrName
-> Maybe (LHsType RdrName)
-> Located (a,GRHSs RdrName (LHsExpr RdrName))
-> P (HsBind RdrName)
checkValDef msg lhs (Just sig) grhss
-- x :: ty = rhs parses as a *pattern* binding
= checkPatBind msg (L (combineLocs lhs sig)
(ExprWithTySig lhs sig PlaceHolder)) grhss
checkValDef msg lhs opt_sig g@(L l (_,grhss))
= do { mb_fun <- isFunLhs lhs
; case mb_fun of
Just (fun, is_infix, pats) -> checkFunBind msg (getLoc lhs)
fun is_infix pats opt_sig (L l grhss)
Nothing -> checkPatBind msg lhs g }
checkFunBind :: SDoc
-> SrcSpan
-> Located RdrName
-> Bool
-> [LHsExpr RdrName]
-> Maybe (LHsType RdrName)
-> Located (GRHSs RdrName (LHsExpr RdrName))
-> P (HsBind RdrName)
checkFunBind msg lhs_loc fun is_infix pats opt_sig (L rhs_span grhss)
= do ps <- checkPatterns msg pats
let match_span = combineSrcSpans lhs_loc rhs_span
return (makeFunBind fun is_infix
[L match_span (Match (Just (fun,is_infix)) ps opt_sig grhss)])
-- The span of the match covers the entire equation.
-- That isn't quite right, but it'll do for now.
makeFunBind :: Located RdrName -> Bool -> [LMatch RdrName (LHsExpr RdrName)]
-> HsBind RdrName
-- Like HsUtils.mkFunBind, but we need to be able to set the fixity too
makeFunBind fn is_infix ms
= FunBind { fun_id = fn, fun_infix = is_infix,
fun_matches = mkMatchGroup FromSource ms,
fun_co_fn = idHsWrapper,
bind_fvs = placeHolderNames,
fun_tick = [] }
checkPatBind :: SDoc
-> LHsExpr RdrName
-> Located (a,GRHSs RdrName (LHsExpr RdrName))
-> P (HsBind RdrName)
checkPatBind msg lhs (L _ (_,grhss))
= do { lhs <- checkPattern msg lhs
; return (PatBind lhs grhss placeHolderType placeHolderNames
([],[])) }
checkValSig
:: LHsExpr RdrName
-> LHsType RdrName
-> P (Sig RdrName)
checkValSig (L l (HsVar v)) ty
| isUnqual v && not (isDataOcc (rdrNameOcc v))
= return (TypeSig [L l v] ty PlaceHolder)
checkValSig lhs@(L l _) ty
= parseErrorSDoc l ((text "Invalid type signature:" <+>
ppr lhs <+> text "::" <+> ppr ty)
$$ text hint)
where
hint = if foreign_RDR `looks_like` lhs
then "Perhaps you meant to use ForeignFunctionInterface?"
else if default_RDR `looks_like` lhs
then "Perhaps you meant to use DefaultSignatures?"
else "Should be of form <variable> :: <type>"
-- A common error is to forget the ForeignFunctionInterface flag
-- so check for that, and suggest. cf Trac #3805
-- Sadly 'foreign import' still barfs 'parse error' because 'import' is a keyword
looks_like s (L _ (HsVar v)) = v == s
looks_like s (L _ (HsApp lhs _)) = looks_like s lhs
looks_like _ _ = False
foreign_RDR = mkUnqual varName (fsLit "foreign")
default_RDR = mkUnqual varName (fsLit "default")
-- | Check that the default declarations do not contain wildcards in their
-- types, which we do not want as the types in the default declarations must
-- be fully specified.
checkValidDefaults :: [LHsType RdrName] -> P (DefaultDecl RdrName)
checkValidDefaults tys = mapM_ (checkNoPartialType err) tys >> return ret
where ret = DefaultDecl tys
err = text "In declaration:" <+> ppr ret
-- | Check that the pattern synonym type signature does not contain wildcards.
checkValidPatSynSig :: Sig RdrName -> P (Sig RdrName)
checkValidPatSynSig psig@(PatSynSig _ _ prov req ty)
= mapM_ (checkNoPartialType err) (unLoc prov ++ unLoc req ++ [ty])
>> return psig
where err = hang (text "In pattern synonym type signature: ")
2 (ppr psig)
checkValidPatSynSig sig = return sig
-- Should only be called with a pattern synonym type signature
-- | Check the validity of a partial type signature. We check the following
-- things:
--
-- * There should only be one extra-constraints wildcard in the type
-- signature, i.e. the @_@ in @_ => a -> String@.
-- This would be invalid: @(Eq a, _) => a -> (Num a, _) => a -> Bool@.
-- Extra-constraints wildcards are only allowed in the top-level context.
--
-- * Named extra-constraints wildcards aren't allowed,
-- e.g. invalid: @(Show a, _x) => a -> String@.
--
-- * There is only one extra-constraints wildcard in the context and it must
-- come last, e.g. invalid: @(_, Show a) => a -> String@
-- or @(_, Show a, _) => a -> String@.
--
-- * There should be no unnamed wildcards in the context.
--
-- * Named wildcards occurring in the context must also occur in the monotype.
--
-- An error is reported when an invalid wildcard is found.
checkPartialTypeSignature :: LHsType RdrName -> P (LHsType RdrName)
checkPartialTypeSignature fullTy = case fullTy of
(L l (HsForAllTy flag extra bndrs (L lc ctxtP) ty)) -> do
-- Remove parens around types in the context
let ctxt = map ignoreParens ctxtP
-- Check that the type doesn't contain any more extra-constraints wildcards
checkNoExtraConstraintsWildcard ty
-- Named extra-constraints wildcards aren't allowed
whenIsJust (firstMatch isNamedWildcardTy ctxt) $
\(L l _) -> err hintNamed l fullTy
-- There should be no more (extra-constraints) wildcards in the context.
-- If there was one at the end of the context, it is by now already
-- removed from the context and stored in the @extra@ field of the
-- 'HsForAllTy' by 'HsTypes.mkHsForAllTy'.
whenIsJust (firstMatch isWildcardTy ctxt) $
\(L l _) -> err hintLast l fullTy
-- Find all wildcards in the context and the monotype, then divide
-- them in unnamed and named wildcards
let (unnamedInCtxt, namedInCtxt) = splitUnnamedNamed $
concatMap findWildcards ctxt
(_ , namedInTy) = splitUnnamedNamed $
findWildcards ty
-- Unnamed wildcards aren't allowed in the context
case unnamedInCtxt of
(Found lc : _) -> err hintUnnamedConstraint lc fullTy
_ -> return ()
-- Calculcate the set of named wildcards in the context that aren't in the
-- monotype (tau)
let namedWildcardsNotInTau = Set.fromList (namedWildcards namedInCtxt)
`Set.difference`
Set.fromList (namedWildcards namedInTy)
-- Search for the first named wildcard that we encountered in the
-- context that isn't present in the monotype (we lose the order
-- in which they occur when using the Set directly).
case filter (\(FoundNamed _ name) -> Set.member name namedWildcardsNotInTau)
namedInCtxt of
(FoundNamed lc name:_) -> err (hintNamedNotInMonotype name) lc fullTy
_ -> return ()
-- Return the checked type
return $ L l (HsForAllTy flag extra bndrs (L lc ctxtP) ty)
ty -> do
checkNoExtraConstraintsWildcard ty
return ty
where
ignoreParens (L _ (HsParTy ty)) = ty
ignoreParens ty = ty
firstMatch :: (HsType a -> Bool) -> HsContext a -> Maybe (LHsType a)
firstMatch pred ctxt = listToMaybe (filter (pred . unLoc) ctxt)
err hintSDoc lc ty = parseErrorSDoc lc $
text "Invalid partial type signature:" $$
ppr ty $$ hintSDoc
hintLast = sep [ text "An extra-constraints wildcard is only allowed"
, text "at the end of the constraints" ]
hintNamed = text "A named wildcard cannot occur as a constraint"
hintNested = sep [ text "An extra-constraints wildcard is only allowed"
, text "at the top-level of the signature" ]
hintUnnamedConstraint
= text "Wildcards are not allowed within the constraints"
hintNamedNotInMonotype name
= sep [ text "The named wildcard" <+> quotes (ppr name) <+>
text "is only allowed in the constraints"
, text "when it also occurs in the (mono)type" ]
checkNoExtraConstraintsWildcard (L _ ty) = go ty
where
-- Report nested (named) extra-constraints wildcards
go' = go . unLoc
go (HsAppTy x y) = go' x >> go' y
go (HsFunTy x y) = go' x >> go' y
go (HsListTy x) = go' x
go (HsPArrTy x) = go' x
go (HsTupleTy _ xs) = mapM_ go' xs
go (HsOpTy x _ y) = go' x >> go' y
go (HsParTy x) = go' x
go (HsIParamTy _ x) = go' x
go (HsEqTy x y) = go' x >> go' y
go (HsKindSig x y) = go' x >> go' y
go (HsDocTy x _) = go' x
go (HsBangTy _ x) = go' x
go (HsRecTy xs) = mapM_ (go' . getBangType . cd_fld_type . unLoc) xs
go (HsExplicitListTy _ xs) = mapM_ go' xs
go (HsExplicitTupleTy _ xs) = mapM_ go' xs
go (HsWrapTy _ x) = go' (noLoc x)
go (HsForAllTy _ (Just l) _ _ _) = err hintNested l ty
go (HsForAllTy _ Nothing _ (L _ ctxt) x)
| Just (L l _) <- firstMatch isWildcardTy ctxt
= err hintNested l ty
| Just (L l _) <- firstMatch isNamedWildcardTy ctxt
= err hintNamed l ty
| otherwise = go' x
go _ = return ()
checkDoAndIfThenElse :: LHsExpr RdrName
-> Bool
-> LHsExpr RdrName
-> Bool
-> LHsExpr RdrName
-> P ()
checkDoAndIfThenElse guardExpr semiThen thenExpr semiElse elseExpr
| semiThen || semiElse
= do pState <- getPState
unless (xopt Opt_DoAndIfThenElse (dflags pState)) $ do
parseErrorSDoc (combineLocs guardExpr elseExpr)
(text "Unexpected semi-colons in conditional:"
$$ nest 4 expr
$$ text "Perhaps you meant to use DoAndIfThenElse?")
| otherwise = return ()
where pprOptSemi True = semi
pprOptSemi False = empty
expr = text "if" <+> ppr guardExpr <> pprOptSemi semiThen <+>
text "then" <+> ppr thenExpr <> pprOptSemi semiElse <+>
text "else" <+> ppr elseExpr
-- The parser left-associates, so there should
-- not be any OpApps inside the e's
splitBang :: LHsExpr RdrName -> Maybe (LHsExpr RdrName, [LHsExpr RdrName])
-- Splits (f ! g a b) into (f, [(! g), a, b])
splitBang (L loc (OpApp l_arg bang@(L _ (HsVar op)) _ r_arg))
| op == bang_RDR = Just (l_arg, L loc (SectionR bang arg1) : argns)
where
(arg1,argns) = split_bang r_arg []
split_bang (L _ (HsApp f e)) es = split_bang f (e:es)
split_bang e es = (e,es)
splitBang _ = Nothing
isFunLhs :: LHsExpr RdrName
-> P (Maybe (Located RdrName, Bool, [LHsExpr RdrName]))
-- A variable binding is parsed as a FunBind.
-- Just (fun, is_infix, arg_pats) if e is a function LHS
--
-- The whole LHS is parsed as a single expression.
-- Any infix operators on the LHS will parse left-associatively
-- E.g. f !x y !z
-- will parse (rather strangely) as
-- (f ! x y) ! z
-- It's up to isFunLhs to sort out the mess
--
-- a .!. !b
isFunLhs e = go e []
where
go (L loc (HsVar f)) es
| not (isRdrDataCon f) = return (Just (L loc f, False, es))
go (L _ (HsApp f e)) es = go f (e:es)
go (L _ (HsPar e)) es@(_:_) = go e es
-- For infix function defns, there should be only one infix *function*
-- (though there may be infix *datacons* involved too). So we don't
-- need fixity info to figure out which function is being defined.
-- a `K1` b `op` c `K2` d
-- must parse as
-- (a `K1` b) `op` (c `K2` d)
-- The renamer checks later that the precedences would yield such a parse.
--
-- There is a complication to deal with bang patterns.
--
-- ToDo: what about this?
-- x + 1 `op` y = ...
go e@(L loc (OpApp l (L loc' (HsVar op)) fix r)) es
| Just (e',es') <- splitBang e
= do { bang_on <- extension bangPatEnabled
; if bang_on then go e' (es' ++ es)
else return (Just (L loc' op, True, (l:r:es))) }
-- No bangs; behave just like the next case
| not (isRdrDataCon op) -- We have found the function!
= return (Just (L loc' op, True, (l:r:es)))
| otherwise -- Infix data con; keep going
= do { mb_l <- go l es
; case mb_l of
Just (op', True, j : k : es')
-> return (Just (op', True, j : op_app : es'))
where
op_app = L loc (OpApp k (L loc' (HsVar op)) fix r)
_ -> return Nothing }
go _ _ = return Nothing
---------------------------------------------------------------------------
-- Check for monad comprehensions
--
-- If the flag MonadComprehensions is set, return a `MonadComp' context,
-- otherwise use the usual `ListComp' context
checkMonadComp :: P (HsStmtContext Name)
checkMonadComp = do
pState <- getPState
return $ if xopt Opt_MonadComprehensions (dflags pState)
then MonadComp
else ListComp
-- -------------------------------------------------------------------------
-- Checking arrow syntax.
-- We parse arrow syntax as expressions and check for valid syntax below,
-- converting the expression into a pattern at the same time.
checkCommand :: LHsExpr RdrName -> P (LHsCmd RdrName)
checkCommand lc = locMap checkCmd lc
locMap :: (SrcSpan -> a -> P b) -> Located a -> P (Located b)
locMap f (L l a) = f l a >>= (\b -> return $ L l b)
checkCmd :: SrcSpan -> HsExpr RdrName -> P (HsCmd RdrName)
checkCmd _ (HsArrApp e1 e2 ptt haat b) =
return $ HsCmdArrApp e1 e2 ptt haat b
checkCmd _ (HsArrForm e mf args) =
return $ HsCmdArrForm e mf args
checkCmd _ (HsApp e1 e2) =
checkCommand e1 >>= (\c -> return $ HsCmdApp c e2)
checkCmd _ (HsLam mg) =
checkCmdMatchGroup mg >>= (\mg' -> return $ HsCmdLam mg')
checkCmd _ (HsPar e) =
checkCommand e >>= (\c -> return $ HsCmdPar c)
checkCmd _ (HsCase e mg) =
checkCmdMatchGroup mg >>= (\mg' -> return $ HsCmdCase e mg')
checkCmd _ (HsIf cf ep et ee) = do
pt <- checkCommand et
pe <- checkCommand ee
return $ HsCmdIf cf ep pt pe
checkCmd _ (HsLet lb e) =
checkCommand e >>= (\c -> return $ HsCmdLet lb c)
checkCmd _ (HsDo DoExpr stmts ty) =
mapM checkCmdLStmt stmts >>= (\ss -> return $ HsCmdDo ss ty)
checkCmd _ (OpApp eLeft op _fixity eRight) = do
-- OpApp becomes a HsCmdArrForm with a (Just fixity) in it
c1 <- checkCommand eLeft
c2 <- checkCommand eRight
let arg1 = L (getLoc c1) $ HsCmdTop c1 placeHolderType placeHolderType []
arg2 = L (getLoc c2) $ HsCmdTop c2 placeHolderType placeHolderType []
return $ HsCmdArrForm op Nothing [arg1, arg2]
checkCmd l e = cmdFail l e
checkCmdLStmt :: ExprLStmt RdrName -> P (CmdLStmt RdrName)
checkCmdLStmt = locMap checkCmdStmt
checkCmdStmt :: SrcSpan -> ExprStmt RdrName -> P (CmdStmt RdrName)
checkCmdStmt _ (LastStmt e r) =
checkCommand e >>= (\c -> return $ LastStmt c r)
checkCmdStmt _ (BindStmt pat e b f) =
checkCommand e >>= (\c -> return $ BindStmt pat c b f)
checkCmdStmt _ (BodyStmt e t g ty) =
checkCommand e >>= (\c -> return $ BodyStmt c t g ty)
checkCmdStmt _ (LetStmt bnds) = return $ LetStmt bnds
checkCmdStmt _ stmt@(RecStmt { recS_stmts = stmts }) = do
ss <- mapM checkCmdLStmt stmts
return $ stmt { recS_stmts = ss }
checkCmdStmt l stmt = cmdStmtFail l stmt
checkCmdMatchGroup :: MatchGroup RdrName (LHsExpr RdrName) -> P (MatchGroup RdrName (LHsCmd RdrName))
checkCmdMatchGroup mg@(MG { mg_alts = ms }) = do
ms' <- mapM (locMap $ const convert) ms
return $ mg { mg_alts = ms' }
where convert (Match mf pat mty grhss) = do
grhss' <- checkCmdGRHSs grhss
return $ Match mf pat mty grhss'
checkCmdGRHSs :: GRHSs RdrName (LHsExpr RdrName) -> P (GRHSs RdrName (LHsCmd RdrName))
checkCmdGRHSs (GRHSs grhss binds) = do
grhss' <- mapM checkCmdGRHS grhss
return $ GRHSs grhss' binds
checkCmdGRHS :: LGRHS RdrName (LHsExpr RdrName) -> P (LGRHS RdrName (LHsCmd RdrName))
checkCmdGRHS = locMap $ const convert
where
convert (GRHS stmts e) = do
c <- checkCommand e
-- cmdStmts <- mapM checkCmdLStmt stmts
return $ GRHS {- cmdStmts -} stmts c
cmdFail :: SrcSpan -> HsExpr RdrName -> P a
cmdFail loc e = parseErrorSDoc loc (text "Parse error in command:" <+> ppr e)
cmdStmtFail :: SrcSpan -> Stmt RdrName (LHsExpr RdrName) -> P a
cmdStmtFail loc e = parseErrorSDoc loc
(text "Parse error in command statement:" <+> ppr e)
---------------------------------------------------------------------------
-- Miscellaneous utilities
checkPrecP :: Located Int -> P (Located Int)
checkPrecP (L l i)
| 0 <= i && i <= maxPrecedence = return (L l i)
| otherwise
= parseErrorSDoc l (text ("Precedence out of range: " ++ show i))
mkRecConstrOrUpdate
:: LHsExpr RdrName
-> SrcSpan
-> ([LHsRecField RdrName (LHsExpr RdrName)], Bool)
-> P (HsExpr RdrName)
mkRecConstrOrUpdate (L l (HsVar c)) _ (fs,dd)
| isRdrDataCon c
= return (RecordCon (L l c) noPostTcExpr (mk_rec_fields fs dd))
mkRecConstrOrUpdate exp _ (fs,dd)
= return (RecordUpd exp (mk_rec_fields fs dd) [] [] [])
mk_rec_fields :: [LHsRecField id arg] -> Bool -> HsRecFields id arg
mk_rec_fields fs False = HsRecFields { rec_flds = fs, rec_dotdot = Nothing }
mk_rec_fields fs True = HsRecFields { rec_flds = fs, rec_dotdot = Just (length fs) }
mkInlinePragma :: String -> (InlineSpec, RuleMatchInfo) -> Maybe Activation
-> InlinePragma
-- The (Maybe Activation) is because the user can omit
-- the activation spec (and usually does)
mkInlinePragma src (inl, match_info) mb_act
= InlinePragma { inl_src = src -- Note [Pragma source text] in BasicTypes
, inl_inline = inl
, inl_sat = Nothing
, inl_act = act
, inl_rule = match_info }
where
act = case mb_act of
Just act -> act
Nothing -> -- No phase specified
case inl of
NoInline -> NeverActive
_other -> AlwaysActive
-----------------------------------------------------------------------------
-- utilities for foreign declarations
-- construct a foreign import declaration
--
mkImport :: Located CCallConv
-> Located Safety
-> (Located FastString, Located RdrName, LHsType RdrName)
-> P (HsDecl RdrName)
mkImport (L lc cconv) (L ls safety) (L loc entity, v, ty)
| Just loc <- maybeLocation $ findWildcards ty
= parseErrorSDoc loc $
text "Wildcard not allowed" $$
text "In foreign import declaration" <+>
quotes (ppr v) $$ ppr ty
| cconv == PrimCallConv = do
let funcTarget = CFunction (StaticTarget entity Nothing True)
importSpec = CImport (L lc PrimCallConv) (L ls safety) Nothing funcTarget
(L loc (unpackFS entity))
return (ForD (ForeignImport v ty noForeignImportCoercionYet importSpec))
| cconv == JavaScriptCallConv = do
let funcTarget = CFunction (StaticTarget entity Nothing True)
importSpec = CImport (L lc JavaScriptCallConv) (L ls safety) Nothing
funcTarget (L loc (unpackFS entity))
return (ForD (ForeignImport v ty noForeignImportCoercionYet importSpec))
| otherwise = do
case parseCImport (L lc cconv) (L ls safety) (mkExtName (unLoc v))
(unpackFS entity) (L loc (unpackFS entity)) of
Nothing -> parseErrorSDoc loc (text "Malformed entity string")
Just importSpec -> return (ForD (ForeignImport v ty noForeignImportCoercionYet importSpec))
-- the string "foo" is ambigous: either a header or a C identifier. The
-- C identifier case comes first in the alternatives below, so we pick
-- that one.
parseCImport :: Located CCallConv -> Located Safety -> FastString -> String
-> Located SourceText
-> Maybe ForeignImport
parseCImport cconv safety nm str sourceText =
listToMaybe $ map fst $ filter (null.snd) $
readP_to_S parse str
where
parse = do
skipSpaces
r <- choice [
string "dynamic" >> return (mk Nothing (CFunction DynamicTarget)),
string "wrapper" >> return (mk Nothing CWrapper),
do optional (token "static" >> skipSpaces)
((mk Nothing <$> cimp nm) +++
(do h <- munch1 hdr_char
skipSpaces
mk (Just (Header (mkFastString h))) <$> cimp nm))
]
skipSpaces
return r
token str = do _ <- string str
toks <- look
case toks of
c : _
| id_char c -> pfail
_ -> return ()
mk h n = CImport cconv safety h n sourceText
hdr_char c = not (isSpace c) -- header files are filenames, which can contain
-- pretty much any char (depending on the platform),
-- so just accept any non-space character
id_first_char c = isAlpha c || c == '_'
id_char c = isAlphaNum c || c == '_'
cimp nm = (ReadP.char '&' >> skipSpaces >> CLabel <$> cid)
+++ (do isFun <- case cconv of
L _ CApiConv ->
option True
(do token "value"
skipSpaces
return False)
_ -> return True
cid' <- cid
return (CFunction (StaticTarget cid' Nothing isFun)))
where
cid = return nm +++
(do c <- satisfy id_first_char
cs <- many (satisfy id_char)
return (mkFastString (c:cs)))
-- construct a foreign export declaration
--
mkExport :: Located CCallConv
-> (Located FastString, Located RdrName, LHsType RdrName)
-> P (HsDecl RdrName)
mkExport (L lc cconv) (L le entity, v, ty) = do
checkNoPartialType (ptext (sLit "In foreign export declaration") <+>
quotes (ppr v) $$ ppr ty) ty
return $ ForD (ForeignExport v ty noForeignExportCoercionYet
(CExport (L lc (CExportStatic entity' cconv))
(L le (unpackFS entity))))
where
entity' | nullFS entity = mkExtName (unLoc v)
| otherwise = entity
-- Supplying the ext_name in a foreign decl is optional; if it
-- isn't there, the Haskell name is assumed. Note that no transformation
-- of the Haskell name is then performed, so if you foreign export (++),
-- it's external name will be "++". Too bad; it's important because we don't
-- want z-encoding (e.g. names with z's in them shouldn't be doubled)
--
mkExtName :: RdrName -> CLabelString
mkExtName rdrNm = mkFastString (occNameString (rdrNameOcc rdrNm))
--------------------------------------------------------------------------------
-- Help with module system imports/exports
data ImpExpSubSpec = ImpExpAbs | ImpExpAll | ImpExpList [Located RdrName]
mkModuleImpExp :: Located RdrName -> ImpExpSubSpec -> IE RdrName
mkModuleImpExp n@(L l name) subs =
case subs of
ImpExpAbs
| isVarNameSpace (rdrNameSpace name) -> IEVar n
| otherwise -> IEThingAbs (L l nameT)
ImpExpAll -> IEThingAll (L l nameT)
ImpExpList xs -> IEThingWith (L l nameT) xs
where
nameT = setRdrNameSpace name tcClsName
mkTypeImpExp :: Located RdrName -> P (Located RdrName)
mkTypeImpExp name =
do allowed <- extension explicitNamespacesEnabled
if allowed
then return (fmap (`setRdrNameSpace` tcClsName) name)
else parseErrorSDoc (getLoc name)
(text "Illegal keyword 'type' (use ExplicitNamespaces to enable)")
-----------------------------------------------------------------------------
-- Misc utils
parseErrorSDoc :: SrcSpan -> SDoc -> P a
parseErrorSDoc span s = failSpanMsgP span s
|
green-haskell/ghc
|
compiler/parser/RdrHsSyn.hs
|
bsd-3-clause
| 64,184
| 33
| 28
| 20,276
| 16,905
| 8,565
| 8,340
| 1,027
| 23
|
{-# LANGUAGE
DeriveDataTypeable
, RecordWildCards #-}
module Main(main) where
-- Visualize results of Lin-Kernighan on random points
--
-- deps : cabal install diagrams cmdargs
-- build: ghc -O --make visualize.hs
-- usage: ./visualize -?
import qualified Algorithms.Concorde.LinKern as T
-- package 'diagrams' and dependencies
import qualified Diagrams.Prelude as D
import qualified Diagrams.Backend.Cairo as D
import qualified Data.Colour.SRGB as D
import qualified Data.Colour.RGBSpace as D
import qualified Data.Colour.RGBSpace.HSV as D
-- package 'cmdargs'
import qualified System.Console.CmdArgs as Arg
import System.Console.CmdArgs ( (&=), Typeable, Data )
import Control.Monad
import Data.List
import Data.Monoid
import System.IO
import System.Random
import System.Exit
data Visualize = Visualize
{ out :: String
, numPoints :: Int
, linkern :: FilePath
, verbose :: Bool
, timeBound :: Maybe Double
, steps :: Maybe Int
, runs :: Int }
deriving (Show, Typeable, Data)
argSpec :: Visualize
argSpec = Visualize
{ out = "out.pdf" &= Arg.help "Name of output PDF file [out.pdf]"
, numPoints = 1000 &= Arg.help "Number of points [1000]"
, linkern = "linkern" &= Arg.help "Path to linkern executable [search $PATH]"
, verbose = False &= Arg.help "Write progress information to standard output [no]"
, timeBound = Nothing &= Arg.help "Stop looking for better solutions after this many seconds [no]"
, steps = Nothing &= Arg.help "Run this many optimization steps [# points]"
, runs = 1 &= Arg.help "Run this many separate optimizations [1]" }
&= Arg.summary "Visualize results of Lin-Kernighan on random points"
type Diagram = D.Diagram D.Cairo D.R2
diaPoints :: Int -> [T.R2] -> Diagram
diaPoints n = mconcat . map circ . zip [0..] where
nn = fromIntegral n
circ (i,p) = D.translate p . D.fc color $ D.circle 40 where
color = D.uncurryRGB D.sRGB (D.hsv (360*i/nn) 1 1)
diaTour :: [T.R2] -> Diagram
diaTour [] = mempty
diaTour xs@(x:_) = sty . D.fromVertices $ map D.P (xs ++ [x]) where
sty = D.fc D.lightgrey . D.lw 10
writePDF :: FilePath -> Diagram -> IO ()
writePDF pdfName dia = fst $ D.renderDia D.Cairo opts dia where
opts = D.CairoOptions pdfName (D.PDF (400,400))
main :: IO ()
main = do
Visualize{..} <- Arg.cmdArgs argSpec
let cfg = T.Config
{ T.executable = linkern
, T.verbose = verbose
, T.timeBound = timeBound
, T.steps = steps
, T.runs = runs
, T.otherArgs = [] }
vOut = if verbose then putStrLn else const (return ())
vOut "[*] Generating points"
let rnd = randomRIO (0,10000)
points <- replicateM numPoints (liftM2 (,) rnd rnd)
vOut "[*] Computing tour"
tour <- T.tsp cfg id points
vOut "[*] Checking output"
when (sort tour /= sort points) $ do
hPrint stderr (sort tour, sort points)
hPutStrLn stderr "ERROR: tour is not a permutation"
exitFailure
vOut "[*] Writing PDF"
writePDF out (diaPoints numPoints tour D.<> diaTour tour)
vOut "Done!"
|
kmcallister/concorde
|
examples/visualize.hs
|
bsd-3-clause
| 3,245
| 0
| 14
| 841
| 924
| 500
| 424
| 74
| 2
|
{-# LANGUAGE EmptyDataDecls, TypeSynonymInstances #-}
{-# OPTIONS_GHC -fcontext-stack51 #-}
module Games.Chaos2010.Database.Board_sprites1_view where
import Games.Chaos2010.Database.Fields
import Database.HaskellDB.DBLayout
type Board_sprites1_view =
Record
(HCons (LVPair X (Expr (Maybe Int)))
(HCons (LVPair Y (Expr (Maybe Int)))
(HCons (LVPair Ptype (Expr (Maybe String)))
(HCons (LVPair Allegiance (Expr (Maybe String)))
(HCons (LVPair Tag (Expr (Maybe Int)))
(HCons (LVPair Sprite (Expr (Maybe String)))
(HCons (LVPair Colour (Expr (Maybe String)))
(HCons (LVPair Sp (Expr (Maybe Int)))
(HCons (LVPair Start_tick (Expr (Maybe Int)))
(HCons (LVPair Animation_speed (Expr (Maybe Int)))
(HCons (LVPair Selected (Expr (Maybe Bool))) HNil)))))))))))
board_sprites1_view :: Table Board_sprites1_view
board_sprites1_view = baseTable "board_sprites1_view"
|
JakeWheat/Chaos-2010
|
Games/Chaos2010/Database/Board_sprites1_view.hs
|
bsd-3-clause
| 1,104
| 0
| 33
| 346
| 356
| 184
| 172
| 20
| 1
|
{-# OPTIONS_GHC -O0 -fno-case-merge -fno-strictness -fno-cse #-}
{-# LANGUAGE OverloadedStrings #-}
module Text.XmlHtml.HTML.Meta where
import Data.Monoid
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as M
import Data.HashSet (HashSet)
import qualified Data.HashSet as S
import Data.Text (Text)
------------------------------------------------------------------------------
-- Metadata used for HTML5 quirks mode. --
------------------------------------------------------------------------------
{-# NOINLINE voidTags #-}
voidTags :: HashSet Text
voidTags = S.fromList [
"area", "base", "br", "col", "command", "embed", "hr", "img", "input",
"keygen", "link", "meta", "param", "source", "track", "wbr"
]
{-# NOINLINE rawTextTags #-}
rawTextTags :: HashSet Text
rawTextTags = S.fromList [ "script", "style" ]
------------------------------------------------------------------------------
-- | Tags which can be implicitly ended in case they are the last element in
-- their parent. This list actually includes all of the elements that have
-- any kind of omittable end tag, since in general when an element with an
-- omittable end tag isn't specified to be omittable in this way, it's just
-- because in a complete document it isn't expected to ever be the last thing
-- in its parent. We aren't interested in enforcing element structure rules,
-- so we'll allow it anyway.
{-# NOINLINE endOmittableLast #-}
endOmittableLast :: HashSet Text
endOmittableLast = S.fromList [
"body", "colgroup", "dd", "dt", "head", "html", "li", "optgroup",
"option", "p", "rp", "rt", "tbody", "td", "tfoot", "th", "thead", "tr"
]
------------------------------------------------------------------------------
-- | Tags which should be considered automatically ended in case one of a
-- certain set of tags pops up.
{-# NOINLINE endOmittableNext #-}
endOmittableNext :: HashMap Text (HashSet Text)
endOmittableNext = M.fromList [
("colgroup", S.fromList ["caption", "colgroup", "tbody",
"thead", "tfoot", "tr"]),
("dd", S.fromList ["dd", "dt"]),
("dt", S.fromList ["dd", "dt"]),
("head", S.fromList ["body"]),
("li", S.fromList ["li"]),
("optgroup", S.fromList ["optgroup"]),
("option", S.fromList ["optgroup", "option"]),
("p", S.fromList ["address", "article", "aside", "blockquote",
"dir", "div", "dl", "fieldset", "footer",
"form", "h1", "h2", "h3", "h4", "h5", "h6",
"header", "hgroup", "hr", "menu", "nav", "ol",
"p", "pre", "section", "table", "ul"]),
("rp", S.fromList ["rp", "rt"]),
("rt", S.fromList ["rp", "rt"]),
("tbody", S.fromList ["tbody", "tfoot", "thead"]),
("td", S.fromList ["td", "th"]),
("tfoot", S.fromList ["tbody", "tfoot", "thead"]),
("th", S.fromList ["td", "th"]),
("thead", S.fromList ["tbody", "tfoot", "thead"]),
("tr", S.fromList ["tr"])
]
{-# NOINLINE predefinedRefs #-}
predefinedRefs :: HashMap Text Text
predefinedRefs = mconcat $ map M.fromList [
reftab1
, reftab2
, reftab3
, reftab4
, reftab5
, reftab6
, reftab7
, reftab8
, reftab9
, reftab10
, reftab11
, reftab12
, reftab13
, reftab14
, reftab15
, reftab16
, reftab17
, reftab18
, reftab19
, reftab20
, reftab21
, reftab22
, reftab23
, reftab24
, reftab25
, reftab26
, reftab27
, reftab28
, reftab29
, reftab30
, reftab31
, reftab32
, reftab33
, reftab34
, reftab35
, reftab36
, reftab37
, reftab38
, reftab39
, reftab40
, reftab41
, reftab42
, reftab43
, reftab44
, reftab45
, reftab46
, reftab47
, reftab48
, reftab49
, reftab50
, reftab51
, reftab52
, reftab53
, reftab54
, reftab55
, reftab56
, reftab57
, reftab58 ]
{-# NOINLINE reftab1 #-}
reftab1 :: [(Text,Text)]
reftab1 =
[ ("AElig", "\x000C6"),
("AMP", "\x00026"),
("Aacute", "\x000C1"),
("Abreve", "\x00102"),
("Acirc", "\x000C2"),
("Acy", "\x00410"),
("Afr", "\x1D504"),
("Agrave", "\x000C0"),
("Alpha", "\x00391"),
("Amacr", "\x00100"),
("And", "\x02A53"),
("Aogon", "\x00104"),
("Aopf", "\x1D538"),
("ApplyFunction", "\x02061"),
("Aring", "\x000C5"),
("Ascr", "\x1D49C"),
("Assign", "\x02254"),
("Atilde", "\x000C3"),
("Auml", "\x000C4"),
("Backslash", "\x02216"),
("Barv", "\x02AE7"),
("Barwed", "\x02306"),
("Bcy", "\x00411"),
("Because", "\x02235"),
("Bernoullis", "\x0212C"),
("Beta", "\x00392"),
("Bfr", "\x1D505"),
("Bopf", "\x1D539"),
("Breve", "\x002D8"),
("Bscr", "\x0212C"),
("Bumpeq", "\x0224E"),
("CHcy", "\x00427"),
("COPY", "\x000A9"),
("Cacute", "\x00106"),
("Cap", "\x022D2"),
("CapitalDifferentialD", "\x02145"),
("Cayleys", "\x0212D") ]
{-# NOINLINE reftab2 #-}
reftab2 :: [(Text,Text)]
reftab2 =
[ ("Ccaron", "\x0010C"),
("Ccedil", "\x000C7"),
("Ccirc", "\x00108"),
("Cconint", "\x02230"),
("Cdot", "\x0010A"),
("Cedilla", "\x000B8"),
("CenterDot", "\x000B7"),
("Cfr", "\x0212D"),
("Chi", "\x003A7"),
("CircleDot", "\x02299"),
("CircleMinus", "\x02296"),
("CirclePlus", "\x02295"),
("CircleTimes", "\x02297"),
("ClockwiseContourIntegral", "\x02232"),
("CloseCurlyDoubleQuote", "\x0201D"),
("CloseCurlyQuote", "\x02019"),
("Colon", "\x02237"),
("Colone", "\x02A74"),
("Congruent", "\x02261"),
("Conint", "\x0222F"),
("ContourIntegral", "\x0222E"),
("Copf", "\x02102"),
("Coproduct", "\x02210"),
("CounterClockwiseContourIntegral", "\x02233"),
("Cross", "\x02A2F"),
("Cscr", "\x1D49E"),
("Cup", "\x022D3"),
("CupCap", "\x0224D"),
("DD", "\x02145"),
("DDotrahd", "\x02911"),
("DJcy", "\x00402"),
("DScy", "\x00405"),
("DZcy", "\x0040F"),
("Dagger", "\x02021"),
("Darr", "\x021A1"),
("Dashv", "\x02AE4"),
("Dcaron", "\x0010E") ]
{-# NOINLINE reftab3 #-}
reftab3 :: [(Text,Text)]
reftab3 =
[ ("Dcy", "\x00414"),
("Del", "\x02207"),
("Delta", "\x00394"),
("Dfr", "\x1D507"),
("DiacriticalAcute", "\x000B4"),
("DiacriticalDot", "\x002D9"),
("DiacriticalDoubleAcute", "\x002DD"),
("DiacriticalGrave", "\x00060"),
("DiacriticalTilde", "\x002DC"),
("Diamond", "\x022C4"),
("DifferentialD", "\x02146"),
("Dopf", "\x1D53B"),
("Dot", "\x000A8"),
("DotDot", "\x020DC"),
("DotEqual", "\x02250"),
("DoubleContourIntegral", "\x0222F"),
("DoubleDot", "\x000A8"),
("DoubleDownArrow", "\x021D3"),
("DoubleLeftArrow", "\x021D0"),
("DoubleLeftRightArrow", "\x021D4"),
("DoubleLeftTee", "\x02AE4"),
("DoubleLongLeftArrow", "\x027F8"),
("DoubleLongLeftRightArrow", "\x027FA"),
("DoubleLongRightArrow", "\x027F9"),
("DoubleRightArrow", "\x021D2"),
("DoubleRightTee", "\x022A8"),
("DoubleUpArrow", "\x021D1"),
("DoubleUpDownArrow", "\x021D5"),
("DoubleVerticalBar", "\x02225"),
("DownArrow", "\x02193"),
("DownArrowBar", "\x02913"),
("DownArrowUpArrow", "\x021F5"),
("DownBreve", "\x00311"),
("DownLeftRightVector", "\x02950"),
("DownLeftTeeVector", "\x0295E"),
("DownLeftVector", "\x021BD"),
("DownLeftVectorBar", "\x02956") ]
{-# NOINLINE reftab4 #-}
reftab4 :: [(Text,Text)]
reftab4 =
[ ("DownRightTeeVector", "\x0295F"),
("DownRightVector", "\x021C1"),
("DownRightVectorBar", "\x02957"),
("DownTee", "\x022A4"),
("DownTeeArrow", "\x021A7"),
("Downarrow", "\x021D3"),
("Dscr", "\x1D49F"),
("Dstrok", "\x00110"),
("ENG", "\x0014A"),
("ETH", "\x000D0"),
("Eacute", "\x000C9"),
("Ecaron", "\x0011A"),
("Ecirc", "\x000CA"),
("Ecy", "\x0042D"),
("Edot", "\x00116"),
("Efr", "\x1D508"),
("Egrave", "\x000C8"),
("Element", "\x02208"),
("Emacr", "\x00112"),
("EmptySmallSquare", "\x025FB"),
("EmptyVerySmallSquare", "\x025AB"),
("Eogon", "\x00118"),
("Eopf", "\x1D53C"),
("Epsilon", "\x00395"),
("Equal", "\x02A75"),
("EqualTilde", "\x02242"),
("Equilibrium", "\x021CC"),
("Escr", "\x02130"),
("Esim", "\x02A73"),
("Eta", "\x00397"),
("Euml", "\x000CB"),
("Exists", "\x02203"),
("ExponentialE", "\x02147"),
("Fcy", "\x00424"),
("Ffr", "\x1D509"),
("FilledSmallSquare", "\x025FC"),
("FilledVerySmallSquare", "\x025AA") ]
{-# NOINLINE reftab5 #-}
reftab5 :: [(Text,Text)]
reftab5 =
[ ("Fopf", "\x1D53D"),
("ForAll", "\x02200"),
("Fouriertrf", "\x02131"),
("Fscr", "\x02131"),
("GJcy", "\x00403"),
("GT", "\x0003E"),
("Gamma", "\x00393"),
("Gammad", "\x003DC"),
("Gbreve", "\x0011E"),
("Gcedil", "\x00122"),
("Gcirc", "\x0011C"),
("Gcy", "\x00413"),
("Gdot", "\x00120"),
("Gfr", "\x1D50A"),
("Gg", "\x022D9"),
("Gopf", "\x1D53E"),
("GreaterEqual", "\x02265"),
("GreaterEqualLess", "\x022DB"),
("GreaterFullEqual", "\x02267"),
("GreaterGreater", "\x02AA2"),
("GreaterLess", "\x02277"),
("GreaterSlantEqual", "\x02A7E"),
("GreaterTilde", "\x02273"),
("Gscr", "\x1D4A2"),
("Gt", "\x0226B"),
("HARDcy", "\x0042A"),
("Hacek", "\x002C7"),
("Hat", "\x0005E"),
("Hcirc", "\x00124"),
("Hfr", "\x0210C"),
("HilbertSpace", "\x0210B"),
("Hopf", "\x0210D"),
("HorizontalLine", "\x02500"),
("Hscr", "\x0210B"),
("Hstrok", "\x00126"),
("HumpDownHump", "\x0224E"),
("HumpEqual", "\x0224F") ]
{-# NOINLINE reftab6 #-}
reftab6 :: [(Text,Text)]
reftab6 =
[ ("IEcy", "\x00415"),
("IJlig", "\x00132"),
("IOcy", "\x00401"),
("Iacute", "\x000CD"),
("Icirc", "\x000CE"),
("Icy", "\x00418"),
("Idot", "\x00130"),
("Ifr", "\x02111"),
("Igrave", "\x000CC"),
("Im", "\x02111"),
("Imacr", "\x0012A"),
("ImaginaryI", "\x02148"),
("Implies", "\x021D2"),
("Int", "\x0222C"),
("Integral", "\x0222B"),
("Intersection", "\x022C2"),
("InvisibleComma", "\x02063"),
("InvisibleTimes", "\x02062"),
("Iogon", "\x0012E"),
("Iopf", "\x1D540"),
("Iota", "\x00399"),
("Iscr", "\x02110"),
("Itilde", "\x00128"),
("Iukcy", "\x00406"),
("Iuml", "\x000CF"),
("Jcirc", "\x00134"),
("Jcy", "\x00419"),
("Jfr", "\x1D50D"),
("Jopf", "\x1D541"),
("Jscr", "\x1D4A5"),
("Jsercy", "\x00408"),
("Jukcy", "\x00404"),
("KHcy", "\x00425"),
("KJcy", "\x0040C"),
("Kappa", "\x0039A"),
("Kcedil", "\x00136"),
("Kcy", "\x0041A") ]
{-# NOINLINE reftab7 #-}
reftab7 :: [(Text,Text)]
reftab7 =
[ ("Kfr", "\x1D50E"),
("Kopf", "\x1D542"),
("Kscr", "\x1D4A6"),
("LJcy", "\x00409"),
("LT", "\x0003C"),
("Lacute", "\x00139"),
("Lambda", "\x0039B"),
("Lang", "\x027EA"),
("Laplacetrf", "\x02112"),
("Larr", "\x0219E"),
("Lcaron", "\x0013D"),
("Lcedil", "\x0013B"),
("Lcy", "\x0041B"),
("LeftAngleBracket", "\x027E8"),
("LeftArrow", "\x02190"),
("LeftArrowBar", "\x021E4"),
("LeftArrowRightArrow", "\x021C6"),
("LeftCeiling", "\x02308"),
("LeftDoubleBracket", "\x027E6"),
("LeftDownTeeVector", "\x02961"),
("LeftDownVector", "\x021C3"),
("LeftDownVectorBar", "\x02959"),
("LeftFloor", "\x0230A"),
("LeftRightArrow", "\x02194"),
("LeftRightVector", "\x0294E"),
("LeftTee", "\x022A3"),
("LeftTeeArrow", "\x021A4"),
("LeftTeeVector", "\x0295A"),
("LeftTriangle", "\x022B2"),
("LeftTriangleBar", "\x029CF"),
("LeftTriangleEqual", "\x022B4"),
("LeftUpDownVector", "\x02951"),
("LeftUpTeeVector", "\x02960"),
("LeftUpVector", "\x021BF"),
("LeftUpVectorBar", "\x02958"),
("LeftVector", "\x021BC"),
("LeftVectorBar", "\x02952") ]
{-# NOINLINE reftab8 #-}
reftab8 :: [(Text,Text)]
reftab8 =
[ ("Leftarrow", "\x021D0"),
("Leftrightarrow", "\x021D4"),
("LessEqualGreater", "\x022DA"),
("LessFullEqual", "\x02266"),
("LessGreater", "\x02276"),
("LessLess", "\x02AA1"),
("LessSlantEqual", "\x02A7D"),
("LessTilde", "\x02272"),
("Lfr", "\x1D50F"),
("Ll", "\x022D8"),
("Lleftarrow", "\x021DA"),
("Lmidot", "\x0013F"),
("LongLeftArrow", "\x027F5"),
("LongLeftRightArrow", "\x027F7"),
("LongRightArrow", "\x027F6"),
("Longleftarrow", "\x027F8"),
("Longleftrightarrow", "\x027FA"),
("Longrightarrow", "\x027F9"),
("Lopf", "\x1D543"),
("LowerLeftArrow", "\x02199"),
("LowerRightArrow", "\x02198"),
("Lscr", "\x02112"),
("Lsh", "\x021B0"),
("Lstrok", "\x00141"),
("Lt", "\x0226A"),
("Map", "\x02905"),
("Mcy", "\x0041C"),
("MediumSpace", "\x0205F"),
("Mellintrf", "\x02133"),
("Mfr", "\x1D510"),
("MinusPlus", "\x02213"),
("Mopf", "\x1D544"),
("Mscr", "\x02133"),
("Mu", "\x0039C"),
("NJcy", "\x0040A"),
("Nacute", "\x00143"),
("Ncaron", "\x00147") ]
{-# NOINLINE reftab9 #-}
reftab9 :: [(Text,Text)]
reftab9 =
[ ("Ncedil", "\x00145"),
("Ncy", "\x0041D"),
("NegativeMediumSpace", "\x0200B"),
("NegativeThickSpace", "\x0200B"),
("NegativeThinSpace", "\x0200B"),
("NegativeVeryThinSpace", "\x0200B"),
("NestedGreaterGreater", "\x0226B"),
("NestedLessLess", "\x0226A"),
("NewLine", "\x0000A"),
("Nfr", "\x1D511"),
("NoBreak", "\x02060"),
("NonBreakingSpace", "\x000A0"),
("Nopf", "\x02115"),
("Not", "\x02AEC"),
("NotCongruent", "\x02262"),
("NotCupCap", "\x0226D"),
("NotDoubleVerticalBar", "\x02226"),
("NotElement", "\x02209"),
("NotEqual", "\x02260"),
("NotEqualTilde", "\x02242\x00338"),
("NotExists", "\x02204"),
("NotGreater", "\x0226F"),
("NotGreaterEqual", "\x02271"),
("NotGreaterFullEqual", "\x02267\x00338"),
("NotGreaterGreater", "\x0226B\x00338"),
("NotGreaterLess", "\x02279"),
("NotGreaterSlantEqual", "\x02A7E\x00338"),
("NotGreaterTilde", "\x02275"),
("NotHumpDownHump", "\x0224E\x00338"),
("NotHumpEqual", "\x0224F\x00338"),
("NotLeftTriangle", "\x022EA"),
("NotLeftTriangleBar", "\x029CF\x00338"),
("NotLeftTriangleEqual", "\x022EC"),
("NotLess", "\x0226E"),
("NotLessEqual", "\x02270"),
("NotLessGreater", "\x02278"),
("NotLessLess", "\x0226A\x00338") ]
{-# NOINLINE reftab10 #-}
reftab10 :: [(Text,Text)]
reftab10 =
[ ("NotLessSlantEqual", "\x02A7D\x00338"),
("NotLessTilde", "\x02274"),
("NotNestedGreaterGreater", "\x02AA2\x00338"),
("NotNestedLessLess", "\x02AA1\x00338"),
("NotPrecedes", "\x02280"),
("NotPrecedesEqual", "\x02AAF\x00338"),
("NotPrecedesSlantEqual", "\x022E0"),
("NotReverseElement", "\x0220C"),
("NotRightTriangle", "\x022EB"),
("NotRightTriangleBar", "\x029D0\x00338"),
("NotRightTriangleEqual", "\x022ED"),
("NotSquareSubset", "\x0228F\x00338"),
("NotSquareSubsetEqual", "\x022E2"),
("NotSquareSuperset", "\x02290\x00338"),
("NotSquareSupersetEqual", "\x022E3"),
("NotSubset", "\x02282\x020D2"),
("NotSubsetEqual", "\x02288"),
("NotSucceeds", "\x02281"),
("NotSucceedsEqual", "\x02AB0\x00338"),
("NotSucceedsSlantEqual", "\x022E1"),
("NotSucceedsTilde", "\x0227F\x00338"),
("NotSuperset", "\x02283\x020D2"),
("NotSupersetEqual", "\x02289"),
("NotTilde", "\x02241"),
("NotTildeEqual", "\x02244"),
("NotTildeFullEqual", "\x02247"),
("NotTildeTilde", "\x02249"),
("NotVerticalBar", "\x02224"),
("Nscr", "\x1D4A9"),
("Ntilde", "\x000D1"),
("Nu", "\x0039D"),
("OElig", "\x00152"),
("Oacute", "\x000D3"),
("Ocirc", "\x000D4"),
("Ocy", "\x0041E"),
("Odblac", "\x00150"),
("Ofr", "\x1D512") ]
{-# NOINLINE reftab11 #-}
reftab11 :: [(Text,Text)]
reftab11 =
[ ("Ograve", "\x000D2"),
("Omacr", "\x0014C"),
("Omega", "\x003A9"),
("Omicron", "\x0039F"),
("Oopf", "\x1D546"),
("OpenCurlyDoubleQuote", "\x0201C"),
("OpenCurlyQuote", "\x02018"),
("Or", "\x02A54"),
("Oscr", "\x1D4AA"),
("Oslash", "\x000D8"),
("Otilde", "\x000D5"),
("Otimes", "\x02A37"),
("Ouml", "\x000D6"),
("OverBar", "\x0203E"),
("OverBrace", "\x023DE"),
("OverBracket", "\x023B4"),
("OverParenthesis", "\x023DC"),
("PartialD", "\x02202"),
("Pcy", "\x0041F"),
("Pfr", "\x1D513"),
("Phi", "\x003A6"),
("Pi", "\x003A0"),
("PlusMinus", "\x000B1"),
("Poincareplane", "\x0210C"),
("Popf", "\x02119"),
("Pr", "\x02ABB"),
("Precedes", "\x0227A"),
("PrecedesEqual", "\x02AAF"),
("PrecedesSlantEqual", "\x0227C"),
("PrecedesTilde", "\x0227E"),
("Prime", "\x02033"),
("Product", "\x0220F"),
("Proportion", "\x02237"),
("Proportional", "\x0221D"),
("Pscr", "\x1D4AB"),
("Psi", "\x003A8"),
("QUOT", "\x00022") ]
{-# NOINLINE reftab12 #-}
reftab12 :: [(Text,Text)]
reftab12 =
[ ("Qfr", "\x1D514"),
("Qopf", "\x0211A"),
("Qscr", "\x1D4AC"),
("RBarr", "\x02910"),
("REG", "\x000AE"),
("Racute", "\x00154"),
("Rang", "\x027EB"),
("Rarr", "\x021A0"),
("Rarrtl", "\x02916"),
("Rcaron", "\x00158"),
("Rcedil", "\x00156"),
("Rcy", "\x00420"),
("Re", "\x0211C"),
("ReverseElement", "\x0220B"),
("ReverseEquilibrium", "\x021CB"),
("ReverseUpEquilibrium", "\x0296F"),
("Rfr", "\x0211C"),
("Rho", "\x003A1"),
("RightAngleBracket", "\x027E9"),
("RightArrow", "\x02192"),
("RightArrowBar", "\x021E5"),
("RightArrowLeftArrow", "\x021C4"),
("RightCeiling", "\x02309"),
("RightDoubleBracket", "\x027E7"),
("RightDownTeeVector", "\x0295D"),
("RightDownVector", "\x021C2"),
("RightDownVectorBar", "\x02955"),
("RightFloor", "\x0230B"),
("RightTee", "\x022A2"),
("RightTeeArrow", "\x021A6"),
("RightTeeVector", "\x0295B"),
("RightTriangle", "\x022B3"),
("RightTriangleBar", "\x029D0"),
("RightTriangleEqual", "\x022B5"),
("RightUpDownVector", "\x0294F"),
("RightUpTeeVector", "\x0295C"),
("RightUpVector", "\x021BE") ]
{-# NOINLINE reftab13 #-}
reftab13 :: [(Text,Text)]
reftab13 =
[ ("RightUpVectorBar", "\x02954"),
("RightVector", "\x021C0"),
("RightVectorBar", "\x02953"),
("Rightarrow", "\x021D2"),
("Ropf", "\x0211D"),
("RoundImplies", "\x02970"),
("Rrightarrow", "\x021DB"),
("Rscr", "\x0211B"),
("Rsh", "\x021B1"),
("RuleDelayed", "\x029F4"),
("SHCHcy", "\x00429"),
("SHcy", "\x00428"),
("SOFTcy", "\x0042C"),
("Sacute", "\x0015A"),
("Sc", "\x02ABC"),
("Scaron", "\x00160"),
("Scedil", "\x0015E"),
("Scirc", "\x0015C"),
("Scy", "\x00421"),
("Sfr", "\x1D516"),
("ShortDownArrow", "\x02193"),
("ShortLeftArrow", "\x02190"),
("ShortRightArrow", "\x02192"),
("ShortUpArrow", "\x02191"),
("Sigma", "\x003A3"),
("SmallCircle", "\x02218"),
("Sopf", "\x1D54A"),
("Sqrt", "\x0221A"),
("Square", "\x025A1"),
("SquareIntersection", "\x02293"),
("SquareSubset", "\x0228F"),
("SquareSubsetEqual", "\x02291"),
("SquareSuperset", "\x02290"),
("SquareSupersetEqual", "\x02292"),
("SquareUnion", "\x02294"),
("Sscr", "\x1D4AE"),
("Star", "\x022C6") ]
{-# NOINLINE reftab14 #-}
reftab14 :: [(Text,Text)]
reftab14 =
[ ("Sub", "\x022D0"),
("Subset", "\x022D0"),
("SubsetEqual", "\x02286"),
("Succeeds", "\x0227B"),
("SucceedsEqual", "\x02AB0"),
("SucceedsSlantEqual", "\x0227D"),
("SucceedsTilde", "\x0227F"),
("SuchThat", "\x0220B"),
("Sum", "\x02211"),
("Sup", "\x022D1"),
("Superset", "\x02283"),
("SupersetEqual", "\x02287"),
("Supset", "\x022D1"),
("THORN", "\x000DE"),
("TRADE", "\x02122"),
("TSHcy", "\x0040B"),
("TScy", "\x00426"),
("Tab", "\x00009"),
("Tau", "\x003A4"),
("Tcaron", "\x00164"),
("Tcedil", "\x00162"),
("Tcy", "\x00422"),
("Tfr", "\x1D517"),
("Therefore", "\x02234"),
("Theta", "\x00398"),
("ThickSpace", "\x0205F\x0200A"),
("ThinSpace", "\x02009"),
("Tilde", "\x0223C"),
("TildeEqual", "\x02243"),
("TildeFullEqual", "\x02245"),
("TildeTilde", "\x02248"),
("Topf", "\x1D54B"),
("TripleDot", "\x020DB"),
("Tscr", "\x1D4AF"),
("Tstrok", "\x00166"),
("Uacute", "\x000DA"),
("Uarr", "\x0219F") ]
{-# NOINLINE reftab15 #-}
reftab15 :: [(Text,Text)]
reftab15 =
[ ("Uarrocir", "\x02949"),
("Ubrcy", "\x0040E"),
("Ubreve", "\x0016C"),
("Ucirc", "\x000DB"),
("Ucy", "\x00423"),
("Udblac", "\x00170"),
("Ufr", "\x1D518"),
("Ugrave", "\x000D9"),
("Umacr", "\x0016A"),
("UnderBar", "\x0005F"),
("UnderBrace", "\x023DF"),
("UnderBracket", "\x023B5"),
("UnderParenthesis", "\x023DD"),
("Union", "\x022C3"),
("UnionPlus", "\x0228E"),
("Uogon", "\x00172"),
("Uopf", "\x1D54C"),
("UpArrow", "\x02191"),
("UpArrowBar", "\x02912"),
("UpArrowDownArrow", "\x021C5"),
("UpDownArrow", "\x02195"),
("UpEquilibrium", "\x0296E"),
("UpTee", "\x022A5"),
("UpTeeArrow", "\x021A5"),
("Uparrow", "\x021D1"),
("Updownarrow", "\x021D5"),
("UpperLeftArrow", "\x02196"),
("UpperRightArrow", "\x02197"),
("Upsi", "\x003D2"),
("Upsilon", "\x003A5"),
("Uring", "\x0016E"),
("Uscr", "\x1D4B0"),
("Utilde", "\x00168"),
("Uuml", "\x000DC"),
("VDash", "\x022AB"),
("Vbar", "\x02AEB"),
("Vcy", "\x00412") ]
{-# NOINLINE reftab16 #-}
reftab16 :: [(Text,Text)]
reftab16 =
[ ("Vdash", "\x022A9"),
("Vdashl", "\x02AE6"),
("Vee", "\x022C1"),
("Verbar", "\x02016"),
("Vert", "\x02016"),
("VerticalBar", "\x02223"),
("VerticalLine", "\x0007C"),
("VerticalSeparator", "\x02758"),
("VerticalTilde", "\x02240"),
("VeryThinSpace", "\x0200A"),
("Vfr", "\x1D519"),
("Vopf", "\x1D54D"),
("Vscr", "\x1D4B1"),
("Vvdash", "\x022AA"),
("Wcirc", "\x00174"),
("Wedge", "\x022C0"),
("Wfr", "\x1D51A"),
("Wopf", "\x1D54E"),
("Wscr", "\x1D4B2"),
("Xfr", "\x1D51B"),
("Xi", "\x0039E"),
("Xopf", "\x1D54F"),
("Xscr", "\x1D4B3"),
("YAcy", "\x0042F"),
("YIcy", "\x00407"),
("YUcy", "\x0042E"),
("Yacute", "\x000DD"),
("Ycirc", "\x00176"),
("Ycy", "\x0042B"),
("Yfr", "\x1D51C"),
("Yopf", "\x1D550"),
("Yscr", "\x1D4B4"),
("Yuml", "\x00178"),
("ZHcy", "\x00416"),
("Zacute", "\x00179"),
("Zcaron", "\x0017D"),
("Zcy", "\x00417") ]
{-# NOINLINE reftab17 #-}
reftab17 :: [(Text,Text)]
reftab17 =
[ ("Zdot", "\x0017B"),
("ZeroWidthSpace", "\x0200B"),
("Zeta", "\x00396"),
("Zfr", "\x02128"),
("Zopf", "\x02124"),
("Zscr", "\x1D4B5"),
("aacute", "\x000E1"),
("abreve", "\x00103"),
("ac", "\x0223E"),
("acE", "\x0223E\x00333"),
("acd", "\x0223F"),
("acirc", "\x000E2"),
("acute", "\x000B4"),
("acy", "\x00430"),
("aelig", "\x000E6"),
("af", "\x02061"),
("afr", "\x1D51E"),
("agrave", "\x000E0"),
("alefsym", "\x02135"),
("aleph", "\x02135"),
("alpha", "\x003B1"),
("amacr", "\x00101"),
("amalg", "\x02A3F"),
("amp", "\x00026"),
("and", "\x02227"),
("andand", "\x02A55"),
("andd", "\x02A5C"),
("andslope", "\x02A58"),
("andv", "\x02A5A"),
("ang", "\x02220"),
("ange", "\x029A4"),
("angle", "\x02220"),
("angmsd", "\x02221"),
("angmsdaa", "\x029A8"),
("angmsdab", "\x029A9"),
("angmsdac", "\x029AA"),
("angmsdad", "\x029AB") ]
{-# NOINLINE reftab18 #-}
reftab18 :: [(Text,Text)]
reftab18 =
[ ("angmsdae", "\x029AC"),
("angmsdaf", "\x029AD"),
("angmsdag", "\x029AE"),
("angmsdah", "\x029AF"),
("angrt", "\x0221F"),
("angrtvb", "\x022BE"),
("angrtvbd", "\x0299D"),
("angsph", "\x02222"),
("angst", "\x000C5"),
("angzarr", "\x0237C"),
("aogon", "\x00105"),
("aopf", "\x1D552"),
("ap", "\x02248"),
("apE", "\x02A70"),
("apacir", "\x02A6F"),
("ape", "\x0224A"),
("apid", "\x0224B"),
("apos", "\x00027"),
("approx", "\x02248"),
("approxeq", "\x0224A"),
("aring", "\x000E5"),
("ascr", "\x1D4B6"),
("ast", "\x0002A"),
("asymp", "\x02248"),
("asympeq", "\x0224D"),
("atilde", "\x000E3"),
("auml", "\x000E4"),
("awconint", "\x02233"),
("awint", "\x02A11"),
("bNot", "\x02AED"),
("backcong", "\x0224C"),
("backepsilon", "\x003F6"),
("backprime", "\x02035"),
("backsim", "\x0223D"),
("backsimeq", "\x022CD"),
("barvee", "\x022BD"),
("barwed", "\x02305") ]
{-# NOINLINE reftab19 #-}
reftab19 :: [(Text,Text)]
reftab19 =
[ ("barwedge", "\x02305"),
("bbrk", "\x023B5"),
("bbrktbrk", "\x023B6"),
("bcong", "\x0224C"),
("bcy", "\x00431"),
("bdquo", "\x0201E"),
("becaus", "\x02235"),
("because", "\x02235"),
("bemptyv", "\x029B0"),
("bepsi", "\x003F6"),
("bernou", "\x0212C"),
("beta", "\x003B2"),
("beth", "\x02136"),
("between", "\x0226C"),
("bfr", "\x1D51F"),
("bigcap", "\x022C2"),
("bigcirc", "\x025EF"),
("bigcup", "\x022C3"),
("bigodot", "\x02A00"),
("bigoplus", "\x02A01"),
("bigotimes", "\x02A02"),
("bigsqcup", "\x02A06"),
("bigstar", "\x02605"),
("bigtriangledown", "\x025BD"),
("bigtriangleup", "\x025B3"),
("biguplus", "\x02A04"),
("bigvee", "\x022C1"),
("bigwedge", "\x022C0"),
("bkarow", "\x0290D"),
("blacklozenge", "\x029EB"),
("blacksquare", "\x025AA"),
("blacktriangle", "\x025B4"),
("blacktriangledown", "\x025BE"),
("blacktriangleleft", "\x025C2"),
("blacktriangleright", "\x025B8"),
("blank", "\x02423"),
("blk12", "\x02592") ]
{-# NOINLINE reftab20 #-}
reftab20 :: [(Text,Text)]
reftab20 =
[ ("blk14", "\x02591"),
("blk34", "\x02593"),
("block", "\x02588"),
("bne", "\x0003D\x020E5"),
("bnequiv", "\x02261\x020E5"),
("bnot", "\x02310"),
("bopf", "\x1D553"),
("bot", "\x022A5"),
("bottom", "\x022A5"),
("bowtie", "\x022C8"),
("boxDL", "\x02557"),
("boxDR", "\x02554"),
("boxDl", "\x02556"),
("boxDr", "\x02553"),
("boxH", "\x02550"),
("boxHD", "\x02566"),
("boxHU", "\x02569"),
("boxHd", "\x02564"),
("boxHu", "\x02567"),
("boxUL", "\x0255D"),
("boxUR", "\x0255A"),
("boxUl", "\x0255C"),
("boxUr", "\x02559"),
("boxV", "\x02551"),
("boxVH", "\x0256C"),
("boxVL", "\x02563"),
("boxVR", "\x02560"),
("boxVh", "\x0256B"),
("boxVl", "\x02562"),
("boxVr", "\x0255F"),
("boxbox", "\x029C9"),
("boxdL", "\x02555"),
("boxdR", "\x02552"),
("boxdl", "\x02510"),
("boxdr", "\x0250C"),
("boxh", "\x02500"),
("boxhD", "\x02565") ]
{-# NOINLINE reftab21 #-}
reftab21 :: [(Text,Text)]
reftab21 =
[ ("boxhU", "\x02568"),
("boxhd", "\x0252C"),
("boxhu", "\x02534"),
("boxminus", "\x0229F"),
("boxplus", "\x0229E"),
("boxtimes", "\x022A0"),
("boxuL", "\x0255B"),
("boxuR", "\x02558"),
("boxul", "\x02518"),
("boxur", "\x02514"),
("boxv", "\x02502"),
("boxvH", "\x0256A"),
("boxvL", "\x02561"),
("boxvR", "\x0255E"),
("boxvh", "\x0253C"),
("boxvl", "\x02524"),
("boxvr", "\x0251C"),
("bprime", "\x02035"),
("breve", "\x002D8"),
("brvbar", "\x000A6"),
("bscr", "\x1D4B7"),
("bsemi", "\x0204F"),
("bsim", "\x0223D"),
("bsime", "\x022CD"),
("bsol", "\x0005C"),
("bsolb", "\x029C5"),
("bsolhsub", "\x027C8"),
("bull", "\x02022"),
("bullet", "\x02022"),
("bump", "\x0224E"),
("bumpE", "\x02AAE"),
("bumpe", "\x0224F"),
("bumpeq", "\x0224F"),
("cacute", "\x00107"),
("cap", "\x02229"),
("capand", "\x02A44"),
("capbrcup", "\x02A49") ]
{-# NOINLINE reftab22 #-}
reftab22 :: [(Text,Text)]
reftab22 =
[ ("capcap", "\x02A4B"),
("capcup", "\x02A47"),
("capdot", "\x02A40"),
("caps", "\x02229\x0FE00"),
("caret", "\x02041"),
("caron", "\x002C7"),
("ccaps", "\x02A4D"),
("ccaron", "\x0010D"),
("ccedil", "\x000E7"),
("ccirc", "\x00109"),
("ccups", "\x02A4C"),
("ccupssm", "\x02A50"),
("cdot", "\x0010B"),
("cedil", "\x000B8"),
("cemptyv", "\x029B2"),
("cent", "\x000A2"),
("centerdot", "\x000B7"),
("cfr", "\x1D520"),
("chcy", "\x00447"),
("check", "\x02713"),
("checkmark", "\x02713"),
("chi", "\x003C7"),
("cir", "\x025CB"),
("cirE", "\x029C3"),
("circ", "\x002C6"),
("circeq", "\x02257"),
("circlearrowleft", "\x021BA"),
("circlearrowright", "\x021BB"),
("circledR", "\x000AE"),
("circledS", "\x024C8"),
("circledast", "\x0229B"),
("circledcirc", "\x0229A"),
("circleddash", "\x0229D"),
("cire", "\x02257"),
("cirfnint", "\x02A10"),
("cirmid", "\x02AEF"),
("cirscir", "\x029C2") ]
{-# NOINLINE reftab23 #-}
reftab23 :: [(Text,Text)]
reftab23 =
[ ("clubs", "\x02663"),
("clubsuit", "\x02663"),
("colon", "\x0003A"),
("colone", "\x02254"),
("coloneq", "\x02254"),
("comma", "\x0002C"),
("commat", "\x00040"),
("comp", "\x02201"),
("compfn", "\x02218"),
("complement", "\x02201"),
("complexes", "\x02102"),
("cong", "\x02245"),
("congdot", "\x02A6D"),
("conint", "\x0222E"),
("copf", "\x1D554"),
("coprod", "\x02210"),
("copy", "\x000A9"),
("copysr", "\x02117"),
("crarr", "\x021B5"),
("cross", "\x02717"),
("cscr", "\x1D4B8"),
("csub", "\x02ACF"),
("csube", "\x02AD1"),
("csup", "\x02AD0"),
("csupe", "\x02AD2"),
("ctdot", "\x022EF"),
("cudarrl", "\x02938"),
("cudarrr", "\x02935"),
("cuepr", "\x022DE"),
("cuesc", "\x022DF"),
("cularr", "\x021B6"),
("cularrp", "\x0293D"),
("cup", "\x0222A"),
("cupbrcap", "\x02A48"),
("cupcap", "\x02A46"),
("cupcup", "\x02A4A"),
("cupdot", "\x0228D") ]
{-# NOINLINE reftab24 #-}
reftab24 :: [(Text,Text)]
reftab24 =
[ ("cupor", "\x02A45"),
("cups", "\x0222A\x0FE00"),
("curarr", "\x021B7"),
("curarrm", "\x0293C"),
("curlyeqprec", "\x022DE"),
("curlyeqsucc", "\x022DF"),
("curlyvee", "\x022CE"),
("curlywedge", "\x022CF"),
("curren", "\x000A4"),
("curvearrowleft", "\x021B6"),
("curvearrowright", "\x021B7"),
("cuvee", "\x022CE"),
("cuwed", "\x022CF"),
("cwconint", "\x02232"),
("cwint", "\x02231"),
("cylcty", "\x0232D"),
("dArr", "\x021D3"),
("dHar", "\x02965"),
("dagger", "\x02020"),
("daleth", "\x02138"),
("darr", "\x02193"),
("dash", "\x02010"),
("dashv", "\x022A3"),
("dbkarow", "\x0290F"),
("dblac", "\x002DD"),
("dcaron", "\x0010F"),
("dcy", "\x00434"),
("dd", "\x02146"),
("ddagger", "\x02021"),
("ddarr", "\x021CA"),
("ddotseq", "\x02A77"),
("deg", "\x000B0"),
("delta", "\x003B4"),
("demptyv", "\x029B1"),
("dfisht", "\x0297F"),
("dfr", "\x1D521"),
("dharl", "\x021C3") ]
{-# NOINLINE reftab25 #-}
reftab25 :: [(Text,Text)]
reftab25 =
[ ("dharr", "\x021C2"),
("diam", "\x022C4"),
("diamond", "\x022C4"),
("diamondsuit", "\x02666"),
("diams", "\x02666"),
("die", "\x000A8"),
("digamma", "\x003DD"),
("disin", "\x022F2"),
("div", "\x000F7"),
("divide", "\x000F7"),
("divideontimes", "\x022C7"),
("divonx", "\x022C7"),
("djcy", "\x00452"),
("dlcorn", "\x0231E"),
("dlcrop", "\x0230D"),
("dollar", "\x00024"),
("dopf", "\x1D555"),
("dot", "\x002D9"),
("doteq", "\x02250"),
("doteqdot", "\x02251"),
("dotminus", "\x02238"),
("dotplus", "\x02214"),
("dotsquare", "\x022A1"),
("doublebarwedge", "\x02306"),
("downarrow", "\x02193"),
("downdownarrows", "\x021CA"),
("downharpoonleft", "\x021C3"),
("downharpoonright", "\x021C2"),
("drbkarow", "\x02910"),
("drcorn", "\x0231F"),
("drcrop", "\x0230C"),
("dscr", "\x1D4B9"),
("dscy", "\x00455"),
("dsol", "\x029F6"),
("dstrok", "\x00111"),
("dtdot", "\x022F1"),
("dtri", "\x025BF") ]
{-# NOINLINE reftab26 #-}
reftab26 :: [(Text,Text)]
reftab26 =
[ ("dtrif", "\x025BE"),
("duarr", "\x021F5"),
("duhar", "\x0296F"),
("dwangle", "\x029A6"),
("dzcy", "\x0045F"),
("dzigrarr", "\x027FF"),
("eDDot", "\x02A77"),
("eDot", "\x02251"),
("eacute", "\x000E9"),
("easter", "\x02A6E"),
("ecaron", "\x0011B"),
("ecir", "\x02256"),
("ecirc", "\x000EA"),
("ecolon", "\x02255"),
("ecy", "\x0044D"),
("edot", "\x00117"),
("ee", "\x02147"),
("efDot", "\x02252"),
("efr", "\x1D522"),
("eg", "\x02A9A"),
("egrave", "\x000E8"),
("egs", "\x02A96"),
("egsdot", "\x02A98"),
("el", "\x02A99"),
("elinters", "\x023E7"),
("ell", "\x02113"),
("els", "\x02A95"),
("elsdot", "\x02A97"),
("emacr", "\x00113"),
("empty", "\x02205"),
("emptyset", "\x02205"),
("emptyv", "\x02205"),
("emsp", "\x02003"),
("emsp13", "\x02004"),
("emsp14", "\x02005"),
("eng", "\x0014B"),
("ensp", "\x02002") ]
{-# NOINLINE reftab27 #-}
reftab27 :: [(Text,Text)]
reftab27 =
[ ("eogon", "\x00119"),
("eopf", "\x1D556"),
("epar", "\x022D5"),
("eparsl", "\x029E3"),
("eplus", "\x02A71"),
("epsi", "\x003B5"),
("epsilon", "\x003B5"),
("epsiv", "\x003F5"),
("eqcirc", "\x02256"),
("eqcolon", "\x02255"),
("eqsim", "\x02242"),
("eqslantgtr", "\x02A96"),
("eqslantless", "\x02A95"),
("equals", "\x0003D"),
("equest", "\x0225F"),
("equiv", "\x02261"),
("equivDD", "\x02A78"),
("eqvparsl", "\x029E5"),
("erDot", "\x02253"),
("erarr", "\x02971"),
("escr", "\x0212F"),
("esdot", "\x02250"),
("esim", "\x02242"),
("eta", "\x003B7"),
("eth", "\x000F0"),
("euml", "\x000EB"),
("euro", "\x020AC"),
("excl", "\x00021"),
("exist", "\x02203"),
("expectation", "\x02130"),
("exponentiale", "\x02147"),
("fallingdotseq", "\x02252"),
("fcy", "\x00444"),
("female", "\x02640"),
("ffilig", "\x0FB03"),
("fflig", "\x0FB00"),
("ffllig", "\x0FB04") ]
{-# NOINLINE reftab28 #-}
reftab28 :: [(Text,Text)]
reftab28 =
[ ("ffr", "\x1D523"),
("filig", "\x0FB01"),
("fjlig", "\x00066\x0006A"),
("flat", "\x0266D"),
("fllig", "\x0FB02"),
("fltns", "\x025B1"),
("fnof", "\x00192"),
("fopf", "\x1D557"),
("forall", "\x02200"),
("fork", "\x022D4"),
("forkv", "\x02AD9"),
("fpartint", "\x02A0D"),
("frac12", "\x000BD"),
("frac13", "\x02153"),
("frac14", "\x000BC"),
("frac15", "\x02155"),
("frac16", "\x02159"),
("frac18", "\x0215B"),
("frac23", "\x02154"),
("frac25", "\x02156"),
("frac34", "\x000BE"),
("frac35", "\x02157"),
("frac38", "\x0215C"),
("frac45", "\x02158"),
("frac56", "\x0215A"),
("frac58", "\x0215D"),
("frac78", "\x0215E"),
("frasl", "\x02044"),
("frown", "\x02322"),
("fscr", "\x1D4BB"),
("gE", "\x02267"),
("gEl", "\x02A8C"),
("gacute", "\x001F5"),
("gamma", "\x003B3"),
("gammad", "\x003DD"),
("gap", "\x02A86"),
("gbreve", "\x0011F") ]
{-# NOINLINE reftab29 #-}
reftab29 :: [(Text,Text)]
reftab29 =
[ ("gcirc", "\x0011D"),
("gcy", "\x00433"),
("gdot", "\x00121"),
("ge", "\x02265"),
("gel", "\x022DB"),
("geq", "\x02265"),
("geqq", "\x02267"),
("geqslant", "\x02A7E"),
("ges", "\x02A7E"),
("gescc", "\x02AA9"),
("gesdot", "\x02A80"),
("gesdoto", "\x02A82"),
("gesdotol", "\x02A84"),
("gesl", "\x022DB\x0FE00"),
("gesles", "\x02A94"),
("gfr", "\x1D524"),
("gg", "\x0226B"),
("ggg", "\x022D9"),
("gimel", "\x02137"),
("gjcy", "\x00453"),
("gl", "\x02277"),
("glE", "\x02A92"),
("gla", "\x02AA5"),
("glj", "\x02AA4"),
("gnE", "\x02269"),
("gnap", "\x02A8A"),
("gnapprox", "\x02A8A"),
("gne", "\x02A88"),
("gneq", "\x02A88"),
("gneqq", "\x02269"),
("gnsim", "\x022E7"),
("gopf", "\x1D558"),
("grave", "\x00060"),
("gscr", "\x0210A"),
("gsim", "\x02273"),
("gsime", "\x02A8E"),
("gsiml", "\x02A90") ]
{-# NOINLINE reftab30 #-}
reftab30 :: [(Text,Text)]
reftab30 =
[ ("gt", "\x0003E"),
("gtcc", "\x02AA7"),
("gtcir", "\x02A7A"),
("gtdot", "\x022D7"),
("gtlPar", "\x02995"),
("gtquest", "\x02A7C"),
("gtrapprox", "\x02A86"),
("gtrarr", "\x02978"),
("gtrdot", "\x022D7"),
("gtreqless", "\x022DB"),
("gtreqqless", "\x02A8C"),
("gtrless", "\x02277"),
("gtrsim", "\x02273"),
("gvertneqq", "\x02269\x0FE00"),
("gvnE", "\x02269\x0FE00"),
("hArr", "\x021D4"),
("hairsp", "\x0200A"),
("half", "\x000BD"),
("hamilt", "\x0210B"),
("hardcy", "\x0044A"),
("harr", "\x02194"),
("harrcir", "\x02948"),
("harrw", "\x021AD"),
("hbar", "\x0210F"),
("hcirc", "\x00125"),
("hearts", "\x02665"),
("heartsuit", "\x02665"),
("hellip", "\x02026"),
("hercon", "\x022B9"),
("hfr", "\x1D525"),
("hksearow", "\x02925"),
("hkswarow", "\x02926"),
("hoarr", "\x021FF"),
("homtht", "\x0223B"),
("hookleftarrow", "\x021A9"),
("hookrightarrow", "\x021AA"),
("hopf", "\x1D559") ]
{-# NOINLINE reftab31 #-}
reftab31 :: [(Text,Text)]
reftab31 =
[ ("horbar", "\x02015"),
("hscr", "\x1D4BD"),
("hslash", "\x0210F"),
("hstrok", "\x00127"),
("hybull", "\x02043"),
("hyphen", "\x02010"),
("iacute", "\x000ED"),
("ic", "\x02063"),
("icirc", "\x000EE"),
("icy", "\x00438"),
("iecy", "\x00435"),
("iexcl", "\x000A1"),
("iff", "\x021D4"),
("ifr", "\x1D526"),
("igrave", "\x000EC"),
("ii", "\x02148"),
("iiiint", "\x02A0C"),
("iiint", "\x0222D"),
("iinfin", "\x029DC"),
("iiota", "\x02129"),
("ijlig", "\x00133"),
("imacr", "\x0012B"),
("image", "\x02111"),
("imagline", "\x02110"),
("imagpart", "\x02111"),
("imath", "\x00131"),
("imof", "\x022B7"),
("imped", "\x001B5"),
("in", "\x02208"),
("incare", "\x02105"),
("infin", "\x0221E"),
("infintie", "\x029DD"),
("inodot", "\x00131"),
("int", "\x0222B"),
("intcal", "\x022BA"),
("integers", "\x02124"),
("intercal", "\x022BA") ]
{-# NOINLINE reftab32 #-}
reftab32 :: [(Text,Text)]
reftab32 =
[ ("intlarhk", "\x02A17"),
("intprod", "\x02A3C"),
("iocy", "\x00451"),
("iogon", "\x0012F"),
("iopf", "\x1D55A"),
("iota", "\x003B9"),
("iprod", "\x02A3C"),
("iquest", "\x000BF"),
("iscr", "\x1D4BE"),
("isin", "\x02208"),
("isinE", "\x022F9"),
("isindot", "\x022F5"),
("isins", "\x022F4"),
("isinsv", "\x022F3"),
("isinv", "\x02208"),
("it", "\x02062"),
("itilde", "\x00129"),
("iukcy", "\x00456"),
("iuml", "\x000EF"),
("jcirc", "\x00135"),
("jcy", "\x00439"),
("jfr", "\x1D527"),
("jmath", "\x00237"),
("jopf", "\x1D55B"),
("jscr", "\x1D4BF"),
("jsercy", "\x00458"),
("jukcy", "\x00454"),
("kappa", "\x003BA"),
("kappav", "\x003F0"),
("kcedil", "\x00137"),
("kcy", "\x0043A"),
("kfr", "\x1D528"),
("kgreen", "\x00138"),
("khcy", "\x00445"),
("kjcy", "\x0045C"),
("kopf", "\x1D55C"),
("kscr", "\x1D4C0") ]
{-# NOINLINE reftab33 #-}
reftab33 :: [(Text,Text)]
reftab33 =
[ ("lAarr", "\x021DA"),
("lArr", "\x021D0"),
("lAtail", "\x0291B"),
("lBarr", "\x0290E"),
("lE", "\x02266"),
("lEg", "\x02A8B"),
("lHar", "\x02962"),
("lacute", "\x0013A"),
("laemptyv", "\x029B4"),
("lagran", "\x02112"),
("lambda", "\x003BB"),
("lang", "\x027E8"),
("langd", "\x02991"),
("langle", "\x027E8"),
("lap", "\x02A85"),
("laquo", "\x000AB"),
("larr", "\x02190"),
("larrb", "\x021E4"),
("larrbfs", "\x0291F"),
("larrfs", "\x0291D"),
("larrhk", "\x021A9"),
("larrlp", "\x021AB"),
("larrpl", "\x02939"),
("larrsim", "\x02973"),
("larrtl", "\x021A2"),
("lat", "\x02AAB"),
("latail", "\x02919"),
("late", "\x02AAD"),
("lates", "\x02AAD\x0FE00"),
("lbarr", "\x0290C"),
("lbbrk", "\x02772"),
("lbrace", "\x0007B"),
("lbrack", "\x0005B"),
("lbrke", "\x0298B"),
("lbrksld", "\x0298F"),
("lbrkslu", "\x0298D"),
("lcaron", "\x0013E") ]
{-# NOINLINE reftab34 #-}
reftab34 :: [(Text,Text)]
reftab34 =
[ ("lcedil", "\x0013C"),
("lceil", "\x02308"),
("lcub", "\x0007B"),
("lcy", "\x0043B"),
("ldca", "\x02936"),
("ldquo", "\x0201C"),
("ldquor", "\x0201E"),
("ldrdhar", "\x02967"),
("ldrushar", "\x0294B"),
("ldsh", "\x021B2"),
("le", "\x02264"),
("leftarrow", "\x02190"),
("leftarrowtail", "\x021A2"),
("leftharpoondown", "\x021BD"),
("leftharpoonup", "\x021BC"),
("leftleftarrows", "\x021C7"),
("leftrightarrow", "\x02194"),
("leftrightarrows", "\x021C6"),
("leftrightharpoons", "\x021CB"),
("leftrightsquigarrow", "\x021AD"),
("leftthreetimes", "\x022CB"),
("leg", "\x022DA"),
("leq", "\x02264"),
("leqq", "\x02266"),
("leqslant", "\x02A7D"),
("les", "\x02A7D"),
("lescc", "\x02AA8"),
("lesdot", "\x02A7F"),
("lesdoto", "\x02A81"),
("lesdotor", "\x02A83"),
("lesg", "\x022DA\x0FE00"),
("lesges", "\x02A93"),
("lessapprox", "\x02A85"),
("lessdot", "\x022D6"),
("lesseqgtr", "\x022DA"),
("lesseqqgtr", "\x02A8B"),
("lessgtr", "\x02276") ]
{-# NOINLINE reftab35 #-}
reftab35 :: [(Text,Text)]
reftab35 =
[ ("lesssim", "\x02272"),
("lfisht", "\x0297C"),
("lfloor", "\x0230A"),
("lfr", "\x1D529"),
("lg", "\x02276"),
("lgE", "\x02A91"),
("lhard", "\x021BD"),
("lharu", "\x021BC"),
("lharul", "\x0296A"),
("lhblk", "\x02584"),
("ljcy", "\x00459"),
("ll", "\x0226A"),
("llarr", "\x021C7"),
("llcorner", "\x0231E"),
("llhard", "\x0296B"),
("lltri", "\x025FA"),
("lmidot", "\x00140"),
("lmoust", "\x023B0"),
("lmoustache", "\x023B0"),
("lnE", "\x02268"),
("lnap", "\x02A89"),
("lnapprox", "\x02A89"),
("lne", "\x02A87"),
("lneq", "\x02A87"),
("lneqq", "\x02268"),
("lnsim", "\x022E6"),
("loang", "\x027EC"),
("loarr", "\x021FD"),
("lobrk", "\x027E6"),
("longleftarrow", "\x027F5"),
("longleftrightarrow", "\x027F7"),
("longmapsto", "\x027FC"),
("longrightarrow", "\x027F6"),
("looparrowleft", "\x021AB"),
("looparrowright", "\x021AC"),
("lopar", "\x02985"),
("lopf", "\x1D55D") ]
{-# NOINLINE reftab36 #-}
reftab36 :: [(Text,Text)]
reftab36 =
[ ("loplus", "\x02A2D"),
("lotimes", "\x02A34"),
("lowast", "\x02217"),
("lowbar", "\x0005F"),
("loz", "\x025CA"),
("lozenge", "\x025CA"),
("lozf", "\x029EB"),
("lpar", "\x00028"),
("lparlt", "\x02993"),
("lrarr", "\x021C6"),
("lrcorner", "\x0231F"),
("lrhar", "\x021CB"),
("lrhard", "\x0296D"),
("lrm", "\x0200E"),
("lrtri", "\x022BF"),
("lsaquo", "\x02039"),
("lscr", "\x1D4C1"),
("lsh", "\x021B0"),
("lsim", "\x02272"),
("lsime", "\x02A8D"),
("lsimg", "\x02A8F"),
("lsqb", "\x0005B"),
("lsquo", "\x02018"),
("lsquor", "\x0201A"),
("lstrok", "\x00142"),
("lt", "\x0003C"),
("ltcc", "\x02AA6"),
("ltcir", "\x02A79"),
("ltdot", "\x022D6"),
("lthree", "\x022CB"),
("ltimes", "\x022C9"),
("ltlarr", "\x02976"),
("ltquest", "\x02A7B"),
("ltrPar", "\x02996"),
("ltri", "\x025C3"),
("ltrie", "\x022B4"),
("ltrif", "\x025C2") ]
{-# NOINLINE reftab37 #-}
reftab37 :: [(Text,Text)]
reftab37 =
[ ("lurdshar", "\x0294A"),
("luruhar", "\x02966"),
("lvertneqq", "\x02268\x0FE00"),
("lvnE", "\x02268\x0FE00"),
("mDDot", "\x0223A"),
("macr", "\x000AF"),
("male", "\x02642"),
("malt", "\x02720"),
("maltese", "\x02720"),
("map", "\x021A6"),
("mapsto", "\x021A6"),
("mapstodown", "\x021A7"),
("mapstoleft", "\x021A4"),
("mapstoup", "\x021A5"),
("marker", "\x025AE"),
("mcomma", "\x02A29"),
("mcy", "\x0043C"),
("mdash", "\x02014"),
("measuredangle", "\x02221"),
("mfr", "\x1D52A"),
("mho", "\x02127"),
("micro", "\x000B5"),
("mid", "\x02223"),
("midast", "\x0002A"),
("midcir", "\x02AF0"),
("middot", "\x000B7"),
("minus", "\x02212"),
("minusb", "\x0229F"),
("minusd", "\x02238"),
("minusdu", "\x02A2A"),
("mlcp", "\x02ADB"),
("mldr", "\x02026"),
("mnplus", "\x02213"),
("models", "\x022A7"),
("mopf", "\x1D55E"),
("mp", "\x02213"),
("mscr", "\x1D4C2") ]
{-# NOINLINE reftab38 #-}
reftab38 :: [(Text,Text)]
reftab38 =
[ ("mstpos", "\x0223E"),
("mu", "\x003BC"),
("multimap", "\x022B8"),
("mumap", "\x022B8"),
("nGg", "\x022D9\x00338"),
("nGt", "\x0226B\x020D2"),
("nGtv", "\x0226B\x00338"),
("nLeftarrow", "\x021CD"),
("nLeftrightarrow", "\x021CE"),
("nLl", "\x022D8\x00338"),
("nLt", "\x0226A\x020D2"),
("nLtv", "\x0226A\x00338"),
("nRightarrow", "\x021CF"),
("nVDash", "\x022AF"),
("nVdash", "\x022AE"),
("nabla", "\x02207"),
("nacute", "\x00144"),
("nang", "\x02220\x020D2"),
("nap", "\x02249"),
("napE", "\x02A70\x00338"),
("napid", "\x0224B\x00338"),
("napos", "\x00149"),
("napprox", "\x02249"),
("natur", "\x0266E"),
("natural", "\x0266E"),
("naturals", "\x02115"),
("nbsp", "\x000A0"),
("nbump", "\x0224E\x00338"),
("nbumpe", "\x0224F\x00338"),
("ncap", "\x02A43"),
("ncaron", "\x00148"),
("ncedil", "\x00146"),
("ncong", "\x02247"),
("ncongdot", "\x02A6D\x00338"),
("ncup", "\x02A42"),
("ncy", "\x0043D"),
("ndash", "\x02013") ]
{-# NOINLINE reftab39 #-}
reftab39 :: [(Text,Text)]
reftab39 =
[ ("ne", "\x02260"),
("neArr", "\x021D7"),
("nearhk", "\x02924"),
("nearr", "\x02197"),
("nearrow", "\x02197"),
("nedot", "\x02250\x00338"),
("nequiv", "\x02262"),
("nesear", "\x02928"),
("nesim", "\x02242\x00338"),
("nexist", "\x02204"),
("nexists", "\x02204"),
("nfr", "\x1D52B"),
("ngE", "\x02267\x00338"),
("nge", "\x02271"),
("ngeq", "\x02271"),
("ngeqq", "\x02267\x00338"),
("ngeqslant", "\x02A7E\x00338"),
("nges", "\x02A7E\x00338"),
("ngsim", "\x02275"),
("ngt", "\x0226F"),
("ngtr", "\x0226F"),
("nhArr", "\x021CE"),
("nharr", "\x021AE"),
("nhpar", "\x02AF2"),
("ni", "\x0220B"),
("nis", "\x022FC"),
("nisd", "\x022FA"),
("niv", "\x0220B"),
("njcy", "\x0045A"),
("nlArr", "\x021CD"),
("nlE", "\x02266\x00338"),
("nlarr", "\x0219A"),
("nldr", "\x02025"),
("nle", "\x02270"),
("nleftarrow", "\x0219A"),
("nleftrightarrow", "\x021AE"),
("nleq", "\x02270") ]
{-# NOINLINE reftab40 #-}
reftab40 :: [(Text,Text)]
reftab40 =
[ ("nleqq", "\x02266\x00338"),
("nleqslant", "\x02A7D\x00338"),
("nles", "\x02A7D\x00338"),
("nless", "\x0226E"),
("nlsim", "\x02274"),
("nlt", "\x0226E"),
("nltri", "\x022EA"),
("nltrie", "\x022EC"),
("nmid", "\x02224"),
("nopf", "\x1D55F"),
("not", "\x000AC"),
("notin", "\x02209"),
("notinE", "\x022F9\x00338"),
("notindot", "\x022F5\x00338"),
("notinva", "\x02209"),
("notinvb", "\x022F7"),
("notinvc", "\x022F6"),
("notni", "\x0220C"),
("notniva", "\x0220C"),
("notnivb", "\x022FE"),
("notnivc", "\x022FD"),
("npar", "\x02226"),
("nparallel", "\x02226"),
("nparsl", "\x02AFD\x020E5"),
("npart", "\x02202\x00338"),
("npolint", "\x02A14"),
("npr", "\x02280"),
("nprcue", "\x022E0"),
("npre", "\x02AAF\x00338"),
("nprec", "\x02280"),
("npreceq", "\x02AAF\x00338"),
("nrArr", "\x021CF"),
("nrarr", "\x0219B"),
("nrarrc", "\x02933\x00338"),
("nrarrw", "\x0219D\x00338"),
("nrightarrow", "\x0219B"),
("nrtri", "\x022EB") ]
{-# NOINLINE reftab41 #-}
reftab41 :: [(Text,Text)]
reftab41 =
[ ("nrtrie", "\x022ED"),
("nsc", "\x02281"),
("nsccue", "\x022E1"),
("nsce", "\x02AB0\x00338"),
("nscr", "\x1D4C3"),
("nshortmid", "\x02224"),
("nshortparallel", "\x02226"),
("nsim", "\x02241"),
("nsime", "\x02244"),
("nsimeq", "\x02244"),
("nsmid", "\x02224"),
("nspar", "\x02226"),
("nsqsube", "\x022E2"),
("nsqsupe", "\x022E3"),
("nsub", "\x02284"),
("nsubE", "\x02AC5\x00338"),
("nsube", "\x02288"),
("nsubset", "\x02282\x020D2"),
("nsubseteq", "\x02288"),
("nsubseteqq", "\x02AC5\x00338"),
("nsucc", "\x02281"),
("nsucceq", "\x02AB0\x00338"),
("nsup", "\x02285"),
("nsupE", "\x02AC6\x00338"),
("nsupe", "\x02289"),
("nsupset", "\x02283\x020D2"),
("nsupseteq", "\x02289"),
("nsupseteqq", "\x02AC6\x00338"),
("ntgl", "\x02279"),
("ntilde", "\x000F1"),
("ntlg", "\x02278"),
("ntriangleleft", "\x022EA"),
("ntrianglelefteq", "\x022EC"),
("ntriangleright", "\x022EB"),
("ntrianglerighteq", "\x022ED"),
("nu", "\x003BD"),
("num", "\x00023") ]
{-# NOINLINE reftab42 #-}
reftab42 :: [(Text,Text)]
reftab42 =
[ ("numero", "\x02116"),
("numsp", "\x02007"),
("nvDash", "\x022AD"),
("nvHarr", "\x02904"),
("nvap", "\x0224D\x020D2"),
("nvdash", "\x022AC"),
("nvge", "\x02265\x020D2"),
("nvgt", "\x0003E\x020D2"),
("nvinfin", "\x029DE"),
("nvlArr", "\x02902"),
("nvle", "\x02264\x020D2"),
("nvlt", "\x0003C\x020D2"),
("nvltrie", "\x022B4\x020D2"),
("nvrArr", "\x02903"),
("nvrtrie", "\x022B5\x020D2"),
("nvsim", "\x0223C\x020D2"),
("nwArr", "\x021D6"),
("nwarhk", "\x02923"),
("nwarr", "\x02196"),
("nwarrow", "\x02196"),
("nwnear", "\x02927"),
("oS", "\x024C8"),
("oacute", "\x000F3"),
("oast", "\x0229B"),
("ocir", "\x0229A"),
("ocirc", "\x000F4"),
("ocy", "\x0043E"),
("odash", "\x0229D"),
("odblac", "\x00151"),
("odiv", "\x02A38"),
("odot", "\x02299"),
("odsold", "\x029BC"),
("oelig", "\x00153"),
("ofcir", "\x029BF"),
("ofr", "\x1D52C"),
("ogon", "\x002DB"),
("ograve", "\x000F2") ]
{-# NOINLINE reftab43 #-}
reftab43 :: [(Text,Text)]
reftab43 =
[ ("ogt", "\x029C1"),
("ohbar", "\x029B5"),
("ohm", "\x003A9"),
("oint", "\x0222E"),
("olarr", "\x021BA"),
("olcir", "\x029BE"),
("olcross", "\x029BB"),
("oline", "\x0203E"),
("olt", "\x029C0"),
("omacr", "\x0014D"),
("omega", "\x003C9"),
("omicron", "\x003BF"),
("omid", "\x029B6"),
("ominus", "\x02296"),
("oopf", "\x1D560"),
("opar", "\x029B7"),
("operp", "\x029B9"),
("oplus", "\x02295"),
("or", "\x02228"),
("orarr", "\x021BB"),
("ord", "\x02A5D"),
("order", "\x02134"),
("orderof", "\x02134"),
("ordf", "\x000AA"),
("ordm", "\x000BA"),
("origof", "\x022B6"),
("oror", "\x02A56"),
("orslope", "\x02A57"),
("orv", "\x02A5B"),
("oscr", "\x02134"),
("oslash", "\x000F8"),
("osol", "\x02298"),
("otilde", "\x000F5"),
("otimes", "\x02297"),
("otimesas", "\x02A36"),
("ouml", "\x000F6"),
("ovbar", "\x0233D") ]
{-# NOINLINE reftab44 #-}
reftab44 :: [(Text,Text)]
reftab44 =
[ ("par", "\x02225"),
("para", "\x000B6"),
("parallel", "\x02225"),
("parsim", "\x02AF3"),
("parsl", "\x02AFD"),
("part", "\x02202"),
("pcy", "\x0043F"),
("percnt", "\x00025"),
("period", "\x0002E"),
("permil", "\x02030"),
("perp", "\x022A5"),
("pertenk", "\x02031"),
("pfr", "\x1D52D"),
("phi", "\x003C6"),
("phiv", "\x003D5"),
("phmmat", "\x02133"),
("phone", "\x0260E"),
("pi", "\x003C0"),
("pitchfork", "\x022D4"),
("piv", "\x003D6"),
("planck", "\x0210F"),
("planckh", "\x0210E"),
("plankv", "\x0210F"),
("plus", "\x0002B"),
("plusacir", "\x02A23"),
("plusb", "\x0229E"),
("pluscir", "\x02A22"),
("plusdo", "\x02214"),
("plusdu", "\x02A25"),
("pluse", "\x02A72"),
("plusmn", "\x000B1"),
("plussim", "\x02A26"),
("plustwo", "\x02A27"),
("pm", "\x000B1"),
("pointint", "\x02A15"),
("popf", "\x1D561"),
("pound", "\x000A3") ]
{-# NOINLINE reftab45 #-}
reftab45 :: [(Text,Text)]
reftab45 =
[ ("pr", "\x0227A"),
("prE", "\x02AB3"),
("prap", "\x02AB7"),
("prcue", "\x0227C"),
("pre", "\x02AAF"),
("prec", "\x0227A"),
("precapprox", "\x02AB7"),
("preccurlyeq", "\x0227C"),
("preceq", "\x02AAF"),
("precnapprox", "\x02AB9"),
("precneqq", "\x02AB5"),
("precnsim", "\x022E8"),
("precsim", "\x0227E"),
("prime", "\x02032"),
("primes", "\x02119"),
("prnE", "\x02AB5"),
("prnap", "\x02AB9"),
("prnsim", "\x022E8"),
("prod", "\x0220F"),
("profalar", "\x0232E"),
("profline", "\x02312"),
("profsurf", "\x02313"),
("prop", "\x0221D"),
("propto", "\x0221D"),
("prsim", "\x0227E"),
("prurel", "\x022B0"),
("pscr", "\x1D4C5"),
("psi", "\x003C8"),
("puncsp", "\x02008"),
("qfr", "\x1D52E"),
("qint", "\x02A0C"),
("qopf", "\x1D562"),
("qprime", "\x02057"),
("qscr", "\x1D4C6"),
("quaternions", "\x0210D"),
("quatint", "\x02A16"),
("quest", "\x0003F") ]
{-# NOINLINE reftab46 #-}
reftab46 :: [(Text,Text)]
reftab46 =
[ ("questeq", "\x0225F"),
("quot", "\x00022"),
("rAarr", "\x021DB"),
("rArr", "\x021D2"),
("rAtail", "\x0291C"),
("rBarr", "\x0290F"),
("rHar", "\x02964"),
("race", "\x0223D\x00331"),
("racute", "\x00155"),
("radic", "\x0221A"),
("raemptyv", "\x029B3"),
("rang", "\x027E9"),
("rangd", "\x02992"),
("range", "\x029A5"),
("rangle", "\x027E9"),
("raquo", "\x000BB"),
("rarr", "\x02192"),
("rarrap", "\x02975"),
("rarrb", "\x021E5"),
("rarrbfs", "\x02920"),
("rarrc", "\x02933"),
("rarrfs", "\x0291E"),
("rarrhk", "\x021AA"),
("rarrlp", "\x021AC"),
("rarrpl", "\x02945"),
("rarrsim", "\x02974"),
("rarrtl", "\x021A3"),
("rarrw", "\x0219D"),
("ratail", "\x0291A"),
("ratio", "\x02236"),
("rationals", "\x0211A"),
("rbarr", "\x0290D"),
("rbbrk", "\x02773"),
("rbrace", "\x0007D"),
("rbrack", "\x0005D"),
("rbrke", "\x0298C"),
("rbrksld", "\x0298E") ]
{-# NOINLINE reftab47 #-}
reftab47 :: [(Text,Text)]
reftab47 =
[ ("rbrkslu", "\x02990"),
("rcaron", "\x00159"),
("rcedil", "\x00157"),
("rceil", "\x02309"),
("rcub", "\x0007D"),
("rcy", "\x00440"),
("rdca", "\x02937"),
("rdldhar", "\x02969"),
("rdquo", "\x0201D"),
("rdquor", "\x0201D"),
("rdsh", "\x021B3"),
("real", "\x0211C"),
("realine", "\x0211B"),
("realpart", "\x0211C"),
("reals", "\x0211D"),
("rect", "\x025AD"),
("reg", "\x000AE"),
("rfisht", "\x0297D"),
("rfloor", "\x0230B"),
("rfr", "\x1D52F"),
("rhard", "\x021C1"),
("rharu", "\x021C0"),
("rharul", "\x0296C"),
("rho", "\x003C1"),
("rhov", "\x003F1"),
("rightarrow", "\x02192"),
("rightarrowtail", "\x021A3"),
("rightharpoondown", "\x021C1"),
("rightharpoonup", "\x021C0"),
("rightleftarrows", "\x021C4"),
("rightleftharpoons", "\x021CC"),
("rightrightarrows", "\x021C9"),
("rightsquigarrow", "\x0219D"),
("rightthreetimes", "\x022CC"),
("ring", "\x002DA"),
("risingdotseq", "\x02253"),
("rlarr", "\x021C4") ]
{-# NOINLINE reftab48 #-}
reftab48 :: [(Text,Text)]
reftab48 =
[ ("rlhar", "\x021CC"),
("rlm", "\x0200F"),
("rmoust", "\x023B1"),
("rmoustache", "\x023B1"),
("rnmid", "\x02AEE"),
("roang", "\x027ED"),
("roarr", "\x021FE"),
("robrk", "\x027E7"),
("ropar", "\x02986"),
("ropf", "\x1D563"),
("roplus", "\x02A2E"),
("rotimes", "\x02A35"),
("rpar", "\x00029"),
("rpargt", "\x02994"),
("rppolint", "\x02A12"),
("rrarr", "\x021C9"),
("rsaquo", "\x0203A"),
("rscr", "\x1D4C7"),
("rsh", "\x021B1"),
("rsqb", "\x0005D"),
("rsquo", "\x02019"),
("rsquor", "\x02019"),
("rthree", "\x022CC"),
("rtimes", "\x022CA"),
("rtri", "\x025B9"),
("rtrie", "\x022B5"),
("rtrif", "\x025B8"),
("rtriltri", "\x029CE"),
("ruluhar", "\x02968"),
("rx", "\x0211E"),
("sacute", "\x0015B"),
("sbquo", "\x0201A"),
("sc", "\x0227B"),
("scE", "\x02AB4"),
("scap", "\x02AB8"),
("scaron", "\x00161"),
("sccue", "\x0227D") ]
{-# NOINLINE reftab49 #-}
reftab49 :: [(Text,Text)]
reftab49 =
[ ("sce", "\x02AB0"),
("scedil", "\x0015F"),
("scirc", "\x0015D"),
("scnE", "\x02AB6"),
("scnap", "\x02ABA"),
("scnsim", "\x022E9"),
("scpolint", "\x02A13"),
("scsim", "\x0227F"),
("scy", "\x00441"),
("sdot", "\x022C5"),
("sdotb", "\x022A1"),
("sdote", "\x02A66"),
("seArr", "\x021D8"),
("searhk", "\x02925"),
("searr", "\x02198"),
("searrow", "\x02198"),
("sect", "\x000A7"),
("semi", "\x0003B"),
("seswar", "\x02929"),
("setminus", "\x02216"),
("setmn", "\x02216"),
("sext", "\x02736"),
("sfr", "\x1D530"),
("sfrown", "\x02322"),
("sharp", "\x0266F"),
("shchcy", "\x00449"),
("shcy", "\x00448"),
("shortmid", "\x02223"),
("shortparallel", "\x02225"),
("shy", "\x000AD"),
("sigma", "\x003C3"),
("sigmaf", "\x003C2"),
("sigmav", "\x003C2"),
("sim", "\x0223C"),
("simdot", "\x02A6A"),
("sime", "\x02243"),
("simeq", "\x02243") ]
{-# NOINLINE reftab50 #-}
reftab50 :: [(Text,Text)]
reftab50 =
[ ("simg", "\x02A9E"),
("simgE", "\x02AA0"),
("siml", "\x02A9D"),
("simlE", "\x02A9F"),
("simne", "\x02246"),
("simplus", "\x02A24"),
("simrarr", "\x02972"),
("slarr", "\x02190"),
("smallsetminus", "\x02216"),
("smashp", "\x02A33"),
("smeparsl", "\x029E4"),
("smid", "\x02223"),
("smile", "\x02323"),
("smt", "\x02AAA"),
("smte", "\x02AAC"),
("smtes", "\x02AAC\x0FE00"),
("softcy", "\x0044C"),
("sol", "\x0002F"),
("solb", "\x029C4"),
("solbar", "\x0233F"),
("sopf", "\x1D564"),
("spades", "\x02660"),
("spadesuit", "\x02660"),
("spar", "\x02225"),
("sqcap", "\x02293"),
("sqcaps", "\x02293\x0FE00"),
("sqcup", "\x02294"),
("sqcups", "\x02294\x0FE00"),
("sqsub", "\x0228F"),
("sqsube", "\x02291"),
("sqsubset", "\x0228F"),
("sqsubseteq", "\x02291"),
("sqsup", "\x02290"),
("sqsupe", "\x02292"),
("sqsupset", "\x02290"),
("sqsupseteq", "\x02292"),
("squ", "\x025A1") ]
{-# NOINLINE reftab51 #-}
reftab51 :: [(Text,Text)]
reftab51 =
[ ("square", "\x025A1"),
("squarf", "\x025AA"),
("squf", "\x025AA"),
("srarr", "\x02192"),
("sscr", "\x1D4C8"),
("ssetmn", "\x02216"),
("ssmile", "\x02323"),
("sstarf", "\x022C6"),
("star", "\x02606"),
("starf", "\x02605"),
("straightepsilon", "\x003F5"),
("straightphi", "\x003D5"),
("strns", "\x000AF"),
("sub", "\x02282"),
("subE", "\x02AC5"),
("subdot", "\x02ABD"),
("sube", "\x02286"),
("subedot", "\x02AC3"),
("submult", "\x02AC1"),
("subnE", "\x02ACB"),
("subne", "\x0228A"),
("subplus", "\x02ABF"),
("subrarr", "\x02979"),
("subset", "\x02282"),
("subseteq", "\x02286"),
("subseteqq", "\x02AC5"),
("subsetneq", "\x0228A"),
("subsetneqq", "\x02ACB"),
("subsim", "\x02AC7"),
("subsub", "\x02AD5"),
("subsup", "\x02AD3"),
("succ", "\x0227B"),
("succapprox", "\x02AB8"),
("succcurlyeq", "\x0227D"),
("succeq", "\x02AB0"),
("succnapprox", "\x02ABA"),
("succneqq", "\x02AB6") ]
{-# NOINLINE reftab52 #-}
reftab52 :: [(Text,Text)]
reftab52 =
[ ("succnsim", "\x022E9"),
("succsim", "\x0227F"),
("sum", "\x02211"),
("sung", "\x0266A"),
("sup", "\x02283"),
("sup1", "\x000B9"),
("sup2", "\x000B2"),
("sup3", "\x000B3"),
("supE", "\x02AC6"),
("supdot", "\x02ABE"),
("supdsub", "\x02AD8"),
("supe", "\x02287"),
("supedot", "\x02AC4"),
("suphsol", "\x027C9"),
("suphsub", "\x02AD7"),
("suplarr", "\x0297B"),
("supmult", "\x02AC2"),
("supnE", "\x02ACC"),
("supne", "\x0228B"),
("supplus", "\x02AC0"),
("supset", "\x02283"),
("supseteq", "\x02287"),
("supseteqq", "\x02AC6"),
("supsetneq", "\x0228B"),
("supsetneqq", "\x02ACC"),
("supsim", "\x02AC8"),
("supsub", "\x02AD4"),
("supsup", "\x02AD6"),
("swArr", "\x021D9"),
("swarhk", "\x02926"),
("swarr", "\x02199"),
("swarrow", "\x02199"),
("swnwar", "\x0292A"),
("szlig", "\x000DF"),
("target", "\x02316"),
("tau", "\x003C4"),
("tbrk", "\x023B4") ]
{-# NOINLINE reftab53 #-}
reftab53 :: [(Text,Text)]
reftab53 =
[ ("tcaron", "\x00165"),
("tcedil", "\x00163"),
("tcy", "\x00442"),
("tdot", "\x020DB"),
("telrec", "\x02315"),
("tfr", "\x1D531"),
("there4", "\x02234"),
("therefore", "\x02234"),
("theta", "\x003B8"),
("thetasym", "\x003D1"),
("thetav", "\x003D1"),
("thickapprox", "\x02248"),
("thicksim", "\x0223C"),
("thinsp", "\x02009"),
("thkap", "\x02248"),
("thksim", "\x0223C"),
("thorn", "\x000FE"),
("tilde", "\x002DC"),
("times", "\x000D7"),
("timesb", "\x022A0"),
("timesbar", "\x02A31"),
("timesd", "\x02A30"),
("tint", "\x0222D"),
("toea", "\x02928"),
("top", "\x022A4"),
("topbot", "\x02336"),
("topcir", "\x02AF1"),
("topf", "\x1D565"),
("topfork", "\x02ADA"),
("tosa", "\x02929"),
("tprime", "\x02034"),
("trade", "\x02122"),
("triangle", "\x025B5"),
("triangledown", "\x025BF"),
("triangleleft", "\x025C3"),
("trianglelefteq", "\x022B4"),
("triangleq", "\x0225C") ]
{-# NOINLINE reftab54 #-}
reftab54 :: [(Text,Text)]
reftab54 =
[ ("triangleright", "\x025B9"),
("trianglerighteq", "\x022B5"),
("tridot", "\x025EC"),
("trie", "\x0225C"),
("triminus", "\x02A3A"),
("triplus", "\x02A39"),
("trisb", "\x029CD"),
("tritime", "\x02A3B"),
("trpezium", "\x023E2"),
("tscr", "\x1D4C9"),
("tscy", "\x00446"),
("tshcy", "\x0045B"),
("tstrok", "\x00167"),
("twixt", "\x0226C"),
("twoheadleftarrow", "\x0219E"),
("twoheadrightarrow", "\x021A0"),
("uArr", "\x021D1"),
("uHar", "\x02963"),
("uacute", "\x000FA"),
("uarr", "\x02191"),
("ubrcy", "\x0045E"),
("ubreve", "\x0016D"),
("ucirc", "\x000FB"),
("ucy", "\x00443"),
("udarr", "\x021C5"),
("udblac", "\x00171"),
("udhar", "\x0296E"),
("ufisht", "\x0297E"),
("ufr", "\x1D532"),
("ugrave", "\x000F9"),
("uharl", "\x021BF"),
("uharr", "\x021BE"),
("uhblk", "\x02580"),
("ulcorn", "\x0231C"),
("ulcorner", "\x0231C"),
("ulcrop", "\x0230F"),
("ultri", "\x025F8") ]
{-# NOINLINE reftab55 #-}
reftab55 :: [(Text,Text)]
reftab55 =
[ ("umacr", "\x0016B"),
("uml", "\x000A8"),
("uogon", "\x00173"),
("uopf", "\x1D566"),
("uparrow", "\x02191"),
("updownarrow", "\x02195"),
("upharpoonleft", "\x021BF"),
("upharpoonright", "\x021BE"),
("uplus", "\x0228E"),
("upsi", "\x003C5"),
("upsih", "\x003D2"),
("upsilon", "\x003C5"),
("upuparrows", "\x021C8"),
("urcorn", "\x0231D"),
("urcorner", "\x0231D"),
("urcrop", "\x0230E"),
("uring", "\x0016F"),
("urtri", "\x025F9"),
("uscr", "\x1D4CA"),
("utdot", "\x022F0"),
("utilde", "\x00169"),
("utri", "\x025B5"),
("utrif", "\x025B4"),
("uuarr", "\x021C8"),
("uuml", "\x000FC"),
("uwangle", "\x029A7"),
("vArr", "\x021D5"),
("vBar", "\x02AE8"),
("vBarv", "\x02AE9"),
("vDash", "\x022A8"),
("vangrt", "\x0299C"),
("varepsilon", "\x003F5"),
("varkappa", "\x003F0"),
("varnothing", "\x02205"),
("varphi", "\x003D5"),
("varpi", "\x003D6"),
("varpropto", "\x0221D") ]
{-# NOINLINE reftab56 #-}
reftab56 :: [(Text,Text)]
reftab56 =
[ ("varr", "\x02195"),
("varrho", "\x003F1"),
("varsigma", "\x003C2"),
("varsubsetneq", "\x0228A\x0FE00"),
("varsubsetneqq", "\x02ACB\x0FE00"),
("varsupsetneq", "\x0228B\x0FE00"),
("varsupsetneqq", "\x02ACC\x0FE00"),
("vartheta", "\x003D1"),
("vartriangleleft", "\x022B2"),
("vartriangleright", "\x022B3"),
("vcy", "\x00432"),
("vdash", "\x022A2"),
("vee", "\x02228"),
("veebar", "\x022BB"),
("veeeq", "\x0225A"),
("vellip", "\x022EE"),
("verbar", "\x0007C"),
("vert", "\x0007C"),
("vfr", "\x1D533"),
("vltri", "\x022B2"),
("vnsub", "\x02282\x020D2"),
("vnsup", "\x02283\x020D2"),
("vopf", "\x1D567"),
("vprop", "\x0221D"),
("vrtri", "\x022B3"),
("vscr", "\x1D4CB"),
("vsubnE", "\x02ACB\x0FE00"),
("vsubne", "\x0228A\x0FE00"),
("vsupnE", "\x02ACC\x0FE00"),
("vsupne", "\x0228B\x0FE00"),
("vzigzag", "\x0299A"),
("wcirc", "\x00175"),
("wedbar", "\x02A5F"),
("wedge", "\x02227"),
("wedgeq", "\x02259"),
("weierp", "\x02118"),
("wfr", "\x1D534") ]
{-# NOINLINE reftab57 #-}
reftab57 :: [(Text,Text)]
reftab57 =
[ ("wopf", "\x1D568"),
("wp", "\x02118"),
("wr", "\x02240"),
("wreath", "\x02240"),
("wscr", "\x1D4CC"),
("xcap", "\x022C2"),
("xcirc", "\x025EF"),
("xcup", "\x022C3"),
("xdtri", "\x025BD"),
("xfr", "\x1D535"),
("xhArr", "\x027FA"),
("xharr", "\x027F7"),
("xi", "\x003BE"),
("xlArr", "\x027F8"),
("xlarr", "\x027F5"),
("xmap", "\x027FC"),
("xnis", "\x022FB"),
("xodot", "\x02A00"),
("xopf", "\x1D569"),
("xoplus", "\x02A01"),
("xotime", "\x02A02"),
("xrArr", "\x027F9"),
("xrarr", "\x027F6"),
("xscr", "\x1D4CD"),
("xsqcup", "\x02A06"),
("xuplus", "\x02A04"),
("xutri", "\x025B3"),
("xvee", "\x022C1"),
("xwedge", "\x022C0"),
("yacute", "\x000FD"),
("yacy", "\x0044F"),
("ycirc", "\x00177"),
("ycy", "\x0044B"),
("yen", "\x000A5"),
("yfr", "\x1D536"),
("yicy", "\x00457"),
("yopf", "\x1D56A") ]
{-# NOINLINE reftab58 #-}
reftab58 :: [(Text,Text)]
reftab58 =
[ ("yscr", "\x1D4CE"),
("yucy", "\x0044E"),
("yuml", "\x000FF"),
("zacute", "\x0017A"),
("zcaron", "\x0017E"),
("zcy", "\x00437"),
("zdot", "\x0017C"),
("zeetrf", "\x02128"),
("zeta", "\x003B6"),
("zfr", "\x1D537"),
("zhcy", "\x00436"),
("zigrarr", "\x021DD"),
("zopf", "\x1D56B"),
("zscr", "\x1D4CF"),
("zwj", "\x0200D"),
("zwnj", "\x0200C") ]
|
silkapp/xmlhtml
|
src/Text/XmlHtml/HTML/Meta.hs
|
bsd-3-clause
| 67,184
| 0
| 9
| 14,442
| 21,159
| 14,055
| 7,104
| 2,406
| 1
|
{-# LANGUAGE UnboxedTuples, MagicHash #-}
module Data.TrieMap.TrieKey.Indexable where
import Data.TrieMap.TrieKey.Zippable
import Data.TrieMap.Sized
import GHC.Exts
class Indexable f where
index :: Sized a => Int# -> f a -> (# Int#, a, Zipper f a #)
index' :: (Indexable f, Sized a) => Int -> f a -> (Int, a, Zipper f a)
index' (I# i#) m = case index i# m of
(# i'#, a, z #) -> (I# i'#, a, z)
indexFail :: a
indexFail = error "Error: index out of bounds"
|
lowasser/TrieMap
|
Data/TrieMap/TrieKey/Indexable.hs
|
bsd-3-clause
| 463
| 0
| 11
| 91
| 181
| 99
| 82
| 12
| 1
|
{-# OPTIONS -Wall #-}
module Scope.Cairo.Types (
-- * Types
ViewCairo(..)
) where
import qualified Graphics.UI.Gtk as G
----------------------------------------------------------------------
data ViewCairo = ViewCairo
{ frame :: G.VBox
, canvas :: G.DrawingArea
, adj :: G.Adjustment
}
|
kfish/scope-cairo
|
Scope/Cairo/Types.hs
|
bsd-3-clause
| 321
| 0
| 9
| 71
| 61
| 41
| 20
| 8
| 0
|
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Jana.Types (
Array, Stack,
Value(..), nil, performOperation, performModOperation,
showValueType, typesMatch, truthy,
Store, printVdecl, showStore, emptyStore, storeFromList,
getRef, getVar, getRefValue, bindVar, unbindVar, setVar,
EvalEnv(..),
EvalOptions(..), defaultOptions,
ProcEnv, emptyProcEnv, procEnvFromList, getProc,
Eval, runEval, (<!!>)
) where
import Prelude hiding (GT, LT, EQ)
import Data.Bits
import Data.List (intercalate)
import Data.IORef
import Control.Applicative
import Control.Monad.State
import Control.Monad.Reader
import Control.Monad.Except
import Text.Printf (printf)
import qualified Data.Maybe as Maybe
import qualified Data.Map as Map
import Text.Parsec.Pos
import Jana.Aliases
import Jana.Ast
import Jana.Error
import Jana.ErrorMessages
type Array = [Integer]
type Stack = [Integer]
-- Types of values an expression can evaluate to.
data Value
= JInt Integer
| JBool Bool
| JArray Array
| JStack Stack
deriving (Eq)
instance Show Value where
show (JInt x) = show x
show (JArray xs) = "{" ++ intercalate ", " (map show xs) ++ "}"
show (JStack []) = "nil"
show (JStack xs) = "<" ++ intercalate ", " (map show xs) ++ "]"
showValueType :: Value -> String
showValueType (JInt _) = "int"
showValueType (JStack _) = "stack"
showValueType (JArray _) = "array"
showValueType (JBool _) = "bool"
typesMatch :: Value -> Value -> Bool
typesMatch (JInt _) (JInt _) = True
typesMatch (JArray _) (JArray _) = True
typesMatch (JStack _) (JStack _) = True
typesMatch (JBool _) (JBool _) = True
typesMatch _ _ = False
nil = JStack []
truthy :: Value -> Bool
truthy (JInt 0) = False
truthy (JStack []) = False
truthy _ = True
boolToInt :: Num a => (a -> a -> Bool) -> a -> a -> a
boolToInt f x y = if f x y then 1 else 0
wrap :: (a -> Value) -> (Integer -> Integer -> a) -> Integer -> Integer -> Value
wrap m f x y = m $ f x y
opFunc :: BinOp -> Integer -> Integer -> Value
opFunc Add = wrap JInt (+)
opFunc Sub = wrap JInt (-)
opFunc Mul = wrap JInt (*)
opFunc Div = wrap JInt div
opFunc Mod = wrap JInt mod
opFunc And = wrap JInt (.&.)
opFunc Or = wrap JInt (.|.)
opFunc Xor = wrap JInt xor
opFunc LAnd = undefined -- handled by evalExpr
opFunc LOr = undefined -- handled by evalExpr
opFunc GT = wrap JBool (>)
opFunc LT = wrap JBool (<)
opFunc EQ = wrap JBool (==)
opFunc NEQ = wrap JBool (/=)
opFunc GE = wrap JBool (>=)
opFunc LE = wrap JBool (<=)
performOperation :: BinOp -> Value -> Value -> SourcePos -> SourcePos -> Eval Value
performOperation Div (JInt _) (JInt 0) _ pos =
pos <!!> divisionByZero
performOperation op (JInt x) (JInt y) _ _ =
return $ opFunc op x y
performOperation _ (JInt _) val _ pos =
pos <!!> typeMismatch ["int"] (showValueType val)
performOperation _ val _ pos _ =
pos <!!> typeMismatch ["int"] (showValueType val)
performModOperation :: ModOp -> Value -> Value -> SourcePos -> SourcePos -> Eval Value
performModOperation modOp = performOperation $ modOpToBinOp modOp
where modOpToBinOp AddEq = Add
modOpToBinOp SubEq = Sub
modOpToBinOp XorEq = Xor
--
-- Environment
--
type Store = Map.Map String (IORef Value)
printVdecl :: String -> Value -> String
printVdecl name val@(JArray xs) = printf "%s[%d] = %s" name (length xs) (show val)
printVdecl name val = printf "%s = %s" name (show val)
showStore :: Store -> IO String
showStore store =
liftM (intercalate "\n")
(mapM (\(name, ref) -> liftM (printVdecl name) (readIORef ref))
(Map.toList store))
emptyStore = Map.empty
storeFromList :: [(String, IORef Value)] -> Store
storeFromList = Map.fromList
getRef :: Ident -> Eval (IORef Value)
getRef (Ident name pos) =
do storeEnv <- get
case Map.lookup name storeEnv of
Just ref -> return ref
Nothing -> pos <!!> unboundVar name
getVar :: Ident -> Eval Value
getVar id = getRef id >>= liftIO . readIORef
getRefValue :: IORef Value -> Eval Value
getRefValue = liftIO . readIORef
-- Bind a variable name to a new reference
bindVar :: Ident -> Value -> Eval ()
bindVar (Ident name pos) val =
do storeEnv <- get
ref <- liftIO $ newIORef val
case Map.lookup name storeEnv of
Nothing -> put $ Map.insert name ref storeEnv
Just _ -> pos <!!> alreadyBound name
unbindVar :: Ident -> Eval ()
unbindVar = modify . Map.delete . ident
-- Set the value of a variable (modifying the reference)
setVar :: Ident -> Value -> Eval ()
setVar id val =
do ref <- getRef id
liftIO $ writeIORef ref val
data EvalEnv = EE { evalOptions :: EvalOptions
, procEnv :: ProcEnv
, aliases :: AliasSet }
data EvalOptions = EvalOptions { modInt :: Bool, runReverse :: Bool }
defaultOptions = EvalOptions { modInt = False, runReverse = False }
type ProcEnv = Map.Map String Proc
emptyProcEnv = Map.empty
procEnvFromList :: [Proc] -> Either JanaError ProcEnv
procEnvFromList = foldM insertProc emptyProcEnv
where insertProc env p = if Map.notMember (ident p) env
then if checkDuplicateArgs (makeIdentList p)
then Right (Map.insert (ident p) p env)
else Left $ newErrorMessage (ppos p) (procDuplicateArgs p)
else Left $ newErrorMessage (ppos p) (procDefined p)
ppos Proc { procname = (Ident _ pos) } = pos
makeIdentList :: Proc -> [Ident]
makeIdentList (Proc {params = params}) = map getVdeclIdent params
where
getVdeclIdent (Scalar _ id _) = id
getVdeclIdent (Array id _ _) = id
checkDuplicateArgs :: [Ident] -> Bool
checkDuplicateArgs [] = True
checkDuplicateArgs ([arg]) = True
checkDuplicateArgs (arg:args) =
arg `notElem` args && checkDuplicateArgs args
getProc :: Ident -> Eval Proc
getProc (Ident funName pos) =
do when (funName == "main") $ pos <!!> callingMainError
procEnv <- asks procEnv
case Map.lookup funName procEnv of
Just proc -> return proc
Nothing -> pos <!!> undefProc funName
--
-- Evaluation
--
instance Functor Eval where
fmap = liftM
instance Applicative Eval where
pure = return
(<*>) = ap -- defined in Control.Monad
newtype Eval a = E { runE :: StateT Store (ReaderT EvalEnv (ExceptT JanaError IO)) a }
deriving (Monad, MonadIO, MonadError JanaError, MonadReader EvalEnv, MonadState Store)
runEval :: Eval a -> Store -> EvalEnv -> IO (Either JanaError (a, Store))
runEval eval store procs = runExceptT (runReaderT (runStateT (runE eval) store) procs)
throwJanaError :: SourcePos -> Message -> Eval a
throwJanaError pos msg = throwError $ newErrorMessage pos msg
infixr 1 <!!>
pos <!!> msg = throwJanaError pos msg
|
mbudde/jana
|
src/Jana/Types.hs
|
bsd-3-clause
| 6,812
| 0
| 13
| 1,571
| 2,475
| 1,301
| 1,174
| 170
| 3
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UnboxedTuples #-}
{-# LANGUAGE ViewPatterns #-}
module Numeric.Quaternion.Internal
( Quaternion (..), Quater(Quater)
) where
import Numeric.DataFrame.Type (KnownBackend)
import Numeric.Matrix.Internal (Matrix)
import Numeric.PrimBytes (PrimBytes)
import Numeric.Vector.Internal (Vector)
import Text.Read
-- | @(x,y,z,w)@ of a quaternion
pattern Quater :: Quaternion t => t -> t -> t -> t -> Quater t
pattern Quater a b c d <- (unpackQ# -> (# a, b, c, d #))
where
Quater = packQ
{-# COMPLETE Quater #-}
-- | Quaternion operations
class ( Floating (Quater t), Floating t, Ord t, PrimBytes t
, KnownBackend t '[3], KnownBackend t '[4]
, KnownBackend t '[3,3], KnownBackend t '[4, 4]
) => Quaternion t where
-- | Quaternion data type. The ordering of coordinates is @(x,y,z,w)@,
-- where @w@ is the argument, and @x y z@ are the components of a 3D vector
data Quater t
-- | Set the quaternion in format @(x,y,z,w)@
packQ :: t -> t -> t -> t -> Quater t
-- | Get the values of the quaternion in format @(x,y,z,w)@
unpackQ# :: Quater t -> (# t, t, t, t #)
-- | Set the quaternion from 3D axis vector and argument
fromVecNum :: Vector t 3 -> t -> Quater t
-- | Set the quaternion from 4D vector in format @(x,y,z,w)@
fromVec4 :: Vector t 4 -> Quater t
-- | Transform the quaternion to 4D vector in format @(x,y,z,w)@
toVec4 :: Quater t -> Vector t 4
-- | Get scalar square of the quaternion.
--
-- >>> realToFrac (square q) == q * conjugate q
square :: Quater t -> t
-- | Imaginary part of the quaternion (orientation vector)
im :: Quater t -> Quater t
-- | Real part of the quaternion
re :: Quater t -> Quater t
-- | Imaginary part of the quaternion as a 3D vector
imVec :: Quater t -> Vector t 3
-- | Real part of the quaternion as a scalar
taker :: Quater t -> t
-- | i-th component
takei :: Quater t -> t
-- | j-th component
takej :: Quater t -> t
-- | k-th component
takek :: Quater t -> t
-- | Conjugate quaternion (negate imaginary part)
conjugate :: Quater t -> Quater t
-- | Rotates and scales vector in 3D using quaternion.
-- Let \( q = c (\cos \frac{\alpha}{2}, v \sin \frac{\alpha}{2}) \)
-- , \( c > 0 \), \( {|v|}^2 = 1 \);
-- then the rotation angle is \( \alpha \), and the axis of rotation is \(v\).
-- Scaling is proportional to \( c^2 \).
--
-- >>> rotScale q x == q * x * (conjugate q)
rotScale :: Quater t -> Vector t 3 -> Vector t 3
-- | Creates a quaternion @q@ from two vectors @a@ and @b@,
-- such that @rotScale q a == b@.
getRotScale :: Vector t 3 -> Vector t 3 -> Quater t
-- | Creates a rotation versor from an axis vector and an angle in radians.
-- Result is always a unit quaternion (versor).
-- If the argument vector is zero, then result is a real unit quaternion.
axisRotation :: Vector t 3 -> t -> Quater t
-- | Quaternion rotation angle \( \alpha \)
-- (where \( q = c (\cos \frac{\alpha}{2}, v \sin \frac{\alpha}{2}) \)
-- , \( c > 0 \), \( {|v|}^2 = 1 \)).
--
-- >>> q /= 0 ==> axisRotation (imVec q) (qArg q) == signum q
qArg :: Quater t -> t
-- | Create a quaternion from a rotation matrix.
-- Note, that rotations of \(q\) and \(-q\) are equivalent, there result of this
-- function may be ambiguious. Assume the sign of the result to be chosen arbitrarily.
fromMatrix33 :: Matrix t 3 3 -> Quater t
-- | Create a quaternion from a homogenious coordinates trasform matrix.
-- Ignores matrix translation transform.
-- Note, that rotations of \(q\) and \(-q\) are equivalent, there result of this
-- function may be ambiguious. Assume the sign of the result to be chosen arbitrarily.
fromMatrix44 :: Matrix t 4 4 -> Quater t
-- | Create a rotation matrix from a quaternion.
-- Note, that rotations of \(q\) and \(-q\) are equivalent, so the following property holds:
--
-- >>> toMatrix33 q == toMatrix33 (-q)
toMatrix33 :: Quater t -> Matrix t 3 3
-- | Create a homogenious coordinates trasform matrix from a quaternion.
-- Translation of the output matrix is zero.
-- Note, that rotations of \(q\) and \(-q\) are equivalent, so the following property holds:
--
-- >>> toMatrix44 q == toMatrix44 (-q)
toMatrix44 :: Quater t -> Matrix t 4 4
instance (Show t, Quaternion t, Ord t, Num t) => Show (Quater t) where
showsPrec p (Quater x y z w)
= case finS of
SEmpty -> showChar '0'
Simple -> finF
SParen -> showParen (p > 6) finF
where
(finS, finF) = go SEmpty
[(w, Nothing), (x, Just 'i'), (y, Just 'j'), (z, Just 'k')]
go :: ShowState -> [(t, Maybe Char)] -> (ShowState, ShowS)
go s ((v,l):xs)
| (s0, f0) <- showComponent s v l
, (s', f') <- go s0 xs
= (s', f0 . f')
go s [] = (s, id)
showLabel Nothing = id
showLabel (Just c) = showChar c
showComponent :: ShowState -> t -> Maybe Char -> (ShowState, ShowS)
showComponent sState val mLabel = case (sState, compare val 0) of
(_ , EQ) -> ( sState, id )
(SEmpty, GT) -> ( Simple, shows val . showLabel mLabel )
(SEmpty, LT) -> ( SParen, shows val . showLabel mLabel )
(_ , GT) -> ( SParen
, showString " + " . shows val . showLabel mLabel )
(_ , LT) -> ( SParen
, showString " - " . shows (negate val) . showLabel mLabel )
data ShowState = SEmpty | Simple | SParen
deriving Eq
instance (Read t, Quaternion t, Num t) => Read (Quater t) where
readPrec = parens $ readPrec >>= go id 0 0 0 0
where
go :: (t -> t) -> t -> t -> t -> t -> t -> ReadPrec (Quater t)
go f x y z w new =
let def = pure (Quater x y z (f new))
withLabel EOF = def
withLabel (Ident "i")
= (lexP >>= proceed (f new) y z w) <++ pure (Quater (f new) y z w)
withLabel (Ident "j")
= (lexP >>= proceed x (f new) z w) <++ pure (Quater x (f new) z w)
withLabel (Ident "k")
= (lexP >>= proceed x y (f new) w) <++ pure (Quater x y (f new) w)
withLabel l = proceed x y z (f new) l
in (lexP >>= withLabel) <++ def
proceed :: t -> t -> t -> t -> Lexeme -> ReadPrec (Quater t)
proceed x y z w (Symbol "+") = readPrec >>= go id x y z w
proceed x y z w (Symbol "-") = readPrec >>= go negate x y z w
proceed x y z w EOF = pure (Quater x y z w)
proceed _ _ _ _ _ = pfail
readListPrec = readListPrecDefault
readList = readListDefault
|
achirkin/easytensor
|
easytensor/src/Numeric/Quaternion/Internal.hs
|
bsd-3-clause
| 7,142
| 0
| 17
| 2,207
| 1,776
| 946
| 830
| 98
| 0
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE DoAndIfThenElse #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Web.Spock.SafeSpec (spec) where
import Control.Monad
#if MIN_VERSION_base(4,11,0)
#else
import Data.Monoid
#endif
import Control.Monad.Trans.Class
import qualified Data.ByteString.Lazy.Char8 as BSLC
import qualified Data.HashSet as HS
import Data.IORef
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Network.Wai.Test as Wai
import Test.Hspec
import qualified Test.Hspec.Wai as Test
import qualified Test.Hspec.Wai.Internal as Test
import Web.Spock
import Web.Spock.Config
import Web.Spock.TestUtils
-- import qualified Test.Hspec.Wai.Internal as Test
sessionSpec :: Spec
sessionSpec =
describe "SessionManager" $
do
Test.with sessionApp $
it "should generate random session ids" $
do
ids <- Test.liftIO $ newIORef HS.empty
-- of course this sample is too small to prove anything, but it's a good
-- smoke test...
replicateM_ 500 $
do
Test.WaiSession $ lift $ Wai.deleteClientCookie "spockcookie"
res <- Test.get "/test"
Test.liftIO $ checkCookie ids res `shouldReturn` True
Test.with sessionApp $
it "should remember a session" $
do
res <- Test.get "/set/5"
case getSessCookie res of
Nothing ->
Test.liftIO $
expectationFailure $
"Missing spockcookie in " ++ show (Wai.simpleHeaders res)
Just sessCookie ->
Test.request "GET" "/check" [("Cookie", T.encodeUtf8 $ "spockcookie=" <> sessCookie)] ""
`Test.shouldRespondWith` "5"
Test.with sessionApp $
it "should update internal session id correctly" $
do
bdy <- fmap Wai.simpleBody (Test.get "/regenerate-different-sids")
case BSLC.split '|' bdy of
[a, b] | a /= b -> pure ()
xs -> Test.liftIO $ expectationFailure ("Bad result: " ++ show xs)
Test.with sessionApp $
it "should regenerate and preserve all content" $
do
res <- Test.get "/set/5"
case getSessCookie res of
Nothing ->
Test.liftIO $
expectationFailure $
"Missing spockcookie in " ++ show (Wai.simpleHeaders res)
Just sessCookie ->
do
Test.WaiSession $ lift $ Wai.deleteClientCookie "spockcookie"
res2 <- Test.request "GET" "/regenerate" [("Cookie", T.encodeUtf8 $ "spockcookie=" <> sessCookie)] ""
case getSessCookie res2 of
Nothing ->
Test.liftIO $
expectationFailure $
"Missing spockcookie in " ++ show (Wai.simpleHeaders res)
Just sessCookie2 ->
do
Test.WaiSession $ lift $ Wai.deleteClientCookie "spockcookie"
Test.request "GET" "/check" [("Cookie", T.encodeUtf8 $ "spockcookie=" <> sessCookie2)] ""
`Test.shouldRespondWith` "5"
Test.WaiSession $ lift $ Wai.deleteClientCookie "spockcookie"
Test.request "GET" "/check" [("Cookie", T.encodeUtf8 $ "spockcookie=" <> sessCookie)] ""
`Test.shouldRespondWith` "0"
where
sessionApp =
spockAsApp $
spockCfg >>= \cfg ->
spock cfg $
do
get "test" $ getSessionId >>= text
get ("set" <//> var) $ \number -> writeSession number >> text "done"
get "regenerate" $ sessionRegenerateId >> text "done"
get "regenerate-different-sids" $
do
s1 <- getSessionId
sessionRegenerateId
s2 <- getSessionId
text $ s1 <> "|" <> s2
get "check" $
do
val <- readSession
text (T.pack $ show val)
spockCfg =
defaultSpockCfg (0 :: Int) PCNoDatabase True
checkCookie :: IORef (HS.HashSet T.Text) -> Wai.SResponse -> IO Bool
checkCookie setRef resp =
do
let mSessCookie = getSessCookie resp
case mSessCookie of
Nothing ->
do
expectationFailure $
"Missing spockcookie in " ++ show (Wai.simpleHeaders resp)
return False
Just sessionId ->
do
set <- readIORef setRef
if HS.member sessionId set
then fail $ "Reused " ++ show sessionId ++ " (" ++ show set ++ ")"
else do
writeIORef setRef $ HS.insert sessionId set
return True
spec :: Spec
spec =
describe "SafeRouting" $ sessionSpec
|
agrafix/Spock
|
Spock/test/Web/Spock/SafeSpec.hs
|
bsd-3-clause
| 5,028
| 0
| 27
| 1,858
| 1,150
| 571
| 579
| 119
| 7
|
{-# LANGUAGE Rank2Types #-}
module Control.Category.Hask.Laws.NatTrans where
import Control.Category.Hask.Definition (NatTrans(..))
naturalityWith :: (Functor f, Functor g) => (g b -> g b -> Bool) -> NatTrans f g -> (a -> b) -> f a -> Bool
naturalityWith eq nt h x = nt (fmap_F h x) `eq` fmap_G h (nt x) where
fmap_F = fmap
fmap_G = fmap
naturality :: (Functor f, Functor g, Eq (g b)) => NatTrans f g -> (a -> b) -> f a -> Bool
naturality = naturalityWith (==)
|
andorp/category-test-laws
|
src/Control/Category/Hask/Laws/NatTrans.hs
|
bsd-3-clause
| 469
| 0
| 10
| 93
| 217
| 117
| 100
| 9
| 1
|
{-# LANGUAGE TypeFamilies#-}
module Data.SymReg.Evolvable(
ASTGenOpts(..)
) where
import Control.Monad.State
import Control.Monad.Random
import Data.SymReg.AST
import Data.SymReg.Misc
import Data.SymReg.Functions
import Data.Genetics.Class
instance Evolvable AST where
type EvData AST = ASTData
type GMCOptions AST = ASTGenOpts
generate = generateAST
mutate = mutateAST
crossover gopts = crossoverAST (goMaxDepth gopts)
fitness = fitnessAST
data ExpType = ExpConst | ExpVar | ExpFunc
data ASTGenOpts = ASTGenOpts{
goMaxDepth :: Int
, goVarCount :: Int
, goConstRange :: (Double,Double)
, goCVF :: (Int,Int,Int)
}
generateAST :: ASTGenOpts -> IO AST
generateAST gopts = evalStateT generateAST' gopts
generateAST' :: StateT ASTGenOpts IO AST
generateAST' = do
ASTGenOpts d varCount r (c,v,f) <- get
e <- if(d==0)
then if(varCount == 0)
then return ExpConst
else uniform [ExpConst, ExpVar]
else if(varCount == 0)
then fromList $ zip [ExpConst, ExpFunc] $ fromIntegral <$> [c,f]
else fromList $ zip [ExpConst, ExpVar, ExpFunc] $ fromIntegral <$> [c,v,f]
case e of
ExpConst -> do
val <- getRandomR r
return $ Const val
ExpVar -> do
var <- getRandomR (0,(varCount-1))
return $ Variable var
ExpFunc -> do
op <- liftIO $ uniform operands
let n = operandArity op
let opts = ASTGenOpts (d-1) varCount r (c,v,f)
asts <- liftIO $ sequence $ evalStateT generateAST' <$> replicate n opts
return $ Function op asts
mutateAST :: ASTGenOpts -> AST -> IO AST
mutateAST ASTGenOpts{..} ast = do
(_,bc) <- randomNode ast
let gopts' = ASTGenOpts (goMaxDepth - (length bc)) goVarCount goConstRange goCVF
node <- generate gopts'
return $ insertNodeAt node ast bc
crossoverAST :: Depth -> (AST,AST) -> IO (AST,AST)
crossoverAST maxDepth (p1,p2) = do
((a1,b1),(a2,b2)) <- getPersistently 5 p1 p2
let c1 = insertNodeAt a2 p1 b1
let c2 = insertNodeAt a1 p2 b2
return (c1,c2)
where
getPersistently :: Int -> AST -> AST -> IO (((AST, Breadcrumb),(AST, Breadcrumb)))
getPersistently 0 p1 p2 = return $ ((p1,[]),(p2,[]))
getPersistently n p1 p2 = do
(a1,b1) <- randomNode p1
(a2,b2) <- randomBounded maxDepth (calcHeight a1, length b1) p2
if b2 == [-1]
then getPersistently (n-1) p1 p2
else return ((a1,b1),(a2,b2))
fitnessAST :: ASTData -> AST -> Double
fitnessAST datum ast = (/) (fromIntegral $ length datum) $ sum $ (\(p,a) -> (a - evalAST ast p)^^2) <$> datum
|
Teaspot-Studio/genmus
|
src/Data/SymReg/Evolvable.hs
|
bsd-3-clause
| 2,553
| 0
| 17
| 581
| 1,039
| 555
| 484
| -1
| -1
|
{-# LANGUAGE ScopedTypeVariables, FlexibleContexts #-}
-- |
-- This package provides the choice operator ('||>') for
-- lifted IO monad.
module Control.Exception.IOChoice.Lifted where
import Control.Exception (IOException)
import qualified Control.Exception.Lifted as L (catch, throwIO)
import Control.Monad.Base (MonadBase)
import Control.Monad.IO.Class
import Control.Monad.Trans.Control (MonadBaseControl)
-- |
-- If 'IOException' occurs or 'goNext' is used in the left monad,
-- then the right monad is performed. Note that 'fail'
-- throws 'IOException'.
(||>) :: MonadBaseControl IO m => m a -> m a -> m a
x ||> y = x `L.catch` (\(_ :: IOException) -> y)
infixr 3 ||>
-- | Go to the next 'IO' monad by throwing 'IOException'.
goNext :: (MonadIO m, MonadBase IO m) => m a
goNext = L.throwIO $ userError "goNext for lifted IO"
-- | Run any one lifted 'IO' monad.
runAnyOne :: (MonadIO m, MonadBaseControl IO m) => [m a] -> m a
runAnyOne = foldr (||>) goNext
|
kazu-yamamoto/io-choice
|
Control/Exception/IOChoice/Lifted.hs
|
bsd-3-clause
| 970
| 0
| 9
| 160
| 233
| 137
| 96
| 14
| 1
|
{-# OPTIONS_GHC -Wno-missing-fields #-}
module Dir.QuasiQuoter(quasi) where
import Language.Haskell.TH.Quote
{-# NOINLINE quasi #-}
quasi :: QuasiQuoter
quasi = QuasiQuoter {quoteDec = const $ return []}
|
ndmitchell/weeder
|
test/foo/src/Dir/QuasiQuoter.hs
|
bsd-3-clause
| 207
| 0
| 9
| 28
| 47
| 29
| 18
| 6
| 1
|
{-# LANGUAGE OverloadedStrings #-}
import qualified Aws
import qualified Aws.S3 as S3
import Data.Conduit
import Data.Conduit.Binary
import Data.IORef
import Data.Monoid
-- A small function to save the object's data into a file.
saveObject :: Aws.HTTPResponseConsumer ()
saveObject status headers source = source $$ sinkFile "cloud-remote.pdf"
main :: IO ()
main = do
-- Set up AWS credentials and the default configuration.
cfg <- Aws.baseConfiguration
-- Create an IORef to store the response Metadata (so it is also available in case of an error).
metadataRef <- newIORef mempty
-- Create a request object with S3.getObject and run the request with simpleAwsRef.
Aws.simpleAwsRef cfg metadataRef $ S3.getObject "haskell-aws" "cloud-remote.pdf" saveObject
-- Print the response metadata.
print =<< readIORef metadataRef
|
jgm/aws
|
Examples/GetObject.hs
|
bsd-3-clause
| 844
| 0
| 9
| 139
| 138
| 73
| 65
| 15
| 1
|
{-# LANGUAGE CPP, DeriveDataTypeable, Rank2Types #-}
-- |
-- Module: Data.Aeson.Types.Internal
-- Copyright: (c) 2011, 2012 Bryan O'Sullivan
-- (c) 2011 MailRank, Inc.
-- License: Apache
-- Maintainer: Bryan O'Sullivan <bos@serpentine.com>
-- Stability: experimental
-- Portability: portable
--
-- Types for working with JSON data.
module Data.Aeson.Types.Internal
(
-- * Core JSON types
Value(..)
, Array
, emptyArray, isEmptyArray
, Pair
, Object
, emptyObject
-- * Type conversion
, Parser
, Result(..)
, parse
, parseEither
, parseMaybe
, modifyFailure
-- * Constructors and accessors
, object
-- * Generic and TH encoding configuration
, Options(..)
, SumEncoding(..)
, defaultOptions
, defaultTaggedObject
) where
import Control.Applicative
import Control.Monad
import Control.DeepSeq (NFData(..))
import Data.Attoparsec.Char8 (Number(..))
import Data.Hashable (Hashable(..))
import Data.HashMap.Strict (HashMap)
import Data.Monoid (Monoid(..))
import Data.String (IsString(..))
import Data.Text (Text, pack)
import Data.Typeable (Typeable)
import Data.Vector (Vector)
import qualified Data.HashMap.Strict as H
import qualified Data.Vector as V
-- | The result of running a 'Parser'.
data Result a = Error String
| Success a
deriving (Eq, Show, Typeable)
instance (NFData a) => NFData (Result a) where
rnf (Success a) = rnf a
rnf (Error err) = rnf err
instance Functor Result where
fmap f (Success a) = Success (f a)
fmap _ (Error err) = Error err
{-# INLINE fmap #-}
instance Monad Result where
return = Success
{-# INLINE return #-}
Success a >>= k = k a
Error err >>= _ = Error err
{-# INLINE (>>=) #-}
instance Applicative Result where
pure = return
{-# INLINE pure #-}
(<*>) = ap
{-# INLINE (<*>) #-}
instance MonadPlus Result where
mzero = fail "mzero"
{-# INLINE mzero #-}
mplus a@(Success _) _ = a
mplus _ b = b
{-# INLINE mplus #-}
instance Alternative Result where
empty = mzero
{-# INLINE empty #-}
(<|>) = mplus
{-# INLINE (<|>) #-}
instance Monoid (Result a) where
mempty = fail "mempty"
{-# INLINE mempty #-}
mappend = mplus
{-# INLINE mappend #-}
-- | Failure continuation.
type Failure f r = String -> f r
-- | Success continuation.
type Success a f r = a -> f r
-- | A continuation-based parser type.
newtype Parser a = Parser {
runParser :: forall f r.
Failure f r
-> Success a f r
-> f r
}
instance Monad Parser where
m >>= g = Parser $ \kf ks -> let ks' a = runParser (g a) kf ks
in runParser m kf ks'
{-# INLINE (>>=) #-}
return a = Parser $ \_kf ks -> ks a
{-# INLINE return #-}
fail msg = Parser $ \kf _ks -> kf msg
{-# INLINE fail #-}
instance Functor Parser where
fmap f m = Parser $ \kf ks -> let ks' a = ks (f a)
in runParser m kf ks'
{-# INLINE fmap #-}
instance Applicative Parser where
pure = return
{-# INLINE pure #-}
(<*>) = apP
{-# INLINE (<*>) #-}
instance Alternative Parser where
empty = fail "empty"
{-# INLINE empty #-}
(<|>) = mplus
{-# INLINE (<|>) #-}
instance MonadPlus Parser where
mzero = fail "mzero"
{-# INLINE mzero #-}
mplus a b = Parser $ \kf ks -> let kf' _ = runParser b kf ks
in runParser a kf' ks
{-# INLINE mplus #-}
instance Monoid (Parser a) where
mempty = fail "mempty"
{-# INLINE mempty #-}
mappend = mplus
{-# INLINE mappend #-}
apP :: Parser (a -> b) -> Parser a -> Parser b
apP d e = do
b <- d
a <- e
return (b a)
{-# INLINE apP #-}
-- | A JSON \"object\" (key\/value map).
type Object = HashMap Text Value
-- | A JSON \"array\" (sequence).
type Array = Vector Value
-- | A JSON value represented as a Haskell value.
data Value = Object !Object
| Array !Array
| String !Text
| Number !Number
| Bool !Bool
| Null
deriving (Eq, Show, Typeable)
instance NFData Value where
rnf (Object o) = rnf o
rnf (Array a) = V.foldl' (\x y -> rnf y `seq` x) () a
rnf (String s) = rnf s
rnf (Number n) = case n of I i -> rnf i; D d -> rnf d
rnf (Bool b) = rnf b
rnf Null = ()
instance IsString Value where
fromString = String . pack
{-# INLINE fromString #-}
instance Hashable Value where
hashWithSalt s (Object o) = H.foldl' hashWithSalt
(s `hashWithSalt` (0::Int)) o
hashWithSalt s (Array a) = V.foldl' hashWithSalt
(s `hashWithSalt` (1::Int)) a
hashWithSalt s (String str) = s `hashWithSalt` (2::Int) `hashWithSalt` str
hashWithSalt s (Number n) = 3 `hashWithSalt`
case n of I i -> hashWithSalt s i
D d -> hashWithSalt s d
hashWithSalt s (Bool b) = s `hashWithSalt` (4::Int) `hashWithSalt` b
hashWithSalt s Null = s `hashWithSalt` (5::Int)
-- | The empty array.
emptyArray :: Value
emptyArray = Array V.empty
-- | Determines if the 'Value' is an empty 'Array'.
-- Note that: @isEmptyArray 'emptyArray'@.
isEmptyArray :: Value -> Bool
isEmptyArray (Array arr) = V.null arr
isEmptyArray _ = False
-- | The empty object.
emptyObject :: Value
emptyObject = Object H.empty
-- | Run a 'Parser'.
parse :: (a -> Parser b) -> a -> Result b
parse m v = runParser (m v) Error Success
{-# INLINE parse #-}
-- | Run a 'Parser' with a 'Maybe' result type.
parseMaybe :: (a -> Parser b) -> a -> Maybe b
parseMaybe m v = runParser (m v) (const Nothing) Just
{-# INLINE parseMaybe #-}
-- | Run a 'Parser' with an 'Either' result type.
parseEither :: (a -> Parser b) -> a -> Either String b
parseEither m v = runParser (m v) Left Right
{-# INLINE parseEither #-}
-- | A key\/value pair for an 'Object'.
type Pair = (Text, Value)
-- | Create a 'Value' from a list of name\/value 'Pair's. If duplicate
-- keys arise, earlier keys and their associated values win.
object :: [Pair] -> Value
object = Object . H.fromList
{-# INLINE object #-}
-- | If the inner @Parser@ failed, modify the failure message using the
-- provided function. This allows you to create more descriptive error messages.
-- For example:
--
-- > parseJSON (Object o) = modifyFailure
-- > ("Parsing of the Foo value failed: " ++)
-- > (Foo <$> o .: "someField")
--
-- Since 0.6.2.0
modifyFailure :: (String -> String) -> Parser a -> Parser a
modifyFailure f (Parser p) = Parser $ \kf -> p (kf . f)
--------------------------------------------------------------------------------
-- Generic and TH encoding configuration
--------------------------------------------------------------------------------
-- | Options that specify how to encode\/decode your datatype to\/from JSON.
data Options = Options
{ fieldLabelModifier :: String -> String
-- ^ Function applied to field labels.
-- Handy for removing common record prefixes for example.
, constructorTagModifier :: String -> String
-- ^ Function applied to constructor tags which could be handy
-- for lower-casing them for example.
, allNullaryToStringTag :: Bool
-- ^ If 'True' the constructors of a datatype, with /all/
-- nullary constructors, will be encoded to just a string with
-- the constructor tag. If 'False' the encoding will always
-- follow the `sumEncoding`.
, omitNothingFields :: Bool
-- ^ If 'True' record fields with a 'Nothing' value will be
-- omitted from the resulting object. If 'False' the resulting
-- object will include those fields mapping to @null@.
, sumEncoding :: SumEncoding
-- ^ Specifies how to encode constructors of a sum datatype.
}
-- | Specifies how to encode constructors of a sum datatype.
data SumEncoding =
TaggedObject { tagFieldName :: String
, contentsFieldName :: String
}
-- ^ A constructor will be encoded to an object with a field
-- 'tagFieldName' which specifies the constructor tag (modified by
-- the 'constructorTagModifier'). If the constructor is a record
-- the encoded record fields will be unpacked into this object. So
-- make sure that your record doesn't have a field with the same
-- label as the 'tagFieldName'. Otherwise the tag gets overwritten
-- by the encoded value of that field! If the constructor is not a
-- record the encoded constructor contents will be stored under
-- the 'contentsFieldName' field.
| ObjectWithSingleField
-- ^ A constructor will be encoded to an object with a single
-- field named after the constructor tag (modified by the
-- 'constructorTagModifier') which maps to the encoded contents of
-- the constructor.
| TwoElemArray
-- ^ A constructor will be encoded to a 2-element array where the
-- first element is the tag of the constructor (modified by the
-- 'constructorTagModifier') and the second element the encoded
-- contents of the constructor.
-- | Default encoding 'Options':
--
-- @
-- 'Options'
-- { 'fieldLabelModifier' = id
-- , 'constructorTagModifier' = id
-- , 'allNullaryToStringTag' = True
-- , 'omitNothingFields' = False
-- , 'sumEncoding' = 'defaultTaggedObject'
-- }
-- @
defaultOptions :: Options
defaultOptions = Options
{ fieldLabelModifier = id
, constructorTagModifier = id
, allNullaryToStringTag = True
, omitNothingFields = False
, sumEncoding = defaultTaggedObject
}
-- | Default 'TaggedObject' 'SumEncoding' options:
--
-- @
-- defaultTaggedObject = 'TaggedObject'
-- { 'tagFieldName' = \"tag\"
-- , 'contentsFieldName' = \"contents\"
-- }
-- @
defaultTaggedObject :: SumEncoding
defaultTaggedObject = TaggedObject
{ tagFieldName = "tag"
, contentsFieldName = "contents"
}
|
moonKimura/aeson-0.6.2.1
|
Data/Aeson/Types/Internal.hs
|
bsd-3-clause
| 10,354
| 0
| 14
| 2,934
| 2,018
| 1,145
| 873
| 200
| 1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Main where
import Pdf.Toolbox.Document
import Options.Applicative
import System.IO
import Data.Text (unpack)
data ExtractorOptions = ExtractorOptions {
argFilename :: String
}
opts :: Parser ExtractorOptions
opts = ExtractorOptions <$> argument str (metavar "FILENAME")
extractorOptionParser :: ParserInfo ExtractorOptions
extractorOptionParser =
info (helper <*> opts)
(fullDesc <>
progDesc "Outputs the textual content of a PDF file" <>
header "unpdf - extracts the textual content of a PDF file")
extractFile :: ExtractorOptions -> IO ()
extractFile ExtractorOptions{..} = do
res <- withBinaryFile argFilename ReadMode $ \handle ->
runPdfWithHandle handle knownFilters $ do
pgRoot <- document >>= documentCatalog >>= catalogPageNode
nPages <- pageNodeNKids pgRoot
pages <- mapM (pageNodePageByNum pgRoot) (enumFromTo 0 (nPages - 1))
txts <- mapM pageExtractText pages
liftIO $ mapM_ (putStrLn . unpack) txts
case res of
Left badness -> hPutStr stderr $ "PDF error: " ++ show badness
Right _ -> return ()
main :: IO ()
main = execParser extractorOptionParser >>= extractFile
|
fractalcat/unpdf
|
Main.hs
|
mit
| 1,281
| 0
| 18
| 289
| 330
| 164
| 166
| 31
| 2
|
{- Simple IO exception handling (and some more)
-
- Copyright 2011-2014 Joey Hess <id@joeyh.name>
-
- License: BSD-2-clause
-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-tabs #-}
module Utility.Exception (
module X,
catchBoolIO,
catchMaybeIO,
catchDefaultIO,
catchMsgIO,
catchIO,
tryIO,
bracketIO,
catchNonAsync,
tryNonAsync,
tryWhenExists,
) where
import Control.Monad.Catch as X hiding (Handler)
import qualified Control.Monad.Catch as M
import Control.Exception (IOException, AsyncException)
import Control.Monad
import Control.Monad.IO.Class (liftIO, MonadIO)
import System.IO.Error (isDoesNotExistError)
import Utility.Data
{- Catches IO errors and returns a Bool -}
catchBoolIO :: MonadCatch m => m Bool -> m Bool
catchBoolIO = catchDefaultIO False
{- Catches IO errors and returns a Maybe -}
catchMaybeIO :: MonadCatch m => m a -> m (Maybe a)
catchMaybeIO a = do
catchDefaultIO Nothing $ do
v <- a
return (Just v)
{- Catches IO errors and returns a default value. -}
catchDefaultIO :: MonadCatch m => a -> m a -> m a
catchDefaultIO def a = catchIO a (const $ return def)
{- Catches IO errors and returns the error message. -}
catchMsgIO :: MonadCatch m => m a -> m (Either String a)
catchMsgIO a = do
v <- tryIO a
return $ either (Left . show) Right v
{- catch specialized for IO errors only -}
catchIO :: MonadCatch m => m a -> (IOException -> m a) -> m a
catchIO = M.catch
{- try specialized for IO errors only -}
tryIO :: MonadCatch m => m a -> m (Either IOException a)
tryIO = M.try
{- bracket with setup and cleanup actions lifted to IO.
-
- Note that unlike catchIO and tryIO, this catches all exceptions. -}
bracketIO :: (MonadMask m, MonadIO m) => IO v -> (v -> IO b) -> (v -> m a) -> m a
bracketIO setup cleanup = bracket (liftIO setup) (liftIO . cleanup)
{- Catches all exceptions except for async exceptions.
- This is often better to use than catching them all, so that
- ThreadKilled and UserInterrupt get through.
-}
catchNonAsync :: MonadCatch m => m a -> (SomeException -> m a) -> m a
catchNonAsync a onerr = a `catches`
[ M.Handler (\ (e :: AsyncException) -> throwM e)
, M.Handler (\ (e :: SomeException) -> onerr e)
]
tryNonAsync :: MonadCatch m => m a -> m (Either SomeException a)
tryNonAsync a = go `catchNonAsync` (return . Left)
where
go = do
v <- a
return (Right v)
{- Catches only DoesNotExist exceptions, and lets all others through. -}
tryWhenExists :: MonadCatch m => m a -> m (Maybe a)
tryWhenExists a = do
v <- tryJust (guard . isDoesNotExistError) a
return (eitherToMaybe v)
|
shosti/propellor
|
src/Utility/Exception.hs
|
bsd-2-clause
| 2,587
| 26
| 12
| 489
| 782
| 406
| 376
| 53
| 1
|
{-# Language FlexibleContexts, FlexibleInstances #-}
module Network.RTbl.Parser ( parseRTbl_ipv6, parseRTbl_ipv4, rTblToIsabelle, RTbl, Routing_rule)
where
import Text.Parsec
import Data.Functor ((<$>), ($>))
import Control.Applicative ((<*), (*>), (<$>), (<*>))
import qualified Network.IPTables.Generated as Isabelle
import Network.IPTables.Ruleset
import Network.IPTables.ParserHelper
import Network.IPTables.IsabelleToString (Word32, Word128)
import qualified Network.IPTables.Generated as Isabelle
import Network.IPTables.Generated (metric_update, routing_action_next_hop_update, routing_action_oiface_update, empty_rr_hlp)
import Data.Maybe (catMaybes, Maybe (Just, Nothing), fromMaybe)
import Control.Monad (void,liftM)
type Routing_rule a = Isabelle.Routing_rule_ext a ()
data RTbl a = RTbl [Routing_rule a]
parseRTbl ippars = flip runParser () $ RTbl . (\t -> if Isabelle.sanity_ip_route t then t else error "Routing table sanity check failed.") . Isabelle.sort_rtbl <$> many (parseRTblEntry ippars)
parseRTbl_ipv4 = parseRTbl ipv4dotdecimal
parseRTbl_ipv6 = parseRTbl ipv6colonsep
parseRTblEntry :: Isabelle.Len a => Parsec String s (Isabelle.Word a) -> Parsec String s (Routing_rule a)
parseRTblEntry ippars = do
pfx <- ipaddrOrCidr ippars <|> defaultParser
skipWS
opts <- parseOpts ippars
many1 (char '\n')
return $ opts . empty_rr_hlp $ pfx
where
defaultParser = Prelude.const (Isabelle.default_prefix) <$> lit "default"
parseOpt :: Isabelle.Len a => Parsec String s (Isabelle.Word a) -> Parsec String s (Routing_rule a -> Routing_rule a)
parseOpt ippars = choice (map try [parseOIF, parseNH ippars, parseMetric, ignoreScope, ignoreProto, ignoreSrc ippars])
parseOpts :: Isabelle.Len a => Parsec String s (Isabelle.Word a) -> Parsec String s (Routing_rule a -> Routing_rule a)
parseOpts ippars = flip (foldl (flip id)) <$> many (parseOpt ippars <* skipWS)
litornat l = (void $ nat) <|> void (choice (map lit l))
ignoreScope = do
lit "scope"
skipWS
litornat ["host", "link", "global"]
return id
ignoreProto = do
lit "proto"
skipWS
litornat ["kernel", "boot", "static", "dhcp"]
return id
ignoreSrc ippars = do
lit "src"
skipWS
ippars
return id
parseOIF :: Isabelle.Len a => Parsec String s (Routing_rule a -> Routing_rule a)
parseOIF = do
lit "dev"
skipWS
routing_action_oiface_update <$> siface
parseNH ippars = do
lit "via"
skipWS
routing_action_next_hop_update <$> ippars
parseMetric :: Isabelle.Len a => Parsec String s (Routing_rule a -> Routing_rule a)
parseMetric = do
lit "metric"
skipWS
metric_update . const . Isabelle.nat_of_integer <$> nat
rTblToIsabelle (RTbl t) = t
instance Show (RTbl Word32) where
show (RTbl t) = unlines . map show $ t
instance Show (RTbl Word128) where
show (RTbl t) = unlines . map show $ t
{- now, for some code duplication... -}
skipWS = void $ many $ oneOf " \t"
lit str = (string str)
ipaddrOrCidr ippars = try (Isabelle.PrefixMatch <$> (ippars <* char '/') <*> (Isabelle.nat_of_integer <$> nat))
<|> try (flip Isabelle.PrefixMatch (Isabelle.nat_of_integer 32) <$> ippars)
siface = many1 (oneOf $ ['A'..'Z'] ++ ['a'..'z'] ++ ['0'..'9'] ++ ['+', '*', '.', '-'])
|
diekmann/Iptables_Semantics
|
haskell_tool/lib/Network/RTbl/Parser.hs
|
bsd-2-clause
| 3,357
| 0
| 12
| 668
| 1,136
| 586
| 550
| 70
| 2
|
module Util.IO ( getEnvVar
, makeExecutable
, readProcessWithExitCodeInEnv
, Environment
, createTemporaryDirectory
, which
) where
import System.Environment (getEnv)
import System.IO.Error (isDoesNotExistError)
import System.Directory (getPermissions, setPermissions, executable, removeFile, createDirectory, doesFileExist)
import Control.Concurrent (forkIO, putMVar, takeMVar, newEmptyMVar)
import Control.Exception as Exception (catch, evaluate)
import System.Process (runInteractiveProcess, waitForProcess)
import System.IO (hGetContents, hPutStr, hFlush, hClose, openTempFile)
import System.Exit (ExitCode)
import Data.List.Split (splitOn)
import Control.Monad (foldM)
import System.FilePath ((</>))
-- Computation getEnvVar var returns Just the value of the environment variable var,
-- or Nothing if the environment variable does not exist
getEnvVar :: String -> IO (Maybe String)
getEnvVar var = Just `fmap` getEnv var `Exception.catch` noValueHandler
where noValueHandler e | isDoesNotExistError e = return Nothing
| otherwise = ioError e
makeExecutable :: FilePath -> IO ()
makeExecutable path = do
perms <- getPermissions path
setPermissions path perms{executable = True}
type Environment = [(String, String)]
-- like readProcessWithExitCode, but takes additional environment argument
readProcessWithExitCodeInEnv :: Environment -> FilePath -> [String] -> Maybe String -> IO (ExitCode, String, String)
readProcessWithExitCodeInEnv env progName args input = do
(inh, outh, errh, pid) <- runInteractiveProcess progName args Nothing (Just env)
out <- hGetContents outh
outMVar <- newEmptyMVar
_ <- forkIO $ evaluate (length out) >> putMVar outMVar ()
err <- hGetContents errh
errMVar <- newEmptyMVar
_ <- forkIO $ evaluate (length err) >> putMVar errMVar ()
case input of
Just inp | not (null inp) -> hPutStr inh inp >> hFlush inh
_ -> return ()
hClose inh
takeMVar outMVar
hClose outh
takeMVar errMVar
hClose errh
ex <- waitForProcess pid
return (ex, out, err)
-- similar to openTempFile, but creates a temporary directory
-- and returns its path
createTemporaryDirectory :: FilePath -> String -> IO FilePath
createTemporaryDirectory parentDir templateName = do
(path, handle) <- openTempFile parentDir templateName
hClose handle
removeFile path
createDirectory path
return path
which :: Maybe String -> String -> IO (Maybe FilePath)
which pathVar name = do
path <- case pathVar of
Nothing -> getEnvVar "PATH"
Just path -> return $ Just path
case path of
Nothing -> return Nothing
Just path' -> do
let pathElems = splitOn ":" path'
aux x@(Just _) _ = return x
aux Nothing pathDir = do
let programPath = pathDir </> name
flag <- doesFileExist programPath
if flag then
return $ Just programPath
else
return Nothing
foldM aux Nothing pathElems
|
Paczesiowa/hsenv
|
src/Util/IO.hs
|
bsd-3-clause
| 3,094
| 0
| 20
| 726
| 885
| 445
| 440
| 69
| 5
|
{-# LANGUAGE Haskell2010 #-}
{-# LINE 1 "src/GHC/Integer/Logarithms/Compat.hs" #-}
-- |
-- Module: GHC.Integer.Logarithms.Compat
-- Copyright: (c) 2011 Daniel Fischer
-- Licence: MIT
-- Maintainer: Daniel Fischer <daniel.is.fischer@googlemail.com>
-- Stability: Provisional
-- Portability: Non-portable (GHC extensions)
--
-- Low level stuff for integer logarithms.
{-# LANGUAGE CPP, MagicHash, UnboxedTuples #-}
module GHC.Integer.Logarithms.Compat
( -- * Functions
integerLogBase#
, integerLog2#
, wordLog2#
) where
-- Stuff is already there
import GHC.Integer.Logarithms
|
phischu/fragnix
|
tests/packages/scotty/GHC.Integer.Logarithms.Compat.hs
|
bsd-3-clause
| 668
| 0
| 4
| 164
| 39
| 31
| 8
| 9
| 0
|
{-# OPTIONS -cpp -fglasgow-exts #-}
{-# OPTIONS -w #-}
-- The above warning supression flag is a temporary kludge.
-- While working on this module you are encouraged to remove it and fix
-- any warnings in the module. See
-- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
-- for details
module Main(main) where
#include "../../includes/ghcconfig.h"
#include "../../includes/stg/MachRegs.h"
#include "../../includes/rts/Constants.h"
-- Needed for TAG_BITS
#include "../../includes/MachDeps.h"
import Text.PrettyPrint
import Data.Word
import Data.Bits
import Data.List ( intersperse )
import System.Exit
import System.Environment
import System.IO
-- -----------------------------------------------------------------------------
-- Argument kinds (rougly equivalent to PrimRep)
data ArgRep
= N -- non-ptr
| P -- ptr
| V -- void
| F -- float
| D -- double
| L -- long (64-bit)
-- size of a value in *words*
argSize :: ArgRep -> Int
argSize N = 1
argSize P = 1
argSize V = 0
argSize F = 1
argSize D = (SIZEOF_DOUBLE `quot` SIZEOF_VOID_P :: Int)
argSize L = (8 `quot` SIZEOF_VOID_P :: Int)
showArg :: ArgRep -> Char
showArg N = 'n'
showArg P = 'p'
showArg V = 'v'
showArg F = 'f'
showArg D = 'd'
showArg L = 'l'
-- is a value a pointer?
isPtr :: ArgRep -> Bool
isPtr P = True
isPtr _ = False
-- -----------------------------------------------------------------------------
-- Registers
data RegStatus = Registerised | Unregisterised
type Reg = String
availableRegs :: RegStatus -> ([Reg],[Reg],[Reg],[Reg])
availableRegs Unregisterised = ([],[],[],[])
availableRegs Registerised =
( vanillaRegs MAX_REAL_VANILLA_REG,
floatRegs MAX_REAL_FLOAT_REG,
doubleRegs MAX_REAL_DOUBLE_REG,
longRegs MAX_REAL_LONG_REG
)
vanillaRegs, floatRegs, doubleRegs, longRegs :: Int -> [Reg]
vanillaRegs n = [ "R" ++ show m | m <- [2..n] ] -- never use R1
floatRegs n = [ "F" ++ show m | m <- [1..n] ]
doubleRegs n = [ "D" ++ show m | m <- [1..n] ]
longRegs n = [ "L" ++ show m | m <- [1..n] ]
-- -----------------------------------------------------------------------------
-- Loading/saving register arguments to the stack
loadRegArgs :: RegStatus -> Int -> [ArgRep] -> (Doc,Int)
loadRegArgs regstatus sp args
= (loadRegOffs reg_locs, sp')
where (reg_locs, _, sp') = assignRegs regstatus sp args
loadRegOffs :: [(Reg,Int)] -> Doc
loadRegOffs = vcat . map (uncurry assign_stk_to_reg)
saveRegOffs :: [(Reg,Int)] -> Doc
saveRegOffs = vcat . map (uncurry assign_reg_to_stk)
-- a bit like assignRegs in CgRetConv.lhs
assignRegs
:: RegStatus -- are we registerised?
-> Int -- Sp of first arg
-> [ArgRep] -- args
-> ([(Reg,Int)], -- regs and offsets to load
[ArgRep], -- left-over args
Int) -- Sp of left-over args
assignRegs regstatus sp args = assign sp args (availableRegs regstatus) []
assign sp [] regs doc = (doc, [], sp)
assign sp (V : args) regs doc = assign sp args regs doc
assign sp (arg : args) regs doc
= case findAvailableReg arg regs of
Just (reg, regs') -> assign (sp + argSize arg) args regs'
((reg, sp) : doc)
Nothing -> (doc, (arg:args), sp)
findAvailableReg N (vreg:vregs, fregs, dregs, lregs) =
Just (vreg, (vregs,fregs,dregs,lregs))
findAvailableReg P (vreg:vregs, fregs, dregs, lregs) =
Just (vreg, (vregs,fregs,dregs,lregs))
findAvailableReg F (vregs, freg:fregs, dregs, lregs) =
Just (freg, (vregs,fregs,dregs,lregs))
findAvailableReg D (vregs, fregs, dreg:dregs, lregs) =
Just (dreg, (vregs,fregs,dregs,lregs))
findAvailableReg L (vregs, fregs, dregs, lreg:lregs) =
Just (lreg, (vregs,fregs,dregs,lregs))
findAvailableReg _ _ = Nothing
assign_reg_to_stk reg sp
= loadSpWordOff (regRep reg) sp <> text " = " <> text reg <> semi
assign_stk_to_reg reg sp
= text reg <> text " = " <> loadSpWordOff (regRep reg) sp <> semi
regRep ('F':_) = "F_"
regRep ('D':_) = "D_"
regRep ('L':_) = "L_"
regRep _ = "W_"
loadSpWordOff :: String -> Int -> Doc
loadSpWordOff rep off = text rep <> text "[Sp+WDS(" <> int off <> text ")]"
-- make a ptr/non-ptr bitmap from a list of argument types
mkBitmap :: [ArgRep] -> Word32
mkBitmap args = foldr f 0 args
where f arg bm | isPtr arg = bm `shiftL` 1
| otherwise = (bm `shiftL` size) .|. ((1 `shiftL` size) - 1)
where size = argSize arg
-- -----------------------------------------------------------------------------
-- Generating the application functions
-- A SUBTLE POINT about stg_ap functions (can't think of a better
-- place to put this comment --SDM):
--
-- The entry convention to an stg_ap_ function is as follows: all the
-- arguments are on the stack (we might revisit this at some point,
-- but it doesn't make any difference on x86), and THERE IS AN EXTRA
-- EMPTY STACK SLOT at the top of the stack.
--
-- Why? Because in several cases, stg_ap_* will need an extra stack
-- slot, eg. to push a return address in the THUNK case, and this is a
-- way of pushing the stack check up into the caller which is probably
-- doing one anyway. Allocating the extra stack slot in the caller is
-- also probably free, because it will be adjusting Sp after pushing
-- the args anyway (this might not be true of register-rich machines
-- when we start passing args to stg_ap_* in regs).
mkApplyName args
= text "stg_ap_" <> text (map showArg args)
mkApplyRetName args
= mkApplyName args <> text "_ret"
mkApplyFastName args
= mkApplyName args <> text "_fast"
mkApplyInfoName args
= mkApplyName args <> text "_info"
mb_tag_node arity | Just tag <- tagForArity arity = mkTagStmt tag <> semi
| otherwise = empty
mkTagStmt tag = text ("R1 = R1 + "++ show tag)
genMkPAP regstatus macro jump ticker disamb
no_load_regs -- don't load argumnet regs before jumping
args_in_regs -- arguments are already in regs
is_pap args all_args_size fun_info_label
is_fun_case
= smaller_arity_cases
$$ exact_arity_case
$$ larger_arity_case
where
n_args = length args
-- offset of arguments on the stack at slow apply calls.
stk_args_slow_offset = 1
stk_args_offset
| args_in_regs = 0
| otherwise = stk_args_slow_offset
-- The SMALLER ARITY cases:
-- if (arity == 1) {
-- Sp[0] = Sp[1];
-- Sp[1] = (W_)&stg_ap_1_info;
-- JMP_(GET_ENTRY(R1.cl));
smaller_arity_cases = vcat [ smaller_arity i | i <- [1..n_args-1] ]
smaller_arity arity
= text "if (arity == " <> int arity <> text ") {" $$
nest 4 (vcat [
-- text "TICK_SLOW_CALL_" <> text ticker <> text "_TOO_MANY();",
-- load up regs for the call, if necessary
load_regs,
-- If we have more args in registers than are required
-- for the call, then we must save some on the stack,
-- and set up the stack for the follow-up call.
-- If the extra arguments are on the stack, then we must
-- instead shuffle them down to make room for the info
-- table for the follow-on call.
if overflow_regs
then save_extra_regs
else shuffle_extra_args,
-- for a PAP, we have to arrange that the stack contains a
-- return address in the even that stg_PAP_entry fails its
-- heap check. See stg_PAP_entry in Apply.hc for details.
if is_pap
then text "R2 = " <> mkApplyInfoName this_call_args <> semi
else empty,
if is_fun_case then mb_tag_node arity else empty,
if overflow_regs
then text "jump_SAVE_CCCS" <> parens (text jump) <> semi
else text "jump " <> text jump <> semi
]) $$
text "}"
where
-- offsets in case we need to save regs:
(reg_locs, _, _)
= assignRegs regstatus stk_args_offset args
-- register assignment for *this function call*
(reg_locs', reg_call_leftovers, reg_call_sp_stk_args)
= assignRegs regstatus stk_args_offset (take arity args)
load_regs
| no_load_regs || args_in_regs = empty
| otherwise = loadRegOffs reg_locs'
(this_call_args, rest_args) = splitAt arity args
-- the offset of the stack args from initial Sp
sp_stk_args
| args_in_regs = stk_args_offset
| no_load_regs = stk_args_offset
| otherwise = reg_call_sp_stk_args
-- the stack args themselves
this_call_stack_args
| args_in_regs = reg_call_leftovers -- sp offsets are wrong
| no_load_regs = this_call_args
| otherwise = reg_call_leftovers
stack_args_size = sum (map argSize this_call_stack_args)
overflow_regs = args_in_regs && length reg_locs > length reg_locs'
save_extra_regs
= -- we have extra arguments in registers to save
let
extra_reg_locs = drop (length reg_locs') (reverse reg_locs)
adj_reg_locs = [ (reg, off - adj + 1) |
(reg,off) <- extra_reg_locs ]
adj = case extra_reg_locs of
(reg, fst_off):_ -> fst_off
size = snd (last adj_reg_locs)
in
text "Sp_adj(" <> int (-size - 1) <> text ");" $$
saveRegOffs adj_reg_locs $$
loadSpWordOff "W_" 0 <> text " = " <>
mkApplyInfoName rest_args <> semi
shuffle_extra_args
= vcat [text "#ifdef PROFILING",
shuffle True,
text "#else",
shuffle False,
text "#endif"]
where
-- Sadly here we have to insert an stg_restore_cccs frame
-- just underneath the stg_ap_*_info frame if we're
-- profiling; see Note [jump_SAVE_CCCS]
shuffle prof =
let offset = if prof then 2 else 0 in
vcat (map (shuffle_down (offset+1))
[sp_stk_args .. sp_stk_args+stack_args_size-1]) $$
(if prof
then
loadSpWordOff "W_" (sp_stk_args+stack_args_size-3)
<> text " = stg_restore_cccs_info;" $$
loadSpWordOff "W_" (sp_stk_args+stack_args_size-2)
<> text " = CCCS;"
else empty) $$
loadSpWordOff "W_" (sp_stk_args+stack_args_size-1)
<> text " = "
<> mkApplyInfoName rest_args <> semi $$
text "Sp_adj(" <> int (sp_stk_args - 1 - offset) <> text ");"
shuffle_down j i =
loadSpWordOff "W_" (i-j) <> text " = " <>
loadSpWordOff "W_" i <> semi
-- The EXACT ARITY case
--
-- if (arity == 1) {
-- Sp++;
-- JMP_(GET_ENTRY(R1.cl));
exact_arity_case
= text "if (arity == " <> int n_args <> text ") {" $$
let
(reg_doc, sp')
| no_load_regs || args_in_regs = (empty, stk_args_offset)
| otherwise = loadRegArgs regstatus stk_args_offset args
in
nest 4 (vcat [
-- text "TICK_SLOW_CALL_" <> text ticker <> text "_CORRECT();",
reg_doc,
text "Sp_adj(" <> int sp' <> text ");",
if is_pap
then text "R2 = " <> fun_info_label <> semi
else empty,
if is_fun_case then mb_tag_node n_args else empty,
text "jump " <> text jump <> semi
])
-- The LARGER ARITY cases:
--
-- } else /* arity > 1 */ {
-- BUILD_PAP(1,0,(W_)&stg_ap_v_info);
-- }
larger_arity_case =
text "} else {" $$
let
save_regs
| args_in_regs =
text "Sp_adj(" <> int (-sp_offset) <> text ");" $$
saveRegOffs reg_locs
| otherwise =
empty
in
nest 4 (vcat [
-- text "TICK_SLOW_CALL_" <> text ticker <> text "_TOO_FEW();",
save_regs,
-- Before building the PAP, tag the function closure pointer
if is_fun_case then
vcat [
text "if (arity < " <> int tAG_BITS_MAX <> text ") {",
text " R1 = R1 + arity" <> semi,
text "}"
]
else empty
,
text macro <> char '(' <> int n_args <> comma <>
int all_args_size <>
text "," <> fun_info_label <>
text "," <> text disamb <>
text ");"
]) $$
char '}'
where
-- offsets in case we need to save regs:
(reg_locs, leftovers, sp_offset)
= assignRegs regstatus stk_args_slow_offset args
-- BUILD_PAP assumes args start at offset 1
-- Note [jump_SAVE_CCCS]
-- when profiling, if we have some extra arguments to apply that we
-- save to the stack, we must also save the current cost centre stack
-- and restore it when applying the extra arguments. This is all
-- handled by the macro jump_SAVE_CCCS(target), defined in
-- rts/AutoApply.h.
--
-- At the jump, the stack will look like this:
--
-- ... extra args ...
-- stg_ap_pp_info
-- CCCS
-- stg_restore_cccs_info
-- --------------------------------------
-- Examine tag bits of function pointer and enter it
-- directly if needed.
-- TODO: remove the redundant case in the original code.
enterFastPath regstatus no_load_regs args_in_regs args
| Just tag <- tagForArity (length args)
= enterFastPathHelper tag regstatus no_load_regs args_in_regs args
enterFastPath _ _ _ _ = empty
-- Copied from Constants.lhs & CgUtils.hs, i'd rather have this imported:
-- (arity,tag)
tAG_BITS = (TAG_BITS :: Int)
tAG_BITS_MAX = ((1 `shiftL` tAG_BITS) :: Int)
tagForArity :: Int -> Maybe Int
tagForArity i | i < tAG_BITS_MAX = Just i
| otherwise = Nothing
enterFastPathHelper tag regstatus no_load_regs args_in_regs args =
vcat [text "if (GETTAG(R1)==" <> int tag <> text ") {",
reg_doc,
text " Sp_adj(" <> int sp' <> text ");",
-- enter, but adjust offset with tag
text " jump " <> text "%GET_ENTRY(R1-" <> int tag <> text ");",
text "}"
]
-- I don't totally understand this code, I copied it from
-- exact_arity_case
-- TODO: refactor
where
-- offset of arguments on the stack at slow apply calls.
stk_args_slow_offset = 1
stk_args_offset
| args_in_regs = 0
| otherwise = stk_args_slow_offset
(reg_doc, sp')
| no_load_regs || args_in_regs = (empty, stk_args_offset)
| otherwise = loadRegArgs regstatus stk_args_offset args
tickForArity arity
| True
= empty
| Just tag <- tagForArity arity
= vcat [
text "W_[TOTAL_CALLS] = W_[TOTAL_CALLS] + 1;",
text "W_[SLOW_CALLS_" <> int arity <> text "] = W_[SLOW_CALLS_" <> int arity <> text "] + 1;",
text "if (TO_W_(StgFunInfoExtra_arity(%FUN_INFO(%INFO_PTR(UNTAG(R1))))) == " <> int arity <> text " ) {",
text " W_[RIGHT_ARITY_" <> int arity <> text "] = W_[RIGHT_ARITY_" <> int arity <> text "] + 1;",
text " if (GETTAG(R1)==" <> int tag <> text ") {",
text " W_[TAGGED_PTR_" <> int arity <> text "] = W_[TAGGED_PTR_" <> int arity <> text "] + 1;",
text " } else {",
-- force a halt when not tagged!
-- text " W_[0]=0;",
text " }",
text "}"
]
tickForArity _ = text "W_[TOTAL_CALLS] = W_[TOTAL_CALLS] + 1;"
-- -----------------------------------------------------------------------------
-- generate an apply function
-- args is a list of 'p', 'n', 'f', 'd' or 'l'
formalParam :: ArgRep -> Int -> Doc
formalParam V _ = empty
formalParam arg n =
formalParamType arg <> space <>
text "arg" <> int n <> text ", "
formalParamType arg = argRep arg
argRep F = text "F_"
argRep D = text "D_"
argRep L = text "L_"
argRep P = text "gcptr"
argRep _ = text "W_"
genApply regstatus args =
let
fun_ret_label = mkApplyRetName args
fun_info_label = mkApplyInfoName args
all_args_size = sum (map argSize args)
in
vcat [
text "INFO_TABLE_RET(" <> mkApplyName args <> text ", " <>
text "RET_SMALL, " <> (cat $ zipWith formalParam args [1..]) <>
text ")\n{",
nest 4 (vcat [
text "W_ info;",
text "W_ arity;",
-- if fast == 1:
-- print "static void *lbls[] ="
-- print " { [FUN] &&fun_lbl,"
-- print " [FUN_1_0] &&fun_lbl,"
-- print " [FUN_0_1] &&fun_lbl,"
-- print " [FUN_2_0] &&fun_lbl,"
-- print " [FUN_1_1] &&fun_lbl,"
-- print " [FUN_0_2] &&fun_lbl,"
-- print " [FUN_STATIC] &&fun_lbl,"
-- print " [PAP] &&pap_lbl,"
-- print " [THUNK] &&thunk_lbl,"
-- print " [THUNK_1_0] &&thunk_lbl,"
-- print " [THUNK_0_1] &&thunk_lbl,"
-- print " [THUNK_2_0] &&thunk_lbl,"
-- print " [THUNK_1_1] &&thunk_lbl,"
-- print " [THUNK_0_2] &&thunk_lbl,"
-- print " [THUNK_STATIC] &&thunk_lbl,"
-- print " [THUNK_SELECTOR] &&thunk_lbl,"
-- print " [IND] &&ind_lbl,"
-- print " [IND_STATIC] &&ind_lbl,"
-- print " [IND_PERM] &&ind_lbl,"
-- print " };"
tickForArity (length args),
text "",
text "IF_DEBUG(apply,foreign \"C\" debugBelch(\"" <> fun_ret_label <>
text "... \"); foreign \"C\" printClosure(R1 \"ptr\"));",
text "IF_DEBUG(sanity,foreign \"C\" checkStackFrame(Sp+WDS(" <> int (1 + all_args_size)
<> text ")\"ptr\"));",
-- text "IF_DEBUG(sanity,checkStackChunk(Sp+" <> int (1 + all_args_size) <>
-- text ", CurrentTSO->stack + CurrentTSO->stack_size));",
-- text "TICK_SLOW_CALL(" <> int (length args) <> text ");",
let do_assert [] _ = []
do_assert (arg:args) offset
| isPtr arg = this : rest
| otherwise = rest
where this = text "ASSERT(LOOKS_LIKE_CLOSURE_PTR(Sp("
<> int offset <> text ")));"
rest = do_assert args (offset + argSize arg)
in
vcat (do_assert args 1),
text "again:",
-- if pointer is tagged enter it fast!
enterFastPath regstatus False False args,
-- Functions can be tagged, so we untag them!
text "R1 = UNTAG(R1);",
text "info = %INFO_PTR(R1);",
-- if fast == 1:
-- print " goto *lbls[info->type];";
-- else:
text "switch [INVALID_OBJECT .. N_CLOSURE_TYPES] (TO_W_(%INFO_TYPE(%STD_INFO(info)))) {",
nest 4 (vcat [
-- if fast == 1:
-- print " bco_lbl:"
-- else:
text "case BCO: {",
nest 4 (vcat [
text "arity = TO_W_(StgBCO_arity(R1));",
text "ASSERT(arity > 0);",
genMkPAP regstatus "BUILD_PAP" "ENTRY_LBL(stg_BCO)" "FUN" "BCO"
True{-stack apply-} False{-args on stack-} False{-not a PAP-}
args all_args_size fun_info_label {- tag stmt -}False
]),
text "}",
-- if fast == 1:
-- print " fun_lbl:"
-- else:
text "case FUN,",
text " FUN_1_0,",
text " FUN_0_1,",
text " FUN_2_0,",
text " FUN_1_1,",
text " FUN_0_2,",
text " FUN_STATIC: {",
nest 4 (vcat [
text "arity = TO_W_(StgFunInfoExtra_arity(%FUN_INFO(info)));",
text "ASSERT(arity > 0);",
genMkPAP regstatus "BUILD_PAP" "%GET_ENTRY(UNTAG(R1))" "FUN" "FUN"
False{-reg apply-} False{-args on stack-} False{-not a PAP-}
args all_args_size fun_info_label {- tag stmt -}True
]),
text "}",
-- if fast == 1:
-- print " pap_lbl:"
-- else:
text "case PAP: {",
nest 4 (vcat [
text "arity = TO_W_(StgPAP_arity(R1));",
text "ASSERT(arity > 0);",
genMkPAP regstatus "NEW_PAP" "stg_PAP_apply" "PAP" "PAP"
True{-stack apply-} False{-args on stack-} True{-is a PAP-}
args all_args_size fun_info_label {- tag stmt -}False
]),
text "}",
text "",
-- if fast == 1:
-- print " thunk_lbl:"
-- else:
text "case AP,",
text " AP_STACK,",
text " BLACKHOLE,",
text " WHITEHOLE,",
text " THUNK,",
text " THUNK_1_0,",
text " THUNK_0_1,",
text " THUNK_2_0,",
text " THUNK_1_1,",
text " THUNK_0_2,",
text " THUNK_STATIC,",
text " THUNK_SELECTOR: {",
nest 4 (vcat [
-- text "TICK_SLOW_CALL_UNEVALD(" <> int (length args) <> text ");",
text "Sp(0) = " <> fun_info_label <> text ";",
-- CAREFUL! in SMP mode, the info table may already have been
-- overwritten by an indirection, so we must enter the original
-- info pointer we read, don't read it again, because it might
-- not be enterable any more.
text "jump_SAVE_CCCS(%ENTRY_CODE(info));",
-- see Note [jump_SAVE_CCCS]
text ""
]),
text "}",
-- if fast == 1:
-- print " ind_lbl:"
-- else:
text "case IND,",
text " IND_STATIC,",
text " IND_PERM: {",
nest 4 (vcat [
text "R1 = StgInd_indirectee(R1);",
-- An indirection node might contain a tagged pointer
text "goto again;"
]),
text "}",
text "",
-- if fast == 0:
text "default: {",
nest 4 (
text "foreign \"C\" barf(\"" <> fun_ret_label <> text "\") never returns;"
),
text "}"
]),
text "}"
]),
text "}"
]
-- -----------------------------------------------------------------------------
-- Making a fast unknown application, args are in regs
genApplyFast regstatus args =
let
fun_fast_label = mkApplyFastName args
fun_ret_label = text "RET_LBL" <> parens (mkApplyName args)
fun_info_label = mkApplyInfoName args
all_args_size = sum (map argSize args)
in
vcat [
fun_fast_label,
char '{',
nest 4 (vcat [
text "W_ info;",
text "W_ arity;",
tickForArity (length args),
-- if pointer is tagged enter it fast!
enterFastPath regstatus False True args,
-- Functions can be tagged, so we untag them!
text "R1 = UNTAG(R1);",
text "info = %GET_STD_INFO(R1);",
text "switch [INVALID_OBJECT .. N_CLOSURE_TYPES] (TO_W_(%INFO_TYPE(info))) {",
nest 4 (vcat [
text "case FUN,",
text " FUN_1_0,",
text " FUN_0_1,",
text " FUN_2_0,",
text " FUN_1_1,",
text " FUN_0_2,",
text " FUN_STATIC: {",
nest 4 (vcat [
text "arity = TO_W_(StgFunInfoExtra_arity(%GET_FUN_INFO(R1)));",
text "ASSERT(arity > 0);",
genMkPAP regstatus "BUILD_PAP" "%GET_ENTRY(UNTAG(R1))" "FUN" "FUN"
False{-reg apply-} True{-args in regs-} False{-not a PAP-}
args all_args_size fun_info_label {- tag stmt -}True
]),
char '}',
text "default: {",
let
(reg_locs, leftovers, sp_offset) = assignRegs regstatus 1 args
-- leave a one-word space on the top of the stack when
-- calling the slow version
in
nest 4 (vcat [
text "Sp_adj" <> parens (int (-sp_offset)) <> semi,
saveRegOffs reg_locs,
text "jump" <+> fun_ret_label <> semi
]),
char '}'
]),
char '}'
]),
char '}'
]
-- -----------------------------------------------------------------------------
-- Making a stack apply
-- These little functions are like slow entry points. They provide
-- the layer between the PAP entry code and the function's fast entry
-- point: namely they load arguments off the stack into registers (if
-- available) and jump to the function's entry code.
--
-- On entry: R1 points to the function closure
-- arguments are on the stack starting at Sp
--
-- Invariant: the list of arguments never contains void. Since we're only
-- interested in loading arguments off the stack here, we can ignore
-- void arguments.
mkStackApplyEntryLabel:: [ArgRep] -> Doc
mkStackApplyEntryLabel args = text "stg_ap_stk_" <> text (map showArg args)
genStackApply :: RegStatus -> [ArgRep] -> Doc
genStackApply regstatus args =
let fn_entry_label = mkStackApplyEntryLabel args in
vcat [
fn_entry_label,
text "{", nest 4 body, text "}"
]
where
(assign_regs, sp') = loadRegArgs regstatus 0 args
body = vcat [assign_regs,
text "Sp_adj" <> parens (int sp') <> semi,
text "jump %GET_ENTRY(UNTAG(R1));"
]
-- -----------------------------------------------------------------------------
-- Stack save entry points.
--
-- These code fragments are used to save registers on the stack at a heap
-- check failure in the entry code for a function. We also have to save R1
-- and the return address (stg_gc_fun_info) on the stack. See stg_gc_fun_gen
-- in HeapStackCheck.hc for more details.
mkStackSaveEntryLabel :: [ArgRep] -> Doc
mkStackSaveEntryLabel args = text "stg_stk_save_" <> text (map showArg args)
genStackSave :: RegStatus -> [ArgRep] -> Doc
genStackSave regstatus args =
let fn_entry_label= mkStackSaveEntryLabel args in
vcat [
fn_entry_label,
text "{", nest 4 body, text "}"
]
where
body = vcat [text "Sp_adj" <> parens (int (-sp_offset)) <> semi,
saveRegOffs reg_locs,
text "Sp(2) = R1;",
text "Sp(1) =" <+> int stk_args <> semi,
text "Sp(0) = stg_gc_fun_info;",
text "jump stg_gc_noregs;"
]
std_frame_size = 3 -- the std bits of the frame. See StgRetFun in Closures.h,
-- and the comment on stg_fun_gc_gen in HeapStackCheck.hc.
(reg_locs, leftovers, sp_offset) = assignRegs regstatus std_frame_size args
-- number of words of arguments on the stack.
stk_args = sum (map argSize leftovers) + sp_offset - std_frame_size
-- -----------------------------------------------------------------------------
-- The prologue...
main = do
args <- getArgs
regstatus <- case args of
[] -> return Registerised
["-u"] -> return Unregisterised
_other -> do hPutStrLn stderr "syntax: genapply [-u]"
exitWith (ExitFailure 1)
let the_code = vcat [
text "// DO NOT EDIT!",
text "// Automatically generated by GenApply.hs",
text "",
text "#include \"Cmm.h\"",
text "#include \"AutoApply.h\"",
text "",
vcat (intersperse (text "") $
map (genApply regstatus) applyTypes),
vcat (intersperse (text "") $
map (genStackFns regstatus) stackApplyTypes),
vcat (intersperse (text "") $
map (genApplyFast regstatus) applyTypes),
genStackApplyArray stackApplyTypes,
genStackSaveArray stackApplyTypes,
genBitmapArray stackApplyTypes,
text "" -- add a newline at the end of the file
]
-- in
putStr (render the_code)
-- These have been shown to cover about 99% of cases in practice...
applyTypes = [
[V],
[F],
[D],
[L],
[N],
[P],
[P,V],
[P,P],
[P,P,V],
[P,P,P],
[P,P,P,V],
[P,P,P,P],
[P,P,P,P,P],
[P,P,P,P,P,P]
]
-- No need for V args in the stack apply cases.
-- ToDo: the stack apply and stack save code doesn't make a distinction
-- between N and P (they both live in the same register), only the bitmap
-- changes, so we could share the apply/save code between lots of cases.
stackApplyTypes = [
[],
[N],
[P],
[F],
[D],
[L],
[N,N],
[N,P],
[P,N],
[P,P],
[N,N,N],
[N,N,P],
[N,P,N],
[N,P,P],
[P,N,N],
[P,N,P],
[P,P,N],
[P,P,P],
[P,P,P,P],
[P,P,P,P,P],
[P,P,P,P,P,P],
[P,P,P,P,P,P,P],
[P,P,P,P,P,P,P,P]
]
genStackFns regstatus args
= genStackApply regstatus args
$$ genStackSave regstatus args
genStackApplyArray types =
vcat [
text "section \"relrodata\" {",
text "stg_ap_stack_entries:",
text "W_ 0; W_ 0; W_ 0;", -- ARG_GEN, ARG_GEN_BIG, ARG_BCO
vcat (map arr_ent types),
text "}"
]
where
arr_ent ty = text "W_" <+> mkStackApplyEntryLabel ty <> semi
genStackSaveArray types =
vcat [
text "section \"relrodata\" {",
text "stg_stack_save_entries:",
text "W_ 0; W_ 0; W_ 0;", -- ARG_GEN, ARG_GEN_BIG, ARG_BCO
vcat (map arr_ent types),
text "}"
]
where
arr_ent ty = text "W_" <+> mkStackSaveEntryLabel ty <> semi
genBitmapArray :: [[ArgRep]] -> Doc
genBitmapArray types =
vcat [
text "section \"rodata\" {",
text "stg_arg_bitmaps:",
text "W_ 0; W_ 0; W_ 0;", -- ARG_GEN, ARG_GEN_BIG, ARG_BCO
vcat (map gen_bitmap types),
text "}"
]
where
gen_bitmap ty = text "W_" <+> int bitmap_val <> semi
where bitmap_val =
(fromIntegral (mkBitmap ty) `shiftL` BITMAP_BITS_SHIFT)
.|. sum (map argSize ty)
|
mcmaniac/ghc
|
utils/genapply/GenApply.hs
|
bsd-3-clause
| 27,998
| 454
| 30
| 7,373
| 6,185
| 3,415
| 2,770
| 540
| 10
|
{-
(c) The University of Glasgow, 1994-2006
Core pass to saturate constructors and PrimOps
-}
{-# LANGUAGE BangPatterns, CPP #-}
module CorePrep (
corePrepPgm, corePrepExpr, cvtLitInteger,
lookupMkIntegerName, lookupIntegerSDataConName
) where
#include "HsVersions.h"
import OccurAnal
import HscTypes
import PrelNames
import MkId ( realWorldPrimId )
import CoreUtils
import CoreArity
import CoreFVs
import CoreMonad ( CoreToDo(..) )
import CoreLint ( endPassIO )
import CoreSyn
import CoreSubst
import MkCore hiding( FloatBind(..) ) -- We use our own FloatBind here
import Type
import Literal
import Coercion
import TcEnv
import TyCon
import Demand
import Var
import VarSet
import VarEnv
import Id
import IdInfo
import TysWiredIn
import DataCon
import PrimOp
import BasicTypes
import Module
import UniqSupply
import Maybes
import OrdList
import ErrUtils
import DynFlags
import Util
import Pair
import Outputable
import Platform
import FastString
import Config
import Name ( NamedThing(..), nameSrcSpan )
import SrcLoc ( SrcSpan(..), realSrcLocSpan, mkRealSrcLoc )
import Data.Bits
import MonadUtils ( mapAccumLM )
import Data.List ( mapAccumL )
import Control.Monad
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative
#endif
{-
-- ---------------------------------------------------------------------------
-- Overview
-- ---------------------------------------------------------------------------
The goal of this pass is to prepare for code generation.
1. Saturate constructor and primop applications.
2. Convert to A-normal form; that is, function arguments
are always variables.
* Use case for strict arguments:
f E ==> case E of x -> f x
(where f is strict)
* Use let for non-trivial lazy arguments
f E ==> let x = E in f x
(were f is lazy and x is non-trivial)
3. Similarly, convert any unboxed lets into cases.
[I'm experimenting with leaving 'ok-for-speculation'
rhss in let-form right up to this point.]
4. Ensure that *value* lambdas only occur as the RHS of a binding
(The code generator can't deal with anything else.)
Type lambdas are ok, however, because the code gen discards them.
5. [Not any more; nuked Jun 2002] Do the seq/par munging.
6. Clone all local Ids.
This means that all such Ids are unique, rather than the
weaker guarantee of no clashes which the simplifier provides.
And that is what the code generator needs.
We don't clone TyVars or CoVars. The code gen doesn't need that,
and doing so would be tiresome because then we'd need
to substitute in types and coercions.
7. Give each dynamic CCall occurrence a fresh unique; this is
rather like the cloning step above.
8. Inject bindings for the "implicit" Ids:
* Constructor wrappers
* Constructor workers
We want curried definitions for all of these in case they
aren't inlined by some caller.
9. Replace (lazy e) by e. See Note [lazyId magic] in MkId.hs
10. Convert (LitInteger i t) into the core representation
for the Integer i. Normally this uses mkInteger, but if
we are using the integer-gmp implementation then there is a
special case where we use the S# constructor for Integers that
are in the range of Int.
11. Uphold tick consistency while doing this: We move ticks out of
(non-type) applications where we can, and make sure that we
annotate according to scoping rules when floating.
This is all done modulo type applications and abstractions, so that
when type erasure is done for conversion to STG, we don't end up with
any trivial or useless bindings.
Invariants
~~~~~~~~~~
Here is the syntax of the Core produced by CorePrep:
Trivial expressions
triv ::= lit | var
| triv ty | /\a. triv
| truv co | /\c. triv | triv |> co
Applications
app ::= lit | var | app triv | app ty | app co | app |> co
Expressions
body ::= app
| let(rec) x = rhs in body -- Boxed only
| case body of pat -> body
| /\a. body | /\c. body
| body |> co
Right hand sides (only place where value lambdas can occur)
rhs ::= /\a.rhs | \x.rhs | body
We define a synonym for each of these non-terminals. Functions
with the corresponding name produce a result in that syntax.
-}
type CpeTriv = CoreExpr -- Non-terminal 'triv'
type CpeApp = CoreExpr -- Non-terminal 'app'
type CpeBody = CoreExpr -- Non-terminal 'body'
type CpeRhs = CoreExpr -- Non-terminal 'rhs'
{-
************************************************************************
* *
Top level stuff
* *
************************************************************************
-}
corePrepPgm :: HscEnv -> ModLocation -> CoreProgram -> [TyCon] -> IO CoreProgram
corePrepPgm hsc_env mod_loc binds data_tycons = do
let dflags = hsc_dflags hsc_env
showPass dflags "CorePrep"
us <- mkSplitUniqSupply 's'
initialCorePrepEnv <- mkInitialCorePrepEnv dflags hsc_env
let implicit_binds = mkDataConWorkers dflags mod_loc data_tycons
-- NB: we must feed mkImplicitBinds through corePrep too
-- so that they are suitably cloned and eta-expanded
binds_out = initUs_ us $ do
floats1 <- corePrepTopBinds initialCorePrepEnv binds
floats2 <- corePrepTopBinds initialCorePrepEnv implicit_binds
return (deFloatTop (floats1 `appendFloats` floats2))
endPassIO hsc_env alwaysQualify CorePrep binds_out []
return binds_out
corePrepExpr :: DynFlags -> HscEnv -> CoreExpr -> IO CoreExpr
corePrepExpr dflags hsc_env expr = do
showPass dflags "CorePrep"
us <- mkSplitUniqSupply 's'
initialCorePrepEnv <- mkInitialCorePrepEnv dflags hsc_env
let new_expr = initUs_ us (cpeBodyNF initialCorePrepEnv expr)
dumpIfSet_dyn dflags Opt_D_dump_prep "CorePrep" (ppr new_expr)
return new_expr
corePrepTopBinds :: CorePrepEnv -> [CoreBind] -> UniqSM Floats
-- Note [Floating out of top level bindings]
corePrepTopBinds initialCorePrepEnv binds
= go initialCorePrepEnv binds
where
go _ [] = return emptyFloats
go env (bind : binds) = do (env', bind') <- cpeBind TopLevel env bind
binds' <- go env' binds
return (bind' `appendFloats` binds')
mkDataConWorkers :: DynFlags -> ModLocation -> [TyCon] -> [CoreBind]
-- See Note [Data constructor workers]
-- c.f. Note [Injecting implicit bindings] in TidyPgm
mkDataConWorkers dflags mod_loc data_tycons
= [ NonRec id (tick_it (getName data_con) (Var id))
-- The ice is thin here, but it works
| tycon <- data_tycons, -- CorePrep will eta-expand it
data_con <- tyConDataCons tycon,
let id = dataConWorkId data_con
]
where
-- If we want to generate debug info, we put a source note on the
-- worker. This is useful, especially for heap profiling.
tick_it name
| not (gopt Opt_Debug dflags) = id
| RealSrcSpan span <- nameSrcSpan name = tick span
| Just file <- ml_hs_file mod_loc = tick (span1 file)
| otherwise = tick (span1 "???")
where tick span = Tick (SourceNote span $ showSDoc dflags (ppr name))
span1 file = realSrcLocSpan $ mkRealSrcLoc (mkFastString file) 1 1
{-
Note [Floating out of top level bindings]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
NB: we do need to float out of top-level bindings
Consider x = length [True,False]
We want to get
s1 = False : []
s2 = True : s1
x = length s2
We return a *list* of bindings, because we may start with
x* = f (g y)
where x is demanded, in which case we want to finish with
a = g y
x* = f a
And then x will actually end up case-bound
Note [CafInfo and floating]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
What happens when we try to float bindings to the top level? At this
point all the CafInfo is supposed to be correct, and we must make certain
that is true of the new top-level bindings. There are two cases
to consider
a) The top-level binding is marked asCafRefs. In that case we are
basically fine. The floated bindings had better all be lazy lets,
so they can float to top level, but they'll all have HasCafRefs
(the default) which is safe.
b) The top-level binding is marked NoCafRefs. This really happens
Example. CoreTidy produces
$fApplicativeSTM [NoCafRefs] = D:Alternative retry# ...blah...
Now CorePrep has to eta-expand to
$fApplicativeSTM = let sat = \xy. retry x y
in D:Alternative sat ...blah...
So what we *want* is
sat [NoCafRefs] = \xy. retry x y
$fApplicativeSTM [NoCafRefs] = D:Alternative sat ...blah...
So, gruesomely, we must set the NoCafRefs flag on the sat bindings,
*and* substutite the modified 'sat' into the old RHS.
It should be the case that 'sat' is itself [NoCafRefs] (a value, no
cafs) else the original top-level binding would not itself have been
marked [NoCafRefs]. The DEBUG check in CoreToStg for
consistentCafInfo will find this.
This is all very gruesome and horrible. It would be better to figure
out CafInfo later, after CorePrep. We'll do that in due course.
Meanwhile this horrible hack works.
Note [Data constructor workers]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Create any necessary "implicit" bindings for data con workers. We
create the rather strange (non-recursive!) binding
$wC = \x y -> $wC x y
i.e. a curried constructor that allocates. This means that we can
treat the worker for a constructor like any other function in the rest
of the compiler. The point here is that CoreToStg will generate a
StgConApp for the RHS, rather than a call to the worker (which would
give a loop). As Lennart says: the ice is thin here, but it works.
Hmm. Should we create bindings for dictionary constructors? They are
always fully applied, and the bindings are just there to support
partial applications. But it's easier to let them through.
Note [Dead code in CorePrep]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Imagine that we got an input program like this (see Trac #4962):
f :: Show b => Int -> (Int, b -> Maybe Int -> Int)
f x = (g True (Just x) + g () (Just x), g)
where
g :: Show a => a -> Maybe Int -> Int
g _ Nothing = x
g y (Just z) = if z > 100 then g y (Just (z + length (show y))) else g y unknown
After specialisation and SpecConstr, we would get something like this:
f :: Show b => Int -> (Int, b -> Maybe Int -> Int)
f x = (g$Bool_True_Just x + g$Unit_Unit_Just x, g)
where
{-# RULES g $dBool = g$Bool
g $dUnit = g$Unit #-}
g = ...
{-# RULES forall x. g$Bool True (Just x) = g$Bool_True_Just x #-}
g$Bool = ...
{-# RULES forall x. g$Unit () (Just x) = g$Unit_Unit_Just x #-}
g$Unit = ...
g$Bool_True_Just = ...
g$Unit_Unit_Just = ...
Note that the g$Bool and g$Unit functions are actually dead code: they
are only kept alive by the occurrence analyser because they are
referred to by the rules of g, which is being kept alive by the fact
that it is used (unspecialised) in the returned pair.
However, at the CorePrep stage there is no way that the rules for g
will ever fire, and it really seems like a shame to produce an output
program that goes to the trouble of allocating a closure for the
unreachable g$Bool and g$Unit functions.
The way we fix this is to:
* In cloneBndr, drop all unfoldings/rules
* In deFloatTop, run a simple dead code analyser on each top-level
RHS to drop the dead local bindings. For that call to OccAnal, we
disable the binder swap, else the occurrence analyser sometimes
introduces new let bindings for cased binders, which lead to the bug
in #5433.
The reason we don't just OccAnal the whole output of CorePrep is that
the tidier ensures that all top-level binders are GlobalIds, so they
don't show up in the free variables any longer. So if you run the
occurrence analyser on the output of CoreTidy (or later) you e.g. turn
this program:
Rec {
f = ... f ...
}
Into this one:
f = ... f ...
(Since f is not considered to be free in its own RHS.)
************************************************************************
* *
The main code
* *
************************************************************************
-}
cpeBind :: TopLevelFlag -> CorePrepEnv -> CoreBind
-> UniqSM (CorePrepEnv, Floats)
cpeBind top_lvl env (NonRec bndr rhs)
= do { (_, bndr1) <- cpCloneBndr env bndr
; let dmd = idDemandInfo bndr
is_unlifted = isUnLiftedType (idType bndr)
; (floats, bndr2, rhs2) <- cpePair top_lvl NonRecursive
dmd
is_unlifted
env bndr1 rhs
; let new_float = mkFloat dmd is_unlifted bndr2 rhs2
-- We want bndr'' in the envt, because it records
-- the evaluated-ness of the binder
; return (extendCorePrepEnv env bndr bndr2,
addFloat floats new_float) }
cpeBind top_lvl env (Rec pairs)
= do { let (bndrs,rhss) = unzip pairs
; (env', bndrs1) <- cpCloneBndrs env (map fst pairs)
; stuff <- zipWithM (cpePair top_lvl Recursive topDmd False env') bndrs1 rhss
; let (floats_s, bndrs2, rhss2) = unzip3 stuff
all_pairs = foldrOL add_float (bndrs2 `zip` rhss2)
(concatFloats floats_s)
; return (extendCorePrepEnvList env (bndrs `zip` bndrs2),
unitFloat (FloatLet (Rec all_pairs))) }
where
-- Flatten all the floats, and the currrent
-- group into a single giant Rec
add_float (FloatLet (NonRec b r)) prs2 = (b,r) : prs2
add_float (FloatLet (Rec prs1)) prs2 = prs1 ++ prs2
add_float b _ = pprPanic "cpeBind" (ppr b)
---------------
cpePair :: TopLevelFlag -> RecFlag -> Demand -> Bool
-> CorePrepEnv -> Id -> CoreExpr
-> UniqSM (Floats, Id, CpeRhs)
-- Used for all bindings
cpePair top_lvl is_rec dmd is_unlifted env bndr rhs
= do { (floats1, rhs1) <- cpeRhsE env rhs
-- See if we are allowed to float this stuff out of the RHS
; (floats2, rhs2) <- float_from_rhs floats1 rhs1
-- Make the arity match up
; (floats3, rhs3)
<- if manifestArity rhs1 <= arity
then return (floats2, cpeEtaExpand arity rhs2)
else WARN(True, text "CorePrep: silly extra arguments:" <+> ppr bndr)
-- Note [Silly extra arguments]
(do { v <- newVar (idType bndr)
; let float = mkFloat topDmd False v rhs2
; return ( addFloat floats2 float
, cpeEtaExpand arity (Var v)) })
-- Wrap floating ticks
; let (floats4, rhs4) = wrapTicks floats3 rhs3
-- Record if the binder is evaluated
-- and otherwise trim off the unfolding altogether
-- It's not used by the code generator; getting rid of it reduces
-- heap usage and, since we may be changing uniques, we'd have
-- to substitute to keep it right
; let bndr' | exprIsHNF rhs3 = bndr `setIdUnfolding` evaldUnfolding
| otherwise = bndr `setIdUnfolding` noUnfolding
; return (floats4, bndr', rhs4) }
where
is_strict_or_unlifted = (isStrictDmd dmd) || is_unlifted
platform = targetPlatform (cpe_dynFlags env)
arity = idArity bndr -- We must match this arity
---------------------
float_from_rhs floats rhs
| isEmptyFloats floats = return (emptyFloats, rhs)
| isTopLevel top_lvl = float_top floats rhs
| otherwise = float_nested floats rhs
---------------------
float_nested floats rhs
| wantFloatNested is_rec is_strict_or_unlifted floats rhs
= return (floats, rhs)
| otherwise = dont_float floats rhs
---------------------
float_top floats rhs -- Urhgh! See Note [CafInfo and floating]
| mayHaveCafRefs (idCafInfo bndr)
, allLazyTop floats
= return (floats, rhs)
-- So the top-level binding is marked NoCafRefs
| Just (floats', rhs') <- canFloatFromNoCaf platform floats rhs
= return (floats', rhs')
| otherwise
= dont_float floats rhs
---------------------
dont_float floats rhs
-- Non-empty floats, but do not want to float from rhs
-- So wrap the rhs in the floats
-- But: rhs1 might have lambdas, and we can't
-- put them inside a wrapBinds
= do { body <- rhsToBodyNF rhs
; return (emptyFloats, wrapBinds floats body) }
{- Note [Silly extra arguments]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we had this
f{arity=1} = \x\y. e
We *must* match the arity on the Id, so we have to generate
f' = \x\y. e
f = \x. f' x
It's a bizarre case: why is the arity on the Id wrong? Reason
(in the days of __inline_me__):
f{arity=0} = __inline_me__ (let v = expensive in \xy. e)
When InlineMe notes go away this won't happen any more. But
it seems good for CorePrep to be robust.
-}
-- ---------------------------------------------------------------------------
-- CpeRhs: produces a result satisfying CpeRhs
-- ---------------------------------------------------------------------------
cpeRhsE :: CorePrepEnv -> CoreExpr -> UniqSM (Floats, CpeRhs)
-- If
-- e ===> (bs, e')
-- then
-- e = let bs in e' (semantically, that is!)
--
-- For example
-- f (g x) ===> ([v = g x], f v)
cpeRhsE _env expr@(Type {}) = return (emptyFloats, expr)
cpeRhsE _env expr@(Coercion {}) = return (emptyFloats, expr)
cpeRhsE env (Lit (LitInteger i _))
= cpeRhsE env (cvtLitInteger (cpe_dynFlags env) (getMkIntegerId env)
(cpe_integerSDataCon env) i)
cpeRhsE _env expr@(Lit {}) = return (emptyFloats, expr)
cpeRhsE env expr@(Var {}) = cpeApp env expr
cpeRhsE env (Var f `App` _{-type-} `App` arg)
| f `hasKey` lazyIdKey -- Replace (lazy a) by a
= cpeRhsE env arg -- See Note [lazyId magic] in MkId
-- See Note [runRW magic] in MkId
| f `hasKey` runRWKey -- Replace (runRW# f) by (f realWorld#),
= case arg of -- beta reducing if possible
Lam s body -> cpeRhsE env (substExpr (text "runRW#") subst body)
where subst = extendIdSubst emptySubst s (Var realWorldPrimId)
-- XXX I think we can use emptySubst here
-- because realWorldPrimId is a global variable
-- and so cannot be bound by a lambda in body
_ -> cpeRhsE env (arg `App` Var realWorldPrimId)
cpeRhsE env expr@(App {}) = cpeApp env expr
cpeRhsE env (Let bind expr)
= do { (env', new_binds) <- cpeBind NotTopLevel env bind
; (floats, body) <- cpeRhsE env' expr
; return (new_binds `appendFloats` floats, body) }
cpeRhsE env (Tick tickish expr)
| tickishPlace tickish == PlaceNonLam && tickish `tickishScopesLike` SoftScope
= do { (floats, body) <- cpeRhsE env expr
-- See [Floating Ticks in CorePrep]
; return (unitFloat (FloatTick tickish) `appendFloats` floats, body) }
| otherwise
= do { body <- cpeBodyNF env expr
; return (emptyFloats, mkTick tickish' body) }
where
tickish' | Breakpoint n fvs <- tickish
= Breakpoint n (map (lookupCorePrepEnv env) fvs)
| otherwise
= tickish
cpeRhsE env (Cast expr co)
= do { (floats, expr') <- cpeRhsE env expr
; return (floats, Cast expr' co) }
cpeRhsE env expr@(Lam {})
= do { let (bndrs,body) = collectBinders expr
; (env', bndrs') <- cpCloneBndrs env bndrs
; body' <- cpeBodyNF env' body
; return (emptyFloats, mkLams bndrs' body') }
cpeRhsE env (Case scrut bndr ty alts)
= do { (floats, scrut') <- cpeBody env scrut
; let bndr1 = bndr `setIdUnfolding` evaldUnfolding
-- Record that the case binder is evaluated in the alternatives
; (env', bndr2) <- cpCloneBndr env bndr1
; alts' <- mapM (sat_alt env') alts
; return (floats, Case scrut' bndr2 ty alts') }
where
sat_alt env (con, bs, rhs)
= do { (env2, bs') <- cpCloneBndrs env bs
; rhs' <- cpeBodyNF env2 rhs
; return (con, bs', rhs') }
cvtLitInteger :: DynFlags -> Id -> Maybe DataCon -> Integer -> CoreExpr
-- Here we convert a literal Integer to the low-level
-- represenation. Exactly how we do this depends on the
-- library that implements Integer. If it's GMP we
-- use the S# data constructor for small literals.
-- See Note [Integer literals] in Literal
cvtLitInteger dflags _ (Just sdatacon) i
| inIntRange dflags i -- Special case for small integers
= mkConApp sdatacon [Lit (mkMachInt dflags i)]
cvtLitInteger dflags mk_integer _ i
= mkApps (Var mk_integer) [isNonNegative, ints]
where isNonNegative = if i < 0 then mkConApp falseDataCon []
else mkConApp trueDataCon []
ints = mkListExpr intTy (f (abs i))
f 0 = []
f x = let low = x .&. mask
high = x `shiftR` bits
in mkConApp intDataCon [Lit (mkMachInt dflags low)] : f high
bits = 31
mask = 2 ^ bits - 1
-- ---------------------------------------------------------------------------
-- CpeBody: produces a result satisfying CpeBody
-- ---------------------------------------------------------------------------
cpeBodyNF :: CorePrepEnv -> CoreExpr -> UniqSM CpeBody
cpeBodyNF env expr
= do { (floats, body) <- cpeBody env expr
; return (wrapBinds floats body) }
--------
cpeBody :: CorePrepEnv -> CoreExpr -> UniqSM (Floats, CpeBody)
cpeBody env expr
= do { (floats1, rhs) <- cpeRhsE env expr
; (floats2, body) <- rhsToBody rhs
; return (floats1 `appendFloats` floats2, body) }
--------
rhsToBodyNF :: CpeRhs -> UniqSM CpeBody
rhsToBodyNF rhs = do { (floats,body) <- rhsToBody rhs
; return (wrapBinds floats body) }
--------
rhsToBody :: CpeRhs -> UniqSM (Floats, CpeBody)
-- Remove top level lambdas by let-binding
rhsToBody (Tick t expr)
| tickishScoped t == NoScope -- only float out of non-scoped annotations
= do { (floats, expr') <- rhsToBody expr
; return (floats, mkTick t expr') }
rhsToBody (Cast e co)
-- You can get things like
-- case e of { p -> coerce t (\s -> ...) }
= do { (floats, e') <- rhsToBody e
; return (floats, Cast e' co) }
rhsToBody expr@(Lam {})
| Just no_lam_result <- tryEtaReducePrep bndrs body
= return (emptyFloats, no_lam_result)
| all isTyVar bndrs -- Type lambdas are ok
= return (emptyFloats, expr)
| otherwise -- Some value lambdas
= do { fn <- newVar (exprType expr)
; let rhs = cpeEtaExpand (exprArity expr) expr
float = FloatLet (NonRec fn rhs)
; return (unitFloat float, Var fn) }
where
(bndrs,body) = collectBinders expr
rhsToBody expr = return (emptyFloats, expr)
-- ---------------------------------------------------------------------------
-- CpeApp: produces a result satisfying CpeApp
-- ---------------------------------------------------------------------------
cpeApp :: CorePrepEnv -> CoreExpr -> UniqSM (Floats, CpeRhs)
-- May return a CpeRhs because of saturating primops
cpeApp env expr
= do { (app, (head,depth), _, floats, ss) <- collect_args expr 0
; MASSERT(null ss) -- make sure we used all the strictness info
-- Now deal with the function
; case head of
Var fn_id -> do { sat_app <- maybeSaturate fn_id app depth
; return (floats, sat_app) }
_other -> return (floats, app) }
where
-- Deconstruct and rebuild the application, floating any non-atomic
-- arguments to the outside. We collect the type of the expression,
-- the head of the application, and the number of actual value arguments,
-- all of which are used to possibly saturate this application if it
-- has a constructor or primop at the head.
collect_args
:: CoreExpr
-> Int -- Current app depth
-> UniqSM (CpeApp, -- The rebuilt expression
(CoreExpr,Int), -- The head of the application,
-- and no. of args it was applied to
Type, -- Type of the whole expr
Floats, -- Any floats we pulled out
[Demand]) -- Remaining argument demands
collect_args (App fun arg@(Type arg_ty)) depth
= do { (fun',hd,fun_ty,floats,ss) <- collect_args fun depth
; return (App fun' arg, hd, applyTy fun_ty arg_ty, floats, ss) }
collect_args (App fun arg@(Coercion arg_co)) depth
= do { (fun',hd,fun_ty,floats,ss) <- collect_args fun depth
; return (App fun' arg, hd, applyCo fun_ty arg_co, floats, ss) }
collect_args (App fun arg) depth
= do { (fun',hd,fun_ty,floats,ss) <- collect_args fun (depth+1)
; let
(ss1, ss_rest) = case ss of
(ss1:ss_rest) -> (ss1, ss_rest)
[] -> (topDmd, [])
(arg_ty, res_ty) = expectJust "cpeBody:collect_args" $
splitFunTy_maybe fun_ty
; (fs, arg') <- cpeArg env ss1 arg arg_ty
; return (App fun' arg', hd, res_ty, fs `appendFloats` floats, ss_rest) }
collect_args (Var v) depth
= do { v1 <- fiddleCCall v
; let v2 = lookupCorePrepEnv env v1
; return (Var v2, (Var v2, depth), idType v2, emptyFloats, stricts) }
where
stricts = case idStrictness v of
StrictSig (DmdType _ demands _)
| listLengthCmp demands depth /= GT -> demands
-- length demands <= depth
| otherwise -> []
-- If depth < length demands, then we have too few args to
-- satisfy strictness info so we have to ignore all the
-- strictness info, e.g. + (error "urk")
-- Here, we can't evaluate the arg strictly, because this
-- partial application might be seq'd
collect_args (Cast fun co) depth
= do { let Pair _ty1 ty2 = coercionKind co
; (fun', hd, _, floats, ss) <- collect_args fun depth
; return (Cast fun' co, hd, ty2, floats, ss) }
collect_args (Tick tickish fun) depth
| tickishPlace tickish == PlaceNonLam
&& tickish `tickishScopesLike` SoftScope
= do { (fun',hd,fun_ty,floats,ss) <- collect_args fun depth
-- See [Floating Ticks in CorePrep]
; return (fun',hd,fun_ty,addFloat floats (FloatTick tickish),ss) }
-- N-variable fun, better let-bind it
collect_args fun depth
= do { (fun_floats, fun') <- cpeArg env evalDmd fun ty
-- The evalDmd says that it's sure to be evaluated,
-- so we'll end up case-binding it
; return (fun', (fun', depth), ty, fun_floats, []) }
where
ty = exprType fun
-- ---------------------------------------------------------------------------
-- CpeArg: produces a result satisfying CpeArg
-- ---------------------------------------------------------------------------
-- This is where we arrange that a non-trivial argument is let-bound
cpeArg :: CorePrepEnv -> Demand
-> CoreArg -> Type -> UniqSM (Floats, CpeTriv)
cpeArg env dmd arg arg_ty
= do { (floats1, arg1) <- cpeRhsE env arg -- arg1 can be a lambda
; (floats2, arg2) <- if want_float floats1 arg1
then return (floats1, arg1)
else do { body1 <- rhsToBodyNF arg1
; return (emptyFloats, wrapBinds floats1 body1) }
-- Else case: arg1 might have lambdas, and we can't
-- put them inside a wrapBinds
; if cpe_ExprIsTrivial arg2 -- Do not eta expand a trivial argument
then return (floats2, arg2)
else do
{ v <- newVar arg_ty
; let arg3 = cpeEtaExpand (exprArity arg2) arg2
arg_float = mkFloat dmd is_unlifted v arg3
; return (addFloat floats2 arg_float, varToCoreExpr v) } }
where
is_unlifted = isUnLiftedType arg_ty
is_strict = isStrictDmd dmd
want_float = wantFloatNested NonRecursive (is_strict || is_unlifted)
{-
Note [Floating unlifted arguments]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider C (let v* = expensive in v)
where the "*" indicates "will be demanded". Usually v will have been
inlined by now, but let's suppose it hasn't (see Trac #2756). Then we
do *not* want to get
let v* = expensive in C v
because that has different strictness. Hence the use of 'allLazy'.
(NB: the let v* turns into a FloatCase, in mkLocalNonRec.)
------------------------------------------------------------------------------
-- Building the saturated syntax
-- ---------------------------------------------------------------------------
maybeSaturate deals with saturating primops and constructors
The type is the type of the entire application
-}
maybeSaturate :: Id -> CpeApp -> Int -> UniqSM CpeRhs
maybeSaturate fn expr n_args
| Just DataToTagOp <- isPrimOpId_maybe fn -- DataToTag must have an evaluated arg
-- A gruesome special case
= saturateDataToTag sat_expr
| hasNoBinding fn -- There's no binding
= return sat_expr
| otherwise
= return expr
where
fn_arity = idArity fn
excess_arity = fn_arity - n_args
sat_expr = cpeEtaExpand excess_arity expr
-------------
saturateDataToTag :: CpeApp -> UniqSM CpeApp
-- See Note [dataToTag magic]
saturateDataToTag sat_expr
= do { let (eta_bndrs, eta_body) = collectBinders sat_expr
; eta_body' <- eval_data2tag_arg eta_body
; return (mkLams eta_bndrs eta_body') }
where
eval_data2tag_arg :: CpeApp -> UniqSM CpeBody
eval_data2tag_arg app@(fun `App` arg)
| exprIsHNF arg -- Includes nullary constructors
= return app -- The arg is evaluated
| otherwise -- Arg not evaluated, so evaluate it
= do { arg_id <- newVar (exprType arg)
; let arg_id1 = setIdUnfolding arg_id evaldUnfolding
; return (Case arg arg_id1 (exprType app)
[(DEFAULT, [], fun `App` Var arg_id1)]) }
eval_data2tag_arg (Tick t app) -- Scc notes can appear
= do { app' <- eval_data2tag_arg app
; return (Tick t app') }
eval_data2tag_arg other -- Should not happen
= pprPanic "eval_data2tag" (ppr other)
{-
Note [dataToTag magic]
~~~~~~~~~~~~~~~~~~~~~~
Horrid: we must ensure that the arg of data2TagOp is evaluated
(data2tag x) --> (case x of y -> data2tag y)
(yuk yuk) take into account the lambdas we've now introduced
How might it not be evaluated? Well, we might have floated it out
of the scope of a `seq`, or dropped the `seq` altogether.
************************************************************************
* *
Simple CoreSyn operations
* *
************************************************************************
-}
cpe_ExprIsTrivial :: CoreExpr -> Bool
-- Version that doesn't consider an scc annotation to be trivial.
cpe_ExprIsTrivial (Var _) = True
cpe_ExprIsTrivial (Type _) = True
cpe_ExprIsTrivial (Coercion _) = True
cpe_ExprIsTrivial (Lit _) = True
cpe_ExprIsTrivial (App e arg) = isTypeArg arg && cpe_ExprIsTrivial e
cpe_ExprIsTrivial (Tick t e) = not (tickishIsCode t) && cpe_ExprIsTrivial e
cpe_ExprIsTrivial (Cast e _) = cpe_ExprIsTrivial e
cpe_ExprIsTrivial (Lam b body) | isTyVar b = cpe_ExprIsTrivial body
cpe_ExprIsTrivial _ = False
{-
-- -----------------------------------------------------------------------------
-- Eta reduction
-- -----------------------------------------------------------------------------
Note [Eta expansion]
~~~~~~~~~~~~~~~~~~~~~
Eta expand to match the arity claimed by the binder Remember,
CorePrep must not change arity
Eta expansion might not have happened already, because it is done by
the simplifier only when there at least one lambda already.
NB1:we could refrain when the RHS is trivial (which can happen
for exported things). This would reduce the amount of code
generated (a little) and make things a little words for
code compiled without -O. The case in point is data constructor
wrappers.
NB2: we have to be careful that the result of etaExpand doesn't
invalidate any of the assumptions that CorePrep is attempting
to establish. One possible cause is eta expanding inside of
an SCC note - we're now careful in etaExpand to make sure the
SCC is pushed inside any new lambdas that are generated.
Note [Eta expansion and the CorePrep invariants]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It turns out to be much much easier to do eta expansion
*after* the main CorePrep stuff. But that places constraints
on the eta expander: given a CpeRhs, it must return a CpeRhs.
For example here is what we do not want:
f = /\a -> g (h 3) -- h has arity 2
After ANFing we get
f = /\a -> let s = h 3 in g s
and now we do NOT want eta expansion to give
f = /\a -> \ y -> (let s = h 3 in g s) y
Instead CoreArity.etaExpand gives
f = /\a -> \y -> let s = h 3 in g s y
-}
cpeEtaExpand :: Arity -> CpeRhs -> CpeRhs
cpeEtaExpand arity expr
| arity == 0 = expr
| otherwise = etaExpand arity expr
{-
-- -----------------------------------------------------------------------------
-- Eta reduction
-- -----------------------------------------------------------------------------
Why try eta reduction? Hasn't the simplifier already done eta?
But the simplifier only eta reduces if that leaves something
trivial (like f, or f Int). But for deLam it would be enough to
get to a partial application:
case x of { p -> \xs. map f xs }
==> case x of { p -> map f }
-}
tryEtaReducePrep :: [CoreBndr] -> CoreExpr -> Maybe CoreExpr
tryEtaReducePrep bndrs expr@(App _ _)
| ok_to_eta_reduce f
, n_remaining >= 0
, and (zipWith ok bndrs last_args)
, not (any (`elemVarSet` fvs_remaining) bndrs)
, exprIsHNF remaining_expr -- Don't turn value into a non-value
-- else the behaviour with 'seq' changes
= Just remaining_expr
where
(f, args) = collectArgs expr
remaining_expr = mkApps f remaining_args
fvs_remaining = exprFreeVars remaining_expr
(remaining_args, last_args) = splitAt n_remaining args
n_remaining = length args - length bndrs
ok bndr (Var arg) = bndr == arg
ok _ _ = False
-- We can't eta reduce something which must be saturated.
ok_to_eta_reduce (Var f) = not (hasNoBinding f)
ok_to_eta_reduce _ = False -- Safe. ToDo: generalise
tryEtaReducePrep bndrs (Let bind@(NonRec _ r) body)
| not (any (`elemVarSet` fvs) bndrs)
= case tryEtaReducePrep bndrs body of
Just e -> Just (Let bind e)
Nothing -> Nothing
where
fvs = exprFreeVars r
tryEtaReducePrep bndrs (Tick tickish e)
= fmap (mkTick tickish) $ tryEtaReducePrep bndrs e
tryEtaReducePrep _ _ = Nothing
{-
************************************************************************
* *
Floats
* *
************************************************************************
Note [Pin demand info on floats]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We pin demand info on floated lets so that we can see the one-shot thunks.
-}
data FloatingBind
= FloatLet CoreBind -- Rhs of bindings are CpeRhss
-- They are always of lifted type;
-- unlifted ones are done with FloatCase
| FloatCase
Id CpeBody
Bool -- The bool indicates "ok-for-speculation"
-- | See Note [Floating Ticks in CorePrep]
| FloatTick (Tickish Id)
data Floats = Floats OkToSpec (OrdList FloatingBind)
instance Outputable FloatingBind where
ppr (FloatLet b) = ppr b
ppr (FloatCase b r ok) = brackets (ppr ok) <+> ppr b <+> equals <+> ppr r
ppr (FloatTick t) = ppr t
instance Outputable Floats where
ppr (Floats flag fs) = ptext (sLit "Floats") <> brackets (ppr flag) <+>
braces (vcat (map ppr (fromOL fs)))
instance Outputable OkToSpec where
ppr OkToSpec = ptext (sLit "OkToSpec")
ppr IfUnboxedOk = ptext (sLit "IfUnboxedOk")
ppr NotOkToSpec = ptext (sLit "NotOkToSpec")
-- Can we float these binds out of the rhs of a let? We cache this decision
-- to avoid having to recompute it in a non-linear way when there are
-- deeply nested lets.
data OkToSpec
= OkToSpec -- Lazy bindings of lifted type
| IfUnboxedOk -- A mixture of lazy lifted bindings and n
-- ok-to-speculate unlifted bindings
| NotOkToSpec -- Some not-ok-to-speculate unlifted bindings
mkFloat :: Demand -> Bool -> Id -> CpeRhs -> FloatingBind
mkFloat dmd is_unlifted bndr rhs
| use_case = FloatCase bndr rhs (exprOkForSpeculation rhs)
| is_hnf = FloatLet (NonRec bndr rhs)
| otherwise = FloatLet (NonRec (setIdDemandInfo bndr dmd) rhs)
-- See Note [Pin demand info on floats]
where
is_hnf = exprIsHNF rhs
is_strict = isStrictDmd dmd
use_case = is_unlifted || is_strict && not is_hnf
-- Don't make a case for a value binding,
-- even if it's strict. Otherwise we get
-- case (\x -> e) of ...!
emptyFloats :: Floats
emptyFloats = Floats OkToSpec nilOL
isEmptyFloats :: Floats -> Bool
isEmptyFloats (Floats _ bs) = isNilOL bs
wrapBinds :: Floats -> CpeBody -> CpeBody
wrapBinds (Floats _ binds) body
= foldrOL mk_bind body binds
where
mk_bind (FloatCase bndr rhs _) body = Case rhs bndr (exprType body) [(DEFAULT, [], body)]
mk_bind (FloatLet bind) body = Let bind body
mk_bind (FloatTick tickish) body = mkTick tickish body
addFloat :: Floats -> FloatingBind -> Floats
addFloat (Floats ok_to_spec floats) new_float
= Floats (combine ok_to_spec (check new_float)) (floats `snocOL` new_float)
where
check (FloatLet _) = OkToSpec
check (FloatCase _ _ ok_for_spec)
| ok_for_spec = IfUnboxedOk
| otherwise = NotOkToSpec
check FloatTick{} = OkToSpec
-- The ok-for-speculation flag says that it's safe to
-- float this Case out of a let, and thereby do it more eagerly
-- We need the top-level flag because it's never ok to float
-- an unboxed binding to the top level
unitFloat :: FloatingBind -> Floats
unitFloat = addFloat emptyFloats
appendFloats :: Floats -> Floats -> Floats
appendFloats (Floats spec1 floats1) (Floats spec2 floats2)
= Floats (combine spec1 spec2) (floats1 `appOL` floats2)
concatFloats :: [Floats] -> OrdList FloatingBind
concatFloats = foldr (\ (Floats _ bs1) bs2 -> appOL bs1 bs2) nilOL
combine :: OkToSpec -> OkToSpec -> OkToSpec
combine NotOkToSpec _ = NotOkToSpec
combine _ NotOkToSpec = NotOkToSpec
combine IfUnboxedOk _ = IfUnboxedOk
combine _ IfUnboxedOk = IfUnboxedOk
combine _ _ = OkToSpec
deFloatTop :: Floats -> [CoreBind]
-- For top level only; we don't expect any FloatCases
deFloatTop (Floats _ floats)
= foldrOL get [] floats
where
get (FloatLet b) bs = occurAnalyseRHSs b : bs
get b _ = pprPanic "corePrepPgm" (ppr b)
-- See Note [Dead code in CorePrep]
occurAnalyseRHSs (NonRec x e) = NonRec x (occurAnalyseExpr_NoBinderSwap e)
occurAnalyseRHSs (Rec xes) = Rec [(x, occurAnalyseExpr_NoBinderSwap e) | (x, e) <- xes]
---------------------------------------------------------------------------
canFloatFromNoCaf :: Platform -> Floats -> CpeRhs -> Maybe (Floats, CpeRhs)
-- Note [CafInfo and floating]
canFloatFromNoCaf platform (Floats ok_to_spec fs) rhs
| OkToSpec <- ok_to_spec -- Worth trying
, Just (subst, fs') <- go (emptySubst, nilOL) (fromOL fs)
= Just (Floats OkToSpec fs', subst_expr subst rhs)
| otherwise
= Nothing
where
subst_expr = substExpr (text "CorePrep")
go :: (Subst, OrdList FloatingBind) -> [FloatingBind]
-> Maybe (Subst, OrdList FloatingBind)
go (subst, fbs_out) [] = Just (subst, fbs_out)
go (subst, fbs_out) (FloatLet (NonRec b r) : fbs_in)
| rhs_ok r
= go (subst', fbs_out `snocOL` new_fb) fbs_in
where
(subst', b') = set_nocaf_bndr subst b
new_fb = FloatLet (NonRec b' (subst_expr subst r))
go (subst, fbs_out) (FloatLet (Rec prs) : fbs_in)
| all rhs_ok rs
= go (subst', fbs_out `snocOL` new_fb) fbs_in
where
(bs,rs) = unzip prs
(subst', bs') = mapAccumL set_nocaf_bndr subst bs
rs' = map (subst_expr subst') rs
new_fb = FloatLet (Rec (bs' `zip` rs'))
go (subst, fbs_out) (ft@FloatTick{} : fbs_in)
= go (subst, fbs_out `snocOL` ft) fbs_in
go _ _ = Nothing -- Encountered a caffy binding
------------
set_nocaf_bndr subst bndr
= (extendIdSubst subst bndr (Var bndr'), bndr')
where
bndr' = bndr `setIdCafInfo` NoCafRefs
------------
rhs_ok :: CoreExpr -> Bool
-- We can only float to top level from a NoCaf thing if
-- the new binding is static. However it can't mention
-- any non-static things or it would *already* be Caffy
rhs_ok = rhsIsStatic platform (\_ -> False)
(\i -> pprPanic "rhsIsStatic" (integer i))
-- Integer literals should not show up
wantFloatNested :: RecFlag -> Bool -> Floats -> CpeRhs -> Bool
wantFloatNested is_rec strict_or_unlifted floats rhs
= isEmptyFloats floats
|| strict_or_unlifted
|| (allLazyNested is_rec floats && exprIsHNF rhs)
-- Why the test for allLazyNested?
-- v = f (x `divInt#` y)
-- we don't want to float the case, even if f has arity 2,
-- because floating the case would make it evaluated too early
allLazyTop :: Floats -> Bool
allLazyTop (Floats OkToSpec _) = True
allLazyTop _ = False
allLazyNested :: RecFlag -> Floats -> Bool
allLazyNested _ (Floats OkToSpec _) = True
allLazyNested _ (Floats NotOkToSpec _) = False
allLazyNested is_rec (Floats IfUnboxedOk _) = isNonRec is_rec
{-
************************************************************************
* *
Cloning
* *
************************************************************************
-}
-- ---------------------------------------------------------------------------
-- The environment
-- ---------------------------------------------------------------------------
data CorePrepEnv = CPE {
cpe_dynFlags :: DynFlags,
cpe_env :: (IdEnv Id), -- Clone local Ids
cpe_mkIntegerId :: Id,
cpe_integerSDataCon :: Maybe DataCon
}
lookupMkIntegerName :: DynFlags -> HscEnv -> IO Id
lookupMkIntegerName dflags hsc_env
= guardIntegerUse dflags $ liftM tyThingId $
lookupGlobal hsc_env mkIntegerName
lookupIntegerSDataConName :: DynFlags -> HscEnv -> IO (Maybe DataCon)
lookupIntegerSDataConName dflags hsc_env = case cIntegerLibraryType of
IntegerGMP -> guardIntegerUse dflags $ liftM (Just . tyThingDataCon) $
lookupGlobal hsc_env integerSDataConName
IntegerSimple -> return Nothing
-- | Helper for 'lookupMkIntegerName' and 'lookupIntegerSDataConName'
guardIntegerUse :: DynFlags -> IO a -> IO a
guardIntegerUse dflags act
| thisPackage dflags == primUnitId
= return $ panic "Can't use Integer in ghc-prim"
| thisPackage dflags == integerUnitId
= return $ panic "Can't use Integer in integer-*"
| otherwise = act
mkInitialCorePrepEnv :: DynFlags -> HscEnv -> IO CorePrepEnv
mkInitialCorePrepEnv dflags hsc_env
= do mkIntegerId <- lookupMkIntegerName dflags hsc_env
integerSDataCon <- lookupIntegerSDataConName dflags hsc_env
return $ CPE {
cpe_dynFlags = dflags,
cpe_env = emptyVarEnv,
cpe_mkIntegerId = mkIntegerId,
cpe_integerSDataCon = integerSDataCon
}
extendCorePrepEnv :: CorePrepEnv -> Id -> Id -> CorePrepEnv
extendCorePrepEnv cpe id id'
= cpe { cpe_env = extendVarEnv (cpe_env cpe) id id' }
extendCorePrepEnvList :: CorePrepEnv -> [(Id,Id)] -> CorePrepEnv
extendCorePrepEnvList cpe prs
= cpe { cpe_env = extendVarEnvList (cpe_env cpe) prs }
lookupCorePrepEnv :: CorePrepEnv -> Id -> Id
lookupCorePrepEnv cpe id
= case lookupVarEnv (cpe_env cpe) id of
Nothing -> id
Just id' -> id'
getMkIntegerId :: CorePrepEnv -> Id
getMkIntegerId = cpe_mkIntegerId
------------------------------------------------------------------------------
-- Cloning binders
-- ---------------------------------------------------------------------------
cpCloneBndrs :: CorePrepEnv -> [Var] -> UniqSM (CorePrepEnv, [Var])
cpCloneBndrs env bs = mapAccumLM cpCloneBndr env bs
cpCloneBndr :: CorePrepEnv -> Var -> UniqSM (CorePrepEnv, Var)
cpCloneBndr env bndr
| isLocalId bndr, not (isCoVar bndr)
= do bndr' <- setVarUnique bndr <$> getUniqueM
-- We are going to OccAnal soon, so drop (now-useless) rules/unfoldings
-- so that we can drop more stuff as dead code.
-- See also Note [Dead code in CorePrep]
let bndr'' = bndr' `setIdUnfolding` noUnfolding
`setIdSpecialisation` emptyRuleInfo
return (extendCorePrepEnv env bndr bndr'', bndr'')
| otherwise -- Top level things, which we don't want
-- to clone, have become GlobalIds by now
-- And we don't clone tyvars, or coercion variables
= return (env, bndr)
------------------------------------------------------------------------------
-- Cloning ccall Ids; each must have a unique name,
-- to give the code generator a handle to hang it on
-- ---------------------------------------------------------------------------
fiddleCCall :: Id -> UniqSM Id
fiddleCCall id
| isFCallId id = (id `setVarUnique`) <$> getUniqueM
| otherwise = return id
------------------------------------------------------------------------------
-- Generating new binders
-- ---------------------------------------------------------------------------
newVar :: Type -> UniqSM Id
newVar ty
= seqType ty `seq` do
uniq <- getUniqueM
return (mkSysLocal (fsLit "sat") uniq ty)
------------------------------------------------------------------------------
-- Floating ticks
-- ---------------------------------------------------------------------------
--
-- Note [Floating Ticks in CorePrep]
--
-- It might seem counter-intuitive to float ticks by default, given
-- that we don't actually want to move them if we can help it. On the
-- other hand, nothing gets very far in CorePrep anyway, and we want
-- to preserve the order of let bindings and tick annotations in
-- relation to each other. For example, if we just wrapped let floats
-- when they pass through ticks, we might end up performing the
-- following transformation:
--
-- src<...> let foo = bar in baz
-- ==> let foo = src<...> bar in src<...> baz
--
-- Because the let-binding would float through the tick, and then
-- immediately materialize, achieving nothing but decreasing tick
-- accuracy. The only special case is the following scenario:
--
-- let foo = src<...> (let a = b in bar) in baz
-- ==> let foo = src<...> bar; a = src<...> b in baz
--
-- Here we would not want the source tick to end up covering "baz" and
-- therefore refrain from pushing ticks outside. Instead, we copy them
-- into the floating binds (here "a") in cpePair. Note that where "b"
-- or "bar" are (value) lambdas we have to push the annotations
-- further inside in order to uphold our rules.
--
-- All of this is implemented below in @wrapTicks@.
-- | Like wrapFloats, but only wraps tick floats
wrapTicks :: Floats -> CoreExpr -> (Floats, CoreExpr)
wrapTicks (Floats flag floats0) expr = (Floats flag floats1, expr')
where (floats1, expr') = foldrOL go (nilOL, expr) floats0
go (FloatTick t) (fs, e) = ASSERT(tickishPlace t == PlaceNonLam)
(mapOL (wrap t) fs, mkTick t e)
go other (fs, e) = (other `consOL` fs, e)
wrap t (FloatLet bind) = FloatLet (wrapBind t bind)
wrap t (FloatCase b r ok) = FloatCase b (mkTick t r) ok
wrap _ other = pprPanic "wrapTicks: unexpected float!"
(ppr other)
wrapBind t (NonRec binder rhs) = NonRec binder (mkTick t rhs)
wrapBind t (Rec pairs) = Rec (mapSnd (mkTick t) pairs)
|
elieux/ghc
|
compiler/coreSyn/CorePrep.hs
|
bsd-3-clause
| 50,522
| 56
| 17
| 13,945
| 8,807
| 4,642
| 4,165
| 585
| 9
|
{-# 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.ElastiCache.ModifyCacheSubnetGroup
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- 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 <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | The /ModifyCacheSubnetGroup/ action modifies an existing cache subnet group.
--
-- <http://docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/API_ModifyCacheSubnetGroup.html>
module Network.AWS.ElastiCache.ModifyCacheSubnetGroup
(
-- * Request
ModifyCacheSubnetGroup
-- ** Request constructor
, modifyCacheSubnetGroup
-- ** Request lenses
, mcsgCacheSubnetGroupDescription
, mcsgCacheSubnetGroupName
, mcsgSubnetIds
-- * Response
, ModifyCacheSubnetGroupResponse
-- ** Response constructor
, modifyCacheSubnetGroupResponse
-- ** Response lenses
, mcsgrCacheSubnetGroup
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.ElastiCache.Types
import qualified GHC.Exts
data ModifyCacheSubnetGroup = ModifyCacheSubnetGroup
{ _mcsgCacheSubnetGroupDescription :: Maybe Text
, _mcsgCacheSubnetGroupName :: Text
, _mcsgSubnetIds :: List "member" Text
} deriving (Eq, Ord, Read, Show)
-- | 'ModifyCacheSubnetGroup' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'mcsgCacheSubnetGroupDescription' @::@ 'Maybe' 'Text'
--
-- * 'mcsgCacheSubnetGroupName' @::@ 'Text'
--
-- * 'mcsgSubnetIds' @::@ ['Text']
--
modifyCacheSubnetGroup :: Text -- ^ 'mcsgCacheSubnetGroupName'
-> ModifyCacheSubnetGroup
modifyCacheSubnetGroup p1 = ModifyCacheSubnetGroup
{ _mcsgCacheSubnetGroupName = p1
, _mcsgCacheSubnetGroupDescription = Nothing
, _mcsgSubnetIds = mempty
}
-- | A description for the cache subnet group.
mcsgCacheSubnetGroupDescription :: Lens' ModifyCacheSubnetGroup (Maybe Text)
mcsgCacheSubnetGroupDescription =
lens _mcsgCacheSubnetGroupDescription
(\s a -> s { _mcsgCacheSubnetGroupDescription = a })
-- | The name for the cache subnet group. This value is stored as a lowercase
-- string.
--
-- Constraints: Must contain no more than 255 alphanumeric characters or
-- hyphens.
--
-- Example: 'mysubnetgroup'
mcsgCacheSubnetGroupName :: Lens' ModifyCacheSubnetGroup Text
mcsgCacheSubnetGroupName =
lens _mcsgCacheSubnetGroupName
(\s a -> s { _mcsgCacheSubnetGroupName = a })
-- | The EC2 subnet IDs for the cache subnet group.
mcsgSubnetIds :: Lens' ModifyCacheSubnetGroup [Text]
mcsgSubnetIds = lens _mcsgSubnetIds (\s a -> s { _mcsgSubnetIds = a }) . _List
newtype ModifyCacheSubnetGroupResponse = ModifyCacheSubnetGroupResponse
{ _mcsgrCacheSubnetGroup :: Maybe CacheSubnetGroup
} deriving (Eq, Read, Show)
-- | 'ModifyCacheSubnetGroupResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'mcsgrCacheSubnetGroup' @::@ 'Maybe' 'CacheSubnetGroup'
--
modifyCacheSubnetGroupResponse :: ModifyCacheSubnetGroupResponse
modifyCacheSubnetGroupResponse = ModifyCacheSubnetGroupResponse
{ _mcsgrCacheSubnetGroup = Nothing
}
mcsgrCacheSubnetGroup :: Lens' ModifyCacheSubnetGroupResponse (Maybe CacheSubnetGroup)
mcsgrCacheSubnetGroup =
lens _mcsgrCacheSubnetGroup (\s a -> s { _mcsgrCacheSubnetGroup = a })
instance ToPath ModifyCacheSubnetGroup where
toPath = const "/"
instance ToQuery ModifyCacheSubnetGroup where
toQuery ModifyCacheSubnetGroup{..} = mconcat
[ "CacheSubnetGroupDescription" =? _mcsgCacheSubnetGroupDescription
, "CacheSubnetGroupName" =? _mcsgCacheSubnetGroupName
, "SubnetIds" =? _mcsgSubnetIds
]
instance ToHeaders ModifyCacheSubnetGroup
instance AWSRequest ModifyCacheSubnetGroup where
type Sv ModifyCacheSubnetGroup = ElastiCache
type Rs ModifyCacheSubnetGroup = ModifyCacheSubnetGroupResponse
request = post "ModifyCacheSubnetGroup"
response = xmlResponse
instance FromXML ModifyCacheSubnetGroupResponse where
parseXML = withElement "ModifyCacheSubnetGroupResult" $ \x -> ModifyCacheSubnetGroupResponse
<$> x .@? "CacheSubnetGroup"
|
romanb/amazonka
|
amazonka-elasticache/gen/Network/AWS/ElastiCache/ModifyCacheSubnetGroup.hs
|
mpl-2.0
| 5,031
| 0
| 10
| 1,006
| 568
| 345
| 223
| 70
| 1
|
import BasePrelude
import MTLPrelude
import Data.Text (Text)
import Data.Vector (Vector)
import Data.Time
import qualified Hasql as H
import qualified Hasql.Postgres as H
import qualified ListT
import qualified Test.QuickCheck.Gen as Q
import qualified Test.QuickCheck.Arbitrary as Q
import qualified Test.QuickCheck.Instances
main = do
rows :: [(Text, Day)] <-
liftIO $ replicateM 100 $
(,) <$> Q.generate Q.arbitrary <*> Q.generate Q.arbitrary
H.session (H.PostgresParams host port user password db) (fromJust $ H.sessionSettings 1 30) $ do
H.tx Nothing $ do
H.unit [H.stmt|DROP TABLE IF EXISTS a|]
H.unit [H.stmt|CREATE TABLE a (id SERIAL NOT NULL,
name VARCHAR NOT NULL,
birthday DATE,
PRIMARY KEY (id))|]
forM_ rows $ \(name, birthday) -> do
H.unit $ [H.stmt|INSERT INTO a (name, birthday) VALUES (?, ?)|] name birthday
replicateM_ 2000 $ do
H.tx Nothing $ do
H.list $ [H.stmt|SELECT * FROM a|] :: H.Tx H.Postgres s [(Int, Text, Day)]
host = "localhost"
port = 5432
user = "postgres"
password = ""
db = "postgres"
|
mikeplus64/hasql-postgres
|
profiling/Main.hs
|
mit
| 1,201
| 0
| 19
| 336
| 349
| 195
| 154
| -1
| -1
|
{- Contributed by Liyang HU <haskell.org@liyang.hu> -}
module Main where
import Prelude
import Control.Applicative
import Control.Monad
import Control.DeepSeq
import Data.Time
import Data.Time.Clock.POSIX
import System.Random
main :: IO ()
main = do
ts <- replicateM 100000 $ do
t <- posixSecondsToUTCTime . realToFrac <$>
( (*) . fromInteger <$> randomRIO (-15*10^21, 15*10^21) <*>
randomIO :: IO Double ) :: IO UTCTime
rnf t `seq` return t
now <- getCurrentTime
print . sum $ map (diffUTCTime now) ts
print =<< flip diffUTCTime now <$> getCurrentTime
|
bergmark/time
|
test/Test/RealToFracBenchmark.hs
|
bsd-3-clause
| 616
| 0
| 20
| 146
| 200
| 104
| 96
| 18
| 1
|
-- |
-- Module : Crypto.Internal.Endian
-- License : BSD-style
-- Maintainer : Vincent Hanquez <vincent@snarc.org>
-- Stability : stable
-- Portability : good
--
{-# LANGUAGE CPP #-}
module Crypto.Internal.Endian
( fromBE64, toBE64
, fromLE64, toLE64
) where
import Crypto.Internal.Compat (byteSwap64)
import Data.Word (Word64)
#ifdef ARCH_IS_LITTLE_ENDIAN
fromLE64 :: Word64 -> Word64
fromLE64 = id
toLE64 :: Word64 -> Word64
toLE64 = id
fromBE64 :: Word64 -> Word64
fromBE64 = byteSwap64
toBE64 :: Word64 -> Word64
toBE64 = byteSwap64
#else
fromLE64 :: Word64 -> Word64
fromLE64 = byteSwap64
toLE64 :: Word64 -> Word64
toLE64 = byteSwap64
fromBE64 :: Word64 -> Word64
fromBE64 = id
toBE64 :: Word64 -> Word64
toBE64 = id
#endif
|
vincenthz/cryptonite
|
Crypto/Internal/Endian.hs
|
bsd-3-clause
| 762
| 0
| 5
| 145
| 109
| 70
| 39
| 14
| 1
|
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_HADDOCK show-extensions #-}
-- |
-- Module : Yi.Mode.Buffers
-- License : GPL-2
-- Maintainer : yi-devel@googlegroups.com
-- Stability : experimental
-- Portability : portable
--
-- A minimalist emulation of emacs buffer menu mode, to be fleshed out later
module Yi.Mode.Buffers (listBuffers) where
import Control.Category ((>>>))
import Lens.Micro.Platform ((.=), (%~), (.~))
import Data.List.NonEmpty (toList)
import qualified Data.Text as T (intercalate, pack)
import System.FilePath (takeFileName)
import Yi.Buffer
import Yi.Editor
import Yi.Keymap (Keymap, YiM, topKeymapA)
import Yi.Keymap.Keys
import qualified Yi.Rope as R (fromText, toString)
-- | Retrieve buffer list and open a them in buffer mode using the
-- 'bufferKeymap'.
listBuffers :: YiM ()
listBuffers = do
withEditor $ do
bs <- toList <$> getBufferStack
let bufferList = R.fromText . T.intercalate "\n" $ map identString bs
bufRef <- stringToNewBuffer (MemBuffer "Buffer List") bufferList
switchToBufferE bufRef
withCurrentBuffer $ do
modifyMode $ modeKeymapA .~ topKeymapA %~ bufferKeymap
>>> modeNameA .~ "buffers"
readOnlyA .= True
-- | Switch to the buffer with name at current name. If it it starts
-- with a @/@ then assume it's a file and try to open it that way.
switch :: YiM ()
switch = do
-- the YiString -> FilePath -> Text conversion sucks
s <- R.toString <$> withCurrentBuffer readLnB
let short = T.pack $ if take 1 s == "/" then takeFileName s else s
withEditor $ switchToBufferWithNameE short
-- | Keymap for the buffer mode.
--
-- @
-- __p__ → line up
-- __n__ or __SPACE__ → line down
-- __ENTER__ or __f__ → open buffer
-- __v__ → open buffer as read-only
-- @
bufferKeymap :: Keymap -> Keymap
bufferKeymap = important $ choice
[ char 'p' ?>>! lineUp
, oneOf [ char 'n', char ' ' ] >>! lineDown
, oneOf [ spec KEnter, char 'f' ] >>! (switch >> setReadOnly False)
, char 'v' ?>>! (switch >> setReadOnly True)
]
where
setReadOnly = withCurrentBuffer . (.=) readOnlyA
|
siddhanathan/yi
|
yi-misc-modes/src/Yi/Mode/Buffers.hs
|
gpl-2.0
| 2,297
| 0
| 16
| 609
| 475
| 265
| 210
| 36
| 2
|
{-# LANGUAGE TemplateHaskell #-}
{-| Unittests for Attoparsec support for unicode -}
{-
Copyright (C) 2012 Google Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
-}
module Test.Ganeti.Attoparsec (testAttoparsec) where
import Test.HUnit
import Test.Ganeti.TestHelper
import qualified Data.Attoparsec.Text as A
import Data.Attoparsec.Text (Parser)
import Data.Text (pack, unpack)
-- | Unicode test string, first part.
part1 :: String
part1 = "äßĉ"
-- | Unicode test string, second part.
part2 :: String
part2 = "ðèق"
-- | Simple parser able to split a string in two parts, name and
-- value, separated by a '=' sign.
simpleParser :: Parser (String, String)
simpleParser = do
n <- A.takeTill (\c -> A.isHorizontalSpace c || c == '=')
A.skipWhile A.isHorizontalSpace
_ <- A.char '='
A.skipWhile A.isHorizontalSpace
v <- A.takeTill A.isEndOfLine
return (unpack n, unpack v)
{-# ANN case_unicodeParsing "HLint: ignore Use camelCase" #-}
-- | Tests whether a Unicode string is still Unicode after being
-- parsed.
case_unicodeParsing :: Assertion
case_unicodeParsing =
case A.parseOnly simpleParser text of
Right (name, value) -> do
assertEqual "name part" part1 name
assertEqual "value part" part2 value
Left msg -> assertFailure $ "Failed to parse: " ++ msg
where text = Data.Text.pack $ part1 ++ " = \t" ++ part2
testSuite "Attoparsec"
[ 'case_unicodeParsing
]
|
vladimir-ipatov/ganeti
|
test/hs/Test/Ganeti/Attoparsec.hs
|
gpl-2.0
| 2,072
| 0
| 14
| 384
| 309
| 166
| 143
| 30
| 2
|
module ShouldSucceed where
class Eq' a where
deq :: a -> a -> Bool
instance Eq' Int where
deq x y = True
instance (Eq' a) => Eq' [a] where
deq (a:as) (b:bs) = if (deq a b) then (deq as bs) else False
f x = deq x [1]
|
urbanslug/ghc
|
testsuite/tests/typecheck/should_compile/tc053.hs
|
bsd-3-clause
| 223
| 0
| 8
| 57
| 128
| 68
| 60
| 8
| 1
|
#define DEFINED_FUNC(x) 3 - (x)
|
SanDisk-Open-Source/SSD_Dashboard
|
uefi/gcc/gcc-4.6.3/gcc/testsuite/gcc.dg/pch/macro-3.hs
|
gpl-2.0
| 33
| 0
| 2
| 6
| 3
| 2
| 1
| 1
| 0
|
{-|
Module : Database.Orville.PostgreSQL.Internal.Monad
Copyright : Flipstone Technology Partners 2016-2018
License : MIT
'Database.Orville.PostgreSQL.MonadBaseControl' provides functions and instances for
using 'MonadOrville' and 'OrvilleT' for situations where you need to use
'MonadBaseControl'. If you do not know if you need 'MonadBaseControl', then
you probably don't need to use this module. If you are thinking about
using 'MonadBaseControl' instead of 'MonadUnliftIO', we recommend
reading Michael Snoyman's excellent "A Tale of Two Brackets"
(https://www.fpcomplete.com/blog/2017/06/tale-of-two-brackets) if you
have not already done so.
If you're still here after reading above, this module provides
the functions you need to implement 'MonadOrvilleControl' for your
Monad stack using its 'MonadBaseControl' instance. The most common way
to do this is simply to add the following 'MonadOrvilleControl' instance:
@
instance MonadOrvilleControl MyMonad where
liftWithConnection = liftWithConnectionViaBaseControl
liftFinally = liftFinallyViaBaseControl
@
This module also provides a 'MonadOrvilleControl' for 'StateT' as well as
'MonadBaseControl' and 'MonadTransControl' instances for 'OrvilleT' and
'OrvilleTriggerT'.
-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE TypeFamilies #-}
module Database.Orville.PostgreSQL.MonadBaseControl
( liftWithConnectionViaBaseControl
, liftFinallyViaBaseControl
) where
import Control.Monad.Reader (ReaderT)
import Control.Monad.State (StateT)
import qualified Control.Monad.Trans.Control as MTC
import qualified Database.Orville.PostgreSQL as O
import qualified Database.Orville.PostgreSQL.Internal.Monad as InternalMonad
import qualified Database.Orville.PostgreSQL.Internal.Trigger as InternalTrigger
import qualified Database.Orville.PostgreSQL.Trigger as OT
{-|
liftWithConnectionViaBaseControl can be use as the implementation of
'liftWithConnection' for 'MonadOrvilleControl' when the 'Monad'
implements 'MonadBaseControl'.
-}
liftWithConnectionViaBaseControl ::
MTC.MonadBaseControl IO m
=> (forall b. (conn -> IO b) -> IO b)
-> (conn -> m a)
-> m a
liftWithConnectionViaBaseControl ioWithConn action =
MTC.control $ \runInIO -> ioWithConn (runInIO . action)
{-|
liftFinallyViaBaseControl can be use as the implementation of
'liftFinally for 'MonadOrvilleControl' when the 'Monad'
implements 'MonadBaseControl'.
-}
liftFinallyViaBaseControl ::
MTC.MonadBaseControl IO m
=> (forall c d. IO c -> IO d -> IO c)
-> m a
-> m b
-> m a
liftFinallyViaBaseControl ioFinally action cleanup =
MTC.control $ \runInIO -> ioFinally (runInIO action) (runInIO cleanup)
{-|
Because lifting control operations into 'StateT' is fraught with peril, a
'MonadOrvilleControl' instance for 'StateT' is provided here and implemented
via 'MonadBaseControl' rather than together with the 'MonadOrvilleControl'
definition. We do not recommend using stateful Monad transformer layers in
Monad stacks based on IO. For anyone that must, this is the canonical
instance for 'StateT'
-}
instance MTC.MonadBaseControl IO m => O.MonadOrvilleControl (StateT a m) where
liftWithConnection = liftWithConnectionViaBaseControl
liftFinally = liftFinallyViaBaseControl
{-|
Because we recommend using 'MonadUnliftIO' rather than 'MonadTransControl',
we do not provide 'MonadTransControl' instance for 'OrvilleT' by default
along with the definition. If you do need to use 'MonadTransControl',
however, this is the canonical instance for 'OrvilleT'.
-}
instance MTC.MonadTransControl (O.OrvilleT conn) where
type StT (O.OrvilleT conn) a = MTC.StT (ReaderT (O.OrvilleEnv conn)) a
liftWith =
MTC.defaultLiftWith InternalMonad.OrvilleT InternalMonad.unOrvilleT
restoreT = MTC.defaultRestoreT InternalMonad.OrvilleT
{-|
Because we recommend using 'MonadUnliftIO' rather than 'MonadBaseControl',
we do not provide 'MonadBaseControl' instance for 'OrvilleT' by default
along with the definition. If you do need to use 'MonadBaseControl',
however, this is the canonical instance for 'OrvilleT'.
-}
instance MTC.MonadBaseControl b m =>
MTC.MonadBaseControl b (O.OrvilleT conn m) where
type StM (O.OrvilleT conn m) a = MTC.ComposeSt (O.OrvilleT conn) m a
liftBaseWith = MTC.defaultLiftBaseWith
restoreM = MTC.defaultRestoreM
instance MTC.MonadTransControl (OT.OrvilleTriggerT trigger conn) where
type StT (OT.OrvilleTriggerT trigger conn) a = MTC.StT (ReaderT (InternalTrigger.RecordedTriggersRef trigger)) (MTC.StT (O.OrvilleT conn) a)
liftWith f =
InternalTrigger.OrvilleTriggerT $
MTC.liftWith $ \runReader ->
MTC.liftWith $ \runOrville ->
f (runOrville . runReader . InternalTrigger.unTriggerT)
restoreT = InternalTrigger.OrvilleTriggerT . MTC.restoreT . MTC.restoreT
instance MTC.MonadBaseControl b m =>
MTC.MonadBaseControl b (OT.OrvilleTriggerT trigger conn m) where
type StM (OT.OrvilleTriggerT trigger conn m) a = MTC.StM (ReaderT (InternalTrigger.RecordedTriggersRef trigger) m) a
liftBaseWith = MTC.defaultLiftBaseWith
restoreM = MTC.defaultRestoreM
|
flipstone/orville
|
orville-postgresql/src/Database/Orville/PostgreSQL/MonadBaseControl.hs
|
mit
| 5,265
| 0
| 13
| 804
| 752
| 405
| 347
| -1
| -1
|
-- Generated by protobuf-simple. DO NOT EDIT!
module Types.Int32OptMsg where
import Control.Applicative ((<$>))
import Prelude ()
import qualified Data.ProtoBufInt as PB
newtype Int32OptMsg = Int32OptMsg
{ value :: PB.Maybe PB.Int32
} deriving (PB.Show, PB.Eq, PB.Ord)
instance PB.Default Int32OptMsg where
defaultVal = Int32OptMsg
{ value = PB.defaultVal
}
instance PB.Mergeable Int32OptMsg where
merge a b = Int32OptMsg
{ value = PB.merge (value a) (value b)
}
instance PB.Required Int32OptMsg where
reqTags _ = PB.fromList []
instance PB.WireMessage Int32OptMsg where
fieldToValue (PB.WireTag 1 PB.VarInt) self = (\v -> self{value = PB.merge (value self) v}) <$> PB.getInt32Opt
fieldToValue tag self = PB.getUnknown tag self
messageToFields self = do
PB.putInt32Opt (PB.WireTag 1 PB.VarInt) (value self)
|
sru-systems/protobuf-simple
|
test/Types/Int32OptMsg.hs
|
mit
| 852
| 0
| 13
| 156
| 291
| 156
| 135
| 20
| 0
|
module Main where
import BasicFunctions
import Guess
import Test.QuickCheck
--------------------------------------------------------------------------
-- Introduction:
--
-- In this module, we'll try to write tests for several other pieces of
-- code we have already worked with.
-- If you have implemented a different sorting algorithm than the
-- insertion sort we've just discussed, then test your sorting
-- algorithm.
-- In BasicFunctions, we have defined encoding and decoding for run-length
-- encoding. Test whether encoding and then decoding an arbitrary String
-- yields the original result.
--
-- What about the other direction?
-- If you have implemented the spell checker, then compile it with HPC
-- enabled. Run it on a number of example documents and dictionaries,
-- then check for coverage. Do you reach full coverage?
--------------------------------------------------------------------------
-- Testing the number-guessing game:
--
-- This assumes that you have implemented a solver for the guess game.
--
-- One way to gain some trust in the solver is to see if it
-- terminates and produces the right numbers in a larger number of
-- situations.
playRange :: [Int]
playRange = map (\ n -> play (pick n) guess (Q (1, 100) 50)) [1..100]
-- Try in GHCi:
--
-- [1..100]
-- playRange
--
-- Note that the first is a simple way to generate a list of
-- subsequent numbers. The second call should produce the *same*
-- list if everything is fine. In other words, if you call
-- 'testPlay' as defined here
testPlay :: Bool
testPlay = playRange == [1..100]
-- it should evaluate to 'True'.
--------------------------------------------------------------------------
-- More testing:
-- There are a couple of implicit invariants in our implementation
-- of the number guessing game. For example, if we look at a question,
-- then it contains a range and a guess. For the range, we certainly
-- assume that the upper bound is at least the lower bound.
-- Furthermore, it seems reasonable to require that the guess is
-- actually *within* the range.
--
-- Write a function:
validQuestion :: Question -> Bool
validQuestion = error "TODO: implement validQuestion"
-- that captures these requirements. Note that you can use (<=)
-- rather than 'compare' as a comparison operator returning a 'Bool',
-- and that you can use (&&) to combine requirements.
-- We consider a 'GameState' to be valid if it is a 'Done'-state or if
-- it contains a valid question. Implement this in the following
-- function:
validGameState :: GameState -> Bool
validGameState = error "TODO: implement validGameState"
-- Given these two functions, we can now state a testable property:
guessPreservesValidity :: Question -> Answer -> Property
guessPreservesValidity q a = validQuestion q ==> validGameState (guess q a)
-- The property says that if we start if a valid question 'q' and
-- any answer 'a', then 'guess' should move to a valid state.
-- In order for auto-generation to work, we have to explain
-- how to come up with reasonable random values of type 'Question'
-- and 'Answer' (synyonmous to 'Ordering') by providing instances
-- of class 'Arbitrary'.
--
-- Define an instance for Ordering:
--
-- instance Arbitrary Ordering where ...
--
-- Note that Ordering is an enumeration type.
--
-- Then define an instance for Question:
--
-- instance Arbitrary Question where ...
--
-- Recall that Question is defined as
--
-- data Question = Q Range Guess deriving Show
-- type Range = (Int, Int)
-- type Guess = Int
--
-- So in essence, a question conists of three integers. QuickCheck knows
-- how to generate triple of integers. Use fmap to change such a triple
-- into a question.
--------------------------------------------------------------------------
-- More tasks:
-- * Now that we know that the property doesn't hold, we would of
-- course like to fix the program. Come up with a modified design for
-- which the property (or a slightly modified one) would hold.
--
-- * Think about additional properties about our game that we could
-- test, and test them.
|
NickAger/LearningHaskell
|
well-typed at skills matter/fast-track/exercises/4/Tests.hs
|
mit
| 4,085
| 0
| 11
| 697
| 252
| 176
| 76
| 14
| 1
|
module Add where
import Card
import Display
import Text.Printf(printf)
import qualified Input
data AddAction = NewDeck | ToDeck deriving (Show, Eq)
instance Display AddAction where
display NewDeck = "New deck"
display ToDeck = "Add to deck"
addLoop :: [Card] -> IO [Card]
addLoop decks = do
addAction <- getAddAction decks
runAddAction addAction decks
runAddAction :: Maybe AddAction -> [Card] -> IO [Card]
runAddAction (Just NewDeck) cards = do
printf $ "Press <Enter> at any time to stop adding" ++ "\n"
newDeck cards
runAddAction (Just ToDeck) cards = do
printf $ "Press <Enter> at any time to stop adding" ++ "\n"
toDeck cards
runAddAction Nothing cards = return cards
newDeck :: [Card] -> IO [Card]
newDeck cards = do
deckName <- Input.sameLinePrompt "New deck name : "
case deckName of
"" -> return cards
_ -> if any (\card -> cardDeck card == deckName) cards
then do
printf $ "Invalid input, already a deck with that name" ++ "\n"
newDeck cards
else
toDeckLoop deckName cards
toDeck :: [Card] -> IO [Card]
toDeck cards = do
chosenDeckName <- Input.getUserChoiceStr $ allDeckNames cards
case chosenDeckName of
Just deckName -> toDeckLoop deckName cards
Nothing -> return cards
toDeckLoop :: String -> [Card] -> IO [Card]
toDeckLoop deckName cards = do
question <- Input.sameLinePrompt "Add question : "
case question of
"" -> do
{-printf $ "You wish to stop adding" ++ "\n"-}
printf "\n"
return cards
_ -> do
answer <- Input.sameLinePrompt "Add answer : "
case answer of
"" -> return cards
_ -> do
let card = newCard question answer deckName
toDeckLoop deckName (card:cards)
getAddAction :: [Card] -> IO (Maybe AddAction)
getAddAction [] = return $ Just NewDeck
getAddAction _ = Input.getUserChoice allAddActions
allAddActions :: [AddAction]
allAddActions = [NewDeck, ToDeck]
|
marcusbuffett/Clanki
|
src/Add.hs
|
mit
| 2,149
| 0
| 20
| 655
| 610
| 299
| 311
| 56
| 3
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module GetContents where
import System.IO hiding (getContents)
import Prelude hiding (truncate, getContents)
import Data.Text (Text, pack, unpack)
import Data.Vector (toList)
import Data.ByteString.Base64 (decodeLenient)
import qualified Data.ByteString.Char8 as BS (unpack, pack)
import qualified GitHub.Endpoints.Repos as Github
import GitHub.Auth
import Data.Maybe (isNothing)
import Control.Monad (guard, when)
import Control.Monad.Trans.Class (lift)
import Control.Monad.IO.Class (liftIO)
import Data.String (fromString)
import System.Environment (lookupEnv)
import System.Directory (createDirectoryIfMissing)
import System.FilePath.Posix (dropFileName, (</>))
import Control.Exception.Lifted
import Control.Monad.Trans.Except
import Control.Monad.Trans.List
import Data.EitherR (fmapL)
import Data.Either (partitionEithers)
import Data.Either.Utils (maybeToEither)
tokenName = "GITHUB_DUOMEMO_TOKEN"
getAuth :: IO (Maybe (Auth))
getAuth = do
token <- lookupEnv tokenName
return $ OAuth . fromString <$> token
-- ExceptT :: m (Either e a) -> ExceptT e m a
-- ListT :: m [a] -> ListT m a
-- ExceptT String (ListT IO) (String, String) => (ListT IO) (Either String (String, String)) => IO [Either String (String, String)]
-- ListT (ExceptT String IO) (String, String) => (ExceptT String IO) [(String, String)] => IO Either String [(String, String)]
-- transforms to IO [Either String (String, String)]
getContents :: String -> ExceptT String (ListT IO) (String, String)
getContents gitPath =
do
-- TODO: Find out why the semantics for auth below returning auth::Auth is not equivalent to the simple liftIO $ maybeToEither which returns Either String Auth
(auth::Auth) <-
-- ::ExceptT String (ListT IO) Auth
ExceptT . ListT $
-- ::IO [Either String Auth]
(:[]) <$>
-- maybeToEither :: IO (Either String Auth)
maybeToEither ("Failed to find GIT access token.\nCheck the sytem environment variables and make sure " ++ tokenName ++ " variable contains a valid token. Otherwise generate it here https://github.com/settings/tokens/new")
<$> getAuth
(content::Github.Content)
-- TODO: Why can't i use monadic return or lift.
-- TODO: Study lift again. Search for the possibility of monad decomposition
<- ExceptT . ListT $
-- (:[]) :: IO [Either String Github.Content]
(:[]) <$>
-- fmapL :: IO (Either String Github.Content)
fmapL (show :: Github.Error -> String) <$> Github.contentsFor' (Just auth) "erithion" "temp_test" gitPath Nothing
readItem content
readItem :: Github.Content -> ExceptT String (ListT IO) (String, String)
readItem (Github.ContentFile fileData) =
do
let contentInfo = Github.contentFileInfo fileData
fileName = unpack $ Github.contentPath contentInfo
encoding = unpack $ Github.contentFileEncoding fileData
file = unpack $ Github.contentFileContent fileData
output = BS.unpack ( decodeLenient ( BS.pack file ))
if encoding == "base64"
then ExceptT . ListT . return $
[Right (fileName, output)]
else ExceptT . ListT . return $
[Left $ "Unsupported encoding " ++ encoding ++ "\nfor " ++ unpack (Github.contentUrl contentInfo)]
readItem (Github.ContentDirectory items) =
do
let (names::[String]) = map (unpack . Github.contentPath . Github.contentItemInfo) $ toList items
name <- ExceptT . ListT . return $ Right <$> names
getContents name
writeUTF8File :: String -> (String, String) -> ExceptT String IO ()
writeUTF8File saveTo (fileName, fileData) = ExceptT $
-- tryJust :: IO (Either String String)
-- catching and rethrowing IOExceptions as String
tryJust (return . show :: IOException -> Maybe String) $
do
let filePath = saveTo </> fileName
createDirectoryIfMissing True (dropFileName filePath)
withBinaryFile filePath WriteMode $ \handle->
do
hPutStr handle fileData
main = do
putStrLn "Root"
putStrLn "===="
files <- runListT $ runExceptT $
do
dat <- getContents ""
let (write::IO (Either String ())) = runExceptT . writeUTF8File ".\\data" $ dat
result <- ExceptT . ListT $ (:[]) <$> write
return dat
let (lefts, rights) = partitionEithers files
putStrLn "ERRORS\n\n\n\n"
putStrLn . unlines $ lefts
return ()
--writeUTF8FileError :: (String, String) -> ExceptT String IO ()
--writeUTF8FileError (fileName, fileData) = ExceptT . return . Left $ "I generated error"
|
erithion/duo-memo
|
doc/drafts/GithubUpdate.hs
|
mit
| 5,529
| 0
| 19
| 1,794
| 1,055
| 566
| 489
| 85
| 2
|
-- | This module defines the main data types and functions needed to use
-- Tasty.
module Test.Tasty
(
-- * Organizing tests
TestName
, TestTree
, testGroup
-- * Running tests
, defaultMain
, defaultMainWithIngredients
, defaultIngredients
, includingOptions
-- * Adjusting and querying options
-- | Normally options are specified on the command line. But you can
-- also have different options for different subtrees in the same tree,
-- using the functions below.
--
-- Note that /ingredient options/ (number of threads, hide successes
-- etc.) set in this way will not have any effect. This is for modifying
-- per-test options, such as timeout, number of generated tests etc.
, adjustOption
, localOption
, askOption
-- ** Standard options
, Timeout(..)
, mkTimeout
-- * Resources
-- | Sometimes several tests need to access the same resource — say,
-- a file or a socket. We want to create or grab the resource before
-- the tests are run, and destroy or release afterwards.
, withResource
)
where
import Test.Tasty.Core
import Test.Tasty.Runners
import Test.Tasty.Options
import Test.Tasty.Options.Core
import Test.Tasty.Ingredients.Basic
-- | List of the default ingredients. This is what 'defaultMain' uses.
--
-- At the moment it consists of 'listingTests' and 'consoleTestReporter'.
defaultIngredients :: [Ingredient]
defaultIngredients = [listingTests, consoleTestReporter]
-- | Parse the command line arguments and run the tests
defaultMain :: TestTree -> IO ()
defaultMain = defaultMainWithIngredients defaultIngredients
-- | Locally adjust the option value for the given test subtree
adjustOption :: IsOption v => (v -> v) -> TestTree -> TestTree
adjustOption f = PlusTestOptions $ \opts ->
setOption (f $ lookupOption opts) opts
-- | Locally set the option value for the given test subtree
localOption :: IsOption v => v -> TestTree -> TestTree
localOption v = PlusTestOptions (setOption v)
-- | Customize the test tree based on the run-time options
askOption :: IsOption v => (v -> TestTree) -> TestTree
askOption f = AskOptions $ f . lookupOption
-- | Acquire the resource to run this test (sub)tree and release it
-- afterwards
withResource
:: IO a -- ^ initialize the resource
-> (a -> IO ()) -- ^ free the resource
-> (IO a -> TestTree)
-- ^ @'IO' a@ is an action which returns the acquired resource.
-- Despite it being an 'IO' action, the resource it returns will be
-- acquired only once and shared across all the tests in the tree.
-> TestTree
withResource acq rel = WithResource (ResourceSpec acq rel)
|
SAdams601/ParRegexSearch
|
test/tasty-0.9.0.1/Test/Tasty.hs
|
mit
| 2,622
| 0
| 10
| 507
| 353
| 209
| 144
| 37
| 1
|
module Zwerg.Game where
--TODO: export only what you want, and factor out processEvent into new module
import Zwerg.Component
import Zwerg.Data.Position
import Zwerg.Data.UUIDMap
import Zwerg.Entity
import Zwerg.Entity.AI
import Zwerg.Entity.Compare
import Zwerg.Event.Queue
import Zwerg.Generator
import Zwerg.Generator.World
import Zwerg.Log
import Zwerg.UI.Input
import Zwerg.UI.Menu
import Zwerg.UI.Port
import qualified Data.List.NonEmpty as NE (cons)
import Control.Monad.Random (runRandT, RandT, MonadRandom, getRandomR)
import Lens.Micro.Platform (makeClassy, (%=), use, _2, (.=))
data GameState = GameState
{ _gsComponents :: Components
, _userLog :: Log
, _portal :: Portal
, _gsEventQueue :: ZwergEventQueue
, _playerGoofed :: Bool
}
deriving stock Generic
deriving anyclass Binary
makeClassy ''GameState
instance HasComponents GameState where
components = gsComponents
instance HasZwergEventQueue GameState where
eventQueue = gsEventQueue
{-# INLINABLE pushLogMsgM #-}
pushLogMsgM :: Text -> Game ()
pushLogMsgM message = userLog %= pushLogMsg message
emptyGameState :: GameState
emptyGameState = GameState
{ _gsComponents = zDefault
, _userLog = zDefault
, _portal = initMainMenu :| []
, _gsEventQueue = zDefault
, _playerGoofed = False
}
-- Highest level purely-functional context which encapsulates all game logic/state
newtype Game' a = Game (RandT RanGen (State GameState) a)
deriving newtype ( Functor
, Applicative
, Monad
, MonadState GameState
, MonadRandom
)
type Game a = HasCallStack => Game' a
{-# INLINABLE runGame #-}
runGame :: Game () -> RanGen -> GameState -> GameState
runGame (Game a) gen st = execState (runRandT a gen) st
-- TODO: factor out into Generator.World module
generateGame :: Game ()
generateGame = void $ generate world
-- after we process a player tick, go through all other entities
-- and process their ticks, until the player is ready to tick again
processNonPlayerEvents :: Game ()
processNonPlayerEvents = do
use portal >>= \case
(MainScreen :| _) -> do
(minTick, uuids) <- getMinimumUUIDs <$> getCompUUIDMap ticks
(ticks . _2) %= fmap (\x -> max (x - minTick) 0)
if | notElem playerUUID uuids ->
forM_ uuids $ \i -> do runAI i >> processEvents >> setComp i ticks 100
| otherwise -> return ()
updateGlyphMap
_ -> return ()
processUserInput :: KeyCode -> Game ()
processUserInput k = do
playerGoofed .= False
p <- use portal
processUserInput' p k
playerGeneratedEvent <- (not . zIsNull) <$> use eventQueue
playerScrewedUp <- use playerGoofed
when (not playerScrewedUp && playerGeneratedEvent) $ do
processEvents
resetTicks playerUUID
processNonPlayerEvents
processUserInput' :: Portal -> KeyCode -> Game ()
processUserInput' (MainMenu m :| ps) (KeyChar 'j') = portal .= (MainMenu $ next m) :| ps
processUserInput' (MainMenu m :| ps) (KeyChar 'k') = portal .= (MainMenu $ prev m) :| ps
processUserInput' (MainMenu m :| _) Return =
case label (focus m) of
"new game" -> do
generateGame
portal .= MainScreen :| []
updateGlyphMap
"exit" -> portal .= ExitScreen :| []
_ -> return ()
processUserInput' (MainScreen :| _) (KeyChar 'h') = processPlayerDirectionInput $ Cardinal West
processUserInput' (MainScreen :| _) (KeyChar 'j') = processPlayerDirectionInput $ Cardinal South
processUserInput' (MainScreen :| _) (KeyChar 'k') = processPlayerDirectionInput $ Cardinal North
processUserInput' (MainScreen :| _) (KeyChar 'l') = processPlayerDirectionInput $ Cardinal East
processUserInput' (MainScreen :| _) (LeftArrow) = processPlayerDirectionInput $ Cardinal West
processUserInput' (MainScreen :| _) (UpArrow) = processPlayerDirectionInput $ Cardinal South
processUserInput' (MainScreen :| _) (DownArrow) = processPlayerDirectionInput $ Cardinal North
processUserInput' (MainScreen :| _) (RightArrow) = processPlayerDirectionInput $ Cardinal East
processUserInput' (MainScreen :| _) (KeyChar '>') = $(newEvent "EntityUseStairs") playerUUID Down
processUserInput' (MainScreen :| _) (KeyChar '<') = $(newEvent "EntityUseStairs") playerUUID Up
processUserInput' (MainScreen :| _) (KeyChar 'i') = do
uuids <- unwrap <$> inventory <@> playerUUID
names <- mapM (name <@>) uuids
case zip names uuids of
[] -> do
pushLogMsgM "You don't have any items to look at."
playerGoofed .= True
i:is -> do
portal %= NE.cons (ViewInventory $ makeMenuGroupSelect $ i :| is)
processUserInput' (ViewInventory inv :| ps) (KeyChar 'd') =
portal .= (ViewInventory $ toggleFocus inv) :| ps
processUserInput' (ViewInventory inv :| ps) (KeyChar 'D') = do
forM_ (getAllSelected inv) $ \droppedItemUUID ->
$(newEvent "EntityDroppedItem") playerUUID droppedItemUUID
case ps of
[] -> debug "Port stack empty after leaving Inventory screen!"
p:pss -> portal .= p :| pss
processUserInput' (ViewInventory _ :| ps) (KeyChar 'i') =
case ps of
[] -> debug "Port stack empty after leaving Inventory screen!"
p:pss -> portal .= p :| pss
processUserInput' (ViewInventory inv :| ps) (KeyChar 'j') =
portal .= (ViewInventory $ next inv) :| ps
processUserInput' (ViewInventory inv :| ps) (KeyChar 'k') =
portal .= (ViewInventory $ prev inv) :| ps
processUserInput' (MainScreen :| _) (KeyChar 'x') = do
playerPos <- position <@> playerUUID
portal %= NE.cons (ExamineTiles playerPos)
processUserInput' (ExamineTiles _ :| ps) (KeyChar 'x') =
case ps of
[] -> debug "Port stack empty after leaving ExamineTiles screen!"
p:pss -> portal .= p :| pss
processUserInput' (ExamineTiles pos :| ps) (KeyChar 'h') =
whenJust (movePosDir (Cardinal West) pos) $
\newPos -> portal .= ExamineTiles newPos :| ps
processUserInput' (ExamineTiles pos :| ps) (KeyChar 'j') =
whenJust (movePosDir (Cardinal South) pos) $
\newPos -> portal .= ExamineTiles newPos :| ps
processUserInput' (ExamineTiles pos :| ps) (KeyChar 'k') =
whenJust (movePosDir (Cardinal North) pos) $
\newPos -> portal .= ExamineTiles newPos :| ps
processUserInput' (ExamineTiles pos :| ps) (KeyChar 'l') =
whenJust (movePosDir (Cardinal East) pos) $
\newPos -> portal .= ExamineTiles newPos :| ps
processUserInput' _ _ = return ()
--TODO: pull GlyphMap from level.
updateGlyphMap :: Game ()
updateGlyphMap =
use portal >>= \case
MainScreen :| _ -> do
levelUUID <- level <@> playerUUID
gm <- glyphMap <@> levelUUID
updatedGlyphs <- rc getGlyphMapUpdates
setComp levelUUID glyphMap $ mergeUpdates (fmap (markVisibility False) gm) updatedGlyphs
_ -> return ()
processEvents :: Game ()
processEvents =
whenJustM popEvent $ \nextEvent -> do
processEvent nextEvent
processEvents
processEvent :: ZwergEvent -> Game ()
processEvent (MoveEntityDirectionEvent MoveEntityDirectionEventData{..}) = do
oldPosition <- position <@> moveEntityDirMoverUUID
case movePosDir moveEntityDirDirection oldPosition of
Nothing -> do
-- TODO: check if non player entity and give error
pushLogMsgM "You cannot move into the void."
playerGoofed .= True
Just newPos -> $(newEvent "MoveEntity") moveEntityDirMoverUUID newPos
processEvent (MoveEntityEvent MoveEntityEventData{..}) = do
oldTileUUID <- tileOn <@> moveEntityMoverUUID
levelTiles <- level <@> moveEntityMoverUUID >>= (<@>) tileMap
let newTileUUID = zAt levelTiles moveEntityNewPosition
newTileBlocked <- rc $ tileBlocksPassage newTileUUID
if newTileBlocked
then if moveEntityMoverUUID /= playerUUID
then debug "NPC Entity attempted to move to blocked tile"
else do
pushLogMsgM "You cannot move into a blocked tile."
playerGoofed .= True
else do
transferOccupant moveEntityMoverUUID (Just oldTileUUID) newTileUUID
$(newEvent "EntityLeftTile") moveEntityMoverUUID oldTileUUID
$(newEvent "EntityReachedTile") moveEntityMoverUUID newTileUUID
processEvent (EntityLeftTileEvent _) = return ()
processEvent (EntityReachedTileEvent _) = return ()
processEvent (WeaponAttackAttemptEvent WeaponAttackAttemptEventData{..}) = do
attDEX <- rc $ getStat DEX $ weapAtkAttempAttackerUUID
defDEX <- rc $ getStat DEX $ weapAtkAttempDefenderUUID
let prob = if attDEX > defDEX then 0.75 else 0.5 :: Double
r <- getRandomR (0.0, 1.0)
if (r < prob)
then $(newEvent "WeaponAttackHit") weapAtkAttempAttackerUUID weapAtkAttempDefenderUUID
else $(newEvent "WeaponAttackMiss") weapAtkAttempAttackerUUID weapAtkAttempDefenderUUID
processEvent (WeaponAttackHitEvent WeaponAttackHitEventData{..}) = do
rc (getEquippedWeapon weapAtkHitAttackerUUID) >>= \case
--TODO: decide how to handle unarmed attacks
Nothing -> return ()
Just weaponUUID -> do
chain <- damageChain <@> weaponUUID
forM_ chain $ \damageData -> do
targetedUUIDs <- rc $ getTargetedUUIDs (ddTargetType damageData) weapAtkHitDefenderUUID
forM_ targetedUUIDs $ \targetUUID ->
$(newEvent "IncomingDamage")
weapAtkHitAttackerUUID
targetUUID
(ddAttribute damageData)
(ddDistribution damageData)
processEvent (EntityUseStairsEvent EntityUseStairsEventData{..}) = do
tileUUID <- tileOn <@> entityUseStairsUUID
tileType <@> tileUUID >>= \case
Stairs dir -> do
newTileUUID <- connectedTo <@> tileUUID
newTileBlocked <- rc $ tileBlocksPassage newTileUUID
let stairsGoExpectedDirection = dir == entityUseStairsUpOrDown
isPlayer = entityUseStairsUUID == playerUUID
if | newTileBlocked && not isPlayer ->
debug "NPC Entity attempted to move down stairs to blocked tile."
| newTileBlocked && isPlayer -> do
pushLogMsgM "There's something down there blocking your way."
playerGoofed .= True
| not stairsGoExpectedDirection && not isPlayer ->
debug "NPC Entity attempted to move down up-going stairs!"
| not stairsGoExpectedDirection && isPlayer -> do
pushLogMsgM "You can't go down the up stairs."
playerGoofed .= True
| otherwise -> do
transferOccupant entityUseStairsUUID (Just tileUUID) newTileUUID
$(newEvent "EntityLeftTile") entityUseStairsUUID tileUUID
$(newEvent "EntityReachedTile") entityUseStairsUUID newTileUUID
_ -> debug "Entity attempted to use stairs while not on staircase."
processEvent (WeaponAttackMissEvent _) = return ()
processEvent (DeathEvent DeathEventData{..}) = eraseEntity dyingUUID
processEvent (IncomingDamageEvent IncomingDamageEventData{..}) = do
--TODO: account for weaknesses in creatures and armor
damageDone <- round <$> sample incDamDistribution
$(newEvent "OutgoingDamage") incDamAttackerUUID incDamDefenderUUID damageDone
processEvent (OutgoingDamageEvent OutgoingDamageEventData{..}) = do
whenM (hasComp outDamDefenderUUID hp) $ do
modComp outDamDefenderUUID hp (adjustHP $ subtract $ outDamDamageAmount)
newHP <- hp <@> outDamDefenderUUID
when (outDamAttackerUUID == playerUUID || outDamDefenderUUID == playerUUID) $ do
(attName, defName) <- name <@@!> (outDamAttackerUUID, outDamDefenderUUID)
pushLogMsgM $ attName <> " hit " <> defName <> " for " <> (show $ outDamDamageAmount) <> " damage."
when (fst (unwrap newHP) == 0) $
if outDamDefenderUUID == playerUUID
then portal %= NE.cons (DeathScreen "You died.")
else eraseEntity outDamDefenderUUID
processEvent (EntityDroppedItemEvent EntityDroppedItemEventData{..}) = do
tileUUID <- tileOn <@> entityDroppedItemDropperUUID
modComp entityDroppedItemDropperUUID inventory
$ zDelete entityDroppedItemDroppedUUID
modComp tileUUID occupants $ zAdd entityDroppedItemDroppedUUID
processEvent _ = return ()
getGlyphMapUpdates :: MonadCompRead [(Position,GlyphMapCell)]
getGlyphMapUpdates = do
visibleTiles <- getVisibleTiles playerUUID
forM visibleTiles $ \tileUUID -> do
pos <- position <~> tileUUID
primaryGlyph <- getPrimaryOccupant tileUUID >>= (<~>) glyph
let go bgGlyph = return (pos, GlyphMapCell True primaryGlyph bgGlyph)
getPrimaryStationaryOccupant tileUUID >>= (<~>) glyph >>= \case
PartialGlyph stationaryChar stationaryFG -> do
glyph <~> tileUUID >>= \case
FullGlyph _ _ tileBG -> go $ FullGlyph stationaryChar stationaryFG tileBG
_ -> go zDefault
stationaryGlyph@(FullGlyph _ _ _) -> go stationaryGlyph
_ -> go zDefault
processPlayerDirectionInput :: Direction -> Game ()
processPlayerDirectionInput dir = getPlayerAdjacentEnemy >>= \case
Just attackedUUID -> $(newEvent "WeaponAttackAttempt") playerUUID attackedUUID
Nothing -> $(newEvent "MoveEntityDirection") playerUUID dir
where getPlayerAdjacentEnemy = rc $ do
attackedTileUUID <- tileOn <~> playerUUID >>= getAdjacentTileUUID dir
case attackedTileUUID of
Just attackedTileUUID' -> do
unwrap <$> getOccupantsOfType attackedTileUUID' Enemy >>= \case
[] -> return Nothing
[x] -> return $ Just x
xs -> do
debug "found multiple enemies on same tile"
return $ Just $ head xs
Nothing -> return Nothing
|
zmeadows/zwerg
|
lib/Zwerg/Game.hs
|
mit
| 13,756
| 0
| 22
| 3,124
| 3,790
| 1,851
| 1,939
| -1
| -1
|
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ViewPatterns #-}
module Main where
import Numeric.Units.Dimensional.TF.Prelude
import qualified Prelude ()
km3s2 :: Fractional a => Unit DGravitationalParameter a
km3s2 = cubic (kilo meter) / (second * second)
-- | Standard gravitational parameter for Earth
μe :: GravitationalParameter Double
μe = 398600.441 *~ km3s2
-- | Radius of Earth
re :: Length Double
re = 6371 *~ kilo meter
-- | Number of people on Earth
nump :: Dimensionless Int
nump = 7000000000 *~ one
data Conf = Conf { d :: Length Double -- ^ Satellite altitude
, peru :: Dimensionless Double -- ^ Fraction of people on Earth who are users
, numl :: Dimensionless Int -- ^ Number of launches
}
_10 :: Num a => Dimensionless a
_10 = 10 *~ one
nums :: Conf -> Dimensionless Int
nums Conf { numl } = numl * _10
numu :: Conf -> Dimensionless Int
numu c@(nums -> ns) = round <$> ((fromIntegral <$> nump) * (peru c) / (fromIntegral <$> ns))
-- | $#_s \cdot (1 - \frac{R_E}{\sqrt{R_E^2 + d^2 \tan^2{\theta_s}}}) = 2$
θs :: Conf -> Dimensionless Double
θs c@(Conf { d }) = atan $ sqrt $ ((sq re) - (sq (re / (_1 - (_2 / ns))))) / (sq d)
where
sq x = x * x
ns = fromIntegral <$> nums c
main :: IO ()
main = return ()
|
taktoa/SatOpt
|
optimize.hs
|
mit
| 1,382
| 0
| 16
| 365
| 416
| 226
| 190
| 29
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module LLVM.Examples.Maths (maths) where
import qualified LLVM.General.AST as AST
import Control.Monad
import Control.Lens ((.=))
import LLVM.General.AST.Type (double)
import LLVM.Gen
maths :: AST.Module
maths = mapLLVM . runLLVM defaultModule $ do
moduleName .= "Maths"
defn double "adds" [(double, "a", 8), (double, "b", 8)] $ do
a <- getvar' "a" >>= load double 8
b <- getvar' "b" >>= load double 8
fadd' double a b >>= ret
defn double "subs" [(double, "a", 8), (double, "b", 8)] $ do
a <- getvar' "a" >>= load double 8
b <- getvar' "b" >>= load double 8
fsub' double a b >>= ret
defn double "muls" [(double, "a", 8), (double, "b", 8)] $ do
a <- getvar' "a" >>= load double 8
b <- getvar' "b" >>= load double 8
fmul' double a b >>= ret
defn double "divs" [(double, "a", 8), (double, "b", 8)] $ do
a <- getvar' "a" >>= load double 8
b <- getvar' "b" >>= load double 8
fdiv' double a b >>= ret
|
AKST/scheme.llvm
|
src/LLVM/Examples/Maths.hs
|
mit
| 1,003
| 0
| 13
| 242
| 446
| 229
| 217
| 26
| 1
|
fib n = table !! n
where
table = 0 : 1 : zipWith (+) table (tail table)
euler2 = sum[x | x<- takeWhile ( < 4000000) (map fib [1..]), even(x)]
main = print euler2
|
dmitry106/projecteulerimsa
|
haskell/euler0002.hs
|
mit
| 171
| 4
| 11
| 44
| 113
| 52
| 61
| 4
| 1
|
{-# LANGUAGE ViewPatterns #-}
module StaticCheck where
import Syntax
import Lattice
import Gamma
import Unbound.Generics.LocallyNameless
import Control.Monad.Except hiding (join)
import Control.Monad.Reader hiding (join)
import Control.Monad.Identity hiding (join)
import qualified Data.Map as M
type StaticType = FreshMT (ReaderT Ctx (ExceptT TypeError Identity))
runOverFile :: Ctx -> [(String, Term)] -> Either TypeError Ctx
runOverFile env [] = Right env
runOverFile env (binding@(nm, _):xs) = do
let new = runStatic env binding
case new of
Left err -> Left err
Right gty -> runOverFile (extendGamma env (nm, gty)) xs
inEnv :: (String, GType) -> StaticType a -> StaticType a
inEnv (nm, gt) m = do
let scope e = remove e nm `extendGamma` (nm, gt)
local scope m
lookupVar :: String -> StaticType GType
lookupVar x = do
st <- ask
let (Gamma gm) = gamma st
case M.lookup x gm of
Nothing -> throwError $ NotInScope $ show gm
Just e -> return e
runStatic :: Ctx -> Binding -> Either TypeError GType
runStatic ctx (_, t) = runIdentity . runExceptT . runReaderT (runFreshMT . checkStatic $ t) $ ctx
checkStatic :: Term -> StaticType GType
checkStatic expr =
case expr of
Val _ l -> return $ TyBool l
Var n -> do
let n' = name2String n
lookupVar n'
Op _ b1 b2 -> do
b1' <- checkStatic b1
b2' <- checkStatic b2
b1' `gradJoin` b2'
Lam bnd -> do
(((n, nl), unembed -> Annot (Just l)), body) <- unbind bnd
b' <- inEnv (name2String n, TyBool nl) (checkStatic body)
return $ TyArr (TyBool nl) b' l
App t1 t2 -> do
t1' <- checkStatic t1
t2' <- checkStatic t2
case t1' of
(TyArr s1 s2 l) ->
if t2' `isGradSubTypeOf` s1
then return $ TyBool (getLabel s2 \/ l)
else throwError $ ImplicitFlow s1 t2'
_ -> throwError $ Undefined $ "The first expression should be a function type, but is " ++ show t1'
IfThenElse b t1 t2 -> do
b' <- checkStatic b
case b' of
(TyBool l) -> do
a1' <- checkStatic t1
a2' <- checkStatic t2
arms@(TyBool l') <- gradJoin a1' a2'
if l `flowsTo` l'
then gradJoin b' arms
else throwError $ ImplicitFlow b' arms
_ -> throwError $ Undefined "arms of conditional must be a boolean expression"
_ -> throwError $ Undefined "not written yet"
gradJoin :: GType -> GType -> StaticType GType
gradJoin (TyBool l1) (TyBool l2) = return $ TyBool (l1 \/ l2)
gradJoin (TyArr s11 s12 l) (TyArr s21 s22 l') = do
t1 <- gradMeet s11 s21
t2 <- gradJoin s12 s22
return $ TyArr t1 t2 (l \/ l')
gradJoin t1 t2 = throwError $ ImplicitFlow t1 t2
gradMeet :: GType -> GType -> StaticType GType
gradMeet (TyBool l1) (TyBool l2) = return $ TyBool (l1 /\ l2)
gradMeet (TyArr s11 s12 l) (TyArr s21 s22 l') = do
t1 <- gradJoin s11 s21
t2 <- gradMeet s12 s22
return $ TyArr t1 t2 (l /\ l')
gradMeet t1 t2 = throwError $ ImplicitFlow t1 t2
setLabel :: GType -> GLabel -> GType
setLabel (TyBool _) l' = TyBool l'
setLabel (TyArr x y _) l' = TyArr x y l'
getLabel :: GType -> GLabel
getLabel (TyBool l) = l
getLabel (TyArr _ _ l) = l
isGradSubTypeOf :: GType -> GType -> Bool
(TyBool l) `isGradSubTypeOf` (TyBool l') = l `flowsTo` l'
(TyArr s1 s2 l) `isGradSubTypeOf` (TyArr s1' s2' l') = s1' `isGradSubTypeOf` s1 && s2 `isGradSubTypeOf` s2' && l `flowsTo` l'
_ `isGradSubTypeOf` _ = undefined
|
kellino/TypeSystems
|
gradualSecurity/src/StaticCheck.hs
|
mit
| 3,791
| 0
| 18
| 1,207
| 1,419
| 706
| 713
| 91
| 11
|
import Data.List
import qualified Data.Set as Set
import Math.NumberTheory.Primes.Factorisation
factors :: Int -> [Int]
factors n = nub $ concatMap(\i -> [i, n `div` i]) $ filter (\i -> n `rem` i == 0) [1..(n `div` 2)]
part1 numberToFind = find (\i -> divisorSum i >= 3400000) [1..]
where n = numberToFind `div` 10
part2 numberToFind = find (\i -> realSum i >= n) [1..]
where
n = numberToFind `div` 11
realSum currentNumber = sum $ Set.filter (\i->i * 50 >= currentNumber) $ divisors currentNumber
main = print $ part2 34000000
|
bruno-cadorette/AdventOfCode
|
Day 20/Day20.hs
|
mit
| 565
| 3
| 11
| 128
| 265
| 140
| 125
| 11
| 1
|
-----------------------------------------------------------------------------
-- |
-- Module : Text.ParserCombinators.Parsec.Expr
-- Copyright : (c) Daan Leijen 1999-2001
-- License : BSD-style (see the file libraries/parsec/LICENSE)
--
-- Maintainer : daan@cs.uu.nl
-- Stability : provisional
-- Portability : portable
--
-- A helper module to parse \"expressions\".
-- Builds a parser given a table of operators and associativities.
--
-----------------------------------------------------------------------------
module Text.ParserCombinators.Parsec.ExprFail
( Erring
, Assoc(..), Operator(..), OperatorTable
, buildExpressionParser
) where
import Text.ParserCombinators.Parsec.Prim
import Text.ParserCombinators.Parsec.Combinator
import Control.Applicative ((<*>),(<$>))
type Erring a = Either String a
-----------------------------------------------------------
-- Assoc and OperatorTable
-----------------------------------------------------------
data Assoc = AssocNone
| AssocLeft
| AssocRight
data Operator t st a = Infix (GenParser t st (a -> a -> Erring a)) Assoc
| Prefix (GenParser t st (a -> Erring a))
| Postfix (GenParser t st (a -> Erring a))
type OperatorTable t st a = [[Operator t st a]]
erringToParsec :: Erring a -> GenParser t st a
erringToParsec = either fail return
-----------------------------------------------------------
-- Convert an OperatorTable and basic term parser into
-- a full fledged expression parser
-----------------------------------------------------------
buildExpressionParser :: OperatorTable tok st a -> GenParser tok st a -> GenParser tok st a
buildExpressionParser operators simpleExpr
= foldl (makeParser) simpleExpr operators
where
makeParser term ops
= let (rassoc,lassoc,nassoc
,prefix,postfix) = foldr splitOp ([],[],[],[],[]) ops
rassocOp = choice rassoc
lassocOp = choice lassoc
nassocOp = choice nassoc
prefixOp = choice prefix <?> ""
postfixOp = choice postfix <?> ""
ambigious assoc op= try $
do{ op; fail ("ambiguous use of a " ++ assoc
++ " associative operator")
}
ambigiousRight = ambigious "right" rassocOp
ambigiousLeft = ambigious "left" lassocOp
ambigiousNon = ambigious "non" nassocOp
termP = do{ pre <- prefixP
; x <- term
; post <- postfixP
; erringToParsec (pre x) >>= erringToParsec . post
}
postfixP = postfixOp <|> return Right
prefixP = prefixOp <|> return Right
rassocP x = do{ f <- rassocOp
; y <- do{ z <- termP; rassocP1 z }
; erringToParsec (f x y)
}
<|> ambigiousLeft
<|> ambigiousNon
-- <|> return x
rassocP1 x = rassocP x <|> return x
lassocP x = do{ f <- lassocOp
; y <- termP
; erringToParsec (f x y) >>= rassocP1
}
<|> ambigiousRight
<|> ambigiousNon
-- <|> return x
lassocP1 x = lassocP x <|> return x
nassocP x = do{ f <- nassocOp
; y <- termP
; ambigiousRight
<|> ambigiousLeft
<|> ambigiousNon
<|> erringToParsec (f x y)
}
-- <|> return x
in do{ x <- termP
; rassocP x <|> lassocP x <|> nassocP x <|> return x
<?> "operator"
}
splitOp (Infix op assoc) (rassoc,lassoc,nassoc,prefix,postfix)
= case assoc of
AssocNone -> (rassoc,lassoc,op:nassoc,prefix,postfix)
AssocLeft -> (rassoc,op:lassoc,nassoc,prefix,postfix)
AssocRight -> (op:rassoc,lassoc,nassoc,prefix,postfix)
splitOp (Prefix op) (rassoc,lassoc,nassoc,prefix,postfix)
= (rassoc,lassoc,nassoc,op:prefix,postfix)
splitOp (Postfix op) (rassoc,lassoc,nassoc,prefix,postfix)
= (rassoc,lassoc,nassoc,prefix,op:postfix)
|
nomeata/darcs-mirror-arbtt
|
src/Text/ParserCombinators/Parsec/ExprFail.hs
|
gpl-2.0
| 5,321
| 0
| 18
| 2,411
| 1,024
| 565
| 459
| 70
| 5
|
{-# LANGUAGE ViewPatterns, ScopedTypeVariables, OverloadedStrings #-}
{-
Copyright (C) 2009 John MacFarlane <jgm@berkeley.edu>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- | Functions for writing a parsed formula as MathML.
-}
module Text.TeXMath.Writers.MathML (writeMathML)
where
import Text.XML.Light
import Text.TeXMath.Types
import Text.TeXMath.Unicode.ToUnicode
import Data.Generics (everywhere, mkT)
import Text.TeXMath.Shared (getMMLType, handleDownup)
import Text.TeXMath.Readers.MathML.MMLDict (getMathMLOperator)
import qualified Data.Text as T
import Text.Printf
-- | Transforms an expression tree to a MathML XML tree
writeMathML :: DisplayType -> [Exp] -> Element
writeMathML dt exprs =
add_attr dtattr $ math $ showExp TextNormal $ EGrouped
$ everywhere (mkT $ handleDownup dt) exprs
where dtattr = Attr (unqual "display") dt'
dt' = case dt of
DisplayBlock -> "block"
DisplayInline -> "inline"
math :: Element -> Element
math = add_attr (Attr (unqual "xmlns") "http://www.w3.org/1998/Math/MathML") . unode "math"
mrow :: [Element] -> Element
mrow = unode "mrow"
showFraction :: TextType -> FractionType -> Exp -> Exp -> Element
showFraction tt ft x y =
case ft of
NormalFrac -> unode "mfrac" [x', y']
InlineFrac -> withAttribute "displaystyle" "false" .
unode "mstyle" . unode "mfrac" $ [x', y']
DisplayFrac -> withAttribute "displaystyle" "true" .
unode "mstyle" . unode "mfrac" $ [x', y']
NoLineFrac -> withAttribute "linethickness" "0" .
unode "mfrac" $ [x', y']
where x' = showExp tt x
y' = showExp tt y
spaceWidth :: Rational -> Element
spaceWidth w =
withAttribute "width" (dropTrailing0s
(T.pack $ printf "%.3f" (fromRational w :: Double)) <> "em") $ unode "mspace" ()
makeStretchy :: FormType -> Element -> Element
makeStretchy (fromForm -> t) = withAttribute "stretchy" "true"
. withAttribute "form" t
fromForm :: FormType -> T.Text
fromForm FInfix = "infix"
fromForm FPostfix = "postfix"
fromForm FPrefix = "prefix"
makeScaled :: Rational -> Element -> Element
makeScaled x = withAttribute "minsize" s . withAttribute "maxsize" s
where s = dropTrailing0s $ T.pack $ printf "%.3f" (fromRational x :: Double)
dropTrailing0s :: T.Text -> T.Text
dropTrailing0s t = case T.unsnoc t of -- T.spanEnd does not exist
Just (ts, '0') -> addZero $ T.dropWhileEnd (== '0') ts
_ -> t
where
addZero x = case T.unsnoc x of
Just (_, '.') -> T.snoc x '0'
_ -> x
makeStyled :: TextType -> [Element] -> Element
makeStyled a es = withAttribute "mathvariant" attr
$ unode "mstyle" es
where attr = getMMLType a
-- Note: Converts strings to unicode directly, as few renderers support those mathvariants.
makeText :: TextType -> T.Text -> Element
makeText a s = case (leadingSp, trailingSp) of
(False, False) -> s'
(True, False) -> mrow [sp, s']
(False, True) -> mrow [s', sp]
(True, True) -> mrow [sp, s', sp]
where sp = spaceWidth (1/3)
s' = withAttribute "mathvariant" attr $ tunode "mtext" $ toUnicode a s
trailingSp = case T.unsnoc s of
Just (_, c) -> T.any (== c) " \t"
_ -> False
leadingSp = case T.uncons s of
Just (c, _) -> T.any (== c) " \t"
_ -> False
attr = getMMLType a
makeArray :: TextType -> [Alignment] -> [ArrayLine] -> Element
makeArray tt as ls = unode "mtable" $
map (unode "mtr" .
zipWith (\a -> setAlignment a . unode "mtd". map (showExp tt)) as') ls
where setAlignment AlignLeft = withAttribute "columnalign" "left"
setAlignment AlignRight = withAttribute "columnalign" "right"
setAlignment AlignCenter = withAttribute "columnalign" "center"
as' = as ++ cycle [AlignCenter]
-- Kept as String for Text.XML.Light
withAttribute :: String -> T.Text -> Element -> Element
withAttribute a = add_attr . Attr (unqual a) . T.unpack
accent :: T.Text -> Element
accent = add_attr (Attr (unqual "accent") "true") .
tunode "mo"
makeFence :: FormType -> Element -> Element
makeFence (fromForm -> t) = withAttribute "stretchy" "false" . withAttribute "form" t
showExp' :: TextType -> Exp -> Element
showExp' tt e =
case e of
ESymbol Accent x -> accent x
ESymbol _ x ->
let isaccent = case (elem "accent") . properties <$>
getMathMLOperator x FPostfix of
Just True -> "true"
_ -> "false"
in withAttribute "accent" isaccent $ tunode "mo" x
_ -> showExp tt e
showExp :: TextType -> Exp -> Element
showExp tt e =
case e of
ENumber x -> tunode "mn" x
EGrouped [x] -> showExp tt x
EGrouped xs -> mrow $ map (showExp tt) xs
EDelimited start end xs -> mrow $
[ makeStretchy FPrefix (tunode "mo" start) | not (T.null start) ] ++
map (either (makeStretchy FInfix . tunode "mo") (showExp tt)) xs ++
[ makeStretchy FPostfix (tunode "mo" end) | not (T.null end) ]
EIdentifier x -> tunode "mi" $ toUnicode tt x
EMathOperator x -> tunode "mo" x
ESymbol Open x -> makeFence FPrefix $ tunode "mo" x
ESymbol Close x -> makeFence FPostfix $ tunode "mo" x
ESymbol Ord x -> tunode "mi" x
ESymbol _ x -> tunode "mo" x
ESpace x -> spaceWidth x
EFraction ft x y -> showFraction tt ft x y
ESub x y -> unode "msub" $ map (showExp tt) [x, y]
ESuper x y -> unode "msup" $ map (showExp tt) [x, y]
ESubsup x y z -> unode "msubsup" $ map (showExp tt) [x, y, z]
EUnder _ x y -> unode "munder" [showExp tt x, showExp' tt y]
EOver _ x y -> unode "mover" [showExp tt x, showExp' tt y]
EUnderover _ x y z -> unode "munderover"
[showExp tt x, showExp' tt y, showExp' tt z]
EPhantom x -> unode "mphantom" $ showExp tt x
EBoxed x -> withAttribute "notation" "box" .
unode "menclose" $ showExp tt x
ESqrt x -> unode "msqrt" $ showExp tt x
ERoot i x -> unode "mroot" [showExp tt x, showExp tt i]
EScaled s x -> makeScaled s $ showExp tt x
EArray as ls -> makeArray tt as ls
EText a s -> makeText a s
EStyled a es -> makeStyled a $ map (showExp a) es
-- Kept as String for Text.XML.Light
tunode :: String -> T.Text -> Element
tunode s = unode s . T.unpack
|
jgm/texmath
|
src/Text/TeXMath/Writers/MathML.hs
|
gpl-2.0
| 7,316
| 0
| 16
| 2,048
| 2,252
| 1,121
| 1,131
| 136
| 26
|
-- file: ch4/exA1.hs
-- Safe versions of some basic list manipulation functions.
safeHead :: [a] -> Maybe a
safeHead (x : _) = Just x
safeHead _ = Nothing
safeTail :: [a] -> Maybe [a]
safeTail (_ : xs) = Just xs
safeTail _ = Nothing
safeLast :: [a] -> Maybe a
safeLast [] = Nothing
safeLast xs = Just . head . reverse $ xs
safeInit :: [a] -> Maybe [a]
safeInit [] = Nothing
safeInit xs = Just . reverse . tail . reverse $ xs
|
friedbrice/RealWorldHaskell
|
ch4/exA1.hs
|
gpl-2.0
| 442
| 2
| 8
| 105
| 209
| 100
| 109
| 12
| 1
|
{-# LANGUAGE Arrows, NoMonomorphismRestriction #-}
module Main where
import MapLoader.SVG
import DataLoader.CSV
import Maps.Spatial
import Maps.DataType
import qualified Maps.Map as M
import qualified Data.Map as Map
import Diagrams.Prelude hiding (deep)
import Diagrams.Backend.SVG.CmdLine
import qualified Data.ByteString.Lazy as BL
import Data.Colour.Palette.BrewerSet
import qualified Data.Vector as V
import qualified Data.Csv as C
-- | MAIN ------------------------------------------------------------------------------------------------------------
-- ...................................................................................................................
-- ___________________________________________________________________________________________________________________
-- |In this file we will map a composite parameter, which is the division between the population and the net migration with
-- a custom graph over the regions, which is described in the method "customSymbol"
main :: IO ()
main = do
migrations <- BL.readFile "data/netMigration2013.csv"
gbpdata <- BL.readFile "source/indicators/CSVs/worldGBPCountries.csv"
population <- BL.readFile "data/population.csv"
regions <- parseFile "source/worldmap.svg"
let tree = buildTree regions
let changeColors ds@EntitySet{c = ctx}= ds{c = ctx{brewerset = RdYlBu}}
let m = changeColors (parseCSV migrations 1:: DataSet StvRatio)
let g = parseCSV gbpdata 1:: DataSet StvRatio
let p = parseCSV population 1:: DataSet StvRatio
let gbp = dsToNominal g (\x -> if x>327000000000 then 0 else 1) ["circle","square"]
let mbyp = compositeDs (\a b -> a / b) m p
let res = M.buildDiagram $ [customSymbol gbp m p # M.fAll, M.printRegions # M.mapData M.mapHue mbyp # M.fAll] `M.from` ($ tree)
mainWith ( res )
-- | The custom simbol will map:
-- - A shape depending on the gbp of the country, being a circle for the rich and a square for the poor
-- - A color depending on the net migrations
-- - A size depending on the population of the country
customSymbol :: (RetHue b, RetSize c) => DataSet String -> DataSet b -> DataSet c ->(SPtree, [Region]) -> [(String, Diagram B)]
customSymbol is ic iz (tree, regions) =
let
face r = (innerShape r) # fc (innerColor r) # scale (innerSize r)
innerShape code = symbShape $ Map.lookup code (v is)
innerColor code = hue (c ic) $ Map.lookup code (v ic)
innerSize code = size' (5,20) (c iz) ( Map.lookup code (v iz) )
center c = (\(Just p)->p) $ rcenter c regions
pos c = position [(center c,face c)]
in [ ( "face - " ++ c, pos c) | region <- regions, let c = code region]
symbShape :: Maybe String -> Diagram B
symbShape Nothing = triangle 1
symbShape (Just "circle") = circle 1
symbShape _ = square 1
|
sc14lga/Maps
|
examples/mapping data in custom shapes/Main.hs
|
gpl-2.0
| 2,761
| 2
| 16
| 447
| 811
| 425
| 386
| 43
| 2
|
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Algebra.Morphism.Affine where
import Prelude (Eq(..), Ord(..), Functor(..), id,Bool(..),Show,otherwise)
import Algebra.Classes
import Algebra.Linear
import qualified Data.Map as M
import Data.Either
import Control.Applicative
import Algebra.Morphism.LinComb (LinComb(..))
import qualified Algebra.Morphism.LinComb as LC
data Affine x c = Affine c (LinComb x c)
deriving (Functor, Eq, Ord,Show)
instance Multiplicative c => Scalable c (Affine x c) where
k *^ x = k *< x
instance (Ord x, AbelianAdditive c,DecidableZero c) => AbelianAdditive (Affine x c)
instance (Ord x, AbelianAdditive c,Group c,DecidableZero c) => Group (Affine x c) where
negate = fmap negate
instance (Ord x, AbelianAdditive c,DecidableZero c) => Additive (Affine x c) where
(Affine c1 xs1) + (Affine c2 xs2) = Affine (c1 + c2) (xs1 + xs2)
zero = Affine zero zero
splitVar :: Ord x => Additive c => x -> Affine x c -> (c, Affine x c)
splitVar x (Affine c0 (LinComb m)) = (M.findWithDefault zero x m, Affine c0 (LinComb (M.delete x m)))
-- | @solve x f@ solves the equation @f == 0@ for x.
-- Let f = k x + e. If k == 0, return Left e. Otherwise, x and return Right -e/k. (The value of x)
solve :: (Ord scalar, Eq scalar, Field scalar, Ord x,DecidableZero scalar)
=> x -> Affine x scalar -> Either (Affine x scalar) (Bool,Affine x scalar)
solve x f = if k == zero then Left e else Right (k>zero,recip k *^ negate e)
where (k,e) = splitVar x f
-- | Constant affine expression
constant :: (AbelianAdditive c, DecidableZero c) => Ord x => c -> Affine x c
constant c = Affine c zero
isConstant :: Eq c => Ord x => DecidableZero c => Affine x c -> Either x c
isConstant (Affine k x) = case LC.toList x of
[] -> Right k
((v,_):_) -> Left v
var :: Multiplicative c => Additive c => v -> Affine v c
var x = Affine zero (LC.var x)
eval :: forall x c v. (Additive x, Scalable x x) => (c -> x) -> (v -> x) -> Affine v c -> x
eval fc fv (Affine c p) = fc c + LC.eval fc fv p
subst :: (Ord x, AbelianAdditive c, DecidableZero c, Multiplicative c) => (v -> Affine x c) -> Affine v c -> Affine x c
subst f (Affine c p) = constant c + LC.eval id f p
mapVars :: Ord x => (v -> x) -> Affine v c -> Affine x c
mapVars f (Affine k e) = Affine k (LC.mapVars f e)
traverseVars :: Ord x => Applicative f => (v -> f x) -> Affine v c -> f (Affine x c)
traverseVars f (Affine k e) = Affine k <$> LC.traverseVars f e
|
jyp/gasp
|
Algebra/Morphism/Affine.hs
|
gpl-3.0
| 2,620
| 0
| 11
| 525
| 1,158
| 598
| 560
| 47
| 2
|
module UnitParty.Convert
( convert
, equidimensional
) where
import UnitParty.Types
import qualified Data.Map as M
import Data.Monoid (mempty)
import Data.Function (on)
import Data.Maybe (isNothing, isJust)
import Data.List (find)
import Control.Monad (join)
import Control.Applicative ((<|>))
-- attempt to derive a function to convert between units. this can fail if
-- (a) the units do not have compatible dimensions; or
-- (b) one of the units is nonsense.
convert :: Unit -> Unit -> Either ConversionError (Double -> Double)
convert u1@(U a) u2@(U b) = maybe (Right (to . from)) Left checks
where
checks = mixCheck u1 <|> mixCheck u2 <|> dimCheck u1 u2
from x = (x - constantTerm a) * coefficient a
to y = y / coefficient b + constantTerm b
constantTerm = M.findWithDefault 0 mempty
coefficient = snd . M.findMax
-- boolean test for dimensional compatibility
equidimensional :: Unit -> Unit -> Bool
equidimensional = (isNothing .) . dimCheck
-- test for dimensional compatibility & return an informative error if the
-- test fails.
dimCheck :: Unit -> Unit -> Maybe ConversionError
dimCheck (U u1) (U u2) = join . find isJust $ zipWith check (ds u1) (ds u2)
where ds = M.keys . M.delete mempty
check d1@(D a) d2@(D b) | a =~= b = Nothing
| otherwise = Just (Incommensurable d1 d2)
(=~=) = (==) `on` M.filter (/=0)
-- check for mixed nonzero-degree polynomial dimensions like the you get when
-- computing fahrenheit^2. what does that even mean ??
mixCheck :: Unit -> Maybe ConversionError
mixCheck u@(U a) | M.size (M.delete mempty a) == 1 = Nothing
| otherwise = Just (MixedDegrees u)
|
walpurgisriot/unitparty
|
UnitParty/Convert.hs
|
gpl-3.0
| 1,688
| 0
| 12
| 364
| 535
| 285
| 250
| 29
| 1
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
module Api.Package
( resource
, validatePackage
, loadPackageSummary
) where
import Control.Monad.Except
import Control.Monad.Reader
import Data.Aeson (FromJSON (..), decode, withObject, (.:))
import Data.Bool
import Data.List
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Ord
import qualified Data.Set as Set
import Data.String
import qualified Data.Text as T
import Data.Time
import Rest
import qualified Rest.Resource as R
import Api.Root
import Api.Types
import Api.Utils
import BuildTypes hiding (PkgVerStatus (..))
import Config
import Paths
import Tag
data Listing
= All
| LatestReports
resource :: Resource Root WithPackage PackageName Listing Void
resource = mkResourceReader
{ R.name = "package"
, R.schema = withListing All $ named [ ("name" , singleBy fromString)
, ("latest-reports", listing LatestReports)
]
, R.get = Just get
, R.actions = [("tags", tags)]
, R.list = \case
All -> list
LatestReports -> listLatestReport
}
get :: Handler WithPackage
get = mkIdHandler jsonO $ const handler
where
handler :: PackageName -> ExceptT Reason_ WithPackage Package
handler pkgName = do
validatePackage pkgName
liftIO (xcabalPackage pkgName) `orThrow` Busy
list :: ListHandler Root
list = mkListing jsonO handler
where
handler :: Range -> ExceptT Reason_ Root [PackageMeta]
handler r = do
reports <- reportsByStamp
pkgs <- loadPackageSummary
ts <- loadTags
return . listRange r . f ts reports . Set.toList $ pkgs
f :: Tags -> [ReportMeta] -> [PackageName] -> [PackageMeta]
f ts reps pkgs
= map (\(pn,rs) -> PackageMeta
{ pmName = pn
, pmReport = rs
, pmTags = Tag.lookupByPackage pn ts
}
)
. Map.toList
. foldl' (\pm rt -> Map.insert (rmPackageName rt) (Just $ rmModified rt) pm) pkgMap
$ reps
where
pkgMap :: Map PackageName (Maybe a)
pkgMap = Map.fromList . map (,Nothing) $ pkgs
listLatestReport :: ListHandler Root
listLatestReport = mkListing jsonO handler
where
handler :: Range -> ExceptT Reason_ Root [ReportMeta]
handler r = listRange r <$> reportsByStamp
tags :: Handler WithPackage
tags = mkConstHandler jsonO handler
where
handler :: ExceptT Reason_ WithPackage (Set TagName)
handler = Tag.byPackage =<< ask
reportsByStamp :: (MonadIO m, MonadConfig m) => m [ReportMeta]
reportsByStamp
= fmap (map toReportMeta . sortBy (flip $ comparing snd))
. liftIO . filesByStamp (".json" `isSuffixOf`)
=<< asksConfig reportDir
where
toReportMeta :: (Text, UTCTime) -> ReportMeta
toReportMeta (a,b) = ReportMeta
{ rmPackageName = PackageName . T.reverse . T.drop 5 . T.reverse $ a
, rmModified = b
}
validatePackage :: MonadRoot m => PackageName -> ExceptT Reason_ m ()
validatePackage pkgName =
bool (throwError NotFound) (return ()) . (pkgName `elem`) =<< loadPackageSummary
loadPackageSummary :: (MonadIO m, MonadConfig m) => m (Set PackageName)
loadPackageSummary
= fmap (Set.fromList . fromMaybe [])
. fmap (fmap (map summaryName) . decode)
. liftIO . lazyReadFileP
=<< asksConfig packagesJson
newtype PackageSummary = PackageSummary { summaryName :: PackageName }
deriving (Eq, Show)
instance FromJSON PackageSummary where
parseJSON = withObject "PackageMeta" $ fmap PackageSummary . (.: "packageName")
|
imalsogreg/hackage-matrix-builder
|
src/Api/Package.hs
|
gpl-3.0
| 3,970
| 0
| 16
| 1,177
| 1,104
| 602
| 502
| 97
| 2
|
module Stat where
import System.Fuse
import System.Posix.Files
dirStat :: FuseContext -> FileStat
dirStat ctx = FileStat {
statEntryType = Directory
, statFileMode = foldr1 unionFileModes
[ ownerReadMode
, ownerExecuteMode
, groupReadMode
, groupExecuteMode
, otherReadMode
, otherExecuteMode
]
, statLinkCount = 2
, statFileOwner = fuseCtxUserID ctx
, statFileGroup = fuseCtxGroupID ctx
, statSpecialDeviceID = 0
, statFileSize = 4096
, statBlocks = 1
, statAccessTime = 0
, statModificationTime = 0
, statStatusChangeTime = 0
}
fileStat :: Integral a => FuseContext -> a -> FileStat
fileStat ctx size = FileStat {
statEntryType = RegularFile
, statFileMode = foldr1 unionFileModes
[ ownerReadMode
, groupReadMode
, otherReadMode
, ownerWriteMode
]
, statLinkCount = 1
, statFileOwner = fuseCtxUserID ctx
, statFileGroup = fuseCtxGroupID ctx
, statSpecialDeviceID = 0
, statFileSize = fromIntegral size
, statBlocks = 1
, statAccessTime = 0
, statModificationTime = 0
, statStatusChangeTime = 0
}
linkStat :: Integral a => FuseContext -> a -> FileStat
linkStat ctx size = FileStat {
statEntryType = SymbolicLink
, statFileMode = accessModes
, statLinkCount = 1
, statFileOwner = fuseCtxUserID ctx
, statFileGroup = fuseCtxGroupID ctx
, statSpecialDeviceID = 0
, statFileSize = fromIntegral size
, statBlocks = 1
, statAccessTime = 0
, statModificationTime = 0
, statStatusChangeTime = 0
}
realFileStat :: FilePath -> IO FileStat
realFileStat uri = do
status <- getFileStatus uri
return FileStat {
statEntryType = RegularFile
, statFileMode = fileMode status
, statLinkCount = linkCount status
, statFileOwner = fileOwner status
, statFileGroup = fileGroup status
, statSpecialDeviceID = specialDeviceID status
, statFileSize = fileSize status
, statBlocks = 1 -- This is WRONG. Change
, statAccessTime= accessTime status
, statModificationTime = modificationTime status
, statStatusChangeTime = statusChangeTime status
}
|
ffwng/tagfs
|
Stat.hs
|
gpl-3.0
| 2,024
| 24
| 10
| 389
| 516
| 299
| 217
| 67
| 1
|
module PrettyShow (prettyParse) where
import Parser
import Data.List
indent :: Int -> String
indent depth = concat $ take depth (repeat "---")
class PrettyShow a where
prettyShow :: a -> String
prettyParse :: a -> Int -> String -> String
-- instances for pretty printing
instance PrettyShow Program where
prettyShow _ = "Program\n"
prettyParse b@(Program p) depth acc = prettyParse p (depth + 1) (acc ++ (prettyShow b))
instance PrettyShow BlockList where
prettyShow _ = "BlockList [\n"
prettyParse bl@(BlockList bls) depth acc = acc ++ (indent depth) ++(prettyShow bl) ++ (concat $ map (\b -> case b of
bs@(BlockStatement _ ) -> prettyParse bs (depth+1) ""
fs@(FunctionBlockStatement _ _ _ _ _ ) -> prettyParse fs (depth+1) ""
ud@(UDTStatement _ _) -> prettyParse ud depth ""
) bls) ++ (indent depth) ++ "]\n"
instance PrettyShow BlockStatement where
prettyShow (BlockStatement _ ) = "BlockStatement:\n"
prettyShow (FunctionBlockStatement _ _ _ _ _ ) = "FunctionBlockStatement:"
prettyParse b@(BlockStatement bs) depth acc = (indent depth) ++ (prettyShow b) ++ prettyParse bs (depth+1) ""
prettyParse fs@(FunctionBlockStatement returnType name formalParameters implicitParameters body ) depth acc = (indent depth) ++ concat (intersperse " " [(prettyShow fs)
, (show returnType)
, (show name)
, (show formalParameters)
, (show implicitParameters), "\n"])
++ prettyParse body (depth +1) " "
prettyParse udt@(UDTStatement name signature) depth acc = (indent depth) ++ (show udt) ++ "\n"
instance PrettyShow BlockBody where
prettyShow (BlockBody _ ) = "BlockBody:\n"
prettyParse fb@(BlockBody body) depth acc = (indent depth) ++ (prettyShow fb) ++ prettyParse body (depth+1) acc
instance PrettyShow StatementList where
prettyShow _ = "StatementList [\n"
prettyParse s@(StatementList stmts) depth acc = (indent depth) ++ (prettyShow s) ++ (concat $ map (\stmt ->
prettyParse stmt (depth) (acc ++ (indent depth))
) stmts) ++ (indent $ depth) ++ "]\n"
instance PrettyShow Statement where
prettyShow _ = error "Not Implemented"
prettyParse (AssignStatement ident expr) depth acc = acc ++ (indent depth) ++ "(AssignStatement " ++ (show ident) ++ " " ++ (show expr) ++ ")\n"
prettyParse (LocalVarDeclStatement spec) depth acc = acc ++ (indent depth) ++ "(LocalVarDeclStatement " ++ (show spec) ++ ")\n"
prettyParse (ReturnStatement stmt) depth acc = acc ++ (indent depth) ++ "(ReturnStatement " ++ (show stmt) ++ "\n"
prettyParse (Skip) depth acc = acc ++ "Skip" ++ "\n"
prettyParse (WhileStatement condition body) depth acc = acc ++ (indent depth) ++ "(WhileStatement " ++ (show condition) ++ "\n" ++ (prettyParse body (depth+4) "")
prettyParse (IfStatement condition trueBranch falseBranch) depth acc = acc ++ (indent depth) ++ "(IfStatement " ++ (show condition) ++ "\n" ++ (prettyParse trueBranch (depth+4) "") ++ (prettyParse falseBranch (depth+4) "")
prettyParse (FunctionCallStatement fn) depth acc = acc ++ (indent depth) ++ "(FunctionCallStatement " ++ (show fn) ++ "\n"
|
jsinglet/Paradox
|
src/PrettyShow.hs
|
gpl-3.0
| 4,343
| 0
| 19
| 1,815
| 1,191
| 611
| 580
| 46
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.