code
stringlengths 2
1.05M
| repo_name
stringlengths 5
101
| path
stringlengths 4
991
| language
stringclasses 3
values | license
stringclasses 5
values | size
int64 2
1.05M
|
|---|---|---|---|---|---|
module Vector where
data Vec = V !Int !Int deriving (Show, Eq)
instance Num Vec where
V x1 y1 + V x2 y2 = V (x1+x2) (y1+y2)
V x1 y1 - V x2 y2 = V (x1-x2) (y1-y2)
V x1 y1 * V x2 y2 = V (x1*x2) (y1*y2)
abs (V x y) = V (abs x) (abs y)
signum (V x y) = V (signum x) (signum y)
fromInteger x = V (fromInteger x) (fromInteger x)
|
cobbpg/dow
|
src/Vector.hs
|
Haskell
|
bsd-3-clause
| 337
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE NoImplicitPrelude #-}
module Ircbrowse.View.Template where
import Ircbrowse.View
import Ircbrowse.Types.Import
import qualified Text.Blaze.Html5 as H
import Data.Text (Text)
template :: AttributeValue -> Text -> Html -> Html -> Html
template name thetitle innerhead innerbody = do
docType
html $ do
head $ do H.title $ toHtml thetitle
link ! rel "stylesheet" ! type_ "text/css" ! href "/css/bootstrap.min.css"
link ! rel "stylesheet" ! type_ "text/css" ! href "/css/bootstrap-responsive.css"
link ! rel "stylesheet" ! type_ "text/css" ! href "/css/ircbrowse.css"
meta ! httpEquiv "Content-Type" ! content "text/html; charset=UTF-8"
innerhead
body !# name $ do
innerbody
preEscapedToHtml ("<script type=\"text/javascript\"> var _gaq = _gaq \
\|| []; _gaq.push(['_setAccount', 'UA-38975161-1']);\
\ _gaq.push(['_trackPageview']); (function() {var ga\
\ = document.createElement('script'); ga.type = 'tex\
\t/javascript'; ga.async = true; ga.src = ('https:' \
\== document.location.protocol ? 'https://ssl' : \
\'http://www') + '.google-analytics.com/ga.js'; var\
\ s = document.getElementsByTagName('script')[0]; \
\s.parentNode.insertBefore(ga, s);})(); </script>" :: Text)
channelNav :: Channel -> Html
channelNav channel =
div !. "navbar navbar-static-top navbar-inverse" $
div !. "navbar-inner" $ do
div !. "container" $ do
a !. "brand" ! href "/" $ "IRCBrowse"
ul !. "nav" $ do
li $ a ! href (toValue ("/" ++ showChan channel)) $ do
(toHtml (prettyChan channel))
li $ a ! href (toValue ("/browse/" ++ showChan channel)) $ do
"Browse"
-- li $ a ! href (toValue ("/day/" ++ showChan channel ++ "/today/recent")) $ do
-- "Recent"
-- li $ a ! href (toValue ("/day/" ++ showChan channel ++ "/today")) $ do
-- "Today"
-- li $ a ! href (toValue ("/calendar/" ++ showChan channel)) $ do
-- "Calendar"
-- li $ a ! href (toValue ("/nicks/" ++ showChan channel)) $ do
-- "Nicks"
-- li $ a ! href (toValue ("/pdfs/" ++ showChan channel)) $ do
-- "PDFs"
showCount :: (Show n,Integral n) => n -> String
showCount = reverse . foldr merge "" . zip ("000,00,00,00"::String) . reverse . show where
merge (f,c) rest | f == ',' = "," ++ [c] ++ rest
| otherwise = [c] ++ rest
footer :: Html
footer =
div !# "footer" $
div !. "container" $ do
p !. "muted credit" $ do
a ! href "http://ircbrowse.net" $ "IRC Browse"
" by "
a ! href "http://chrisdone.com" $ "Chris Done"
" | "
a ! href "https://github.com/chrisdone/ircbrowse" $ "Source code"
" | "
a ! href "http://haskell.org/" $ "Haskell"
mainHeading :: Html -> Html
mainHeading inner = h1 $ do
a ! href "/" $ do "IRC Browse"
": "
inner
|
chrisdone/ircbrowse
|
src/Ircbrowse/View/Template.hs
|
Haskell
|
bsd-3-clause
| 3,220
|
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.Compatibility31
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.Compatibility31 (
-- * Types
GLbitfield,
GLboolean,
GLbyte,
GLchar,
GLclampd,
GLclampf,
GLdouble,
GLenum,
GLfloat,
GLhalf,
GLint,
GLintptr,
GLshort,
GLsizei,
GLsizeiptr,
GLubyte,
GLuint,
GLushort,
GLvoid,
-- * Enums
gl_2D,
gl_2_BYTES,
gl_3D,
gl_3D_COLOR,
gl_3D_COLOR_TEXTURE,
gl_3_BYTES,
gl_4D_COLOR_TEXTURE,
gl_4_BYTES,
gl_ACCUM,
gl_ACCUM_ALPHA_BITS,
gl_ACCUM_BLUE_BITS,
gl_ACCUM_BUFFER_BIT,
gl_ACCUM_CLEAR_VALUE,
gl_ACCUM_GREEN_BITS,
gl_ACCUM_RED_BITS,
gl_ACTIVE_ATTRIBUTES,
gl_ACTIVE_ATTRIBUTE_MAX_LENGTH,
gl_ACTIVE_TEXTURE,
gl_ACTIVE_UNIFORMS,
gl_ACTIVE_UNIFORM_BLOCKS,
gl_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH,
gl_ACTIVE_UNIFORM_MAX_LENGTH,
gl_ADD,
gl_ADD_SIGNED,
gl_ALIASED_LINE_WIDTH_RANGE,
gl_ALIASED_POINT_SIZE_RANGE,
gl_ALL_ATTRIB_BITS,
gl_ALPHA,
gl_ALPHA12,
gl_ALPHA16,
gl_ALPHA4,
gl_ALPHA8,
gl_ALPHA_BIAS,
gl_ALPHA_BITS,
gl_ALPHA_INTEGER,
gl_ALPHA_SCALE,
gl_ALPHA_TEST,
gl_ALPHA_TEST_FUNC,
gl_ALPHA_TEST_REF,
gl_ALWAYS,
gl_AMBIENT,
gl_AMBIENT_AND_DIFFUSE,
gl_AND,
gl_AND_INVERTED,
gl_AND_REVERSE,
gl_ARRAY_BUFFER,
gl_ARRAY_BUFFER_BINDING,
gl_ATTACHED_SHADERS,
gl_ATTRIB_STACK_DEPTH,
gl_AUTO_NORMAL,
gl_AUX0,
gl_AUX1,
gl_AUX2,
gl_AUX3,
gl_AUX_BUFFERS,
gl_BACK,
gl_BACK_LEFT,
gl_BACK_RIGHT,
gl_BGR,
gl_BGRA,
gl_BGRA_INTEGER,
gl_BGR_INTEGER,
gl_BITMAP,
gl_BITMAP_TOKEN,
gl_BLEND,
gl_BLEND_DST,
gl_BLEND_DST_ALPHA,
gl_BLEND_DST_RGB,
gl_BLEND_EQUATION_ALPHA,
gl_BLEND_EQUATION_RGB,
gl_BLEND_SRC,
gl_BLEND_SRC_ALPHA,
gl_BLEND_SRC_RGB,
gl_BLUE,
gl_BLUE_BIAS,
gl_BLUE_BITS,
gl_BLUE_INTEGER,
gl_BLUE_SCALE,
gl_BOOL,
gl_BOOL_VEC2,
gl_BOOL_VEC3,
gl_BOOL_VEC4,
gl_BUFFER_ACCESS,
gl_BUFFER_ACCESS_FLAGS,
gl_BUFFER_MAPPED,
gl_BUFFER_MAP_LENGTH,
gl_BUFFER_MAP_OFFSET,
gl_BUFFER_MAP_POINTER,
gl_BUFFER_SIZE,
gl_BUFFER_USAGE,
gl_BYTE,
gl_C3F_V3F,
gl_C4F_N3F_V3F,
gl_C4UB_V2F,
gl_C4UB_V3F,
gl_CCW,
gl_CLAMP,
gl_CLAMP_FRAGMENT_COLOR,
gl_CLAMP_READ_COLOR,
gl_CLAMP_TO_BORDER,
gl_CLAMP_TO_EDGE,
gl_CLAMP_VERTEX_COLOR,
gl_CLEAR,
gl_CLIENT_ACTIVE_TEXTURE,
gl_CLIENT_ALL_ATTRIB_BITS,
gl_CLIENT_ATTRIB_STACK_DEPTH,
gl_CLIENT_PIXEL_STORE_BIT,
gl_CLIENT_VERTEX_ARRAY_BIT,
gl_CLIP_DISTANCE0,
gl_CLIP_DISTANCE1,
gl_CLIP_DISTANCE2,
gl_CLIP_DISTANCE3,
gl_CLIP_DISTANCE4,
gl_CLIP_DISTANCE5,
gl_CLIP_DISTANCE6,
gl_CLIP_DISTANCE7,
gl_CLIP_PLANE0,
gl_CLIP_PLANE1,
gl_CLIP_PLANE2,
gl_CLIP_PLANE3,
gl_CLIP_PLANE4,
gl_CLIP_PLANE5,
gl_COEFF,
gl_COLOR,
gl_COLOR_ARRAY,
gl_COLOR_ARRAY_BUFFER_BINDING,
gl_COLOR_ARRAY_POINTER,
gl_COLOR_ARRAY_SIZE,
gl_COLOR_ARRAY_STRIDE,
gl_COLOR_ARRAY_TYPE,
gl_COLOR_ATTACHMENT0,
gl_COLOR_ATTACHMENT1,
gl_COLOR_ATTACHMENT10,
gl_COLOR_ATTACHMENT11,
gl_COLOR_ATTACHMENT12,
gl_COLOR_ATTACHMENT13,
gl_COLOR_ATTACHMENT14,
gl_COLOR_ATTACHMENT15,
gl_COLOR_ATTACHMENT2,
gl_COLOR_ATTACHMENT3,
gl_COLOR_ATTACHMENT4,
gl_COLOR_ATTACHMENT5,
gl_COLOR_ATTACHMENT6,
gl_COLOR_ATTACHMENT7,
gl_COLOR_ATTACHMENT8,
gl_COLOR_ATTACHMENT9,
gl_COLOR_BUFFER_BIT,
gl_COLOR_CLEAR_VALUE,
gl_COLOR_INDEX,
gl_COLOR_INDEXES,
gl_COLOR_LOGIC_OP,
gl_COLOR_MATERIAL,
gl_COLOR_MATERIAL_FACE,
gl_COLOR_MATERIAL_PARAMETER,
gl_COLOR_SUM,
gl_COLOR_WRITEMASK,
gl_COMBINE,
gl_COMBINE_ALPHA,
gl_COMBINE_RGB,
gl_COMPARE_REF_TO_TEXTURE,
gl_COMPARE_R_TO_TEXTURE,
gl_COMPILE,
gl_COMPILE_AND_EXECUTE,
gl_COMPILE_STATUS,
gl_COMPRESSED_ALPHA,
gl_COMPRESSED_INTENSITY,
gl_COMPRESSED_LUMINANCE,
gl_COMPRESSED_LUMINANCE_ALPHA,
gl_COMPRESSED_RED,
gl_COMPRESSED_RED_RGTC1,
gl_COMPRESSED_RG,
gl_COMPRESSED_RGB,
gl_COMPRESSED_RGBA,
gl_COMPRESSED_RG_RGTC2,
gl_COMPRESSED_SIGNED_RED_RGTC1,
gl_COMPRESSED_SIGNED_RG_RGTC2,
gl_COMPRESSED_SLUMINANCE,
gl_COMPRESSED_SLUMINANCE_ALPHA,
gl_COMPRESSED_SRGB,
gl_COMPRESSED_SRGB_ALPHA,
gl_COMPRESSED_TEXTURE_FORMATS,
gl_CONSTANT,
gl_CONSTANT_ALPHA,
gl_CONSTANT_ATTENUATION,
gl_CONSTANT_COLOR,
gl_CONTEXT_FLAGS,
gl_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT,
gl_COORD_REPLACE,
gl_COPY,
gl_COPY_INVERTED,
gl_COPY_PIXEL_TOKEN,
gl_COPY_READ_BUFFER,
gl_COPY_WRITE_BUFFER,
gl_CULL_FACE,
gl_CULL_FACE_MODE,
gl_CURRENT_BIT,
gl_CURRENT_COLOR,
gl_CURRENT_FOG_COORD,
gl_CURRENT_FOG_COORDINATE,
gl_CURRENT_INDEX,
gl_CURRENT_NORMAL,
gl_CURRENT_PROGRAM,
gl_CURRENT_QUERY,
gl_CURRENT_RASTER_COLOR,
gl_CURRENT_RASTER_DISTANCE,
gl_CURRENT_RASTER_INDEX,
gl_CURRENT_RASTER_POSITION,
gl_CURRENT_RASTER_POSITION_VALID,
gl_CURRENT_RASTER_SECONDARY_COLOR,
gl_CURRENT_RASTER_TEXTURE_COORDS,
gl_CURRENT_SECONDARY_COLOR,
gl_CURRENT_TEXTURE_COORDS,
gl_CURRENT_VERTEX_ATTRIB,
gl_CW,
gl_DECAL,
gl_DECR,
gl_DECR_WRAP,
gl_DELETE_STATUS,
gl_DEPTH,
gl_DEPTH24_STENCIL8,
gl_DEPTH32F_STENCIL8,
gl_DEPTH_ATTACHMENT,
gl_DEPTH_BIAS,
gl_DEPTH_BITS,
gl_DEPTH_BUFFER_BIT,
gl_DEPTH_CLEAR_VALUE,
gl_DEPTH_COMPONENT,
gl_DEPTH_COMPONENT16,
gl_DEPTH_COMPONENT24,
gl_DEPTH_COMPONENT32,
gl_DEPTH_COMPONENT32F,
gl_DEPTH_FUNC,
gl_DEPTH_RANGE,
gl_DEPTH_SCALE,
gl_DEPTH_STENCIL,
gl_DEPTH_STENCIL_ATTACHMENT,
gl_DEPTH_TEST,
gl_DEPTH_TEXTURE_MODE,
gl_DEPTH_WRITEMASK,
gl_DIFFUSE,
gl_DITHER,
gl_DOMAIN,
gl_DONT_CARE,
gl_DOT3_RGB,
gl_DOT3_RGBA,
gl_DOUBLE,
gl_DOUBLEBUFFER,
gl_DRAW_BUFFER,
gl_DRAW_BUFFER0,
gl_DRAW_BUFFER1,
gl_DRAW_BUFFER10,
gl_DRAW_BUFFER11,
gl_DRAW_BUFFER12,
gl_DRAW_BUFFER13,
gl_DRAW_BUFFER14,
gl_DRAW_BUFFER15,
gl_DRAW_BUFFER2,
gl_DRAW_BUFFER3,
gl_DRAW_BUFFER4,
gl_DRAW_BUFFER5,
gl_DRAW_BUFFER6,
gl_DRAW_BUFFER7,
gl_DRAW_BUFFER8,
gl_DRAW_BUFFER9,
gl_DRAW_FRAMEBUFFER,
gl_DRAW_FRAMEBUFFER_BINDING,
gl_DRAW_PIXEL_TOKEN,
gl_DST_ALPHA,
gl_DST_COLOR,
gl_DYNAMIC_COPY,
gl_DYNAMIC_DRAW,
gl_DYNAMIC_READ,
gl_EDGE_FLAG,
gl_EDGE_FLAG_ARRAY,
gl_EDGE_FLAG_ARRAY_BUFFER_BINDING,
gl_EDGE_FLAG_ARRAY_POINTER,
gl_EDGE_FLAG_ARRAY_STRIDE,
gl_ELEMENT_ARRAY_BUFFER,
gl_ELEMENT_ARRAY_BUFFER_BINDING,
gl_EMISSION,
gl_ENABLE_BIT,
gl_EQUAL,
gl_EQUIV,
gl_EVAL_BIT,
gl_EXP,
gl_EXP2,
gl_EXTENSIONS,
gl_EYE_LINEAR,
gl_EYE_PLANE,
gl_FALSE,
gl_FASTEST,
gl_FEEDBACK,
gl_FEEDBACK_BUFFER_POINTER,
gl_FEEDBACK_BUFFER_SIZE,
gl_FEEDBACK_BUFFER_TYPE,
gl_FILL,
gl_FIXED_ONLY,
gl_FLAT,
gl_FLOAT,
gl_FLOAT_32_UNSIGNED_INT_24_8_REV,
gl_FLOAT_MAT2,
gl_FLOAT_MAT2x3,
gl_FLOAT_MAT2x4,
gl_FLOAT_MAT3,
gl_FLOAT_MAT3x2,
gl_FLOAT_MAT3x4,
gl_FLOAT_MAT4,
gl_FLOAT_MAT4x2,
gl_FLOAT_MAT4x3,
gl_FLOAT_VEC2,
gl_FLOAT_VEC3,
gl_FLOAT_VEC4,
gl_FOG,
gl_FOG_BIT,
gl_FOG_COLOR,
gl_FOG_COORD,
gl_FOG_COORDINATE,
gl_FOG_COORDINATE_ARRAY,
gl_FOG_COORDINATE_ARRAY_BUFFER_BINDING,
gl_FOG_COORDINATE_ARRAY_POINTER,
gl_FOG_COORDINATE_ARRAY_STRIDE,
gl_FOG_COORDINATE_ARRAY_TYPE,
gl_FOG_COORDINATE_SOURCE,
gl_FOG_COORD_ARRAY,
gl_FOG_COORD_ARRAY_BUFFER_BINDING,
gl_FOG_COORD_ARRAY_POINTER,
gl_FOG_COORD_ARRAY_STRIDE,
gl_FOG_COORD_ARRAY_TYPE,
gl_FOG_COORD_SRC,
gl_FOG_DENSITY,
gl_FOG_END,
gl_FOG_HINT,
gl_FOG_INDEX,
gl_FOG_MODE,
gl_FOG_START,
gl_FRAGMENT_DEPTH,
gl_FRAGMENT_SHADER,
gl_FRAGMENT_SHADER_DERIVATIVE_HINT,
gl_FRAMEBUFFER,
gl_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE,
gl_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE,
gl_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING,
gl_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE,
gl_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE,
gl_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE,
gl_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME,
gl_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE,
gl_FRAMEBUFFER_ATTACHMENT_RED_SIZE,
gl_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE,
gl_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE,
gl_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER,
gl_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL,
gl_FRAMEBUFFER_BINDING,
gl_FRAMEBUFFER_COMPLETE,
gl_FRAMEBUFFER_DEFAULT,
gl_FRAMEBUFFER_INCOMPLETE_ATTACHMENT,
gl_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER,
gl_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT,
gl_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE,
gl_FRAMEBUFFER_INCOMPLETE_READ_BUFFER,
gl_FRAMEBUFFER_SRGB,
gl_FRAMEBUFFER_UNDEFINED,
gl_FRAMEBUFFER_UNSUPPORTED,
gl_FRONT,
gl_FRONT_AND_BACK,
gl_FRONT_FACE,
gl_FRONT_LEFT,
gl_FRONT_RIGHT,
gl_FUNC_ADD,
gl_FUNC_REVERSE_SUBTRACT,
gl_FUNC_SUBTRACT,
gl_GENERATE_MIPMAP,
gl_GENERATE_MIPMAP_HINT,
gl_GEQUAL,
gl_GREATER,
gl_GREEN,
gl_GREEN_BIAS,
gl_GREEN_BITS,
gl_GREEN_INTEGER,
gl_GREEN_SCALE,
gl_HALF_FLOAT,
gl_HINT_BIT,
gl_INCR,
gl_INCR_WRAP,
gl_INDEX,
gl_INDEX_ARRAY,
gl_INDEX_ARRAY_BUFFER_BINDING,
gl_INDEX_ARRAY_POINTER,
gl_INDEX_ARRAY_STRIDE,
gl_INDEX_ARRAY_TYPE,
gl_INDEX_BITS,
gl_INDEX_CLEAR_VALUE,
gl_INDEX_LOGIC_OP,
gl_INDEX_MODE,
gl_INDEX_OFFSET,
gl_INDEX_SHIFT,
gl_INDEX_WRITEMASK,
gl_INFO_LOG_LENGTH,
gl_INT,
gl_INTENSITY,
gl_INTENSITY12,
gl_INTENSITY16,
gl_INTENSITY4,
gl_INTENSITY8,
gl_INTERLEAVED_ATTRIBS,
gl_INTERPOLATE,
gl_INT_SAMPLER_1D,
gl_INT_SAMPLER_1D_ARRAY,
gl_INT_SAMPLER_2D,
gl_INT_SAMPLER_2D_ARRAY,
gl_INT_SAMPLER_2D_RECT,
gl_INT_SAMPLER_3D,
gl_INT_SAMPLER_BUFFER,
gl_INT_SAMPLER_CUBE,
gl_INT_VEC2,
gl_INT_VEC3,
gl_INT_VEC4,
gl_INVALID_ENUM,
gl_INVALID_FRAMEBUFFER_OPERATION,
gl_INVALID_INDEX,
gl_INVALID_OPERATION,
gl_INVALID_VALUE,
gl_INVERT,
gl_KEEP,
gl_LEFT,
gl_LEQUAL,
gl_LESS,
gl_LIGHT0,
gl_LIGHT1,
gl_LIGHT2,
gl_LIGHT3,
gl_LIGHT4,
gl_LIGHT5,
gl_LIGHT6,
gl_LIGHT7,
gl_LIGHTING,
gl_LIGHTING_BIT,
gl_LIGHT_MODEL_AMBIENT,
gl_LIGHT_MODEL_COLOR_CONTROL,
gl_LIGHT_MODEL_LOCAL_VIEWER,
gl_LIGHT_MODEL_TWO_SIDE,
gl_LINE,
gl_LINEAR,
gl_LINEAR_ATTENUATION,
gl_LINEAR_MIPMAP_LINEAR,
gl_LINEAR_MIPMAP_NEAREST,
gl_LINES,
gl_LINE_BIT,
gl_LINE_LOOP,
gl_LINE_RESET_TOKEN,
gl_LINE_SMOOTH,
gl_LINE_SMOOTH_HINT,
gl_LINE_STIPPLE,
gl_LINE_STIPPLE_PATTERN,
gl_LINE_STIPPLE_REPEAT,
gl_LINE_STRIP,
gl_LINE_TOKEN,
gl_LINE_WIDTH,
gl_LINE_WIDTH_GRANULARITY,
gl_LINE_WIDTH_RANGE,
gl_LINK_STATUS,
gl_LIST_BASE,
gl_LIST_BIT,
gl_LIST_INDEX,
gl_LIST_MODE,
gl_LOAD,
gl_LOGIC_OP,
gl_LOGIC_OP_MODE,
gl_LOWER_LEFT,
gl_LUMINANCE,
gl_LUMINANCE12,
gl_LUMINANCE12_ALPHA12,
gl_LUMINANCE12_ALPHA4,
gl_LUMINANCE16,
gl_LUMINANCE16_ALPHA16,
gl_LUMINANCE4,
gl_LUMINANCE4_ALPHA4,
gl_LUMINANCE6_ALPHA2,
gl_LUMINANCE8,
gl_LUMINANCE8_ALPHA8,
gl_LUMINANCE_ALPHA,
gl_MAJOR_VERSION,
gl_MAP1_COLOR_4,
gl_MAP1_GRID_DOMAIN,
gl_MAP1_GRID_SEGMENTS,
gl_MAP1_INDEX,
gl_MAP1_NORMAL,
gl_MAP1_TEXTURE_COORD_1,
gl_MAP1_TEXTURE_COORD_2,
gl_MAP1_TEXTURE_COORD_3,
gl_MAP1_TEXTURE_COORD_4,
gl_MAP1_VERTEX_3,
gl_MAP1_VERTEX_4,
gl_MAP2_COLOR_4,
gl_MAP2_GRID_DOMAIN,
gl_MAP2_GRID_SEGMENTS,
gl_MAP2_INDEX,
gl_MAP2_NORMAL,
gl_MAP2_TEXTURE_COORD_1,
gl_MAP2_TEXTURE_COORD_2,
gl_MAP2_TEXTURE_COORD_3,
gl_MAP2_TEXTURE_COORD_4,
gl_MAP2_VERTEX_3,
gl_MAP2_VERTEX_4,
gl_MAP_COLOR,
gl_MAP_FLUSH_EXPLICIT_BIT,
gl_MAP_INVALIDATE_BUFFER_BIT,
gl_MAP_INVALIDATE_RANGE_BIT,
gl_MAP_READ_BIT,
gl_MAP_STENCIL,
gl_MAP_UNSYNCHRONIZED_BIT,
gl_MAP_WRITE_BIT,
gl_MATRIX_MODE,
gl_MAX,
gl_MAX_3D_TEXTURE_SIZE,
gl_MAX_ARRAY_TEXTURE_LAYERS,
gl_MAX_ATTRIB_STACK_DEPTH,
gl_MAX_CLIENT_ATTRIB_STACK_DEPTH,
gl_MAX_CLIP_DISTANCES,
gl_MAX_CLIP_PLANES,
gl_MAX_COLOR_ATTACHMENTS,
gl_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS,
gl_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS,
gl_MAX_COMBINED_TEXTURE_IMAGE_UNITS,
gl_MAX_COMBINED_UNIFORM_BLOCKS,
gl_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS,
gl_MAX_CUBE_MAP_TEXTURE_SIZE,
gl_MAX_DRAW_BUFFERS,
gl_MAX_ELEMENTS_INDICES,
gl_MAX_ELEMENTS_VERTICES,
gl_MAX_EVAL_ORDER,
gl_MAX_FRAGMENT_UNIFORM_BLOCKS,
gl_MAX_FRAGMENT_UNIFORM_COMPONENTS,
gl_MAX_GEOMETRY_UNIFORM_BLOCKS,
gl_MAX_LIGHTS,
gl_MAX_LIST_NESTING,
gl_MAX_MODELVIEW_STACK_DEPTH,
gl_MAX_NAME_STACK_DEPTH,
gl_MAX_PIXEL_MAP_TABLE,
gl_MAX_PROGRAM_TEXEL_OFFSET,
gl_MAX_PROJECTION_STACK_DEPTH,
gl_MAX_RECTANGLE_TEXTURE_SIZE,
gl_MAX_RENDERBUFFER_SIZE,
gl_MAX_SAMPLES,
gl_MAX_TEXTURE_BUFFER_SIZE,
gl_MAX_TEXTURE_COORDS,
gl_MAX_TEXTURE_IMAGE_UNITS,
gl_MAX_TEXTURE_LOD_BIAS,
gl_MAX_TEXTURE_SIZE,
gl_MAX_TEXTURE_STACK_DEPTH,
gl_MAX_TEXTURE_UNITS,
gl_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS,
gl_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS,
gl_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS,
gl_MAX_UNIFORM_BLOCK_SIZE,
gl_MAX_UNIFORM_BUFFER_BINDINGS,
gl_MAX_VARYING_COMPONENTS,
gl_MAX_VARYING_FLOATS,
gl_MAX_VERTEX_ATTRIBS,
gl_MAX_VERTEX_TEXTURE_IMAGE_UNITS,
gl_MAX_VERTEX_UNIFORM_BLOCKS,
gl_MAX_VERTEX_UNIFORM_COMPONENTS,
gl_MAX_VIEWPORT_DIMS,
gl_MIN,
gl_MINOR_VERSION,
gl_MIN_PROGRAM_TEXEL_OFFSET,
gl_MIRRORED_REPEAT,
gl_MODELVIEW,
gl_MODELVIEW_MATRIX,
gl_MODELVIEW_STACK_DEPTH,
gl_MODULATE,
gl_MULT,
gl_MULTISAMPLE,
gl_MULTISAMPLE_BIT,
gl_N3F_V3F,
gl_NAME_STACK_DEPTH,
gl_NAND,
gl_NEAREST,
gl_NEAREST_MIPMAP_LINEAR,
gl_NEAREST_MIPMAP_NEAREST,
gl_NEVER,
gl_NICEST,
gl_NONE,
gl_NOOP,
gl_NOR,
gl_NORMALIZE,
gl_NORMAL_ARRAY,
gl_NORMAL_ARRAY_BUFFER_BINDING,
gl_NORMAL_ARRAY_POINTER,
gl_NORMAL_ARRAY_STRIDE,
gl_NORMAL_ARRAY_TYPE,
gl_NORMAL_MAP,
gl_NOTEQUAL,
gl_NO_ERROR,
gl_NUM_COMPRESSED_TEXTURE_FORMATS,
gl_NUM_EXTENSIONS,
gl_OBJECT_LINEAR,
gl_OBJECT_PLANE,
gl_ONE,
gl_ONE_MINUS_CONSTANT_ALPHA,
gl_ONE_MINUS_CONSTANT_COLOR,
gl_ONE_MINUS_DST_ALPHA,
gl_ONE_MINUS_DST_COLOR,
gl_ONE_MINUS_SRC_ALPHA,
gl_ONE_MINUS_SRC_COLOR,
gl_OPERAND0_ALPHA,
gl_OPERAND0_RGB,
gl_OPERAND1_ALPHA,
gl_OPERAND1_RGB,
gl_OPERAND2_ALPHA,
gl_OPERAND2_RGB,
gl_OR,
gl_ORDER,
gl_OR_INVERTED,
gl_OR_REVERSE,
gl_OUT_OF_MEMORY,
gl_PACK_ALIGNMENT,
gl_PACK_IMAGE_HEIGHT,
gl_PACK_LSB_FIRST,
gl_PACK_ROW_LENGTH,
gl_PACK_SKIP_IMAGES,
gl_PACK_SKIP_PIXELS,
gl_PACK_SKIP_ROWS,
gl_PACK_SWAP_BYTES,
gl_PASS_THROUGH_TOKEN,
gl_PERSPECTIVE_CORRECTION_HINT,
gl_PIXEL_MAP_A_TO_A,
gl_PIXEL_MAP_A_TO_A_SIZE,
gl_PIXEL_MAP_B_TO_B,
gl_PIXEL_MAP_B_TO_B_SIZE,
gl_PIXEL_MAP_G_TO_G,
gl_PIXEL_MAP_G_TO_G_SIZE,
gl_PIXEL_MAP_I_TO_A,
gl_PIXEL_MAP_I_TO_A_SIZE,
gl_PIXEL_MAP_I_TO_B,
gl_PIXEL_MAP_I_TO_B_SIZE,
gl_PIXEL_MAP_I_TO_G,
gl_PIXEL_MAP_I_TO_G_SIZE,
gl_PIXEL_MAP_I_TO_I,
gl_PIXEL_MAP_I_TO_I_SIZE,
gl_PIXEL_MAP_I_TO_R,
gl_PIXEL_MAP_I_TO_R_SIZE,
gl_PIXEL_MAP_R_TO_R,
gl_PIXEL_MAP_R_TO_R_SIZE,
gl_PIXEL_MAP_S_TO_S,
gl_PIXEL_MAP_S_TO_S_SIZE,
gl_PIXEL_MODE_BIT,
gl_PIXEL_PACK_BUFFER,
gl_PIXEL_PACK_BUFFER_BINDING,
gl_PIXEL_UNPACK_BUFFER,
gl_PIXEL_UNPACK_BUFFER_BINDING,
gl_POINT,
gl_POINTS,
gl_POINT_BIT,
gl_POINT_DISTANCE_ATTENUATION,
gl_POINT_FADE_THRESHOLD_SIZE,
gl_POINT_SIZE,
gl_POINT_SIZE_GRANULARITY,
gl_POINT_SIZE_MAX,
gl_POINT_SIZE_MIN,
gl_POINT_SIZE_RANGE,
gl_POINT_SMOOTH,
gl_POINT_SMOOTH_HINT,
gl_POINT_SPRITE,
gl_POINT_SPRITE_COORD_ORIGIN,
gl_POINT_TOKEN,
gl_POLYGON,
gl_POLYGON_BIT,
gl_POLYGON_MODE,
gl_POLYGON_OFFSET_FACTOR,
gl_POLYGON_OFFSET_FILL,
gl_POLYGON_OFFSET_LINE,
gl_POLYGON_OFFSET_POINT,
gl_POLYGON_OFFSET_UNITS,
gl_POLYGON_SMOOTH,
gl_POLYGON_SMOOTH_HINT,
gl_POLYGON_STIPPLE,
gl_POLYGON_STIPPLE_BIT,
gl_POLYGON_TOKEN,
gl_POSITION,
gl_PREVIOUS,
gl_PRIMARY_COLOR,
gl_PRIMITIVES_GENERATED,
gl_PRIMITIVE_RESTART,
gl_PRIMITIVE_RESTART_INDEX,
gl_PROJECTION,
gl_PROJECTION_MATRIX,
gl_PROJECTION_STACK_DEPTH,
gl_PROXY_TEXTURE_1D,
gl_PROXY_TEXTURE_1D_ARRAY,
gl_PROXY_TEXTURE_2D,
gl_PROXY_TEXTURE_2D_ARRAY,
gl_PROXY_TEXTURE_3D,
gl_PROXY_TEXTURE_CUBE_MAP,
gl_PROXY_TEXTURE_RECTANGLE,
gl_Q,
gl_QUADRATIC_ATTENUATION,
gl_QUADS,
gl_QUAD_STRIP,
gl_QUERY_BY_REGION_NO_WAIT,
gl_QUERY_BY_REGION_WAIT,
gl_QUERY_COUNTER_BITS,
gl_QUERY_NO_WAIT,
gl_QUERY_RESULT,
gl_QUERY_RESULT_AVAILABLE,
gl_QUERY_WAIT,
gl_R,
gl_R11F_G11F_B10F,
gl_R16,
gl_R16F,
gl_R16I,
gl_R16UI,
gl_R16_SNORM,
gl_R32F,
gl_R32I,
gl_R32UI,
gl_R3_G3_B2,
gl_R8,
gl_R8I,
gl_R8UI,
gl_R8_SNORM,
gl_RASTERIZER_DISCARD,
gl_READ_BUFFER,
gl_READ_FRAMEBUFFER,
gl_READ_FRAMEBUFFER_BINDING,
gl_READ_ONLY,
gl_READ_WRITE,
gl_RED,
gl_RED_BIAS,
gl_RED_BITS,
gl_RED_INTEGER,
gl_RED_SCALE,
gl_REFLECTION_MAP,
gl_RENDER,
gl_RENDERBUFFER,
gl_RENDERBUFFER_ALPHA_SIZE,
gl_RENDERBUFFER_BINDING,
gl_RENDERBUFFER_BLUE_SIZE,
gl_RENDERBUFFER_DEPTH_SIZE,
gl_RENDERBUFFER_GREEN_SIZE,
gl_RENDERBUFFER_HEIGHT,
gl_RENDERBUFFER_INTERNAL_FORMAT,
gl_RENDERBUFFER_RED_SIZE,
gl_RENDERBUFFER_SAMPLES,
gl_RENDERBUFFER_STENCIL_SIZE,
gl_RENDERBUFFER_WIDTH,
gl_RENDERER,
gl_RENDER_MODE,
gl_REPEAT,
gl_REPLACE,
gl_RESCALE_NORMAL,
gl_RETURN,
gl_RG,
gl_RG16,
gl_RG16F,
gl_RG16I,
gl_RG16UI,
gl_RG16_SNORM,
gl_RG32F,
gl_RG32I,
gl_RG32UI,
gl_RG8,
gl_RG8I,
gl_RG8UI,
gl_RG8_SNORM,
gl_RGB,
gl_RGB10,
gl_RGB10_A2,
gl_RGB12,
gl_RGB16,
gl_RGB16F,
gl_RGB16I,
gl_RGB16UI,
gl_RGB16_SNORM,
gl_RGB32F,
gl_RGB32I,
gl_RGB32UI,
gl_RGB4,
gl_RGB5,
gl_RGB5_A1,
gl_RGB8,
gl_RGB8I,
gl_RGB8UI,
gl_RGB8_SNORM,
gl_RGB9_E5,
gl_RGBA,
gl_RGBA12,
gl_RGBA16,
gl_RGBA16F,
gl_RGBA16I,
gl_RGBA16UI,
gl_RGBA16_SNORM,
gl_RGBA2,
gl_RGBA32F,
gl_RGBA32I,
gl_RGBA32UI,
gl_RGBA4,
gl_RGBA8,
gl_RGBA8I,
gl_RGBA8UI,
gl_RGBA8_SNORM,
gl_RGBA_INTEGER,
gl_RGBA_MODE,
gl_RGB_INTEGER,
gl_RGB_SCALE,
gl_RG_INTEGER,
gl_RIGHT,
gl_S,
gl_SAMPLER_1D,
gl_SAMPLER_1D_ARRAY,
gl_SAMPLER_1D_ARRAY_SHADOW,
gl_SAMPLER_1D_SHADOW,
gl_SAMPLER_2D,
gl_SAMPLER_2D_ARRAY,
gl_SAMPLER_2D_ARRAY_SHADOW,
gl_SAMPLER_2D_RECT,
gl_SAMPLER_2D_RECT_SHADOW,
gl_SAMPLER_2D_SHADOW,
gl_SAMPLER_3D,
gl_SAMPLER_BUFFER,
gl_SAMPLER_CUBE,
gl_SAMPLER_CUBE_SHADOW,
gl_SAMPLES,
gl_SAMPLES_PASSED,
gl_SAMPLE_ALPHA_TO_COVERAGE,
gl_SAMPLE_ALPHA_TO_ONE,
gl_SAMPLE_BUFFERS,
gl_SAMPLE_COVERAGE,
gl_SAMPLE_COVERAGE_INVERT,
gl_SAMPLE_COVERAGE_VALUE,
gl_SCISSOR_BIT,
gl_SCISSOR_BOX,
gl_SCISSOR_TEST,
gl_SECONDARY_COLOR_ARRAY,
gl_SECONDARY_COLOR_ARRAY_BUFFER_BINDING,
gl_SECONDARY_COLOR_ARRAY_POINTER,
gl_SECONDARY_COLOR_ARRAY_SIZE,
gl_SECONDARY_COLOR_ARRAY_STRIDE,
gl_SECONDARY_COLOR_ARRAY_TYPE,
gl_SELECT,
gl_SELECTION_BUFFER_POINTER,
gl_SELECTION_BUFFER_SIZE,
gl_SEPARATE_ATTRIBS,
gl_SEPARATE_SPECULAR_COLOR,
gl_SET,
gl_SHADER_SOURCE_LENGTH,
gl_SHADER_TYPE,
gl_SHADE_MODEL,
gl_SHADING_LANGUAGE_VERSION,
gl_SHININESS,
gl_SHORT,
gl_SIGNED_NORMALIZED,
gl_SINGLE_COLOR,
gl_SLUMINANCE,
gl_SLUMINANCE8,
gl_SLUMINANCE8_ALPHA8,
gl_SLUMINANCE_ALPHA,
gl_SMOOTH,
gl_SMOOTH_LINE_WIDTH_GRANULARITY,
gl_SMOOTH_LINE_WIDTH_RANGE,
gl_SMOOTH_POINT_SIZE_GRANULARITY,
gl_SMOOTH_POINT_SIZE_RANGE,
gl_SOURCE0_ALPHA,
gl_SOURCE0_RGB,
gl_SOURCE1_ALPHA,
gl_SOURCE1_RGB,
gl_SOURCE2_ALPHA,
gl_SOURCE2_RGB,
gl_SPECULAR,
gl_SPHERE_MAP,
gl_SPOT_CUTOFF,
gl_SPOT_DIRECTION,
gl_SPOT_EXPONENT,
gl_SRC0_ALPHA,
gl_SRC0_RGB,
gl_SRC1_ALPHA,
gl_SRC1_RGB,
gl_SRC2_ALPHA,
gl_SRC2_RGB,
gl_SRC_ALPHA,
gl_SRC_ALPHA_SATURATE,
gl_SRC_COLOR,
gl_SRGB,
gl_SRGB8,
gl_SRGB8_ALPHA8,
gl_SRGB_ALPHA,
gl_STACK_OVERFLOW,
gl_STACK_UNDERFLOW,
gl_STATIC_COPY,
gl_STATIC_DRAW,
gl_STATIC_READ,
gl_STENCIL,
gl_STENCIL_ATTACHMENT,
gl_STENCIL_BACK_FAIL,
gl_STENCIL_BACK_FUNC,
gl_STENCIL_BACK_PASS_DEPTH_FAIL,
gl_STENCIL_BACK_PASS_DEPTH_PASS,
gl_STENCIL_BACK_REF,
gl_STENCIL_BACK_VALUE_MASK,
gl_STENCIL_BACK_WRITEMASK,
gl_STENCIL_BITS,
gl_STENCIL_BUFFER_BIT,
gl_STENCIL_CLEAR_VALUE,
gl_STENCIL_FAIL,
gl_STENCIL_FUNC,
gl_STENCIL_INDEX,
gl_STENCIL_INDEX1,
gl_STENCIL_INDEX16,
gl_STENCIL_INDEX4,
gl_STENCIL_INDEX8,
gl_STENCIL_PASS_DEPTH_FAIL,
gl_STENCIL_PASS_DEPTH_PASS,
gl_STENCIL_REF,
gl_STENCIL_TEST,
gl_STENCIL_VALUE_MASK,
gl_STENCIL_WRITEMASK,
gl_STEREO,
gl_STREAM_COPY,
gl_STREAM_DRAW,
gl_STREAM_READ,
gl_SUBPIXEL_BITS,
gl_SUBTRACT,
gl_T,
gl_T2F_C3F_V3F,
gl_T2F_C4F_N3F_V3F,
gl_T2F_C4UB_V3F,
gl_T2F_N3F_V3F,
gl_T2F_V3F,
gl_T4F_C4F_N3F_V4F,
gl_T4F_V4F,
gl_TEXTURE,
gl_TEXTURE0,
gl_TEXTURE1,
gl_TEXTURE10,
gl_TEXTURE11,
gl_TEXTURE12,
gl_TEXTURE13,
gl_TEXTURE14,
gl_TEXTURE15,
gl_TEXTURE16,
gl_TEXTURE17,
gl_TEXTURE18,
gl_TEXTURE19,
gl_TEXTURE2,
gl_TEXTURE20,
gl_TEXTURE21,
gl_TEXTURE22,
gl_TEXTURE23,
gl_TEXTURE24,
gl_TEXTURE25,
gl_TEXTURE26,
gl_TEXTURE27,
gl_TEXTURE28,
gl_TEXTURE29,
gl_TEXTURE3,
gl_TEXTURE30,
gl_TEXTURE31,
gl_TEXTURE4,
gl_TEXTURE5,
gl_TEXTURE6,
gl_TEXTURE7,
gl_TEXTURE8,
gl_TEXTURE9,
gl_TEXTURE_1D,
gl_TEXTURE_1D_ARRAY,
gl_TEXTURE_2D,
gl_TEXTURE_2D_ARRAY,
gl_TEXTURE_3D,
gl_TEXTURE_ALPHA_SIZE,
gl_TEXTURE_ALPHA_TYPE,
gl_TEXTURE_BASE_LEVEL,
gl_TEXTURE_BINDING_1D,
gl_TEXTURE_BINDING_1D_ARRAY,
gl_TEXTURE_BINDING_2D,
gl_TEXTURE_BINDING_2D_ARRAY,
gl_TEXTURE_BINDING_3D,
gl_TEXTURE_BINDING_BUFFER,
gl_TEXTURE_BINDING_CUBE_MAP,
gl_TEXTURE_BINDING_RECTANGLE,
gl_TEXTURE_BIT,
gl_TEXTURE_BLUE_SIZE,
gl_TEXTURE_BLUE_TYPE,
gl_TEXTURE_BORDER,
gl_TEXTURE_BORDER_COLOR,
gl_TEXTURE_BUFFER,
gl_TEXTURE_BUFFER_DATA_STORE_BINDING,
gl_TEXTURE_COMPARE_FUNC,
gl_TEXTURE_COMPARE_MODE,
gl_TEXTURE_COMPONENTS,
gl_TEXTURE_COMPRESSED,
gl_TEXTURE_COMPRESSED_IMAGE_SIZE,
gl_TEXTURE_COMPRESSION_HINT,
gl_TEXTURE_COORD_ARRAY,
gl_TEXTURE_COORD_ARRAY_BUFFER_BINDING,
gl_TEXTURE_COORD_ARRAY_POINTER,
gl_TEXTURE_COORD_ARRAY_SIZE,
gl_TEXTURE_COORD_ARRAY_STRIDE,
gl_TEXTURE_COORD_ARRAY_TYPE,
gl_TEXTURE_CUBE_MAP,
gl_TEXTURE_CUBE_MAP_NEGATIVE_X,
gl_TEXTURE_CUBE_MAP_NEGATIVE_Y,
gl_TEXTURE_CUBE_MAP_NEGATIVE_Z,
gl_TEXTURE_CUBE_MAP_POSITIVE_X,
gl_TEXTURE_CUBE_MAP_POSITIVE_Y,
gl_TEXTURE_CUBE_MAP_POSITIVE_Z,
gl_TEXTURE_DEPTH,
gl_TEXTURE_DEPTH_SIZE,
gl_TEXTURE_DEPTH_TYPE,
gl_TEXTURE_ENV,
gl_TEXTURE_ENV_COLOR,
gl_TEXTURE_ENV_MODE,
gl_TEXTURE_FILTER_CONTROL,
gl_TEXTURE_GEN_MODE,
gl_TEXTURE_GEN_Q,
gl_TEXTURE_GEN_R,
gl_TEXTURE_GEN_S,
gl_TEXTURE_GEN_T,
gl_TEXTURE_GREEN_SIZE,
gl_TEXTURE_GREEN_TYPE,
gl_TEXTURE_HEIGHT,
gl_TEXTURE_INTENSITY_SIZE,
gl_TEXTURE_INTENSITY_TYPE,
gl_TEXTURE_INTERNAL_FORMAT,
gl_TEXTURE_LOD_BIAS,
gl_TEXTURE_LUMINANCE_SIZE,
gl_TEXTURE_LUMINANCE_TYPE,
gl_TEXTURE_MAG_FILTER,
gl_TEXTURE_MATRIX,
gl_TEXTURE_MAX_LEVEL,
gl_TEXTURE_MAX_LOD,
gl_TEXTURE_MIN_FILTER,
gl_TEXTURE_MIN_LOD,
gl_TEXTURE_PRIORITY,
gl_TEXTURE_RECTANGLE,
gl_TEXTURE_RED_SIZE,
gl_TEXTURE_RED_TYPE,
gl_TEXTURE_RESIDENT,
gl_TEXTURE_SHARED_SIZE,
gl_TEXTURE_STACK_DEPTH,
gl_TEXTURE_STENCIL_SIZE,
gl_TEXTURE_WIDTH,
gl_TEXTURE_WRAP_R,
gl_TEXTURE_WRAP_S,
gl_TEXTURE_WRAP_T,
gl_TRANSFORM_BIT,
gl_TRANSFORM_FEEDBACK_BUFFER,
gl_TRANSFORM_FEEDBACK_BUFFER_BINDING,
gl_TRANSFORM_FEEDBACK_BUFFER_MODE,
gl_TRANSFORM_FEEDBACK_BUFFER_SIZE,
gl_TRANSFORM_FEEDBACK_BUFFER_START,
gl_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN,
gl_TRANSFORM_FEEDBACK_VARYINGS,
gl_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH,
gl_TRANSPOSE_COLOR_MATRIX,
gl_TRANSPOSE_MODELVIEW_MATRIX,
gl_TRANSPOSE_PROJECTION_MATRIX,
gl_TRANSPOSE_TEXTURE_MATRIX,
gl_TRIANGLES,
gl_TRIANGLE_FAN,
gl_TRIANGLE_STRIP,
gl_TRUE,
gl_UNIFORM_ARRAY_STRIDE,
gl_UNIFORM_BLOCK_ACTIVE_UNIFORMS,
gl_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES,
gl_UNIFORM_BLOCK_BINDING,
gl_UNIFORM_BLOCK_DATA_SIZE,
gl_UNIFORM_BLOCK_INDEX,
gl_UNIFORM_BLOCK_NAME_LENGTH,
gl_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER,
gl_UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER,
gl_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER,
gl_UNIFORM_BUFFER,
gl_UNIFORM_BUFFER_BINDING,
gl_UNIFORM_BUFFER_OFFSET_ALIGNMENT,
gl_UNIFORM_BUFFER_SIZE,
gl_UNIFORM_BUFFER_START,
gl_UNIFORM_IS_ROW_MAJOR,
gl_UNIFORM_MATRIX_STRIDE,
gl_UNIFORM_NAME_LENGTH,
gl_UNIFORM_OFFSET,
gl_UNIFORM_SIZE,
gl_UNIFORM_TYPE,
gl_UNPACK_ALIGNMENT,
gl_UNPACK_IMAGE_HEIGHT,
gl_UNPACK_LSB_FIRST,
gl_UNPACK_ROW_LENGTH,
gl_UNPACK_SKIP_IMAGES,
gl_UNPACK_SKIP_PIXELS,
gl_UNPACK_SKIP_ROWS,
gl_UNPACK_SWAP_BYTES,
gl_UNSIGNED_BYTE,
gl_UNSIGNED_BYTE_2_3_3_REV,
gl_UNSIGNED_BYTE_3_3_2,
gl_UNSIGNED_INT,
gl_UNSIGNED_INT_10F_11F_11F_REV,
gl_UNSIGNED_INT_10_10_10_2,
gl_UNSIGNED_INT_24_8,
gl_UNSIGNED_INT_2_10_10_10_REV,
gl_UNSIGNED_INT_5_9_9_9_REV,
gl_UNSIGNED_INT_8_8_8_8,
gl_UNSIGNED_INT_8_8_8_8_REV,
gl_UNSIGNED_INT_SAMPLER_1D,
gl_UNSIGNED_INT_SAMPLER_1D_ARRAY,
gl_UNSIGNED_INT_SAMPLER_2D,
gl_UNSIGNED_INT_SAMPLER_2D_ARRAY,
gl_UNSIGNED_INT_SAMPLER_2D_RECT,
gl_UNSIGNED_INT_SAMPLER_3D,
gl_UNSIGNED_INT_SAMPLER_BUFFER,
gl_UNSIGNED_INT_SAMPLER_CUBE,
gl_UNSIGNED_INT_VEC2,
gl_UNSIGNED_INT_VEC3,
gl_UNSIGNED_INT_VEC4,
gl_UNSIGNED_NORMALIZED,
gl_UNSIGNED_SHORT,
gl_UNSIGNED_SHORT_1_5_5_5_REV,
gl_UNSIGNED_SHORT_4_4_4_4,
gl_UNSIGNED_SHORT_4_4_4_4_REV,
gl_UNSIGNED_SHORT_5_5_5_1,
gl_UNSIGNED_SHORT_5_6_5,
gl_UNSIGNED_SHORT_5_6_5_REV,
gl_UPPER_LEFT,
gl_V2F,
gl_V3F,
gl_VALIDATE_STATUS,
gl_VENDOR,
gl_VERSION,
gl_VERTEX_ARRAY,
gl_VERTEX_ARRAY_BINDING,
gl_VERTEX_ARRAY_BUFFER_BINDING,
gl_VERTEX_ARRAY_POINTER,
gl_VERTEX_ARRAY_SIZE,
gl_VERTEX_ARRAY_STRIDE,
gl_VERTEX_ARRAY_TYPE,
gl_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING,
gl_VERTEX_ATTRIB_ARRAY_ENABLED,
gl_VERTEX_ATTRIB_ARRAY_INTEGER,
gl_VERTEX_ATTRIB_ARRAY_NORMALIZED,
gl_VERTEX_ATTRIB_ARRAY_POINTER,
gl_VERTEX_ATTRIB_ARRAY_SIZE,
gl_VERTEX_ATTRIB_ARRAY_STRIDE,
gl_VERTEX_ATTRIB_ARRAY_TYPE,
gl_VERTEX_PROGRAM_POINT_SIZE,
gl_VERTEX_PROGRAM_TWO_SIDE,
gl_VERTEX_SHADER,
gl_VIEWPORT,
gl_VIEWPORT_BIT,
gl_WEIGHT_ARRAY_BUFFER_BINDING,
gl_WRITE_ONLY,
gl_XOR,
gl_ZERO,
gl_ZOOM_X,
gl_ZOOM_Y,
-- * Functions
glAccum,
glActiveTexture,
glAlphaFunc,
glAreTexturesResident,
glArrayElement,
glAttachShader,
glBegin,
glBeginConditionalRender,
glBeginQuery,
glBeginTransformFeedback,
glBindAttribLocation,
glBindBuffer,
glBindBufferBase,
glBindBufferRange,
glBindFragDataLocation,
glBindFramebuffer,
glBindRenderbuffer,
glBindTexture,
glBindVertexArray,
glBitmap,
glBlendColor,
glBlendEquation,
glBlendEquationSeparate,
glBlendFunc,
glBlendFuncSeparate,
glBlitFramebuffer,
glBufferData,
glBufferSubData,
glCallList,
glCallLists,
glCheckFramebufferStatus,
glClampColor,
glClear,
glClearAccum,
glClearBufferfi,
glClearBufferfv,
glClearBufferiv,
glClearBufferuiv,
glClearColor,
glClearDepth,
glClearIndex,
glClearStencil,
glClientActiveTexture,
glClipPlane,
glColor3b,
glColor3bv,
glColor3d,
glColor3dv,
glColor3f,
glColor3fv,
glColor3i,
glColor3iv,
glColor3s,
glColor3sv,
glColor3ub,
glColor3ubv,
glColor3ui,
glColor3uiv,
glColor3us,
glColor3usv,
glColor4b,
glColor4bv,
glColor4d,
glColor4dv,
glColor4f,
glColor4fv,
glColor4i,
glColor4iv,
glColor4s,
glColor4sv,
glColor4ub,
glColor4ubv,
glColor4ui,
glColor4uiv,
glColor4us,
glColor4usv,
glColorMask,
glColorMaski,
glColorMaterial,
glColorPointer,
glCompileShader,
glCompressedTexImage1D,
glCompressedTexImage2D,
glCompressedTexImage3D,
glCompressedTexSubImage1D,
glCompressedTexSubImage2D,
glCompressedTexSubImage3D,
glCopyBufferSubData,
glCopyPixels,
glCopyTexImage1D,
glCopyTexImage2D,
glCopyTexSubImage1D,
glCopyTexSubImage2D,
glCopyTexSubImage3D,
glCreateProgram,
glCreateShader,
glCullFace,
glDeleteBuffers,
glDeleteFramebuffers,
glDeleteLists,
glDeleteProgram,
glDeleteQueries,
glDeleteRenderbuffers,
glDeleteShader,
glDeleteTextures,
glDeleteVertexArrays,
glDepthFunc,
glDepthMask,
glDepthRange,
glDetachShader,
glDisable,
glDisableClientState,
glDisableVertexAttribArray,
glDisablei,
glDrawArrays,
glDrawArraysInstanced,
glDrawBuffer,
glDrawBuffers,
glDrawElements,
glDrawElementsInstanced,
glDrawPixels,
glDrawRangeElements,
glEdgeFlag,
glEdgeFlagPointer,
glEdgeFlagv,
glEnable,
glEnableClientState,
glEnableVertexAttribArray,
glEnablei,
glEnd,
glEndConditionalRender,
glEndList,
glEndQuery,
glEndTransformFeedback,
glEvalCoord1d,
glEvalCoord1dv,
glEvalCoord1f,
glEvalCoord1fv,
glEvalCoord2d,
glEvalCoord2dv,
glEvalCoord2f,
glEvalCoord2fv,
glEvalMesh1,
glEvalMesh2,
glEvalPoint1,
glEvalPoint2,
glFeedbackBuffer,
glFinish,
glFlush,
glFlushMappedBufferRange,
glFogCoordPointer,
glFogCoordd,
glFogCoorddv,
glFogCoordf,
glFogCoordfv,
glFogf,
glFogfv,
glFogi,
glFogiv,
glFramebufferRenderbuffer,
glFramebufferTexture1D,
glFramebufferTexture2D,
glFramebufferTexture3D,
glFramebufferTextureLayer,
glFrontFace,
glFrustum,
glGenBuffers,
glGenFramebuffers,
glGenLists,
glGenQueries,
glGenRenderbuffers,
glGenTextures,
glGenVertexArrays,
glGenerateMipmap,
glGetActiveAttrib,
glGetActiveUniform,
glGetActiveUniformBlockName,
glGetActiveUniformBlockiv,
glGetActiveUniformName,
glGetActiveUniformsiv,
glGetAttachedShaders,
glGetAttribLocation,
glGetBooleani_v,
glGetBooleanv,
glGetBufferParameteriv,
glGetBufferPointerv,
glGetBufferSubData,
glGetClipPlane,
glGetCompressedTexImage,
glGetDoublev,
glGetError,
glGetFloatv,
glGetFragDataLocation,
glGetFramebufferAttachmentParameteriv,
glGetIntegeri_v,
glGetIntegerv,
glGetLightfv,
glGetLightiv,
glGetMapdv,
glGetMapfv,
glGetMapiv,
glGetMaterialfv,
glGetMaterialiv,
glGetPixelMapfv,
glGetPixelMapuiv,
glGetPixelMapusv,
glGetPointerv,
glGetPolygonStipple,
glGetProgramInfoLog,
glGetProgramiv,
glGetQueryObjectiv,
glGetQueryObjectuiv,
glGetQueryiv,
glGetRenderbufferParameteriv,
glGetShaderInfoLog,
glGetShaderSource,
glGetShaderiv,
glGetString,
glGetStringi,
glGetTexEnvfv,
glGetTexEnviv,
glGetTexGendv,
glGetTexGenfv,
glGetTexGeniv,
glGetTexImage,
glGetTexLevelParameterfv,
glGetTexLevelParameteriv,
glGetTexParameterIiv,
glGetTexParameterIuiv,
glGetTexParameterfv,
glGetTexParameteriv,
glGetTransformFeedbackVarying,
glGetUniformBlockIndex,
glGetUniformIndices,
glGetUniformLocation,
glGetUniformfv,
glGetUniformiv,
glGetUniformuiv,
glGetVertexAttribIiv,
glGetVertexAttribIuiv,
glGetVertexAttribPointerv,
glGetVertexAttribdv,
glGetVertexAttribfv,
glGetVertexAttribiv,
glHint,
glIndexMask,
glIndexPointer,
glIndexd,
glIndexdv,
glIndexf,
glIndexfv,
glIndexi,
glIndexiv,
glIndexs,
glIndexsv,
glIndexub,
glIndexubv,
glInitNames,
glInterleavedArrays,
glIsBuffer,
glIsEnabled,
glIsEnabledi,
glIsFramebuffer,
glIsList,
glIsProgram,
glIsQuery,
glIsRenderbuffer,
glIsShader,
glIsTexture,
glIsVertexArray,
glLightModelf,
glLightModelfv,
glLightModeli,
glLightModeliv,
glLightf,
glLightfv,
glLighti,
glLightiv,
glLineStipple,
glLineWidth,
glLinkProgram,
glListBase,
glLoadIdentity,
glLoadMatrixd,
glLoadMatrixf,
glLoadName,
glLoadTransposeMatrixd,
glLoadTransposeMatrixf,
glLogicOp,
glMap1d,
glMap1f,
glMap2d,
glMap2f,
glMapBuffer,
glMapBufferRange,
glMapGrid1d,
glMapGrid1f,
glMapGrid2d,
glMapGrid2f,
glMaterialf,
glMaterialfv,
glMateriali,
glMaterialiv,
glMatrixMode,
glMultMatrixd,
glMultMatrixf,
glMultTransposeMatrixd,
glMultTransposeMatrixf,
glMultiDrawArrays,
glMultiDrawElements,
glMultiTexCoord1d,
glMultiTexCoord1dv,
glMultiTexCoord1f,
glMultiTexCoord1fv,
glMultiTexCoord1i,
glMultiTexCoord1iv,
glMultiTexCoord1s,
glMultiTexCoord1sv,
glMultiTexCoord2d,
glMultiTexCoord2dv,
glMultiTexCoord2f,
glMultiTexCoord2fv,
glMultiTexCoord2i,
glMultiTexCoord2iv,
glMultiTexCoord2s,
glMultiTexCoord2sv,
glMultiTexCoord3d,
glMultiTexCoord3dv,
glMultiTexCoord3f,
glMultiTexCoord3fv,
glMultiTexCoord3i,
glMultiTexCoord3iv,
glMultiTexCoord3s,
glMultiTexCoord3sv,
glMultiTexCoord4d,
glMultiTexCoord4dv,
glMultiTexCoord4f,
glMultiTexCoord4fv,
glMultiTexCoord4i,
glMultiTexCoord4iv,
glMultiTexCoord4s,
glMultiTexCoord4sv,
glNewList,
glNormal3b,
glNormal3bv,
glNormal3d,
glNormal3dv,
glNormal3f,
glNormal3fv,
glNormal3i,
glNormal3iv,
glNormal3s,
glNormal3sv,
glNormalPointer,
glOrtho,
glPassThrough,
glPixelMapfv,
glPixelMapuiv,
glPixelMapusv,
glPixelStoref,
glPixelStorei,
glPixelTransferf,
glPixelTransferi,
glPixelZoom,
glPointParameterf,
glPointParameterfv,
glPointParameteri,
glPointParameteriv,
glPointSize,
glPolygonMode,
glPolygonOffset,
glPolygonStipple,
glPopAttrib,
glPopClientAttrib,
glPopMatrix,
glPopName,
glPrimitiveRestartIndex,
glPrioritizeTextures,
glPushAttrib,
glPushClientAttrib,
glPushMatrix,
glPushName,
glRasterPos2d,
glRasterPos2dv,
glRasterPos2f,
glRasterPos2fv,
glRasterPos2i,
glRasterPos2iv,
glRasterPos2s,
glRasterPos2sv,
glRasterPos3d,
glRasterPos3dv,
glRasterPos3f,
glRasterPos3fv,
glRasterPos3i,
glRasterPos3iv,
glRasterPos3s,
glRasterPos3sv,
glRasterPos4d,
glRasterPos4dv,
glRasterPos4f,
glRasterPos4fv,
glRasterPos4i,
glRasterPos4iv,
glRasterPos4s,
glRasterPos4sv,
glReadBuffer,
glReadPixels,
glRectd,
glRectdv,
glRectf,
glRectfv,
glRecti,
glRectiv,
glRects,
glRectsv,
glRenderMode,
glRenderbufferStorage,
glRenderbufferStorageMultisample,
glRotated,
glRotatef,
glSampleCoverage,
glScaled,
glScalef,
glScissor,
glSecondaryColor3b,
glSecondaryColor3bv,
glSecondaryColor3d,
glSecondaryColor3dv,
glSecondaryColor3f,
glSecondaryColor3fv,
glSecondaryColor3i,
glSecondaryColor3iv,
glSecondaryColor3s,
glSecondaryColor3sv,
glSecondaryColor3ub,
glSecondaryColor3ubv,
glSecondaryColor3ui,
glSecondaryColor3uiv,
glSecondaryColor3us,
glSecondaryColor3usv,
glSecondaryColorPointer,
glSelectBuffer,
glShadeModel,
glShaderSource,
glStencilFunc,
glStencilFuncSeparate,
glStencilMask,
glStencilMaskSeparate,
glStencilOp,
glStencilOpSeparate,
glTexBuffer,
glTexCoord1d,
glTexCoord1dv,
glTexCoord1f,
glTexCoord1fv,
glTexCoord1i,
glTexCoord1iv,
glTexCoord1s,
glTexCoord1sv,
glTexCoord2d,
glTexCoord2dv,
glTexCoord2f,
glTexCoord2fv,
glTexCoord2i,
glTexCoord2iv,
glTexCoord2s,
glTexCoord2sv,
glTexCoord3d,
glTexCoord3dv,
glTexCoord3f,
glTexCoord3fv,
glTexCoord3i,
glTexCoord3iv,
glTexCoord3s,
glTexCoord3sv,
glTexCoord4d,
glTexCoord4dv,
glTexCoord4f,
glTexCoord4fv,
glTexCoord4i,
glTexCoord4iv,
glTexCoord4s,
glTexCoord4sv,
glTexCoordPointer,
glTexEnvf,
glTexEnvfv,
glTexEnvi,
glTexEnviv,
glTexGend,
glTexGendv,
glTexGenf,
glTexGenfv,
glTexGeni,
glTexGeniv,
glTexImage1D,
glTexImage2D,
glTexImage3D,
glTexParameterIiv,
glTexParameterIuiv,
glTexParameterf,
glTexParameterfv,
glTexParameteri,
glTexParameteriv,
glTexSubImage1D,
glTexSubImage2D,
glTexSubImage3D,
glTransformFeedbackVaryings,
glTranslated,
glTranslatef,
glUniform1f,
glUniform1fv,
glUniform1i,
glUniform1iv,
glUniform1ui,
glUniform1uiv,
glUniform2f,
glUniform2fv,
glUniform2i,
glUniform2iv,
glUniform2ui,
glUniform2uiv,
glUniform3f,
glUniform3fv,
glUniform3i,
glUniform3iv,
glUniform3ui,
glUniform3uiv,
glUniform4f,
glUniform4fv,
glUniform4i,
glUniform4iv,
glUniform4ui,
glUniform4uiv,
glUniformBlockBinding,
glUniformMatrix2fv,
glUniformMatrix2x3fv,
glUniformMatrix2x4fv,
glUniformMatrix3fv,
glUniformMatrix3x2fv,
glUniformMatrix3x4fv,
glUniformMatrix4fv,
glUniformMatrix4x2fv,
glUniformMatrix4x3fv,
glUnmapBuffer,
glUseProgram,
glValidateProgram,
glVertex2d,
glVertex2dv,
glVertex2f,
glVertex2fv,
glVertex2i,
glVertex2iv,
glVertex2s,
glVertex2sv,
glVertex3d,
glVertex3dv,
glVertex3f,
glVertex3fv,
glVertex3i,
glVertex3iv,
glVertex3s,
glVertex3sv,
glVertex4d,
glVertex4dv,
glVertex4f,
glVertex4fv,
glVertex4i,
glVertex4iv,
glVertex4s,
glVertex4sv,
glVertexAttrib1d,
glVertexAttrib1dv,
glVertexAttrib1f,
glVertexAttrib1fv,
glVertexAttrib1s,
glVertexAttrib1sv,
glVertexAttrib2d,
glVertexAttrib2dv,
glVertexAttrib2f,
glVertexAttrib2fv,
glVertexAttrib2s,
glVertexAttrib2sv,
glVertexAttrib3d,
glVertexAttrib3dv,
glVertexAttrib3f,
glVertexAttrib3fv,
glVertexAttrib3s,
glVertexAttrib3sv,
glVertexAttrib4Nbv,
glVertexAttrib4Niv,
glVertexAttrib4Nsv,
glVertexAttrib4Nub,
glVertexAttrib4Nubv,
glVertexAttrib4Nuiv,
glVertexAttrib4Nusv,
glVertexAttrib4bv,
glVertexAttrib4d,
glVertexAttrib4dv,
glVertexAttrib4f,
glVertexAttrib4fv,
glVertexAttrib4iv,
glVertexAttrib4s,
glVertexAttrib4sv,
glVertexAttrib4ubv,
glVertexAttrib4uiv,
glVertexAttrib4usv,
glVertexAttribI1i,
glVertexAttribI1iv,
glVertexAttribI1ui,
glVertexAttribI1uiv,
glVertexAttribI2i,
glVertexAttribI2iv,
glVertexAttribI2ui,
glVertexAttribI2uiv,
glVertexAttribI3i,
glVertexAttribI3iv,
glVertexAttribI3ui,
glVertexAttribI3uiv,
glVertexAttribI4bv,
glVertexAttribI4i,
glVertexAttribI4iv,
glVertexAttribI4sv,
glVertexAttribI4ubv,
glVertexAttribI4ui,
glVertexAttribI4uiv,
glVertexAttribI4usv,
glVertexAttribIPointer,
glVertexAttribPointer,
glVertexPointer,
glViewport,
glWindowPos2d,
glWindowPos2dv,
glWindowPos2f,
glWindowPos2fv,
glWindowPos2i,
glWindowPos2iv,
glWindowPos2s,
glWindowPos2sv,
glWindowPos3d,
glWindowPos3dv,
glWindowPos3f,
glWindowPos3fv,
glWindowPos3i,
glWindowPos3iv,
glWindowPos3s,
glWindowPos3sv
) where
import Graphics.Rendering.OpenGL.Raw.Types
import Graphics.Rendering.OpenGL.Raw.Tokens
import Graphics.Rendering.OpenGL.Raw.Functions
|
phaazon/OpenGLRaw
|
src/Graphics/Rendering/OpenGL/Raw/Compatibility31.hs
|
Haskell
|
bsd-3-clause
| 38,287
|
module Scheme.DataType (
module Scheme.DataType.Misc,
EvalError, ScmError, TryError,
Expr(..),
ScmCode(..), ScmFile,
Var(..),
Return(..), ReturnE,
Name, AFunc, WAFunc, RFunc, Proc, Synt,
Scm, runScm,
ScmEnv, ScmStates, ScmRef,
MetaInfo(..), Config(..), setConfig, setMSP,
MetaData(..), setTryHeap, setStackTrace,
GEnv, LEnv, MLEnv,
StackTrace(..), Trace, TraceR, initStackTrace, setTraceHeap, setTraceRHeap, setTraceLength,
Try(..), initTry, setDepthLimit, setLoopCount, setBinary, setCapturedDisplays,
DepthLimit(..),
) where
import Config
import Scheme.DataType.Error (ScmError)
import Scheme.DataType.Error.Eval (EvalError)
import Scheme.DataType.Error.Try (TryError)
import Scheme.DataType.Misc
import DeepControl.Applicative
import DeepControl.Monad
import DeepControl.MonadTrans
import DeepControl.Monad.RWS
import DeepControl.Monad.Except
import MonadX.Monad.Reference
import qualified Data.Map as M
import Data.List (intersperse)
type Name = String
----------------------------------------------------------------------------------------------------------------
-- Scm
----------------------------------------------------------------------------------------------------------------
type Scm a = (ExceptT ScmError
(ReferenceT Var
(RWST ScmEnv () ScmStates IO))) a
runScm :: Scm a
-> ScmRef -- Reference
-> ScmEnv -- Reader
-> ScmStates -- State
-> IO ((Either ScmError a, ScmRef), ScmStates, ())
runScm scm ref env states = scm >- runExceptT
>- (unReferenceT >-> (|>ref))
>- (runRWST >-> (|>env) >-> (|>states))
type ScmStates = (GEnv, MetaData) -- State
type ScmEnv = (MLEnv, MetaInfo) -- Reader
type ScmRef = RefEnv Var -- Reference
--
-- Env
--
type GEnv = M.Map Name Expr -- Global Environment
type LEnv = Ref Var{-Vm-} -- Local Environment
type MLEnv = Maybe LEnv
--
-- Variable for RefEnv
--
data Var = Ve Expr
| Vm (M.Map Name Expr{-REF-}) -- for LEnv
deriving (Eq)
instance Show Var where
show (Ve e) = show e
show (Vm map) = show map
--------------------------------------------------
-- Eval
--------------------------------------------------
-- TODO Functor
data Return a = RETURN a
| VOID
deriving (Show, Eq)
type ReturnE = Return Expr
--------------------------------------------------
-- Expr
--------------------------------------------------
-- Scheme Expression
data Expr = NIL
| INT !Integer
| REAL !Double
| SYM !String MSP
| STR !String
| CELL !Expr !Expr MSP
--
| AFUNC Name AFunc -- actual function: +, -, *, /, etc.
| WAFUNC Name WAFunc -- weekly actual function: length, append, etc.
| RFUNC Name RFunc -- referencial function: car, cdr, cons, set!, set-car!, set-cdr!, etc.
| PROC Name Proc -- procedure: display, newline, etc.
| SYNT Name Synt -- syntax: quote, if, define, etc.
| CLOS Expr MLEnv -- closure: λ
| CLOSM Expr MLEnv -- macro-closure
-- for set!, set-car!, set-cdr!, car and cdr; reference manipulation
| REF (Ref Var{-Ve-})
-- for lazy evaluation
| THUNK (Expr, ScmEnv)
instance Show Expr where
show NIL = "()"
show (INT x) = show x
show (REAL x) = show x
show (SYM x _) = x
show (STR x) = show x
show (CELL (SYM "quote" _) (CELL expr NIL _) _) = "'" ++ show expr
show (CELL (SYM "quasiquote" _) (CELL expr NIL _) _) = "`" ++ show expr
show (CELL (SYM "unquote" _) (CELL expr NIL _) _) = "," ++ show expr
show (CELL (SYM "unquote-splicing" _) (CELL expr NIL _) _) = ",@" ++ show expr
show c@(CELL a d _) = "(" ++ showCELL c ++ ")"
where
showCELL NIL = ""
showCELL (CELL a d _) = show a ++ case d of
NIL -> ""
c@(CELL _ _ _) -> " " ++ showCELL c
e -> " . " ++ show e
show (AFUNC x _) = "<" ++ x ++ ">"
show (WAFUNC x _) = "<" ++ x ++ ">"
show (RFUNC x _) = "<" ++ x ++ ">"
show (SYNT x _) = "<" ++ x ++ ">"
show (PROC x _) = "<" ++ x ++ ">"
show (CLOS (CELL args seq _) mlenv) = "(\\"++ show args ++" -> "++ showExprSeq seq ++")"
where
showExprSeq :: Expr -> String
showExprSeq NIL = ""
showExprSeq (CELL s NIL _) = show s
showExprSeq (CELL s1 s2 _) = show s1 ++" >> "++ showExprSeq s2
showExprSeq e = show e
show (CLOSM (CELL args seq _) mlenv) = "(#"++ show args ++" -> "++ showExprSeq seq ++")"
where
showExprSeq :: Expr -> String
showExprSeq NIL = ""
showExprSeq (CELL s NIL _) = show s
showExprSeq (CELL s1 s2 _) = show s1 ++" >> "++ showExprSeq s2
showExprSeq e = show e
show (THUNK (e, _)) = "[" ++ show e ++ "]"
show (REF ref) = "_"
type AFunc = Expr -> Scm Expr -- actual function
type WAFunc = Expr -> Scm Expr -- weekly actual function
type RFunc = Expr -> Scm Expr -- referencial function
type Proc = Expr -> Scm ReturnE -- procedure
type Synt = Expr -> Scm ReturnE -- syntax
instance Eq Expr where
NIL == NIL = True
INT x == INT y = x == y
REAL x == REAL y = x == y
SYM x _ == SYM y _ = x == y
STR x == STR y = x == y
CELL l r _ == CELL l' r' _ = (l,r) == (l',r')
CLOS x a == CLOS y b = (x,a) == (y,b)
CLOSM x a == CLOSM y b = (x,a) == (y,b)
AFUNC x a == AFUNC y b = x == y
WAFUNC x a == WAFUNC y b = x == y
RFUNC x a == RFUNC y b = x == y
SYNT x a == SYNT y b = x == y
PROC x a == PROC y b = x == y
REF x == REF y = x == y
THUNK x == THUNK y = x == y
_ == _ = False
--------------------------------------------------
-- SCode, SFile, SFiles
--------------------------------------------------
data ScmCode = EXPR Expr
| COMMENT String
| LINEBREAK
| EOF
instance Show ScmCode where
show (EXPR x) = show x
show (COMMENT s) = s
show LINEBREAK = ""
type ScmFile = [ScmCode]
----------------------------------------------------------------------------------------------------------------
-- RWS
----------------------------------------------------------------------------------------------------------------
--
-- MetaInfo
--
data MetaInfo = MetaInfo { config :: Config
, msp :: MSP
}
deriving (Show, Eq)
setConfig :: Config -> MetaInfo -> MetaInfo
setConfig x (MetaInfo _ b) = MetaInfo x b
setMSP :: MSP -> MetaInfo -> MetaInfo
setMSP x (MetaInfo a _) = MetaInfo a x
--
-- MetaData
--
data MetaData = MetaData { tryHeap :: [Try]
, stackTrace :: StackTrace
}
deriving (Show)
setTryHeap :: [Try] -> MetaData -> MetaData
setTryHeap x (MetaData _ b) = MetaData x b
setStackTrace :: StackTrace -> MetaData -> MetaData
setStackTrace x (MetaData a _) = MetaData a x
data StackTrace = StackTrace {
traceHeap :: [Trace]
, traceRHeap :: [TraceR] -- trace rusult
, traceLength :: Int
}
deriving (Show)
type Trace = (String, MSP, Maybe String)
type TraceR = Trace
initStackTrace :: StackTrace
initStackTrace = StackTrace [] [] 10
setTraceHeap :: [Trace] -> StackTrace -> StackTrace
setTraceHeap x (StackTrace _ b c) = StackTrace x b c
setTraceRHeap :: [TraceR] -> StackTrace -> StackTrace
setTraceRHeap x (StackTrace a _ c) = StackTrace a x c
setTraceLength :: Int -> StackTrace -> StackTrace
setTraceLength x (StackTrace a b _) = StackTrace a b x
-- TODO: ChaitinTry
data Try = Try { depthLimit :: DepthLimit
, loopCount :: Int
, binary :: Expr
, capturedDisplays :: [Expr]
}
deriving (Show)
data DepthLimit = NOTIMELIMIT
| DEPTHLIMIT Int
deriving (Show, Eq)
instance Ord DepthLimit where
compare NOTIMELIMIT NOTIMELIMIT = EQ
compare NOTIMELIMIT (DEPTHLIMIT _) = GT
compare (DEPTHLIMIT _) NOTIMELIMIT = LT
compare (DEPTHLIMIT n) (DEPTHLIMIT n') = compare n n'
initTry :: Try
initTry = Try NOTIMELIMIT 0 NIL []
setDepthLimit :: DepthLimit -> Try -> Try
setDepthLimit dl (Try _ lc bn cd) = Try dl lc bn cd
setLoopCount :: Int -> Try -> Try
setLoopCount lc (Try dl _ bn cd) = Try dl lc bn cd
setBinary :: Expr -> Try -> Try
setBinary bn (Try dl lc _ cd) = Try dl lc bn cd
setCapturedDisplays :: [Expr] -> Try -> Try
setCapturedDisplays cd (Try dl lc bn _) = Try dl lc bn cd
----------------------------------------------------------------------------------------------------------------
-- Misc
----------------------------------------------------------------------------------------------------------------
|
ocean0yohsuke/Scheme
|
src/Scheme/DataType.hs
|
Haskell
|
bsd-3-clause
| 9,162
|
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, TypeFamilies #-}
module Rubik.Turn where
import Data.Array
import Rubik.Negate as N
import Rubik.Key
data Turn = NoTurn | Clock | OneEighty | CounterClock
deriving (Eq,Ord,Show,Enum,Ix)
instance Negate Turn where
negate NoTurn = NoTurn
negate Clock = CounterClock
negate OneEighty = OneEighty
negate CounterClock = Clock
instance Key Turn where
universe = [ NoTurn, Clock, OneEighty, CounterClock ]
class Rotate a where
type SideOf a
rotate :: SideOf a -> a -> a
-- never used
--instance (Negate a, Rotate a b) => Rotate a (b -> c) where
-- rotate t f a = f (rotate (N.negate t) a)
{-
-- Split into its own module
class Rotate a where
type SideOf a
rotate :: SideOf a -> a -> a
-- can complete either
turn :: a -> a
turn = rotateBy Clock
rotateBy :: Turn -> a -> a
rotateBy Clock = turn
rotateBy OneEighty = turn . turn
rotateBy CounterClock = turn . turn . turn
-- We invert the rotate because it is the co-varient position
instance Rotate a => Rotate (a -> b) where
type SideOf (a -> b) = SideOf a
rotateBy t f a = f (rotateBy (N.negate t) a)
instance (Rotate a,Rotate b) => Rotate (a,b) where
rotateBy t (a,b) = (rotateBy t a, rotateBy t b)
data Apply a b = Apply (a -> b) a
apply :: Apply a b -> b
apply (Apply f a) = f a
instance Rotate a => Rotate (Apply a b) where
turn (Apply f a) = Apply f (turn a)
-}
|
andygill/rubik-solver
|
src/Rubik/Turn.hs
|
Haskell
|
bsd-3-clause
| 1,481
|
{-# LANGUAGE FlexibleInstances #-}
-- ghc options
{-# OPTIONS_GHC -Wall #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- {-# OPTIONS_GHC -fno-warn-name-shadowing #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- {-# OPTIONS_GHC -fno-warn-missing-signatures #-}
-- {-# OPTIONS_GHC -fno-warn-unused-do-bind #-}
-- {-# OPTIONS_GHC -fno-warn-incomplete-patterns #-}
-- {-# OPTIONS_GHC -fno-warn-incomplete-uni-patterns #-}
-- |
-- Copyright : (c) Andreas Reuleaux 2015
-- License : BSD2
-- Maintainer: Andreas Reuleaux <rx@a-rx.info>
-- Stability : experimental
-- Portability: non-portable
--
-- This module provides pretty printing functionality for Pire's
-- abstract and concrete syntax: names
module Pire.Pretty.Nm where
import Pire.Syntax.Nm
-- import Data.Text as T
import Text.PrettyPrint as TPP
import Pire.Pretty.Common
import Pire.Pretty.Ws()
-- instance Disp s => Disp (Nm_ s) where
-- disp (Nm_ nm (Ws ws)) = do
-- dnm <- disp nm
-- return $ dnm <> (text $ T.unpack ws)
instance Disp s => Disp (Nm1 s) where
disp (Nm1 nm) = disp nm
disp (Nm1_ nm ws) = do
dnm <- disp nm
dws <- disp ws
return $ dnm <> dws
instance Disp s => Disp (Nm s s) where
disp (Nm nm) = disp nm
disp (Nm_ nm ws) = do
dnm <- disp nm
dws <- disp ws
return $ dnm <> dws
|
reuleaux/pire
|
src/Pire/Pretty/Nm.hs
|
Haskell
|
bsd-3-clause
| 1,331
|
class X where
foo :: Int
-- | Y
-- Y is something
-- nice.
class Y where
bar :: Int
|
itchyny/vim-haskell-indent
|
test/comment/before_blank_line_and_class.out.hs
|
Haskell
|
mit
| 91
|
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE Arrows #-}
module Main where
import Opaleye
import Data.Profunctor.Product
import Data.Profunctor.Product.Default
import Data.Profunctor.Product.TH (makeAdaptorAndInstance)
import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.FromField (FromField(..))
import Prelude hiding (id)
import Control.Arrow
newtype UserId = UserId Int deriving (Show)
data UserPoly id name email = User { id :: id, name :: name, email :: email } deriving (Show)
type User = UserPoly UserId String String
type UserPGW = UserPoly (Column PGInt4) (Column PGText) (Column PGText)
type UserPGR = UserPoly (Column PGInt4) (Column PGText) (Column PGText)
$(makeAdaptorAndInstance "pUser" ''UserPoly)
userTable :: Table UserPGW UserPGR
userTable = Table "users" (pUser User {
id = required "id",
name = required "name",
email = required "email"
}
)
instance FromField UserId where
fromField field bs = UserId <$> fromField field bs
instance QueryRunnerColumnDefault PGInt4 UserId where
queryRunnerColumnDefault = fieldQueryRunnerColumn
getUserRows :: IO [User]
getUserRows = do
conn <- connect defaultConnectInfo { connectDatabase = "scratch"}
runQuery conn $ proc () ->
do
user@User {name = pgName} <- queryTable userTable -< ()
restrict -< (pgName .== (pgStrictText "John"))
returnA -< user
main :: IO ()
main = do
rows <- getUserRows
putStrLn $ show rows
-- Output
-- [User {id = UserId 1, name = "John", email = "john@mail.com"},User {id = UserId
-- 2, name = "Bob", email = "bob@mail.com"},User {id = UserId 3, name = "Alice",
-- email = "alice@mail.com"}]
|
meditans/haskell-webapps
|
doc/docs/opaleye/code/opaleye-select-with-records-and-restrict.hs
|
Haskell
|
mit
| 1,804
|
module Verifier.SAW.SATQuery
( SATQuery(..)
, SATResult(..)
, satQueryAsTerm
) where
import Control.Monad (foldM)
import Data.Map (Map)
import Data.Set (Set)
import Verifier.SAW.Name
import Verifier.SAW.FiniteValue
import Verifier.SAW.SharedTerm
-- | This datatype represents a satisfiability query that might
-- be dispatched to a solver. It carries a series of assertions
-- to be made to a solver, together with a collection of
-- variables we expect the solver to report models over,
-- and a collection of @VarIndex@ values identifying
-- subterms that should be considered uninterpreted.
--
-- All the @ExtCns@ values in the query should
-- appear either in @satVariables@ or @satUninterp@.
-- Constant values for which definitions are provided
-- may also appear in @satUninterp@, in which case
-- they will be treated as uninterpreted. Otherwise,
-- their definitions will be unfolded.
--
-- Solve solvers do not support uninterpreted values
-- and will fail if presented a query that requests them.
data SATQuery =
SATQuery
{ satVariables :: Map (ExtCns Term) FirstOrderType
-- ^ The variables in the query, for which we
-- expect the solver to find values in satisfiable
-- cases. INVARIANT: The type of the @ExtCns@ keys
-- should correspond to the @FirstOrderType@ values.
, satUninterp :: Set VarIndex
-- ^ A set indicating which variables and constant
-- values should be considered uninterpreted by
-- the solver. Models will not report values
-- for uninterpreted values.
, satAsserts :: [Term]
-- ^ A collection of assertions. These should
-- all be terms of type @Bool@. The overall
-- query should be understood as the conjunction
-- of these terms.
}
-- TODO, allow first-order propositions in addition to Boolean terms.
-- | The result of a sat query. In the event a model is found,
-- return a mapping from the @ExtCns@ variables to values.
data SATResult
= Unsatisfiable
| Satisfiable (ExtCns Term -> IO FirstOrderValue)
| Unknown
-- | Compute the conjunction of all the assertions
-- in this SAT query as a single term of type Bool.
satQueryAsTerm :: SharedContext -> SATQuery -> IO Term
satQueryAsTerm sc satq =
case satAsserts satq of
[] -> scBool sc True
(x:xs) -> foldM (scAnd sc) x xs
-- TODO, we may have to rethink this function
-- once we allow first-order statements.
|
GaloisInc/saw-script
|
saw-core/src/Verifier/SAW/SATQuery.hs
|
Haskell
|
bsd-3-clause
| 2,474
|
{-# LANGUAGE OverloadedStrings, TupleSections #-}
-- | Parser components for the ROS message description language (@msg@
-- files). See http://wiki.ros.org/msg for reference.
module Parse (parseMsg, parseSrv, simpleFieldAssoc) where
import Prelude hiding (takeWhile)
import Control.Applicative
import Control.Arrow ((&&&))
import Data.Attoparsec.ByteString.Char8
import Data.ByteString (ByteString)
import Data.ByteString.Char8 (pack, unpack)
import qualified Data.ByteString.Char8 as B
import Data.Char (toLower, digitToInt)
import Data.Either (partitionEithers)
import Data.List (foldl')
import System.FilePath (dropExtension, takeFileName, splitDirectories)
import Types
simpleFieldTypes :: [MsgType]
simpleFieldTypes = [ RBool, RInt8, RUInt8, RInt16, RUInt16, RInt32, RUInt32,
RInt64, RUInt64, RFloat32, RFloat64, RString,
RTime, RDuration, RByte, RChar ]
simpleFieldAssoc :: [(MsgType, ByteString)]
simpleFieldAssoc = map (id &&& B.pack . map toLower . tail . show)
simpleFieldTypes
eatLine :: Parser ()
eatLine = manyTill anyChar (eitherP endOfLine endOfInput) *> skipSpace
parseName :: Parser ByteString
parseName = skipSpace *> identifier <* eatLine <* try comment
identifier :: Parser ByteString
identifier = B.cons <$> letter_ascii <*> takeWhile validChar
where validChar c = any ($ c) [isDigit, isAlpha_ascii, (== '_'), (== '/')]
parseInt :: Parser Int
parseInt = foldl' (\s x -> s*10 + digitToInt x) 0 <$> many1 digit
comment :: Parser [()]
comment = many $ skipSpace *> try (char '#' *> eatLine)
simpleParser :: (MsgType, ByteString) -> Parser (ByteString, MsgType)
simpleParser (t,b) = (, t) <$> (string b *> space *> parseName)
fixedArrayParser :: (MsgType, ByteString) -> Parser (ByteString, MsgType)
fixedArrayParser (t,b) = (\len name -> (name, RFixedArray len t)) <$>
(string b *> char '[' *> parseInt <* char ']') <*>
(space *> parseName)
varArrayParser :: (MsgType, ByteString) -> Parser (ByteString, MsgType)
varArrayParser (t,b) = (, RVarArray t) <$>
(string b *> string "[]" *> space *> parseName)
userTypeParser :: Parser (ByteString, MsgType)
userTypeParser = choice [userSimple, userVarArray, userFixedArray]
userSimple :: Parser (ByteString, MsgType)
userSimple = (\t name -> (name, RUserType t)) <$>
identifier <*> (space *> parseName)
userVarArray :: Parser (ByteString, MsgType)
userVarArray = (\t name -> (name, RVarArray (RUserType t))) <$>
identifier <*> (string "[]" *> space *> parseName)
userFixedArray :: Parser (ByteString, MsgType)
userFixedArray = (\t n name -> (name, RFixedArray n (RUserType t))) <$>
identifier <*>
(char '[' *> parseInt <* char ']') <*>
(space *> parseName)
-- Parse constants defined in the message
constParser :: ByteString -> MsgType ->
Parser (ByteString, MsgType, ByteString)
constParser s x = (,x,) <$>
(string s *> space *> identifier) <*>
(skipSpace *> char '=' *> skipSpace *> restOfLine <* skipSpace)
where restOfLine :: Parser ByteString
restOfLine = pack <$> manyTill anyChar (eitherP endOfLine endOfInput)
constParsers :: [Parser (ByteString, MsgType, ByteString)]
constParsers = map (uncurry constParser . swap) simpleFieldAssoc
where swap (x,y) = (y,x)
-- String constants are parsed somewhat differently from numeric
-- constants. For numerical constants, we drop comments and trailing
-- spaces. For strings, we take the whole line (so comments aren't
-- stripped).
sanitizeConstants :: (a, MsgType, ByteString) -> (a, MsgType, ByteString)
sanitizeConstants c@(_, RString, _) = c
sanitizeConstants (name, t, val) =
(name, t, B.takeWhile (\c -> c /= '#' && not (isSpace c)) val)
-- Parsers fields and constants.
fieldParsers :: [Parser (Either (ByteString, MsgType)
(ByteString, MsgType, ByteString))]
fieldParsers = map (comment *>) $
map (Right . sanitizeConstants <$>) constParsers ++
map (Left <$>) (builtIns ++ [userTypeParser])
where builtIns = concatMap (`map` simpleFieldAssoc)
[simpleParser, fixedArrayParser, varArrayParser]
mkParser :: MsgName -> String -> ByteString -> Parser Msg
mkParser sname lname txt = aux . partitionEithers <$> many (choice fieldParsers)
where aux (fs, cs) = Msg sname lname txt
(map buildField fs)
(map buildConst cs)
buildField :: (ByteString, MsgType) -> MsgField
buildField (name,typ) = MsgField fname typ name
where fname = B.append "_" $ sanitize name
buildConst :: (ByteString, MsgType, ByteString) -> MsgConst
buildConst (name,typ,val) = MsgConst fname typ val name
where fname = B.map toLower $ sanitize name
{-
testMsg :: ByteString
testMsg = "# Foo bar\n\n# \nHeader header # a header\nuint32 aNum # a number \n # It's not important\ngeometry_msgs/PoseStamped[] poses\nbyte DEBUG=1 #debug level\n"
test :: Result Msg
test = feed (parse (comment *> (mkParser "" "" testMsg)) testMsg) ""
-}
-- Ensure that field and constant names are valid Haskell identifiers
-- and do not coincide with Haskell reserved words.
sanitize :: ByteString -> ByteString
sanitize "data" = "_data"
sanitize "type" = "_type"
sanitize "class" = "_class"
sanitize "module" = "_module"
sanitize x = B.cons (toLower (B.head x)) (B.tail x)
pkgName :: FilePath -> String
pkgName f = let parts = splitDirectories f
[pkg,_,_msgFile] = drop (length parts - 3) parts
in pkg
parseMsg :: FilePath -> IO (Either String Msg)
parseMsg fname = do msgFile <- B.readFile fname
let tName = msgName . dropExtension . takeFileName $ fname
packageName = pkgName fname
return $ parseMsgWithName tName packageName msgFile
parseMsgWithName :: MsgName -> String -> ByteString -> Either String Msg
parseMsgWithName name packageName msgFile =
case feed (parse parser msgFile) "" of
Done leftOver msg
| B.null leftOver -> Right msg
| otherwise -> Left $ "Couldn't parse " ++
unpack leftOver
Fail _ _ctxt err -> Left err
Partial _ -> Left "Incomplete msg definition"
where
parser = comment *> mkParser name packageName msgFile
-- | Parse a service file by splitting the file into a request and a response
-- | and parsing each part separately.
parseSrv :: FilePath -> IO (Either String Srv)
parseSrv fname = do
srvFile <- B.readFile fname
let (request, response) = splitService srvFile
packageName = pkgName fname
rawServiceName = dropExtension . takeFileName $ fname
return $ do
rqst <- parseMsgWithName (requestMsgName rawServiceName) packageName request
resp <- parseMsgWithName (responseMsgName rawServiceName) packageName response
return Srv{srvRequest = rqst
, srvResponse = resp
, srvName = msgName rawServiceName
, srvPackage = packageName
, srvSource = srvFile}
splitService :: ByteString -> (ByteString, ByteString)
splitService service = (request, response) where
-- divider does not include newlines to allow it match even
-- if there is no request or response message
divider = "---"
(request, dividerAndResponse) = B.breakSubstring divider service
--Add 1 to the length of the divider to remove newline
response = B.drop (1 + B.length divider) dividerAndResponse
|
bitemyapp/roshask
|
src/executable/Parse.hs
|
Haskell
|
bsd-3-clause
| 7,585
|
module FunIn3 where
--The application of a function is replaced by the right-hand side of the definition,
--with actual parameters replacing formals.
--In this example, unfold 'addthree'.
--This example aims to test the elimination of extra parentheses when unfolding
--a function defintion.
main :: Int -> Int
main = \x -> case x of
1 -> 1 + main 0
0 ->((1 + 2) + 3)
addthree :: Int -> Int -> Int -> Int
addthree a b c = a + b + c
|
mpickering/HaRe
|
old/testing/unfoldDef/FunIn3_TokOut.hs
|
Haskell
|
bsd-3-clause
| 469
|
module StrategoAST2(module AST) where
import StrategoPattern as AST
import StrategoTerm as AST
import StrategoType as AST
import StrategoProp as AST
import StrategoDecl as AST
|
forste/haReFork
|
tools/hs2stratego/AST/StrategoAST2.hs
|
Haskell
|
bsd-3-clause
| 176
|
module ShowRepoEvents where
import qualified Github.Issues.Events as Github
import Data.List (intercalate)
import Data.Maybe (fromJust)
main = do
possibleEvents <- Github.eventsForRepo "thoughtbot" "paperclip"
case possibleEvents of
(Left error) -> putStrLn $ "Error: " ++ show error
(Right events) -> do
putStrLn $ intercalate "\n" $ map formatEvent events
formatEvent event =
"Issue #" ++ issueNumber event ++ ": " ++
formatEvent' event (Github.eventType event)
where
formatEvent' event Github.Closed =
"closed on " ++ createdAt event ++ " by " ++ loginName event ++
withCommitId event (\commitId -> " in the commit " ++ commitId)
formatEvent' event Github.Reopened =
"reopened on " ++ createdAt event ++ " by " ++ loginName event
formatEvent' event Github.Subscribed =
loginName event ++ " is subscribed to receive notifications"
formatEvent' event Github.Unsubscribed =
loginName event ++ " is unsubscribed from notifications"
formatEvent' event Github.Merged =
"merged by " ++ loginName event ++ " on " ++ createdAt event ++
(withCommitId event $ \commitId -> " in the commit " ++ commitId)
formatEvent' event Github.Referenced =
withCommitId event $ \commitId ->
"referenced from " ++ commitId ++ " by " ++ loginName event
formatEvent' event Github.Mentioned =
loginName event ++ " was mentioned in the issue's body"
formatEvent' event Github.Assigned =
"assigned to " ++ loginName event ++ " on " ++ createdAt event
loginName = Github.githubOwnerLogin . Github.eventActor
createdAt = show . Github.fromGithubDate . Github.eventCreatedAt
withCommitId event f = maybe "" f (Github.eventCommitId event)
issueNumber = show . Github.issueNumber . fromJust . Github.eventIssue
|
bitemyapp/github
|
samples/Issues/Events/ShowRepoEvents.hs
|
Haskell
|
bsd-3-clause
| 1,783
|
module Lib where
import Data.Function (on)
import Data.List (findIndices, minimumBy, transpose)
import Data.Maybe (isJust, isNothing)
data Shape = Nought | Cross
deriving (Read, Show, Eq)
type Cell = Maybe Shape
type Board = [Cell]
boardSize = 3
emptyBoard = replicate (boardSize * boardSize) Nothing
makeBoard :: String -> Board
makeBoard = map charToCell . take (boardSize * boardSize)
where
charToCell 'o' = Just Nought
charToCell 'x' = Just Cross
charToCell _ = Nothing
nextMove :: Board -> Shape -> Board
nextMove brd shp = minimumBy (compare `on` opponentScore) (nextBoards brd shp)
where
opponentScore brd' = scoreFor brd' (opponent shp)
isWinFor :: Board -> Shape -> Bool
isWinFor brd shp = any winningSlice allSlices
where
winningSlice = all (== Just shp)
allSlices = rows brd ++ cols brd ++ diagonals brd
isLossFor :: Board -> Shape -> Bool
isLossFor brd shp = isWinFor brd (opponent shp)
isDraw :: Board -> Bool
isDraw brd = isFull brd && noWin Nought && noWin Cross
where
noWin = not . isWinFor brd
isFull :: Board -> Bool
isFull = all isJust
nextBoards :: Board -> Shape -> [Board]
nextBoards brd shp = map makeMove emptyIdxs
where
makeMove n = fillCell brd n (Just shp)
emptyIdxs = findIndices isNothing brd
fillCell :: Board -> Int -> Cell -> Board
fillCell brd n cell
| n >= (boardSize * boardSize) = brd
| otherwise = before ++ [cell] ++ (drop 1 after)
where
(before, after) = splitAt n brd
scoreFor :: Board -> Shape -> Int
scoreFor brd shp
| isWinFor brd shp = 1
| isLossFor brd shp = -1
| isDraw brd = 0
| otherwise = -(minimum $ map opponentScore (nextBoards brd shp))
where
opponentScore brd' = scoreFor brd' (opponent shp)
rows :: Board -> [[Cell]]
rows brd = map row [0..boardSize-1]
where
row n = take boardSize . drop (n * boardSize) $ brd
cols :: Board -> [[Cell]]
cols = transpose . rows
diagonals :: Board -> [[Cell]]
diagonals brd = map extract [topLeft, topRight]
where
extract = map (brd !!)
topLeft = map (\n -> n * (boardSize + 1)) [0..boardSize-1]
topRight = map (\n -> (n + 1) * (boardSize - 1)) [0..boardSize-1]
opponent :: Shape -> Shape
opponent Nought = Cross
opponent Cross = Nought
|
leocassarani/noughts-and-crosses
|
src/Lib.hs
|
Haskell
|
mit
| 2,262
|
{-|
Module : TestUtils.Validate
Description : The Validate type class
Copyright : (c) Andrew Burnett 2014-2015
Maintainer : andyburnett88@gmail.com
Stability : experimental
Portability : Unknown
'Validate' provides a definition for validating a data structure. For example,
we may cache information about the size of a list as it is created. Validate
would check that this is correct
-}
module TestUtils.Validate (
Validate(..)
) where
{-|
The 'Validate' class provides a validate method for types, to make
sure that they have been defined correctly.
-}
class Validate a where
-- | validate should return a 'Bool' which defines whether a data structure
-- | is valid
validate :: a -> Bool
|
aburnett88/HSat
|
tests-src/TestUtils/Validate.hs
|
Haskell
|
mit
| 712
|
module Language.Aspell (
-- * Constructors
SpellChecker,
spellChecker,
spellCheckerWithOptions,
spellCheckerWithDictionary,
-- * Using the spell checker
check,
suggest
) where
import Data.ByteString.Char8
import Foreign
#if !MIN_VERSION_base(4,7,0)
hiding (unsafePerformIO)
#endif
import Foreign.C.String
import Foreign.C.Types
import Language.Aspell.Options
import System.IO.Unsafe
type AspellConfig = ForeignPtr ()
type SpellChecker = ForeignPtr ()
type CAspellConfig = Ptr ()
type CSpellChecker = Ptr ()
type CAspellCanHaveError = Ptr ()
type CWordList = Ptr ()
type CStringEnumeration = Ptr ()
newConfig :: IO AspellConfig
newConfig = do
cf <- new_aspell_config
newForeignPtr delete_aspell_config cf
setOpts :: [ACOption] -> AspellConfig -> IO AspellConfig
setOpts (Dictionary dict:opts) pt = setOpt "master" dict pt >>= setOpts opts
setOpts (WordListDir dir:opts) pt = setOpt "dict-dir" dir pt >>= setOpts opts
setOpts (Lang lang:opts) pt = setOpt "lang" lang pt >>= setOpts opts
setOpts (Size size:opts) pt = setOpt "size" newSize pt >>= setOpts opts
where
newSize = case size of
Tiny -> "+10"
ReallySmall -> "+20"
Small -> "+30"
MediumSmall -> "+40"
Medium -> "+50"
MediumLarge -> "+60"
Large -> "+70"
Huge -> "+80"
Insane -> "+90"
setOpts (PersonalWordList wl:opts) pt = setOpt "personal" wl pt >>= setOpts opts
setOpts (ReplacementsList rl:opts) pt = setOpt "repl" rl pt >>= setOpts opts
setOpts (Encoding encoding:opts) pt = setOpt "encoding" enc pt >>= setOpts opts
where
enc = case encoding of
UTF8 -> "utf-8"
Latin1 -> "iso-8859-1"
setOpts (Normalize n:opts) pt = setOptBool "normalize" n pt >>= setOpts opts
setOpts (NormalizeStrict n:opts) pt = setOptBool "norm-strict" n pt >>= setOpts opts
setOpts (NormalizeForm form:opts) pt = setOpt "norm-form" nform pt >>= setOpts opts
where
nform = case form of
None -> "none"
NFD -> "nfd"
NFC -> "nfc"
Composed -> "comp"
setOpts (NormalizeRequired b:opts) pt = setOptBool "norm-required" b pt >>= setOpts opts
setOpts (Ignore i:opts) pt = setOptInteger "ignore" i pt >>= setOpts opts
setOpts (IgnoreReplace b:opts) pt = setOptBool "ignore-repl" b pt >>= setOpts opts
setOpts (SaveReplace b:opts) pt = setOptBool "save-repl" b pt >>= setOpts opts
setOpts (KeyboardDef s:opts) pt = setOpt "keyboard" s pt >>= setOpts opts
setOpts (SuggestMode sm:opts) pt = setOpt "sug-mode" mode pt >>= setOpts opts
where
mode = case sm of
Ultra -> "ultra"
Fast -> "fast"
Normal -> "normal"
Slow -> "slow"
BadSpellers -> "bad-spellers"
setOpts (IgnoreCase b:opts) pt = setOptBool "ignore-case" b pt >>= setOpts opts
setOpts (IgnoreAccents b:opts) pt = setOptBool "ignore-accents" b pt >>= setOpts opts
setOpts (FilterMode s:opts) pt = setOpt "mode" s pt >>= setOpts opts
setOpts (EmailMargin n:opts) pt = setOptInteger "email-margin" n pt >>= setOpts opts
setOpts (TeXCheckComments b:opts) pt = setOptBool "tex-check-comments" b pt >>= setOpts opts
setOpts (ContextVisibleFirst b:opts) pt = setOptBool "context-visible-first" b pt >>= setOpts opts
setOpts (RunTogether b:opts) pt = setOptBool "run-together" b pt >>= setOpts opts
setOpts (RunTogetherLimit n:opts) pt = setOptInteger "run-together-limit" n pt >>= setOpts opts
setOpts (RunTogetherMin n:opts) pt = setOptInteger "run-together-min" n pt >>= setOpts opts
setOpts (MainConfig s:opts) pt = setOpt "conf" s pt >>= setOpts opts
setOpts (MainConfigDir s:opts) pt = setOpt "conf-dir" s pt >>= setOpts opts
setOpts (DataDir s:opts) pt = setOpt "data-dir" s pt >>= setOpts opts
setOpts (LocalDataDir s:opts) pt = setOpt "local-data-dir" s pt >>= setOpts opts
setOpts (HomeDir s:opts) pt = setOpt "home-dir" s pt >>= setOpts opts
setOpts (PersonalConfig s:opts) pt = setOpt "per-conf" s pt >>= setOpts opts
setOpts (Layout s:opts) pt = setOpt "keyboard" s pt >>= setOpts opts
setOpts (Prefix s:opts) pt = setOpt "prefix" s pt >>= setOpts opts
setOpts (SetPrefix b:opts) pt = setOptBool "set-prefix" b pt >>= setOpts opts
setOpts [] pt = return pt
setOpt :: ByteString
-> ByteString
-> AspellConfig
-> IO AspellConfig
setOpt key value pt = do
withForeignPtr pt $ \ac ->
useAsCString key $ \k ->
useAsCString value $ aspell_config_replace ac k
return pt
setOptBool :: ByteString -> Bool -> AspellConfig -> IO AspellConfig
setOptBool k v = setOpt k (if v then "true" else "false")
setOptInteger :: ByteString -> Integer -> AspellConfig -> IO AspellConfig
setOptInteger k v = setOpt k (pack $ show v)
-- | Creates a spell checker with default options.
--
-- @
-- 'spellChecker' = 'spellCheckerWithOptions' []
-- @
--
spellChecker :: IO (Either ByteString SpellChecker)
spellChecker = spellCheckerWithOptions []
-- | Creates a spell checker with a custom set of options.
spellCheckerWithOptions :: [ACOption] -> IO (Either ByteString SpellChecker)
spellCheckerWithOptions opts = do
cf <- newConfig
setOpts opts cf
canError <- withForeignPtr cf new_aspell_speller
(errNum :: Int) <- fromIntegral `fmap` aspell_error_number canError
if errNum > 0
then do
errMsg <- aspell_error_message canError >>= packCString
return $ Left errMsg
else do
speller <- to_aspell_speller canError
for <- newForeignPtr delete_aspell_speller speller
return $ Right for
-- | Convenience function for specifying a dictionary.
--
-- You can determine which dictionaries are available to you with @aspell dump dicts@.
--
-- @
-- 'spellCheckerWithDictionary' dict = 'spellCheckerWithOptions' ['Dictionary' dict]
-- @
spellCheckerWithDictionary :: ByteString -> IO (Either ByteString SpellChecker)
spellCheckerWithDictionary b = spellCheckerWithOptions [Dictionary b]
-- | Checks if a word has been spelled correctly.
check :: SpellChecker -> ByteString -> Bool
check checker word = unsafePerformIO $
withForeignPtr checker $ \ck ->
useAsCString word $ \w -> do
res <- aspell_speller_check ck w $ negate 1
return $ res == 1
-- | Lists suggestions for misspelled words.
--
-- If the input is not misspelled according to the dictionary, returns @[]@.
suggest :: SpellChecker -> ByteString -> IO [ByteString]
suggest checker word = withForeignPtr checker $ \ck ->
useAsCString word $ \w -> do
wlist <- aspell_speller_suggest ck w (negate 1)
elems <- aspell_word_list_elements wlist
suggestions <- strEnumToList elems
delete_aspell_string_enumeration elems
return suggestions
strEnumToList :: CStringEnumeration -> IO [ByteString]
strEnumToList enum = go enum
where go e = do
nw <- aspell_string_enumeration_next enum
if nw == nullPtr
then return []
else do
curWord <- packCString nw
next <- go e
return $ curWord:next
foreign import ccall unsafe "aspell.h &delete_aspell_config"
delete_aspell_config :: FunPtr (CAspellConfig -> IO ())
foreign import ccall unsafe "aspell.h &delete_aspell_speller"
delete_aspell_speller :: FunPtr (CSpellChecker -> IO ())
foreign import ccall unsafe "aspell.h delete_aspell_string_enumeration"
delete_aspell_string_enumeration :: CStringEnumeration -> IO ()
foreign import ccall unsafe "aspell.h new_aspell_config"
new_aspell_config :: IO CAspellConfig
foreign import ccall unsafe "aspell.h aspell_config_replace"
aspell_config_replace :: CAspellConfig
-> CString
-> CString
-> IO CAspellConfig
foreign import ccall unsafe "aspell.h new_aspell_speller"
new_aspell_speller :: CAspellConfig
-> IO CAspellCanHaveError
foreign import ccall unsafe "aspell.h aspell_error_number"
aspell_error_number :: CAspellCanHaveError
-> IO CUInt
foreign import ccall unsafe "aspell.h aspell_error_message"
aspell_error_message :: CAspellCanHaveError
-> IO CString
foreign import ccall unsafe "aspell.h to_aspell_speller"
to_aspell_speller :: CAspellCanHaveError
-> IO CSpellChecker
foreign import ccall unsafe "aspell.h aspell_speller_check"
aspell_speller_check :: CSpellChecker
-> CString
-> CInt
-> IO CInt
foreign import ccall unsafe "aspell.h aspell_speller_suggest"
aspell_speller_suggest :: CSpellChecker
-> CString
-> CInt
-> IO CWordList
foreign import ccall unsafe "aspell.h aspell_word_list_elements"
aspell_word_list_elements :: CWordList
-> IO CStringEnumeration
foreign import ccall unsafe "aspell.h aspell_string_enumeration_next"
aspell_string_enumeration_next :: CStringEnumeration
-> IO CString
|
pikajude/haspell
|
Language/Aspell.hs
|
Haskell
|
mit
| 9,412
|
{- |
module: Main
description: Testing the FEN to Unicode conversion
license: MIT
maintainer: Joe Leslie-Hurd <joe@gilith.com>
stability: provisional
portability: portable
-}
module Main
( main )
where
import qualified Unicode
import qualified Chess
tests :: [(String,String,Chess.Edge)]
tests =
[("Initial position",
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR",
Chess.NoEdge),
("Mate in 3",
"KR6/8/kN4r1/p7/8/8/8/8",
Chess.SingleEdge),
("Mate in 4",
"8/8/4K3/1BkN4/8/2NpP3/3P4/8",
Chess.DoubleEdge)]
outputFen :: (String,String,Chess.Edge) -> IO ()
outputFen (s,f,e) =
do putStrLn (s ++ ":")
Unicode.encode (Chess.fenToUnicode f e ++ Unicode.newline)
main :: IO ()
main = mapM_ outputFen tests
|
gilith/opentheory
|
data/haskell/fen2s/src/Test.hs
|
Haskell
|
mit
| 765
|
{-# LANGUAGE TupleSections #-}
module Y2016.M09.D09.Solution where
import Control.Arrow (first)
import Control.Monad (guard, (>=>))
import Data.Function (on)
import Data.List (sortBy)
import Data.Map (Map)
import qualified Data.Map as Map
-- below import available from 1HaskellADay git repository
import Control.List (takeout)
{--
Now for something completely different ...
So some related cryptoarithmetic:
--}
sums :: [(String, String, Int)]
sums = [("FAT", "CAT", 904), ("STORE","CAKE",60836), ("EACH", "ROSE", 7839)]
-- solve these sums
-- Okay, first we need to assign a letter to a value
assign :: Map Char Int -> Char -> [Int] -> [((Char, Int), [Int])]
assign ctx ch domain =
maybe (fmap (first (ch,)) (takeout domain)) (pure . (,domain) . (ch,))
(Map.lookup ch ctx)
-- we do that for each of the letters.
assigns :: Map Char Int -> String -> [Int] -> [([(Char, Int)], [Int])]
assigns _ [] = pure . ([],)
assigns ctx (ch:s) =
assign ctx ch >=> \(a,b) -> assigns ctx s b >>= return . first (a:)
{--
*Y2016.M09.D09.Solution> let ans = assigns Map.empty "FAT" [0..9]
*Y2016.M09.D09.Solution> head ans ~> ([('F',0),('A',1),('T',2)],[3,4,5,6,7,8,9])
*Y2016.M09.D09.Solution> last ans ~> ([('F',9),('A',8),('T',7)],[0,1,2,3,4,5,6])
*Y2016.M09.D09.Solution> length ans ~> 720
--}
-- Okay, we have that, so let's convert that to a map. With arrows, this is
-- easy, right: map (first Map.fromList)
-- Now we convert a word into a number:
numfrom :: Map Char Int -> String -> Int
numfrom ctx = foldl (\tots -> (10 * tots +) . (ctx Map.!)) 0
{--
*Y2016.M09.D09.Solution> let fats = map (first (flip numfrom "FAT" . Map.fromList)) ans
*Y2016.M09.D09.Solution> head fats ~> (210,[3,4,5,6,7,8,9])
*Y2016.M09.D09.Solution> last fats ~> (789,[0,1,2,3,4,5,6])
--}
solver :: (String, String, Int) -> Map Char Int -> [Int] -> [(Map Char Int, [Int])]
solver (a,b,c) ctx domain =
assigns ctx a domain >>= \(asol, rest) ->
let amap = merge ctx asol
na = numfrom amap a in
guard (na < c) >>
assigns amap b rest >>= \(bsol, subdom) ->
let newmap = merge amap bsol in
guard (na + numfrom newmap b == c) >>
return (newmap, subdom)
merge :: Ord a => Map a b -> [(a,b)] -> Map a b
merge m = Map.union m . Map.fromList
-- solving all three will map the letter to the digits [0..9]
{--
*Y2016.M09.D09.Solution> let solves = solver Map.empty [0..9] (head sums)
*Y2016.M09.D09.Solution> length solves ~> 10
*Y2016.M09.D09.Solution> head solves
(fromList [('A',5),('C',8),('F',0),('T',2)],[1,3,4,6,7,9])
so:
--}
solveAll :: [(String, String, Int)] -> Map Char Int -> [Int] -> [Map Char Int]
solveAll [] ctx = const (pure ctx)
solveAll (e:qs) ctx = solver e ctx >=> uncurry (solveAll qs) . first (Map.union ctx)
{--
*Y2016.M09.D09.Solution> solveAll sums Map.empty [0..9] ~>
{[('A',0),('C',8),('E',3),('F',1),('H',6),('K',9),('O',7),('R',4),('S',5),('T',2)]}
--}
-- arrange the character in their digit-value order. What word do you get?
arrange :: Map Char Int -> String
arrange = map fst . sortBy (compare `on` snd) . Map.toList
-- *Y2016.M09.D09.Solution> arrange (head it) ~> "AFTERSHOCK"
|
geophf/1HaskellADay
|
exercises/HAD/Y2016/M09/D09/Solution.hs
|
Haskell
|
mit
| 3,206
|
{-# htermination (scanl :: (a -> b -> a) -> a -> (List b) -> (List a)) #-}
import qualified Prelude
data MyBool = MyTrue | MyFalse
data List a = Cons a (List a) | Nil
scanl0 f q Nil = Nil;
scanl0 f q (Cons x xs) = scanl f (f q x) xs;
scanl :: (b -> a -> b) -> b -> (List a) -> (List b);
scanl f q xs = Cons q (scanl0 f q xs);
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/basic_haskell/scanl_1.hs
|
Haskell
|
mit
| 352
|
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE OverloadedStrings #-}
-- | The GhostLang.Node.Flow module is implementing the Flows -
-- business logic - for the Node.
module GhostLang.Node.Flow
( getHttpConfig
, setHttpConfig
, listPrograms
, listPatternsFromProgram
, runNamedPattern
, runRandomPattern
, loadProgram
, listPatterns
, getGlobalCounter
, getPatternCounter
, patternStatus
) where
import Control.Concurrent.Async (async, poll)
import Control.Concurrent.STM (newTVarIO, readTVarIO)
import Data.ByteString (ByteString)
import Data.List (find)
import Data.Text (Text)
import Data.Text.Encoding (encodeUtf8)
import GhostLang ( GhostPattern
, PatternTuple
, Counter (..)
, compileAndLink
, emptyCounter
, runPattern
, toPatternList
)
import GhostLang.API ( PatternInfo (..)
, ProgramPath (..)
, Resource (..)
, Service (..)
, ExecParams (..)
, NamedPattern (..)
, PatternStatus (..)
, PatternCounter (..)
)
import GhostLang.Node.IdGen (genId)
import GhostLang.Node.State ( State (..)
, ResourceKey
, ProgramRepr (..)
, PatternRepr (..)
, NetworkConfiguration (..)
, insertProgram
, lookupProgram
, allPrograms
, insertPattern
, lookupPattern
, allPatterns
, modifyTVar'IO
, mkRandomSelector
)
import qualified Data.ByteString.Char8 as BS
import qualified Data.Text as T
-- | Get the current http configuration.
getHttpConfig :: State -> IO Service
getHttpConfig state = do
nw <- readTVarIO $ networkConf state
return $ Service { serviceAddress = httpServiceAddress nw
, servicePort = httpServicePort nw }
-- | Set the http configuration.
setHttpConfig :: State -> Service -> IO ()
setHttpConfig State {..} Service {..} =
modifyTVar'IO networkConf $ \nw ->
nw { httpServiceAddress = serviceAddress
, httpServicePort = servicePort }
-- | List all registered programs.
listPrograms :: State -> IO [Resource]
listPrograms state = map (Resource . programUrl) <$> allPrograms state
-- | List the patterns from the selected program.
listPatternsFromProgram :: State -> ResourceKey -> IO (Maybe [PatternInfo])
listPatternsFromProgram state key = do
maybe Nothing (Just . mapPatternInfo) <$> lookupProgram state key
where mapPatternInfo = map (\(l, w, _) -> PatternInfo l w) . patternList
-- | Compile the ghost program, if succesful store it in the state.
loadProgram :: State -> ProgramPath -> IO (Either String Resource)
loadProgram state ProgramPath {..} = do
result <- compileAndLink (T.unpack programPath)
case result of
Right program -> do
key <- genId
randomPattern' <- mkRandomSelector $ toPatternList program
let url = "/program/" `T.append` key
repr = ProgramRepr { programPath_ = programPath
, programUrl = url
, ghostProgram = program
, patternList = toPatternList program
, randomPattern = randomPattern'
}
answer = Resource { resourceUrl = url }
insertProgram state key repr
return $ Right answer
Left err -> return $ Left err
-- | Run a named pattern from the program identified by the resource
-- key.
runNamedPattern :: State -> ResourceKey -> NamedPattern
-> IO (Either ByteString Resource)
runNamedPattern state key NamedPattern {..} = do
-- A lot of looking things up ...
maybeProgram <- lookupProgram state key
case maybeProgram of
Just program ->
case fromPatternList execPattern $ patternList program of
-- Yes, both program and pattern is found.
Just pattern -> Right <$> runSelectedPattern state execParams pattern
-- Not able to find the requested pattern.
Nothing -> return $
Left ("Not found pattern: " `BS.append` encodeUtf8 execPattern)
-- Not able to find the requested program.
Nothing -> return $
Left ("Not found program key: " `BS.append` encodeUtf8 key)
-- | Run a random pattern from the program identified by the resource
-- key.
runRandomPattern :: State -> ResourceKey -> ExecParams
-> IO (Either ByteString Resource)
runRandomPattern state key params = do
maybeProgram <- lookupProgram state key
case maybeProgram of
Just program -> do
pattern <- randomPattern program
Right <$> runSelectedPattern state params pattern
Nothing -> return $
Left ("Not found program key: " `BS.append` encodeUtf8 key)
-- | Help function to run a selected pattern. Do the core stuff.
runSelectedPattern :: State -> ExecParams -> GhostPattern -> IO Resource
runSelectedPattern state ExecParams {..} pattern = do
localCounter' <- newTVarIO emptyCounter
networkConf' <- readTVarIO $ networkConf state
key <- genId
let networkConf'' = networkConf' { srcIpAddress = srcIp }
url = "/pattern/" `T.append` key
async_' <- async $ runPattern pattern [localCounter', globalCounter state]
networkConf''
(dataChunk state)
shallTrace
(logger state)
insertPattern state key $ PatternRepr { patternUrl = url
, ghostPattern = pattern
, localCounter = localCounter'
, async_ = async_' }
return Resource { resourceUrl = url }
-- | List all patterns instances.
listPatterns :: State -> IO [Resource]
listPatterns state = map (Resource . patternUrl) <$> allPatterns state
-- | List the global counter.
getGlobalCounter :: State -> IO PatternCounter
getGlobalCounter state = fromCounter <$> readTVarIO (globalCounter state)
-- | List the counter from a selected pattern.
getPatternCounter :: State -> ResourceKey -> IO (Maybe PatternCounter)
getPatternCounter state key =
maybe (return Nothing) fromCounter' =<< lookupPattern state key
where
fromCounter' :: PatternRepr -> IO (Maybe PatternCounter)
fromCounter' p = Just . fromCounter <$> (readTVarIO $ localCounter p)
-- | List pattern execution status.
patternStatus :: State -> ResourceKey -> IO (Maybe PatternStatus)
patternStatus state key = do
maybe (return Nothing) patternStatus' =<< lookupPattern state key
where
patternStatus' :: PatternRepr -> IO (Maybe PatternStatus)
patternStatus' PatternRepr {..} = do
result <- poll async_
case result of
Just status ->
case status of
Right () ->
return $ Just PatternStatus { completed = True
, failed = False
, failMessage = "" }
Left e ->
return $ Just PatternStatus { completed = True
, failed = True
, failMessage = T.pack $ show e }
Nothing ->
return $ Just PatternStatus { completed = False
, failed = False
, failMessage = "" }
-- | Try find a pattern with a specific name from a list of pattern
-- tuples.
fromPatternList :: Text -> [PatternTuple] -> Maybe GhostPattern
fromPatternList label patterns =
maybe Nothing lastInTuple $ find matchingLabel patterns
where
matchingLabel (label', _, _) = label' == label
lastInTuple (_, _, pattern) = Just pattern
-- | Convert from the internal counter format
fromCounter :: Counter -> PatternCounter
fromCounter Counter {..} =
PatternCounter { totalTimeS = realToFrac patternExecTime
, httpGetTimeS = realToFrac httpGETExecTime
, httpGetBytes = httpGETBytes
, httpPutTimeS = realToFrac httpPUTExecTime
, httpPutBytes = httpPUTBytes
}
|
kosmoskatten/ghost-lang
|
ghost-node/src/GhostLang/Node/Flow.hs
|
Haskell
|
mit
| 8,813
|
{-# LANGUAGE CPP #-}
module GHCJS.DOM.DataTransfer (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
module GHCJS.DOM.JSFFI.Generated.DataTransfer
#else
#endif
) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.DataTransfer
#else
#endif
|
plow-technologies/ghcjs-dom
|
src/GHCJS/DOM/DataTransfer.hs
|
Haskell
|
mit
| 349
|
{-# LANGUAGE BangPatterns, DataKinds, DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module Hadoop.Protos.YarnProtos.AMCommandProto (AMCommandProto(..)) where
import Prelude ((+), (/), (.))
import qualified Prelude as Prelude'
import qualified Data.Typeable as Prelude'
import qualified Data.Data as Prelude'
import qualified Text.ProtocolBuffers.Header as P'
data AMCommandProto = AM_RESYNC
| AM_SHUTDOWN
deriving (Prelude'.Read, Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data)
instance P'.Mergeable AMCommandProto
instance Prelude'.Bounded AMCommandProto where
minBound = AM_RESYNC
maxBound = AM_SHUTDOWN
instance P'.Default AMCommandProto where
defaultValue = AM_RESYNC
toMaybe'Enum :: Prelude'.Int -> P'.Maybe AMCommandProto
toMaybe'Enum 1 = Prelude'.Just AM_RESYNC
toMaybe'Enum 2 = Prelude'.Just AM_SHUTDOWN
toMaybe'Enum _ = Prelude'.Nothing
instance Prelude'.Enum AMCommandProto where
fromEnum AM_RESYNC = 1
fromEnum AM_SHUTDOWN = 2
toEnum
= P'.fromMaybe (Prelude'.error "hprotoc generated code: toEnum failure for type Hadoop.Protos.YarnProtos.AMCommandProto") .
toMaybe'Enum
succ AM_RESYNC = AM_SHUTDOWN
succ _ = Prelude'.error "hprotoc generated code: succ failure for type Hadoop.Protos.YarnProtos.AMCommandProto"
pred AM_SHUTDOWN = AM_RESYNC
pred _ = Prelude'.error "hprotoc generated code: pred failure for type Hadoop.Protos.YarnProtos.AMCommandProto"
instance P'.Wire AMCommandProto where
wireSize ft' enum = P'.wireSize ft' (Prelude'.fromEnum enum)
wirePut ft' enum = P'.wirePut ft' (Prelude'.fromEnum enum)
wireGet 14 = P'.wireGetEnum toMaybe'Enum
wireGet ft' = P'.wireGetErr ft'
wireGetPacked 14 = P'.wireGetPackedEnum toMaybe'Enum
wireGetPacked ft' = P'.wireGetErr ft'
instance P'.GPB AMCommandProto
instance P'.MessageAPI msg' (msg' -> AMCommandProto) AMCommandProto where
getVal m' f' = f' m'
instance P'.ReflectEnum AMCommandProto where
reflectEnum = [(1, "AM_RESYNC", AM_RESYNC), (2, "AM_SHUTDOWN", AM_SHUTDOWN)]
reflectEnumInfo _
= P'.EnumInfo (P'.makePNF (P'.pack ".hadoop.yarn.AMCommandProto") ["Hadoop", "Protos"] ["YarnProtos"] "AMCommandProto")
["Hadoop", "Protos", "YarnProtos", "AMCommandProto.hs"]
[(1, "AM_RESYNC"), (2, "AM_SHUTDOWN")]
instance P'.TextType AMCommandProto where
tellT = P'.tellShow
getT = P'.getRead
|
alexbiehl/hoop
|
hadoop-protos/src/Hadoop/Protos/YarnProtos/AMCommandProto.hs
|
Haskell
|
mit
| 2,466
|
-- module Day04 (solveDay04) where
module Day04 where
import Control.Monad (mapM_)
import Data.Char (chr, isDigit, ord)
import Data.Function (on)
import Data.List (group, nub, sort, sortBy)
import Data.List.Split (splitOn, wordsBy)
isSquareBracket :: Char -> Bool
isSquareBracket c = c == '[' || c == ']'
break' :: String -> ([String], String)
break' s = (takeWhile (not . isDigit . head) ss, last ss)
where ss = splitOn "-" s
breakDogtag :: String -> (Integer, String)
breakDogtag s = (read (head ss) :: Integer, last ss)
where ss = wordsBy isSquareBracket s
mostFrequent :: String -> String
mostFrequent = concat . sortBy (compare `on` (negate . length)) . group . sort
processLine :: String -> (String, String, Integer)
processLine s = (givenName, checksum, value)
where parts = break' s
(value, checksum) = breakDogtag . snd $ parts
sorted = nub . mostFrequent . concat . fst $ parts
givenName = take (length checksum) sorted
processLine' :: String -> (String, Integer)
processLine' s = (unwords . fst $ parts, value)
where parts = break' s
(value, _) = breakDogtag . snd $ parts
decryptShiftRight :: Integer -> Char -> Char
decryptShiftRight _ ' ' = ' '
decryptShiftRight n c = chr (k + ord 'a')
where n' = fromIntegral n :: Int
k = mod (ord c - ord 'a' + n') (ord 'z' - ord 'a' + 1)
decryptName :: (String, Integer) -> (String, Integer)
decryptName (s, v) = (map (decryptShiftRight v) s, v)
solveDay04 :: FilePath -> IO ()
solveDay04 path = do
putStrLn "Solution for day four: "
ls <- readFile path
let ls' = map processLine . lines $ ls
print $ foldr (\(s, s', v) x -> if s == s' then x + v else x) 0 ls'
let ls'' = map processLine' . lines $ ls
let ss = map decryptName ls''
mapM_ print $ filter (\x -> head (fst x) == 'n') ss
putStrLn ""
|
justanotherdot/advent-linguist
|
2016/Haskell/AdventOfCode/src/Day04.hs
|
Haskell
|
mit
| 1,928
|
{-# htermination minFM :: (Ord a, Ord k) => FiniteMap (Either a k) b -> Maybe (Either a k) #-}
import FiniteMap
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/FiniteMap_minFM_10.hs
|
Haskell
|
mit
| 112
|
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeSynonymInstances #-}
module Stackage.BuildPlan
( readBuildPlan
, writeBuildPlan
) where
import qualified Data.Map as Map
import qualified Data.Set as Set
import Distribution.Text (display, simpleParse)
import Stackage.Types
import qualified System.IO.UTF8
import Data.Char (isSpace)
import Stackage.Util
readBuildPlan :: FilePath -> IO BuildPlan
readBuildPlan fp = do
str <- System.IO.UTF8.readFile fp
case fromString str of
Left s -> error $ "Could not read build plan: " ++ s
Right (x, "") -> return x
Right (_, _:_) -> error "Trailing content when reading build plan"
writeBuildPlan :: FilePath -> BuildPlan -> IO ()
writeBuildPlan fp bp = System.IO.UTF8.writeFile fp $ toString bp
class AsString a where
toString :: a -> String
fromString :: String -> Either String (a, String)
instance AsString BuildPlan where
toString BuildPlan {..} = concat
[ makeSection "tools" bpTools
, makeSection "packages" $ Map.toList bpPackages
, makeSection "core" $ Map.toList bpCore
, makeSection "optional-core" $ Map.toList bpOptionalCore
, makeSection "skipped-tests" $ Set.toList bpSkippedTests
]
fromString s1 = do
(tools, s2) <- getSection "tools" s1
(packages, s3) <- getSection "packages" s2
(core, s4) <- getSection "core" s3
(optionalCore, s5) <- getSection "optional-core" s4
(skipped, s6) <- getSection "skipped-tests" s5
let bp = BuildPlan
{ bpTools = tools
, bpPackages = Map.fromList packages
, bpCore = Map.fromList core
, bpOptionalCore = Map.fromList optionalCore
, bpSkippedTests = Set.fromList skipped
}
return (bp, s6)
makeSection :: AsString a => String -> [a] -> String
makeSection title contents = unlines
$ ("-- BEGIN " ++ title)
: map toString contents
++ ["-- END " ++ title, ""]
instance AsString String where
toString = id
fromString s = Right (s, "")
instance AsString PackageName where
toString (PackageName pn) = pn
fromString s = Right (PackageName s, "")
instance AsString (Maybe Version) where
toString Nothing = ""
toString (Just x) = toString x
fromString s
| all isSpace s = return (Nothing, s)
| otherwise = do
(v, s') <- fromString s
return (Just v, s')
instance AsString a => AsString (PackageName, a) where
toString (PackageName pn, s) = concat [pn, " ", toString s]
fromString s = do
(pn, rest) <- takeWord s
(rest', s') <- fromString rest
return ((PackageName pn, rest'), s')
takeWord :: AsString a => String -> Either String (a, String)
takeWord s =
case break (== ' ') s of
(x, _:y) -> do
(x', s') <- fromString x
if null s'
then Right (x', y)
else Left $ "Unconsumed input in takeWord call"
(_, []) -> Left "takeWord failed"
instance AsString SelectedPackageInfo where
toString SelectedPackageInfo {..} = unwords
[ display spiVersion
, toString spiHasTests
, (\v -> if null v then "@" else v) $ githubMentions spiGithubUser
, unMaintainer spiMaintainer
]
fromString s1 = do
(version, s2) <- takeWord s1
(hasTests, s3) <- takeWord s2
(gu, m) <- takeWord s3
Right (SelectedPackageInfo
{ spiVersion = version
, spiHasTests = hasTests
, spiGithubUser = [gu]
, spiMaintainer = Maintainer m
}, "")
instance AsString (Maybe String) where
toString Nothing = "@"
toString (Just x) = "@" ++ x
fromString "@" = Right (Nothing, "")
fromString ('@':rest) = Right (Just rest, "")
fromString x = Left $ "Invalid Github user: " ++ x
instance AsString Bool where
toString True = "test"
toString False = "notest"
fromString "test" = Right (True, "")
fromString "notest" = Right (False, "")
fromString x = Left $ "Invalid test value: " ++ x
instance AsString Version where
toString = display
fromString s =
case simpleParse s of
Nothing -> Left $ "Invalid version: " ++ s
Just v -> Right (v, "")
getSection :: AsString a => String -> String -> Either String ([a], String)
getSection title orig =
case lines orig of
[] -> Left "Unexpected EOF when looking for a section"
l1:ls1
| l1 == begin ->
case break (== end) ls1 of
(here, _:"":rest) -> do
here' <- mapM fromString' here
Right (here', unlines rest)
(_, _) -> Left $ "Could not find section end: " ++ title
| otherwise -> Left $ "Could not find section start: " ++ title
where
begin = "-- BEGIN " ++ title
end = "-- END " ++ title
fromString' x = do
(y, z) <- fromString x
if null z
then return y
else Left $ "Unconsumed input on line: " ++ x
|
yogsototh/stackage
|
Stackage/BuildPlan.hs
|
Haskell
|
mit
| 5,250
|
module Puppet.Master.Interpreter ( InterpreterWorker
, newInterpreterWorker
, ask
, eval
, typeOf
) where
import Exception
import Control.Monad
import GHC
import GHC.Paths ( libdir )
import GHCi
import GhcMonad
import Outputable
import Puppet.Master.Worker
type InterpreterWorker = Worker Ghc
eval :: String -> Ghc String
eval e = liftM (either (const "error") (showSDocUnsafe . ppr)) attempt where
attempt :: Ghc (Either SomeException [Name])
attempt = gtry $ execStmt e (ExecOptions RunToCompletion "prompr" 0 EvalThis) >>= result
result :: ExecResult -> Ghc [Name]
result (ExecComplete (Right ns) _) = return ns
result _ = return []
typeOf :: String -> Ghc String
typeOf e = liftM (either (const "") (showSDocUnsafe . ppr)) attempt where
attempt :: Ghc (Either SomeException Type)
attempt = gtry $ exprType e
initGhc :: Ghc ()
initGhc = do
df <- getSessionDynFlags
setSessionDynFlags $ df { hscTarget = HscInterpreted
, ghcLink = LinkInMemory
}
setContext $ map (IIDecl . simpleImportDecl . mkModuleName) [ "Prelude" ]
return ()
newInterpreterWorker :: IO InterpreterWorker
newInterpreterWorker = newWorker $ runGhc (Just libdir) . (initGhc >>) >=> const (return ())
|
jd823592/puppeteer
|
src/Puppet/Master/Interpreter.hs
|
Haskell
|
mit
| 1,473
|
{-# LANGUAGE Haskell2010
, MagicHash
, FlexibleInstances
, FlexibleContexts
, MultiParamTypeClasses
, FunctionalDependencies
#-}
{-# OPTIONS
-Wall
-fno-warn-missing-signatures
-fno-warn-name-shadowing
#-}
-- | This module contains mostly boiler plate code that is needed
-- for method discovery.
module Foreign.Java.Types (
-- These are human readable short hands for
-- Z, X, C, ... below
boolean, char, byte, short, int, long,
float, double, string, object, array, void,
-- These types are used to describe methods with the
-- same vocabulary as the JNI does.
--
-- Notable additions: A, X, and Q are not defined in
-- the JNI. A and X are used for convenience and
-- resemble Arrays and Strings (S is already taken by
-- Short, therefor X). Q is special and stands for
-- objects in much the same way as L does, but Q will
-- carry it's own low level signature (for example
-- [Ljava.lang.String; ).
Z (Z), C (C), B (B), S (S), I (I), J (J),
D (D), F (F), L (L), V (V), A (A), X (X),
-- P is used to apply the above descriptors.
-- (-->) does the same thing, but is an infix operator.
P (P),
(-->), MethodDescriptor (..),
-- The famous Q. See above.
object', Q (Q),
constructorSignature,
methodSignature,
Constructor,
Method,
Param (..),
JArg (jarg)
) where
import Data.Int
import Data.Word
import Foreign.Java.JNI.Types hiding (JArg)
import qualified Foreign.Java.JNI.Types as Core
import Foreign.Java.Util
data Z = Z deriving Show
data C = C deriving Show
data B = B deriving Show
data S = S deriving Show
data I = I deriving Show
data J = J deriving Show
data F = F deriving Show
data D = D deriving Show
data L = L String deriving Show
data V = V deriving Show
data A x = A x deriving Show
data X = X deriving Show
data Q = Q String deriving Show
boolean = Z
char = C
byte = B
short = S
int = I
long = J
float = F
double = D
object = L
array = A
string = X
void = V
object' = Q
data P a x = P a x deriving Show
class Param a where
fieldSignature :: a -> String
-- These are the translations of descriptors to
-- JNI signatures.
instance Param Z where fieldSignature _ = "Z"
instance Param C where fieldSignature _ = "C"
instance Param B where fieldSignature _ = "B"
instance Param S where fieldSignature _ = "S"
instance Param I where fieldSignature _ = "I"
instance Param J where fieldSignature _ = "J"
instance Param F where fieldSignature _ = "F"
instance Param D where fieldSignature _ = "D"
instance Param L where fieldSignature (L x) = 'L' : tr '.' '/' x ++ ";"
instance Param X where fieldSignature _ = "Ljava/lang/String;"
instance Param x => Param (A x) where fieldSignature (A x) = '[' : fieldSignature x
instance Param Q where fieldSignature (Q s) = s
class JArg a b | a -> b where
jarg :: a -> b -> Core.JArg
-- These are the known argument types.
instance JArg Z Bool where jarg _ = BooleanA
instance JArg C Word16 where jarg _ = CharA
instance JArg B Int8 where jarg _ = ByteA
instance JArg S Int16 where jarg _ = ShortA
instance JArg I Int32 where jarg _ = IntA
instance JArg J Int64 where jarg _ = LongA
instance JArg F Float where jarg _ = FloatA
instance JArg D Double where jarg _ = DoubleA
instance JArg L (Maybe JObject) where jarg _ = ObjectA
instance JArg (A e) (Maybe (JArray e)) where jarg _ = ArrayA
instance JArg X String where jarg _ = StringA
instance JArg Q (Maybe JObject) where jarg _ = ObjectA
-- (-->), (::=) are infix operators for convenience.
infixr 9 -->
infixl 8 ::=
(-->) :: a -> x -> P a x
a --> x = P a x
-- A MethodDescriptor is what is given to
-- 'getMethod', 'getConstructor', and friends.
data MethodDescriptor p = String ::= p
deriving Show
---------------
-- Constructors
--
-- The signatures for looking up constructors are forged here.
constructorSignature :: Constructor p => p
constructorSignature = _constructorSignature "("
class Constructor p where
_constructorSignature :: String -> p
instance Constructor String where
_constructorSignature _ = "()V"
instance (Constructor (t -> r), Param a) => Constructor (P a t -> r) where
_constructorSignature sig (P a t) = _constructorSignature (sig ++ fieldSignature a) t
instance Constructor (Z -> String) where
_constructorSignature sig a = sig ++ fieldSignature a ++ ")V"
instance Constructor (C -> String) where
_constructorSignature sig a = sig ++ fieldSignature a ++ ")V"
instance Constructor (B -> String) where
_constructorSignature sig a = sig ++ fieldSignature a ++ ")V"
instance Constructor (S -> String) where
_constructorSignature sig a = sig ++ fieldSignature a ++ ")V"
instance Constructor (I -> String) where
_constructorSignature sig a = sig ++ fieldSignature a ++ ")V"
instance Constructor (J -> String) where
_constructorSignature sig a = sig ++ fieldSignature a ++ ")V"
instance Constructor (F -> String) where
_constructorSignature sig a = sig ++ fieldSignature a ++ ")V"
instance Constructor (D -> String) where
_constructorSignature sig a = sig ++ fieldSignature a ++ ")V"
instance Constructor (L -> String) where
_constructorSignature sig a = sig ++ fieldSignature a ++ ")V"
instance Param a => Constructor (A a -> String) where
_constructorSignature sig a = sig ++ fieldSignature a ++ ")V"
instance Constructor (X -> String) where
_constructorSignature sig X = sig ++ "Ljava/lang/String;" ++ ")V"
instance Constructor (Q -> String) where
_constructorSignature sig a = sig ++ fieldSignature a ++ ")V"
----------
-- Methods
--
-- The signatures for looking up methods (both static and virtual,
-- that distinction has no meaning on this level) are forged here.
methodSignature :: Method p => p
methodSignature = _methodSignature "("
class Method p where
_methodSignature :: String -> p
instance (Param a, Method r, Method (P b x -> r)) => Method (P a (P b x) -> r) where
_methodSignature sig (P a x) = _methodSignature (sig ++ fieldSignature a) x
instance Param a => Method (P a Z -> String) where
_methodSignature sig (P a _) = _methodSignature (sig ++ fieldSignature a ++ ")Z")
instance Param a => Method (P a C -> String) where
_methodSignature sig (P a _) = _methodSignature (sig ++ fieldSignature a ++ ")C")
instance Param a => Method (P a B -> String) where
_methodSignature sig (P a _) = _methodSignature (sig ++ fieldSignature a ++ ")B")
instance Param a => Method (P a S -> String) where
_methodSignature sig (P a _) = _methodSignature (sig ++ fieldSignature a ++ ")S")
instance Param a => Method (P a I -> String) where
_methodSignature sig (P a _) = _methodSignature (sig ++ fieldSignature a ++ ")I")
instance Param a => Method (P a J -> String) where
_methodSignature sig (P a _) = _methodSignature (sig ++ fieldSignature a ++ ")J")
instance Param a => Method (P a F -> String) where
_methodSignature sig (P a _) = _methodSignature (sig ++ fieldSignature a ++ ")F")
instance Param a => Method (P a D -> String) where
_methodSignature sig (P a _) = _methodSignature (sig ++ fieldSignature a ++ ")D")
instance Param a => Method (P a L -> String) where
_methodSignature sig (P a t) = _methodSignature (sig ++ fieldSignature a ++ ")" ++ fieldSignature t)
instance Param a => Method (P a V -> String) where
_methodSignature sig (P a _) = _methodSignature (sig ++ fieldSignature a ++ ")V")
instance Param a => Method (P a X -> String) where
_methodSignature sig (P a _) = _methodSignature (sig ++ fieldSignature a ++ ")Ljava/lang/String;")
instance (Param a, Param e) => Method (P a (A e) -> String) where
_methodSignature sig (P a t) = _methodSignature (sig ++ fieldSignature a ++ ")" ++ fieldSignature t)
instance Param a => Method (P a Q -> String) where
_methodSignature sig (P a t) = _methodSignature (sig ++ fieldSignature a ++ ")" ++ fieldSignature t)
instance Method (Z -> String) where
_methodSignature sig _ = sig ++ ")Z"
instance Method (C -> String) where
_methodSignature sig _ = sig ++ ")C"
instance Method (B -> String) where
_methodSignature sig _ = sig ++ ")B"
instance Method (S -> String) where
_methodSignature sig _ = sig ++ ")S"
instance Method (I -> String) where
_methodSignature sig _ = sig ++ ")I"
instance Method (J -> String) where
_methodSignature sig _ = sig ++ ")J"
instance Method (F -> String) where
_methodSignature sig _ = sig ++ ")F"
instance Method (D -> String) where
_methodSignature sig _ = sig ++ ")D"
instance Method (L -> String) where
_methodSignature sig s = sig ++ ")" ++ fieldSignature s
instance Method (V -> String) where
_methodSignature sig _ = sig ++ ")V"
instance Method (X -> String) where
_methodSignature sig _ = sig ++ ")Ljava/lang/String;"
instance (Param e, Method (e -> String)) => Method (A e -> String) where
_methodSignature sig s = sig ++ ")" ++ fieldSignature s
instance Method (Q -> String) where
_methodSignature sig s = sig ++ ")" ++ fieldSignature s
instance Method String where
_methodSignature sig = sig
|
fehu/haskell-java-bridge-fork
|
src/Foreign/Java/Types.hs
|
Haskell
|
mit
| 9,256
|
module Feature.DeleteSpec where
import Test.Hspec
import Test.Hspec.Wai
import Text.Heredoc
import SpecHelper
import PostgREST.Types (DbStructure(..))
import qualified Hasql.Connection as H
import Network.HTTP.Types
spec :: DbStructure -> H.Connection -> Spec
spec struct c = beforeAll resetDb
. around (withApp cfgDefault struct c) $
describe "Deleting" $ do
context "existing record" $ do
it "succeeds with 204 and deletion count" $
request methodDelete "/items?id=eq.1" [] ""
`shouldRespondWith` ResponseMatcher {
matchBody = Nothing
, matchStatus = 204
, matchHeaders = ["Content-Range" <:> "*/1"]
}
it "actually clears items ouf the db" $ do
_ <- request methodDelete "/items?id=lt.15" [] ""
get "/items"
`shouldRespondWith` ResponseMatcher {
matchBody = Just [str|[{"id":15}]|]
, matchStatus = 200
, matchHeaders = ["Content-Range" <:> "0-0/1"]
}
context "known route, unknown record" $
it "fails with 404" $
request methodDelete "/items?id=eq.101" [] "" `shouldRespondWith` 404
context "totally unknown route" $
it "fails with 404" $
request methodDelete "/foozle?id=eq.101" [] "" `shouldRespondWith` 404
|
motiz88/postgrest
|
test/Feature/DeleteSpec.hs
|
Haskell
|
mit
| 1,312
|
module Data.HashId
(
-- * Core types
HashId
, HashEncoder
, HashOptions
, Salt
-- * Core functions
, defaultOptions
, mkEncoder
, encode
, decode
, parse
, toText
, salt
) where
import Data.HashId.Internal
|
muhbaasu/hash-id
|
src/Data/HashId.hs
|
Haskell
|
mit
| 325
|
{-# LANGUAGE QuasiQuotes, TemplateHaskell #-}
{-# OPTIONS_GHC -Wall #-}
-- http://www.well-typed.com/blog/2014/10/quasi-quoting-dsls/
import QQAst
import Language.Haskell.TH.Syntax
prog1 :: Prog
prog1 = [prog|
var x ;
x := read ;
write (x + x + 1)
|]
prog2 :: VarName -> Integer -> Prog
prog2 y n = [prog|
var x ;
x := read ;
write (x + y + n)
|]
optimize :: Expr -> Expr
optimize [expr| a + n - m |] | n == m = optimize a
optimize other = other
test1 :: IO ()
test1 = intIO $ intProg prog1
test2 :: IO ()
test2 = intIO $ intProg (prog2 "x" 2)
test3 :: IO ()
test3 = print . optimize =<< parseIO parseExpr =<< getLine
test4 :: Lift a => a -> Q Exp
test4 x = [| id x |]
|
egaburov/funstuff
|
Haskell/thsk/qqast.hs
|
Haskell
|
apache-2.0
| 707
|
-- Copyright 2015 Peter Harpending
--
-- 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 : Main
-- Description : Test of editor-open
-- Copyright : Copyright 2015 Peter Harpending
-- License : Apache-2.0
-- Maintainer : Peter Harpending <peter@harpending.org>
-- Stability : experimental
-- Portability : POSIX
--
module Main where
import qualified Data.ByteString as B
import Paths_editor_open
import System.IO
import Text.Editor
main :: IO ()
main =
getDataFileName "res/bug-schema.yaml" >>=
runUserEditorDWIMFile yamlTemplate >>=
B.hPut stdout
|
pharpend/editor-open
|
tests/test_yaml_file.hs
|
Haskell
|
apache-2.0
| 1,128
|
{-# LANGUAGE OverloadedStrings #-}
module Data.Attoparsec.Text.Machine where
import Data.Attoparsec.Machine (processParserWith, streamParserWith)
import Data.Attoparsec.Text (Parser, parse, takeWhile)
import Data.Machine (ProcessT, asParts, auto, (<~))
import Data.Text (Text)
asLines :: Monad m => ProcessT m Text Text
asLines = asParts <~ auto unpackLine <~ streamParser ((Data.Attoparsec.Text.takeWhile $ \w -> w /= '\n') <* "\n")
where
unpackLine (Right txt) = [txt]
unpackLine (Left _) = []
processParser :: Monad m => Parser a -> ProcessT m Text (Either String (Text, a))
processParser p = processParserWith $ parse p
streamParser :: Monad m => Parser a -> ProcessT m Text (Either String a)
streamParser p = streamParserWith $ parse p
|
aloiscochard/sarsi
|
src/Data/Attoparsec/Text/Machine.hs
|
Haskell
|
apache-2.0
| 756
|
-- |
-- Module : Test.QuickCheck.Util.Combinator
--
-- Copyright : (C) 2010-2012 Joachim Fasting
-- License : BSD-style (see COPYING)
-- Maintainer : Joachim Fasting <joachim.fasting@gmail.com>
--
-- Additional combinators for QuickCheck.
module Test.QuickCheck.Util.Combinator
( pairOf
, tripleOf
, possibly
) where
import Control.Applicative
import Test.QuickCheck (Gen)
import qualified Test.QuickCheck as QC
-- | Create a pair generator.
pairOf :: Applicative m => m a -> m (a, a)
pairOf m = (,) <$> m <*> m
-- | Create a triple generator.
tripleOf :: Applicative m => m a -> m (a, a, a)
tripleOf m = (,,) <$> m <*> m <*> m
-- | Turn a value generator into a generator that _might_ generate a value.
--
-- Example:
--
-- @possibly $ tripleOf negative@
possibly :: Gen a -> Gen (Maybe a)
possibly m = QC.oneof [ Just <$> m , pure Nothing ]
|
joachifm/QuickCheck-util
|
Test/QuickCheck/Util/Combinator.hs
|
Haskell
|
bsd-2-clause
| 872
|
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedLabels #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TupleSections #-}
module YX.Shell
( findShell
, shellExePaths
, ExecuteShellException(..)
, module YX.Type.Shell
-- * Utility functions
, findExecutables
)
where
import Control.Applicative (pure)
import Control.Exception (Exception, throwIO)
import Control.Monad ((>>=))
import Data.Foldable (foldlM)
import Data.Function (($), (.), const, id)
import Data.Functor (fmap)
import Data.Maybe (Maybe(Just, Nothing), maybe)
import Data.String (String)
import System.IO (FilePath, IO)
import Text.Show (Show)
import System.Directory
( doesFileExist
, executable
, findFileWith
, getPermissions
)
import System.FilePath (splitSearchPath)
import Data.Bool.Lifted ((<&&>))
import YX.Type.Shell
data ExecuteShellException = UnableToFindShellExecutable
deriving Show
instance Exception ExecuteShellException
shellExePaths :: Shell -> [FilePath]
shellExePaths = \case
Bash ->
[ "/bin/bash"
, "/usr/bin/bash"
, "/usr/local/bin/bash" -- E.g. FreeBSD
, "bash" -- Try to locate it in "$PATH".
]
findShell
:: Maybe String
-- ^ Search path.
-> Maybe FilePath
-- ^ Preferred shell executable.
-> [FilePath]
-- ^ Absolute paths and executable names of shells to try, in order.
-> IO FilePath
findShell pathVar shellVar otherShells =
findExecutables path shellPaths >>= reportError
where
path = maybe [] splitSearchPath pathVar
shellPaths = maybe id (:) shellVar $ otherShells
reportError :: Maybe FilePath -> IO FilePath
reportError = maybe (throwIO UnableToFindShellExecutable) pure
findExecutables :: [FilePath] -> [FilePath] -> IO (Maybe FilePath)
findExecutables path = go $ \case
r@(Just _) -> const $ pure r
Nothing -> \case
fp@('/' : _) -> do
isExe <- doesFileExist fp <&&> isExecutable fp
pure $ if isExe then Just fp else Nothing
fp -> findFileWith isExecutable path fp
where
go :: (Maybe FilePath -> FilePath -> IO (Maybe FilePath))
-> [FilePath]
-> IO (Maybe FilePath)
go f = foldlM f Nothing
isExecutable = fmap executable . getPermissions
|
trskop/yx
|
src/YX/Shell.hs
|
Haskell
|
bsd-3-clause
| 2,371
|
{-# LANGUAGE FlexibleContexts #-}
module Opaleye.Manipulation (module Opaleye.Manipulation,
U.Unpackspec) where
import qualified Opaleye.Internal.Sql as Sql
import qualified Opaleye.Internal.Print as Print
import qualified Opaleye.RunQuery as RQ
import qualified Opaleye.Internal.RunQuery as IRQ
import qualified Opaleye.Table as T
import qualified Opaleye.Internal.Table as TI
import Opaleye.Internal.Column (Column(Column))
import Opaleye.Internal.Helpers ((.:), (.:.), (.::), (.::.))
import qualified Opaleye.Internal.Unpackspec as U
import Opaleye.PGTypes (PGBool)
import qualified Opaleye.Internal.HaskellDB.Sql as HSql
import qualified Opaleye.Internal.HaskellDB.Sql.Print as HPrint
import qualified Opaleye.Internal.HaskellDB.Sql.Default as SD
import qualified Opaleye.Internal.HaskellDB.Sql.Generate as SG
import qualified Database.PostgreSQL.Simple as PGS
import qualified Data.Profunctor.Product.Default as D
import Data.Int (Int64)
import Data.String (fromString)
import qualified Data.List.NonEmpty as NEL
arrangeInsert :: T.Table columns a -> columns -> HSql.SqlInsert
arrangeInsert t c = arrangeInsertMany t (return c)
arrangeInsertSql :: T.Table columns a -> columns -> String
arrangeInsertSql = show . HPrint.ppInsert .: arrangeInsert
runInsert :: PGS.Connection -> T.Table columns columns' -> columns -> IO Int64
runInsert conn = PGS.execute_ conn . fromString .: arrangeInsertSql
arrangeInsertMany :: T.Table columns a -> NEL.NonEmpty columns -> HSql.SqlInsert
arrangeInsertMany (T.Table tableName (TI.TableProperties writer _)) columns = insert
where (columnExprs, columnNames) = TI.runWriter' writer columns
insert = SG.sqlInsert SD.defaultSqlGenerator
tableName columnNames columnExprs
arrangeInsertManySql :: T.Table columns a -> NEL.NonEmpty columns -> String
arrangeInsertManySql = show . HPrint.ppInsert .: arrangeInsertMany
runInsertMany :: PGS.Connection
-> T.Table columns columns'
-> [columns]
-> IO Int64
runInsertMany conn table columns = case NEL.nonEmpty columns of
-- Inserting the empty list is just the same as returning 0
Nothing -> return 0
Just columns' -> (PGS.execute_ conn . fromString .: arrangeInsertManySql) table columns'
arrangeUpdate :: T.Table columnsW columnsR
-> (columnsR -> columnsW) -> (columnsR -> Column PGBool)
-> HSql.SqlUpdate
arrangeUpdate (TI.Table tableName (TI.TableProperties writer (TI.View tableCols)))
update cond =
SG.sqlUpdate SD.defaultSqlGenerator tableName [condExpr] (update' tableCols)
where update' = map (\(x, y) -> (y, x))
. TI.runWriter writer
. update
Column condExpr = cond tableCols
arrangeUpdateSql :: T.Table columnsW columnsR
-> (columnsR -> columnsW) -> (columnsR -> Column PGBool)
-> String
arrangeUpdateSql = show . HPrint.ppUpdate .:. arrangeUpdate
runUpdate :: PGS.Connection -> T.Table columnsW columnsR
-> (columnsR -> columnsW) -> (columnsR -> Column PGBool)
-> IO Int64
runUpdate conn = PGS.execute_ conn . fromString .:. arrangeUpdateSql
arrangeDelete :: T.Table a columnsR -> (columnsR -> Column PGBool) -> HSql.SqlDelete
arrangeDelete (TI.Table tableName (TI.TableProperties _ (TI.View tableCols)))
cond =
SG.sqlDelete SD.defaultSqlGenerator tableName [condExpr]
where Column condExpr = cond tableCols
arrangeDeleteSql :: T.Table a columnsR -> (columnsR -> Column PGBool) -> String
arrangeDeleteSql = show . HPrint.ppDelete .: arrangeDelete
runDelete :: PGS.Connection -> T.Table a columnsR -> (columnsR -> Column PGBool)
-> IO Int64
runDelete conn = PGS.execute_ conn . fromString .: arrangeDeleteSql
arrangeInsertReturning :: U.Unpackspec returned ignored
-> T.Table columnsW columnsR
-> columnsW
-> (columnsR -> returned)
-> Sql.Returning HSql.SqlInsert
arrangeInsertReturning unpackspec table columns returningf =
Sql.Returning insert returningSEs
where insert = arrangeInsert table columns
TI.Table _ (TI.TableProperties _ (TI.View columnsR)) = table
returningPEs = U.collectPEs unpackspec (returningf columnsR)
returningSEs = Sql.ensureColumnsGen id (map Sql.sqlExpr returningPEs)
arrangeInsertReturningSql :: U.Unpackspec returned ignored
-> T.Table columnsW columnsR
-> columnsW
-> (columnsR -> returned)
-> String
arrangeInsertReturningSql = show
. Print.ppInsertReturning
.:: arrangeInsertReturning
runInsertReturningExplicit :: RQ.QueryRunner returned haskells
-> PGS.Connection
-> T.Table columnsW columnsR
-> columnsW
-> (columnsR -> returned)
-> IO [haskells]
runInsertReturningExplicit qr conn t w r = PGS.queryWith_ parser conn
(fromString
(arrangeInsertReturningSql u t w r))
where IRQ.QueryRunner u _ _ = qr
parser = IRQ.prepareRowParser qr (r v)
TI.Table _ (TI.TableProperties _ (TI.View v)) = t
-- This method of getting hold of the return type feels a bit
-- suspect. I haven't checked it for validity.
-- | @runInsertReturning@'s use of the 'D.Default' typeclass means that the
-- compiler will have trouble inferring types. It is strongly
-- recommended that you provide full type signatures when using
-- @runInsertReturning@.
runInsertReturning :: (D.Default RQ.QueryRunner returned haskells)
=> PGS.Connection
-> T.Table columnsW columnsR
-> columnsW
-> (columnsR -> returned)
-> IO [haskells]
runInsertReturning = runInsertReturningExplicit D.def
arrangeUpdateReturning :: U.Unpackspec returned ignored
-> T.Table columnsW columnsR
-> (columnsR -> columnsW)
-> (columnsR -> Column PGBool)
-> (columnsR -> returned)
-> Sql.Returning HSql.SqlUpdate
arrangeUpdateReturning unpackspec table updatef cond returningf =
Sql.Returning update returningSEs
where update = arrangeUpdate table updatef cond
TI.Table _ (TI.TableProperties _ (TI.View columnsR)) = table
returningPEs = U.collectPEs unpackspec (returningf columnsR)
returningSEs = Sql.ensureColumnsGen id (map Sql.sqlExpr returningPEs)
arrangeUpdateReturningSql :: U.Unpackspec returned ignored
-> T.Table columnsW columnsR
-> (columnsR -> columnsW)
-> (columnsR -> Column PGBool)
-> (columnsR -> returned)
-> String
arrangeUpdateReturningSql = show
. Print.ppUpdateReturning
.::. arrangeUpdateReturning
runUpdateReturningExplicit :: RQ.QueryRunner returned haskells
-> PGS.Connection
-> T.Table columnsW columnsR
-> (columnsR -> columnsW)
-> (columnsR -> Column PGBool)
-> (columnsR -> returned)
-> IO [haskells]
runUpdateReturningExplicit qr conn t update cond r =
PGS.queryWith_ parser conn
(fromString (arrangeUpdateReturningSql u t update cond r))
where IRQ.QueryRunner u _ _ = qr
parser = IRQ.prepareRowParser qr (r v)
TI.Table _ (TI.TableProperties _ (TI.View v)) = t
runUpdateReturning :: (D.Default RQ.QueryRunner returned haskells)
=> PGS.Connection
-> T.Table columnsW columnsR
-> (columnsR -> columnsW)
-> (columnsR -> Column PGBool)
-> (columnsR -> returned)
-> IO [haskells]
runUpdateReturning = runUpdateReturningExplicit D.def
|
danse/haskell-opaleye
|
src/Opaleye/Manipulation.hs
|
Haskell
|
bsd-3-clause
| 8,377
|
{-# LANGUAGE TemplateHaskell #-}
module Horbits.UI.Camera.Internal where
import Control.Lens
import Data.Fixed
import Data.List.NonEmpty as NE
import Linear
import Horbits.UI.Camera.Zoom
-- data type
data OrthoCamera a = OrthoCamera { _orthoCameraCenter :: V3 a
, _orthoCameraColatitude :: a
, _orthoCameraLongitude :: a
, _orthoCameraScale :: a
, _orthoCameraViewportWidth :: Int
, _orthoCameraViewportHeight :: Int
, _orthoCameraZoomModel :: ZoomModel a
} deriving (Show, Eq)
makeLenses ''OrthoCamera
initOrthoCamera :: Num a => ZoomModel a -> OrthoCamera a
initOrthoCamera z@(ZoomModel zs) = OrthoCamera zero 0 0 (NE.last zs) 1 1 z
-- transform matrices
orthoCameraMatrix :: (RealFloat a, Epsilon a) => OrthoCamera a -> M44 a
orthoCameraMatrix cam = scale cam !*! rotateColat cam !*! rotateLong cam !*! translate cam
invOrthoCameraMatrix :: (RealFloat a, Epsilon a) => OrthoCamera a -> M44 a
invOrthoCameraMatrix cam = invTranslate cam !*! invRotateLong cam !*! invRotateColat cam !*! invScale cam
orthoCameraZIndex :: (RealFloat a, Epsilon a) => OrthoCamera a -> V3 a -> a
orthoCameraZIndex c = negate . dot (orthoCameraMatrix c ^. _z . _xyz)
-- update API
addColatitude :: RealFloat a => a -> OrthoCamera a -> OrthoCamera a
addColatitude a cam = cam & orthoCameraColatitude %~ addClamped
where addClamped b = min pi $ max 0 $ a + b
addLongitude :: RealFloat a => a -> OrthoCamera a -> OrthoCamera a
addLongitude a cam = cam & orthoCameraLongitude %~ addWrapped
where addWrapped b = mod' (a + b) (2 * pi)
addTranslation :: (RealFloat a, Epsilon a) => V2 a -> OrthoCamera a -> OrthoCamera a
addTranslation v cam = cam & orthoCameraCenter %~ (^-^ v')
where v' = (invOrthoCameraMatrix cam !* (zero & _xy .~ v)) ^. _xyz
zoomOut :: (Ord a, Num a) => OrthoCamera a -> OrthoCamera a
zoomOut cam = cam & orthoCameraScale %~ zoomModelOut (cam ^. orthoCameraZoomModel)
where
zoomModelOut (ZoomModel zooms) z = NE.head $ foldr NE.cons (NE.last zooms :| []) (NE.dropWhile (<= z) zooms)
zoomIn :: (Ord a, Num a) => OrthoCamera a -> OrthoCamera a
zoomIn cam = cam & orthoCameraScale %~ zoomModelIn (cam ^. orthoCameraZoomModel)
where zoomModelIn (ZoomModel zooms) z = NE.last $ NE.head zooms :| NE.takeWhile (< z) zooms
-- transformation parts
orthoCameraAspectRatio :: (RealFloat a) => OrthoCamera a -> a
orthoCameraAspectRatio cam =
realToFrac (cam ^. orthoCameraViewportWidth) / realToFrac (cam ^. orthoCameraViewportHeight)
translate :: Num a => OrthoCamera a -> M44 a
translate = translate' . negate . view orthoCameraCenter
scale :: RealFloat a => OrthoCamera a -> M44 a
scale = scaling f
where
f sz ar mz = V4 0 0 0 1 & _xy .~ (1 / sz) *^ rs & _z .~ 1 / mz
where
rs = if ar > 1 then V2 (1/ar) (-1) else V2 1 (-ar)
rotateLong :: (Epsilon a, Floating a) => OrthoCamera a -> M44 a
rotateLong = rotateZ . view orthoCameraLongitude
rotateColat :: (Epsilon a, Floating a) => OrthoCamera a -> M44 a
rotateColat = rotateX . views orthoCameraColatitude (pi -)
-- inverse transformation parts
invTranslate :: Num a => OrthoCamera a -> M44 a
invTranslate = translate' . view orthoCameraCenter
invScale :: RealFloat a => OrthoCamera a -> M44 a
invScale = scaling f
where
f sz ar mz = V4 0 0 0 1 & _xy .~ sz *^ rs & _z .~ mz
where
rs = if ar > 1 then V2 ar (-1) else V2 1 (-1 / ar)
invRotateLong :: (Epsilon a, Floating a) => OrthoCamera a -> M44 a
invRotateLong = rotateZ . negate . view orthoCameraLongitude
invRotateColat :: (Epsilon a, Floating a) => OrthoCamera a -> M44 a
invRotateColat = rotateX . negate . views orthoCameraColatitude (pi -)
-- primitive transformations
rotateZ :: (Epsilon a, Floating a) => a -> M44 a
rotateZ a = mkTransformation (axisAngle (V3 0 0 1) a) zero
rotateX :: (Epsilon a, Floating a) => a -> M44 a
rotateX a = mkTransformation (axisAngle (V3 1 0 0) a) zero
translate' :: (Num a) => V3 a -> M44 a
translate' v = identity & column _w . _xyz .~ v
scaling :: (RealFloat a) =>
(a -> a -> a -> V4 a) -> OrthoCamera a -> M44 a
scaling f = do
sz <- view orthoCameraScale
ar <- orthoCameraAspectRatio
mz <- view $ orthoCameraZoomModel . maxZoom
return $ scaled $ f sz ar mz
|
chwthewke/horbits
|
src/horbits/Horbits/UI/Camera/Internal.hs
|
Haskell
|
bsd-3-clause
| 4,533
|
module FP.Parser.SExp where
import FP.Prelude
import FP.Parser.Parser
import FP.Pretty
import qualified Prelude
data SNumber =
SNInteger ℤ
| SNDouble 𝔻
deriving (Eq,Ord)
makePrettySum ''SNumber
data SLit =
SLNumber SNumber
| SLString 𝕊
deriving (Eq,Ord)
makePrettySum ''SLit
data SToken =
STLParen
| STRParen
| STLit SLit
| STSymbol 𝕊
| STWhitespace 𝕊
deriving (Eq,Ord)
makePrettySum ''SToken
makePrisms ''SToken
lparenTok ∷ Parser ℂ ()
lparenTok = pRender darkGray $ void $ pLit '('
rparenTok ∷ Parser ℂ ()
rparenTok = pRender darkGray $ void $ pLit ')'
litTok ∷ Parser ℂ SLit
litTok = pRender darkRed $ mconcat
[ SLNumber ^$ pError "number" numberTok
, SLString ^$ pError "string" stringTok
]
where
numberTok ∷ Parser ℂ SNumber
numberTok = mconcat
[ SNInteger ^$ pError "integer" integerTok
, SNDouble ^$ pError "double" doubleTok
]
where
integerTok ∷ Parser ℂ ℤ
integerTok = do
sign ← signTok
digits ← 𝕤 ^$ pOneOrMoreGreedy $ pSatisfies "digit" isDigit
return $ Prelude.read $ chars $ sign ⧺ digits
doubleTok ∷ Parser ℂ 𝔻
doubleTok = do
sign ← signTok
digitsBefore ← 𝕤 ^$ pOneOrMoreGreedy $ pSatisfies "digit" isDigit
dec ← 𝕤 ^$ mapM pLit $ chars "."
digitsAfter ← 𝕤 ^$ pOneOrMoreGreedy $ pSatisfies "digit" isDigit
return $ Prelude.read $ chars $ sign ⧺ digitsBefore ⧺ dec ⧺ digitsAfter
signTok ∷ Parser ℂ 𝕊
signTok = mconcat
[ 𝕤 ^$ mapM pLit $ chars "-"
, return ""
]
stringTok ∷ Parser ℂ 𝕊
stringTok = do
void $ pLit '"'
s ← concat ^$ pManyGreedy $ mconcat
[ 𝕤 ∘ single ^$ pSatisfies "anything but '\"' or '\\'" $ \ c → not $ c ≟ '"' ∨ c ≟ '\\'
, pAppendError "escape sequence" $ do
bslash ← 𝕤 ∘ single ^$ pLit '\\'
c ← 𝕤 ∘ single ^$ pLit '\\' <⧺> pLit 'n'
return $ bslash ⧺ c
]
void $ pLit '"'
return s
symbolTok ∷ Parser ℂ 𝕊
symbolTok = 𝕤 ^$ pOneOrMoreGreedy $ pSatisfies "letter" isLetter
whitespaceTok ∷ Parser ℂ 𝕊
whitespaceTok = 𝕤 ^$ pOneOrMoreGreedy $ pSatisfies "space" isSpace
tok ∷ Parser ℂ SToken
tok = mconcat
[ const STLParen ^$ pError "lparen" lparenTok
, const STRParen ^$ pError "rparen" rparenTok
, STLit ^$ pError "lit" litTok
, STSymbol ^$ pError "symbol" symbolTok
, STWhitespace ^$ pError "whitespace" whitespaceTok
]
testSExpTokenizerSuccess ∷ IO ()
testSExpTokenizerSuccess = tokenizeIOMain tok $ tokens "((-1-2-1.42(\"astringwith\\\\stuff\\n\" ( "
testSExpTokenizerFailure1 ∷ IO ()
testSExpTokenizerFailure1 = tokenizeIOMain tok $ tokens "((foo-1and0.01+bar"
testSExpTokenizerFailure2 ∷ IO ()
testSExpTokenizerFailure2 = tokenizeIOMain tok $ tokens "()foo-1\"astring\\badescape\""
data FullContext t = FullContext
{ fullContextCaptured ∷ ParserContext t
, fullContextFutureInput ∷ ParserInput t
}
instance Pretty (FullContext t) where
pretty (FullContext (ParserContext pre _ display _ _) (ParserInput ss _)) = concat
[ ppPun "⟬"
, ppAlign $ pre ⧺ (ppUT '^' green display) ⧺ concat (map tokenRender ss)
, ppPun "⟭"
]
data SAtom =
SALit SLit
| SASymbol 𝕊
makePrettySum ''SAtom
data TaggedFix t (f ∷ ★ → ★) = TaggedFix
{ taggedFixContext ∷ FullContext t
, taggedFixValue ∷ f (TaggedFix t f)
}
makePrettySum ''TaggedFix
data PreSExp e =
SEAtom SAtom
| SEExp [e]
makePrettySum ''PreSExp
type SExp = TaggedFix SToken PreSExp
atomPar ∷ Parser SToken SAtom
atomPar = pError "atom" $ mconcat
[ SALit ^$ litPar
, SASymbol ^$ symbolPar
]
litPar ∷ Parser SToken SLit
litPar = pShaped "lit" $ view sTLitL
symbolPar ∷ Parser SToken 𝕊
symbolPar = pShaped "symbol" $ view sTSymbolL
preSExpPar ∷ Parser SToken (PreSExp SExp)
preSExpPar = mconcat
[ SEAtom ^$ atomPar
, SEExp ^$ inParensPar
]
inParensPar ∷ Parser SToken [SExp]
inParensPar = do
void $ pLit STLParen
es ← sexpsPar
void $ pLit STRParen
return es
sexpsPar ∷ Parser SToken [SExp]
sexpsPar = do
void $ pOptionalGreedy $ pSatisfies "whitespace" $ shape sTWhitespaceL
xs ← pManySepByGreedy (void $ pOptionalGreedy $ pSatisfies "whitespace" $ shape sTWhitespaceL) sexpPar
void $ pOptionalGreedy $ pSatisfies "whitespace" $ shape sTWhitespaceL
return xs
sexpPar ∷ Parser SToken SExp
sexpPar = do
(s,cc) ← pCapture $ preSExpPar
pin ← getL parserStateInputL
return $ TaggedFix (FullContext cc pin) s
testSExpParserSuccess ∷ IO ()
testSExpParserSuccess = do
toks ← tokenizeIO tok input
parseIOMain sexpsPar toks
where
input ∷ Stream (Token ℂ)
input = tokens " x y ( -1-2) 0.0"
|
davdar/darailude
|
src/FP/Parser/SExp.hs
|
Haskell
|
bsd-3-clause
| 4,949
|
{-# LANGUAGE OverloadedStrings, RecursiveDo, ScopedTypeVariables, FlexibleContexts, TypeFamilies, ConstraintKinds #-}
module Frontend.Properties.R53
(
r53Properties
) where
import Prelude hiding (mapM, mapM_, all, sequence)
import qualified Data.Map as Map
import Data.Monoid ((<>))
import Data.Text (Text)
import qualified Data.Text as T
import Reflex
import Reflex.Dom.Core
------
import AWSFunction
--------------------------------------------------------------------------
-- Route53 Properties
-------
calcR53ZoneF :: Text -> Text -> Text
calcR53ZoneF hz tf = toText $ hosZ (readDouble hz) + (50.0 * (readDouble tf))
where
hosZ hz'
| hz' <= 25 = 0.50 * hz'
| otherwise = (0.50 * 25) + (0.10 * (hz' - 25))
calcR53Queries :: Text -> Int -> Text -> Int -> Text -> Int -> Text
calcR53Queries sq skey lbrq lkey gdq gkey =
toText $ (standardQ (readDouble sq) skey)
+ (latencyQ (readDouble lbrq) lkey)
+ (geoDnsQ (readDouble gdq) gkey)
where
standardQ i k1 = case k1 of
1 -> 30 * standardQ' i
2 -> 4 * standardQ' i
_ -> standardQ' i
where
standardQ' sq'
| sq' <= 1000 = 0.400 * sq'
| otherwise = (0.400 * 1000) + (0.200 * (sq' - 1000))
latencyQ i k2 = case k2 of
1 -> 30 * latencyQ' i
2 -> 4 * latencyQ' i
_ -> latencyQ' i
where
latencyQ' lq'
| lq' <= 1000 = 0.600 * lq'
| otherwise = (0.600 * 1000) + (0.300 * (lq' - 1000))
geoDnsQ i k3 = case k3 of
1 -> 30 * geoDnsQ' i
2 -> 4 * geoDnsQ' i
_ -> geoDnsQ' i
where
geoDnsQ' gq'
| gq' <= 1000 = 0.700 * gq'
| otherwise = (0.700 * 1000) + (0.350 * (gq' - 1000))
-------------------------------------
r53Properties :: (Reflex t, MonadWidget t m) => Dynamic t (Map.Map T.Text T.Text) -> m (Dynamic t Text)
r53Properties dynAttrs = do
result <- elDynAttr "div" ((constDyn $ idAttrs R53) <> dynAttrs <> rightClassAttrs) $ do
rec
r53HostZ <- r53HostedZone evReset
evReset <- button "Reset"
return $ r53HostZ
return $ result
r53HostedZone :: (Reflex t, MonadWidget t m) => Event t a -> m (Dynamic t Text)
r53HostedZone evReset = do
rec
let
resultR53ZoneF = calcR53ZoneF <$> (value r53Hz)
<*> (value r53Tf)
resultR53Queries = calcR53Queries <$> (value r53Sq)
<*> (value ddR53Sq)
<*> (value r53Lbrq)
<*> (value ddR53Lbrq)
<*> (value r53GeoDQ)
<*> (value ddR53GeoDQ)
resultR53HZone = (+) <$> (readDouble <$> resultR53ZoneF)
<*> (readDouble <$> resultR53Queries)
el "h4" $ text "Hosted Zone: "
el "p" $ text "Hosted Zone:"
r53Hz <- textInput $ def & textInputConfig_inputType .~ "number"
& textInputConfig_initialValue .~ "0"
& setValue .~ (leftmost ["0" <$ evReset])
el "p" $ text "Traffic Flow:"
r53Tf <- textInput $ def & textInputConfig_inputType .~ "number"
& textInputConfig_initialValue .~ "0"
& setValue .~ (leftmost ["0" <$ evReset])
el "p" $ text "Standard Queries"
el "p" $ text "(in Million Queries):"
r53Sq <- textInput $ def & textInputConfig_inputType .~ "number"
& textInputConfig_initialValue .~ "0"
& setValue .~ (leftmost ["0" <$ evReset])
ddR53Sq <- dropdown 3 (constDyn ddPerMonth) def
el "p" $ text "Latency Based"
el "p" $ text "Routing Queries"
el "p" $ text "(in Million Queries):"
r53Lbrq <- textInput $ def & textInputConfig_inputType .~ "number"
& textInputConfig_initialValue .~ "0"
& setValue .~ (leftmost ["0" <$ evReset])
ddR53Lbrq <- dropdown 3 (constDyn ddPerMonth) def
el "p" $ text "Geo DNS Queries"
el "p" $ text "(in Million Queries):"
r53GeoDQ <- textInput $ def & textInputConfig_inputType .~ "number"
& textInputConfig_initialValue .~ "0"
& setValue .~ (leftmost ["0" <$ evReset])
ddR53GeoDQ <- dropdown 3 (constDyn ddPerMonth) def
return $ toDynText resultR53HZone
|
Rizary/awspi
|
Lib/Frontend/Properties/R53.hs
|
Haskell
|
bsd-3-clause
| 4,264
|
{-# LANGUAGE FlexibleInstances #-}
module Eval (
runEval
) where
import Control.Monad.State
import Control.Monad.Writer (WriterT, runWriterT, tell)
import Data.List
import Data.Maybe
import qualified Data.Map as Map
import Text.PrettyPrint
import Pretty
import Syntax
-- Values
data Value
= VInt Integer
| VBool Bool
| VClosure String Expr (Eval.Scope)
instance Pretty Value where
ppr _ (VInt x) = text $ show x
ppr _ (VBool x) = text $ show x
ppr p (VClosure v x env) =
text "\\" <> text v <+> text "." <+> ppr (p+1) x
<> if null env
then text ""
else text " |" <+> (hsep $ map (ppr 0) (Map.assocs env))
instance Pretty (String, Value) where
ppr p (n, v) = text "(" <> text n <> text "," <+> ppr 0 v <> text ")"
type Scope = Map.Map String Value
emptyScope = Map.empty
type Step = (Int, Expr) -- (depth, partially evaluated expression)
type Eval a = WriterT [Step] (State EvalState) a
-- State and logging of evaluation
data EvalState = EvalState
{ depth :: Int
} deriving (Show)
inc :: Eval a -> Eval a
inc m = do
modify $ \s -> s { depth = depth s + 1}
out <- m
modify $ \s -> s { depth = depth s - 1}
return out
record :: Expr -> Eval ()
record x = do
d <- gets depth
tell [(d,x)]
return ()
-- Evaluation
eval :: Eval.Scope -> Expr -> Eval Value
eval scope x = case x of
Lam n _ body -> inc $ do
return $ VClosure n body scope
App a b -> inc $ do
x <- eval scope a
record a
y <- eval scope b
record b
appl x y
Var n -> do
record x
return $ scope Map.! n
Lit (LInt a) -> return $ VInt (fromIntegral a)
Lit (LBool a) -> return $ VBool a
appl :: Value -> Value -> Eval Value
appl (VClosure n e scope) x = do
eval (Map.insert n x scope) e
appl _ _ = error "Tried to apply non-closure"
-- Interface
runEval :: Expr -> (Value, [Step])
runEval x = evalState (runWriterT (eval emptyScope x)) (EvalState 0)
|
zanesterling/haskell-compiler
|
src/Eval.hs
|
Haskell
|
bsd-3-clause
| 1,951
|
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module HTIG.IRCServer.Core
( IRCState(..)
, IRCM
, runIRCM
, runIRCM'
, getConn
, getGlobal
, setGlobal
, modifyGlobal
, modifyGlobal'
, getLocal
, setLocal
, modifyLocal
, modifyLocal'
, liftIO
) where
import Control.Applicative (Applicative(pure, (<*>)))
import Control.Concurrent.STM (TVar, atomically, readTVar, writeTVar)
import Control.Monad.Trans (MonadIO, liftIO)
import Control.Monad.Reader (ReaderT, MonadReader, runReaderT, asks)
import HTIG.IRCServer.Connection (Connection)
data IRCState g l = IRCState { ircGlobal :: TVar g
, ircLocal :: TVar l
, ircConn :: Connection
}
newtype IRCM g l a = IRCM { unIRCM :: ReaderT (IRCState g l) IO a }
deriving (Monad, Functor, MonadIO, MonadReader (IRCState g l))
instance Applicative (IRCM g l) where
pure = return
f <*> x = do
f' <- f
x' <- x
return $ f' x'
runIRCM :: IRCM g l a -> TVar g -> TVar l -> Connection -> IO a
runIRCM m g l conn = runIRCM' m $ IRCState g l conn
runIRCM' :: IRCM g l a -> IRCState g l -> IO a
runIRCM' m s = runReaderT (unIRCM m) s
getConn :: IRCM g l Connection
getConn = asks ircConn
getGlobal :: IRCM g l g
getGlobal = mkGet ircGlobal
setGlobal :: g -> IRCM g l ()
setGlobal g = mkSet ircGlobal g
modifyGlobal :: (g -> g) -> IRCM g l ()
modifyGlobal f = mkModify ircGlobal $ \g -> (f g, ())
modifyGlobal' :: (g -> (g, a)) -> IRCM g l a
modifyGlobal' f = mkModify ircGlobal f
getLocal :: IRCM g l l
getLocal = mkGet ircLocal
setLocal :: l -> IRCM g l ()
setLocal l = mkSet ircLocal l
modifyLocal :: (l -> l) -> IRCM g l ()
modifyLocal f = mkModify ircLocal $ \l -> (f l, ())
modifyLocal' :: (l -> (l, a)) -> IRCM g l a
modifyLocal' f = mkModify ircLocal f
mkGet :: (IRCState g l -> TVar a) -> IRCM g l a
mkGet f = liftIO . atomically . readTVar =<< asks f
mkSet :: (IRCState g l -> TVar a) -> a -> IRCM g l ()
mkSet f v = liftIO . atomically . flip writeTVar v =<< asks f
mkModify :: (IRCState g l -> TVar a) -> (a -> (a, b)) -> IRCM g l b
mkModify f f' = do
tv <- asks f
liftIO $ atomically $ do
v <- readTVar tv
let (v', r) = f' v
writeTVar tv v'
return r
|
nakamuray/htig
|
HTIG/IRCServer/Core.hs
|
Haskell
|
bsd-3-clause
| 2,338
|
{- |
Module : Skel
Description : Description
Copyright : 2014, Peter Harpending.
License : BSD3
Maintainer : Peter Harpending <pharpend2@gmail.com>
Stability : experimental
Portability : archlinux
-}
module Skel where
|
pharpend/flogger
|
skel/Skel.hs
|
Haskell
|
bsd-3-clause
| 240
|
{-
Copyright (c) 2014-2015, Johan Nordlander, Jonas Duregård, Michał Pałka,
Patrik Jansson and Josef Svenningsson
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Chalmers University of Technology nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module ARText where
import Data.Map
data Package = Package {
packagename :: QualName,
imports :: [Import],
typedefsApp :: Map TypeName Type,
typedefsImpl :: Map TypeName Type,
mappingSets :: Map MapName Mapping,
constraints :: Map ConstrName Constraint,
constants :: Map ConstName Constant,
interfaces :: Map IfaceName Interface,
components :: Map CompName Component,
behaviors :: Map BehName Behavior,
implementations :: Map ImpName Implementation,
modegroups :: Map GroupName ModeGroup,
compositions :: Map CompName Composition,
root :: CompName
}
type Name = Int
type TypeName = Name
type MapName = Name
type ConstrName = Name
type ConstName = Name
type IfaceName = Name
type CompName = Name
type BehName = Name
type ImpName = Name
type InstName = Name
type ProtName = Name
type GroupName = Name
type ModeName = Name
type PortName = Name
type ErrName = Name
type OpName = Name
type ElemName = Name
type VarName = Name
type FieldName = Name
type EnumName = Name
type ParName = Name
type ExclName = Name
type RunName = Name
type ShortName = Name
type ParNameOrStar = Name
type ElemNameOrStar = Name
type OpNameOrStar = Name
type QualName = [Name]
data Import = Import QualName
| ImportAll QualName
-- Types --------------------------------------------------------------------------------
data Type = TBool InvalidValue Extends
| TInt Min Max Unit ConstraintRef InvalidValue Extends
| TReal Min Max Encoding AllowNaN Unit InvalidValue Extends ConstraintRef
| TString Length Encoding InvalidValue
| TArray TypeName Int
| TRecord (Map FieldName TypeName)
| TEnum Min Max (Map EnumName (Maybe Int))
| TFixed Slope Bias Min Max Unit ConstraintRef InvalidValue Extends
data Min = Min Value Interval
data Max = Max Value Interval
data Length = Length Int
data Interval = Closed
| Open
| Infinite
data Unit = Unit QualName
| NoUnit
data ConstraintRef = ConstraintRef ConstrName
| NoConstraint
data InvalidValue = InvalidValue Value
| NoInvalid
data Extends = Extends QualName
| NoExtends
data Encoding = EncodingDouble
| EncodingSingle
| Encoding String
| NoEncoding
data AllowNaN = AllowNaN
| NoAllowNaN
data Slope = Slope Double
data Bias = Bias Double
| NoBias
-- Mappings -------------------------------------------------------------------------------
data Mapping = MapT (Map TypeName TypeName)
| MapG (Map TypeName GroupName)
-- Constraints ----------------------------------------------------------------------------
data Constraint = Constraint [Rule]
data Rule = Rule PhysInt Min Max Unit
data PhysInt = Physical
| Internal
-- Constants ------------------------------------------------------------------------------
data Constant = Const TypeName Value
data Value = Void --
| VBool Bool
| VInt Int
| VReal Double
| VString String
| VArray [Value]
-- | VArray TypeName ArrayValue
| VRecord TypeName (Map FieldName Value)
| VEnum EnumName
| VRef ConstName
deriving (Eq,Ord,Show)
data ArrayValue = Init [Value]
| InitAll Value
deriving (Eq,Ord,Show)
-- Interfaces ----------------------------------------------------------------------------
data Interface = SenderReceiver Service (Map ElemName Data)
| ClientServer Service (Map ErrName Int) (Map OpName Operation)
| Param Service (Map ParName Param)
| ModeSwitch Service (Map ProtName GroupName)
data Service = IsService
| NotService
data Data = Data TypeName Queued InitValue
data Queued = Queued
| UnQueued
data InitValue = InitValue Value
| NoInitValue
data Operation = Operation [ErrName] (Map ParName Argument)
data Argument = In TypeName Policy
| InOut TypeName Policy
| Out TypeName Policy
data Policy = UseArgumentType
| UseArrayBaseType
| UseVoid
| NoPolicy
data Param = TypeName String InitValue
-- Components ---------------------------------------------------------------------------
data Component = Application (Map PortName Port)
| SensorActuator (Map PortName Port) Hw
| Service (Map PortName Port)
| Parameter (Map PortName Port)
data Port = SenderProvides IfaceName (Map ElemName ComSpecS)
| ReceiverRequires IfaceName (Map ElemName ComSpecR)
| ClientRequires IfaceName (Map OpName ComSpec0)
| ServerProvides IfaceName (Map OpName ComSpec1)
| ParamProvides IfaceName
| ParamRequires IfaceName
data ComSpecS = QueuedComSpecS CanInvalidate InitValue E2EProtection OutOfRange
| UnQueuedComSpecS E2EProtection OutOfRange
data ComSpecR = QueuedComSpecR Length E2EProtection OutOfRange
| UnQueuedComSpecR TimeOut ResyncTime InvalidType InitValue
EnableUpdate NeverReceived E2EProtection OutOfRange
data ComSpec0 = ComSpec0
data ComSpec1 = ComSpec1 Length
data CanInvalidate = CanInvalidate
| CannotInvalidate
data E2EProtection = UsesEndToEndProtection
| NoEndToEndProtection
data OutOfRange = NONE
| IGNORE
| SATURATE
| DEFAULT
| INVALID
data TimeOut = TimeOut Double
| NoTimeOut
data ResyncTime = ResyncTime Double
| NoResyncTime
data InvalidType = HandleInvalidTypeKeep
| HandleInvalidTypeReplace
| NoHandleInvalidType
data EnableUpdate = EnableUpdate Bool
| NoEnableUpdate
data NeverReceived = HandleNeverReceived
| NoHandleNeverReceived
data Hw = Hw QualName
data Behavior = InternalBehavior {
supportsMultipleInstantiation :: Bool,
forComponent :: CompName,
dataTypeMappings :: [MapName],
exclusiveAreas :: [ExclName],
interRunnableVariables :: Map VarName Variable,
calibrationParams :: Map ParName CalParam,
perInstanceMemories :: Map Name PerInstMem,
portAPIOptions :: [PortAPIOption],
runnables :: Map RunName Runnable
}
data Variable = Var TypeName Explicit InitValue
data Explicit = Explicit
| Implicit
data CalParam = InstanceParam TypeName String
| SharedParam TypeName String
data PerInstMem = PerInstanceMemory String String
data PortAPIOption = PortAPIOption IndirectAPI TakeAddress PortName [(Type,Value)]
data IndirectAPI = IndirectAPI
| NoIndirectAPI
data TakeAddress = EnableTakeAddress
| DisableTakeAddress
data Runnable = Runnable {
concurrent :: Bool,
minimumStartInterval :: Double,
inExclusiveAreas :: [ExclName],
usesExclusiveAreas :: [ExclName],
symbol :: Maybe String,
readVariables :: [VarName],
writtenVariables :: [VarName],
events :: [Event],
parameterAccesses :: [ParamAccess],
dataReadAccesses :: [DataRdAccess],
dataReceivePoints :: [DataRcvPt],
dataSendPoints :: [DataSndPt],
dataWriteAccesses :: [DataWrAccess],
modeSwitchPoints :: [ModeSwitchPt],
modeAccessPoints :: [ModeAccessPt],
serverCallPoints :: [ServerCallPt],
waitPoints :: [WaitPt]
}
data Event = DataReceivedEvent PortName ElemName As Dis
| OperationInvokedEvent PortName OpName As Dis
| ModeSwitchEvent Activation PortName GroupName ModeName As Dis
| InitEvent
| BackgroundEvent
| TimingEvent Double As Dis
| DataSendCompletedEvent ShortName As Dis
| DataWriteCompletedEvent PortName ElemName
| AsynchronousServerCallReturnsEvent ServerCallPt
| ModeSwitchAckEvent PortName GroupName
| ReceiveErrorEvent PortName ElemName As Dis
| ModeManagerErrorEvent
| ExternalTriggerOccurredEvent
| InternalTriggerOccurredEvent
{-
data WPEvent = DataSendCompleted -- Rte_Feedback(PortName,ElemName)
| DataReceived -- Rte_Receive(PortName,ElemName,...)
| AsynchronousServerCallReturns -- Rte_Result(PortName,OpName,...)
| ModeSwitchAck -- Rte_SwitchAck(PortName,GroupName)
-}
data ParamAccess = ParameterAccess ParName As
| ParamPortAccess PortName ParNameOrStar As
data DataRdAccess = DataReadAccess PortName ElemNameOrStar As
data DataRcvPt = DataReceivePoint PortName ElemNameOrStar As
data DataSndPt = DataSendPoint PortName ElemNameOrStar As
data DataWrAccess = DataWriteAccess PortName ElemNameOrStar As
data ModeSwitchPt = ModeSwitchPoint PortName ProtName As
data ModeAccessPt = ModeAccessPoint Activation PortName GroupName As
data ServerCallPt = ServerCallPoint SyncOrAsync TimeOut PortName OpNameOrStar As
data WaitPt = WaitPoint ShortName TimeOut [ShortName]
data SyncOrAsync = Synchronous
| Asynchronous
data Activation = Entry
| Exit
data As = As ShortName
| NoName
data Dis = DisabledFor PortName GroupName ModeName
| NoDis
data Implementation = Implementation {
forBehavior :: BehName,
language :: Language,
codeDescriptor :: String,
codeGenerator :: Maybe String,
requiredRTEVendor :: RTEVendor,
compilers :: [Compiler]
}
data Language = C
| Cpp
| Java
data RTEVendor = RTEVendor String SwVersion VendorId
| NoRTEVendor
data SwVersion = SwVersion Int
| NoSwVersion
data VendorId = VendorId Int
| NoVendorId
data Compiler = Compiler {
compilerName :: Name,
vendor :: String,
version :: String
}
-- ModeGroups ------------------------------------------------------------------------------
data ModeGroup = ModeGroup Initial [ModeName]
data Initial = Initial ModeName
| NoInitial
-- Compositions ----------------------------------------------------------------------------
data Composition = Composition {
subcomponents :: Map InstName CompPrototype,
delegations :: Map PortName Delegation,
connectors :: [Connector]
}
data CompPrototype = Prototype CompName
data Delegation = DelegateRequires IfaceName [(InstName,PortName)]
| DelegateProvides IfaceName [(InstName,PortName)]
deriving (Eq)
data Connector = Connect (InstName,PortName) (InstName,PortName)
| AutoConnect InstName InstName
deriving (Eq)
|
josefs/autosar
|
oldARSim/ARText.hs
|
Haskell
|
bsd-3-clause
| 16,113
|
import Control.Monad
import Control.Concurrent
import Control.Concurrent.STM
import System.Posix.IO
import GHC.Event
main_ :: IO ()
main_ = do
Just em <- getSystemEventManager
registerTimeout em 1000000 (print 888)
registerFd em (\k e -> getLine >>= print >> print k >> print e) stdInput evtRead
threadDelay 2000000
return ()
main :: IO ()
main = do
c <- atomically newTChan
Just em <- getSystemEventManager
registerTimeout em 1000000 (print 888)
forkIO . void $ registerFd em
(\k e -> void $ print k >> print e >> atomically (writeTChan c ()))
stdInput evtRead
atomically $ readTChan c
getLine >>= print
threadDelay 2000000
|
YoshikuniJujo/xmpipe
|
test/testPolling.hs
|
Haskell
|
bsd-3-clause
| 643
|
{-# LANGUAGE TemplateHaskell, FlexibleContexts, FlexibleInstances, MultiParamTypeClasses, TypeFamilies #-}
module WormLikeChain where
import Control.Applicative
import Control.Monad
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector.Generic
import qualified Data.Vector.Generic.Mutable
import Data.Vector.Unboxed.Deriving
import Data.VectorSpace
import Data.Cross
import Data.AffineSpace
import Data.AffineSpace.Point
import Control.Newtype
import Data.Random
import Data.Random.Distribution.Bernoulli
import Data.Number.LogFloat hiding (realToFrac)
derivingUnbox "Point"
[t| (V.Unbox a) => Point (a,a,a) -> (a,a,a) |]
[| \(P x)->x |]
[| P |]
data WormLikeChain = WLC { lp :: Double
, links :: Int
}
type Angle = Double -- ^ Angle in radians
type Dist = Double
type Energy = Double
type Mass = Double
type Charge = Double -- ^ Electric charge
type PTrans = Double -- ^ Momentum transfer
type Intensity = Double -- ^ Scattering Amplitude
type R3 = (Double, Double, Double)
type P3 = Point R3
-- | Chain parametrized by bend angles
newtype ChainConfig = ChainC (V.Vector Angle)
deriving (Show)
instance Newtype ChainConfig (V.Vector Angle) where
pack = ChainC
unpack (ChainC a) = a
-- | Embedding of chain parametrized by dihedral angles
newtype ChainEmbedding = ChainE (V.Vector (Angle,Angle))
deriving (Show)
instance Newtype ChainEmbedding (V.Vector (Angle,Angle)) where
pack = ChainE
unpack (ChainE a) = a
-- | Position of links parametrized in Cartesian 3-space
newtype ChainPos = ChainP (V.Vector P3)
deriving (Show)
instance Newtype ChainPos (V.Vector P3) where
pack = ChainP
unpack (ChainP a) = a
-- | The bend angles of a Euler-angle parametrized embedding
embeddingToConfig :: ChainEmbedding -> ChainConfig
embeddingToConfig (ChainE v) =
ChainC $ V.map (\(α,β)->undefined) v
-- | Dihedral angles to Cartesian embedding given link length
embeddingToPositions :: Dist -> ChainEmbedding -> ChainPos
embeddingToPositions d (ChainE e) =
ChainP $ V.fromList $ reverse $ go [] (V.toList e)
where go :: [P3] -> [(Angle,Angle)] -> [P3]
go ps [] = ps
go [] ((_,_):rest) = go [origin] rest
go ps@(p1:[]) ((_,_):rest) = let p0 = p1 .+^ (1,0,0)
in go (p0:ps) rest
go ps@(p1:p2:[]) ((α,_):rest) = let p0 = p1 .+^ d *^ (cos α, sin α, 0)
in go (p0:ps) rest
go ps@(p1:p2:p3:_) ((α,β):rest) =
let p0 = p1 .+^ d *^ dihedralDir p3 p2 p1 (α,β)
in go (p0:ps) rest
-- | Normalized vector in direction specified by dihedral angles
-- relative to the three points given
--
-- ...--p3--p2 dir
-- \ /
-- p1
dihedralDir :: P3 -> P3 -> P3 -> (Angle,Angle) -> R3
dihedralDir p3 p2 p1 (α,β) =
let x = normalized $ p1 .-. p2
y = x `cross3` z
z = case (p2 .-. p1) `cross3` (p3 .-. p1) of
a | magnitude a < 1e-4 -> (0,0,1)
a -> a
in x ^* cos α ^* cos β ^+^ y ^* sin α ^* cos β ^+^ sin β *^ z
-- | A straight chain
straightChain :: Int -> ChainEmbedding
straightChain n = ChainE $ V.replicate n (0,0)
-- | Bending energy of given configuration under worm-like chain model
bendEnergy :: WormLikeChain -> ChainConfig -> Energy
bendEnergy (WLC lp links) (ChainC config) =
V.sum $ V.map energy config
where energy θ = undefined
-- | Electrostatic self-energy
selfEnergy :: Charge -> Dist -> ChainPos -> Energy
selfEnergy chainQ debyeL (ChainP v) =
sum $ map pairEnergy $ pairsWith distance v
where pairEnergy :: Dist -> Energy
pairEnergy r = 2*chainQ / r * exp (-r / debyeL)
-- | Zip together all combinations (not permutations) of distinct
-- elements with function f
pairsWith :: V.Unbox a => (a -> a -> b) -> V.Vector a -> [b]
pairsWith f v =
case V.toList v of
x:xs -> map (f x) xs ++ pairsWith f (V.tail v)
[] -> []
-- | Generate a random chain
randomChain :: Int -> RVar ChainEmbedding
randomChain n =
(ChainE . V.fromList) <$> replicateM n randomLink
where randomLink = do
α <- uniform 0 (2*pi)
β <- uniform 0 pi
return (α, β)
--- Importance sampling
-- | Propose a new embedding
proposal :: ChainEmbedding -> RVar ChainEmbedding
proposal (ChainE e) = do
n <- uniform 0 (V.length e - 1)
α <- uniform 0 (2*pi)
β <- uniform 0 pi
return $ ChainE $ e V.// [(n,(α,β))]
-- | Metropolis acceptance
accept :: (a -> LogFloat) -> a -> a -> RVar a
accept prob x x'
| p' > p = return x'
| otherwise = do a <- bernoulli $ (realToFrac $ p' / p :: Double)
return $ if a then x' else x
where (p, p') = (prob x, prob x')
-- | Monte Carlo sampling of embedding space
-- 'evolve n energy beta e0' produces 'n' configurations evolved from
-- initial chain configuration 'e0' 'under energy function 'energy' at
-- temperature 'T = 1 / beta / k_B'
evolve :: Int -> (ChainEmbedding -> Energy) -> Energy -> ChainEmbedding -> RVar [ChainEmbedding]
evolve n energy beta = iterateM n go
where go e = proposal e >>= accept prob e
prob x = logToLogFloat $ -energy x * beta
-- | Scattering amplitude for given chain configuration
scattering :: V.Vector P3 -> R3 -> Intensity
scattering v q =
n + 1 + 2*sum (map (\d->cos $ 2*pi * (d <.> q)) $ pairsWith (.-.) v)
where n = realToFrac $ V.length v
--- Observables
-- | End to end distance
endToEndDist :: ChainPos -> Double
endToEndDist (ChainP p) = V.last p `distance` V.head p
-- | Squared radius of gyration
gyrationRad :: V.Vector Mass -> ChainPos -> Double
gyrationRad masses (ChainP e) =
weight * V.sum (V.zipWith (\m p->m * p `distanceSq` origin) masses e) - magnitudeSq cm
where weight = V.sum masses
cm = V.foldl1 (^+^) $ V.zipWith (\m p->m *^ (p .-. origin)) masses e
iterateM :: Monad m => Int -> (a -> m a) -> a -> m [a]
iterateM 0 _ _ = return []
iterateM n f x = do
x' <- f x
xs <- iterateM (n-1) f x'
return $ x':xs
|
bgamari/polymer-models
|
WormLikeChain.hs
|
Haskell
|
bsd-3-clause
| 6,303
|
{-# LANGUAGE TypeFamilies ,MultiParamTypeClasses,DeriveFunctor,DeriveFoldable,DeriveGeneric ,TypeOperators#-}
module Scaling.S1 where
import Space.Class
import Exponential.Class
import Data.Foldable
import Multiplicative.Class
import Data.FMonoid.Class
import Data.Distributive
import Data.Monoid
import Linear.V2
import Linear.V1
import Linear.Vector
import Local
import Data.Functor.Product
import qualified Prelude as Prelude
import Prelude hiding((*))
import SemiProduct
newtype Scale a = Scale {unScale :: a} deriving(Functor,Foldable,Read,Show)
instance Distributive Scale where
distribute x = Scale (fmap unScale x)
instance Exponential Scale where
logM (Scale x) = V1 $ log x
expM (V1 x) = Scale $ exp x
instance Group Scale where
mult (Scale x) (Scale y)= Scale (x Prelude.* y)
invert (Scale x) = Scale (-x )
type instance Local Scale = V1
instance Action Scale V1 where
Scale x |> v = fmap (Prelude.*x) v
instance Floating a => Multiplicative (Scale a) where
one = Scale 1
Scale x * Scale y = Scale $ x Prelude.* y
inversion (Scale x) = Scale $ 1/x
instance Space Scale where
x |+| y = x * expM y
x |-| y = logM $ inversion y * x
|
massudaw/mtk
|
Scaling/S1.hs
|
Haskell
|
bsd-3-clause
| 1,199
|
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-}
module Text.HeX.Standard.LaTeX (defaults) where
import Text.HeX
import Text.HeX.Standard.TeX (ctl, ch, grp)
import Text.HeX.Standard.Generic (getSectionNum)
defaults :: HeX ()
defaults = do
addParser [Inline] $ basicInline ch
addParser [Block] $ basicBlock toPara
newCommand [Inline] "emph" emph
newCommand [Inline] "strong" strong
newCommand [Block] "section" (section 1)
newCommand [Block] "subsection" (section 2)
newCommand [Block] "subsubsection" (section 3)
newCommand [Block] "paragraph" (section 4)
newCommand [Block] "subparagraph" (section 5)
toPara :: [Doc] -> Doc
toPara xs = mconcat xs +++ "\n\n"
emph :: InlineDoc -> Doc
emph (InlineDoc arg) = ctl "emph" +++ grp [arg]
strong :: InlineDoc -> Doc
strong (InlineDoc arg) = ctl "textbf" +++ grp [arg]
section :: Int -> InlineDoc -> HeX Doc
section lev (InlineDoc d) = do
_ <- getSectionNum lev -- we need to increment the number
let secheading = case lev of
1 -> "section"
2 -> "subsection"
3 -> "subsubsection"
4 -> "paragraph"
_ -> "subparagraph"
return $ ctl secheading +++ grp [d] +++ "\n"
|
jgm/HeX
|
Text/HeX/Standard/LaTeX.hs
|
Haskell
|
bsd-3-clause
| 1,264
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Network.Linode.Internal where
import Control.Error
import Control.Exception (IOException, handle)
import Control.Lens ((&), (.~), (^?))
import Control.Monad.IO.Class (liftIO)
import Data.Aeson (FromJSON)
import qualified Data.ByteString.Lazy as B
--import Data.Foldable (traverse_)
import Data.Monoid ((<>))
import qualified Data.Text as T
--import Data.Text.Encoding (decodeUtf8)
--import qualified Data.Text.IO as TIO
import qualified Network.Wreq as W
--import Network.Wreq.Lens
import Network.Linode.Parsing
import Network.Linode.Types
diskTypeToString :: DiskType -> String
diskTypeToString Ext3 = "ext3"
diskTypeToString Ext4 = "ext4"
diskTypeToString Swap = "swap"
diskTypeToString RawDisk = "raw"
paymentTermToInt :: PaymentTerm -> Int
paymentTermToInt OneMonth = 1
paymentTermToInt OneYear = 12
paymentTermToInt TwoYears = 24
getWith :: FromJSON a => W.Options -> ExceptT LinodeError IO a
getWith opts = ExceptT g
where g = handle (\(e :: IOException) -> return (Left $ NetworkError e)) $ do
--liftIO $ print (view params opts :: [(T.Text, T.Text)])
response <- W.getWith opts "https://api.linode.com"
--liftIO $ traverse_ (TIO.putStrLn . decodeUtf8. B.toStrict) $ response ^? W.responseBody
return $ parseResponse (fromMaybe B.empty (response ^? W.responseBody))
simpleGetter :: FromJSON a => String -> ApiKey -> ExceptT LinodeError IO a
simpleGetter action apiKey = getWith opts
where opts = W.defaults & W.param "api_key" .~ [T.pack apiKey]
& W.param "api_action" .~ [T.pack action]
maybeOr :: Monad m => Maybe a -> ExceptT e m a -> ExceptT e m a
maybeOr v p = maybe p return v
fetchAndSelect :: IO (Either LinodeError [a]) -> ([a] -> Maybe a) -> String -> ExceptT LinodeError IO a
fetchAndSelect fetch select name = do
r <- liftIO fetch
case r of
Left e -> throwE $ SelectionError ("Error which fetching a " <> name <> " . " ++ show e)
Right xs -> case select xs of
Nothing -> throwE $ SelectionError ("Error: Selection of " <> name <> " returned no value")
Just x -> return x
|
Helkafen/haskell-linode
|
src/Network/Linode/Internal.hs
|
Haskell
|
bsd-3-clause
| 2,388
|
import Tutorial.Chapter8.Bug (Sex(..), BugColour(..), buildBug)
import ALife.Creatur.Universe (store, mkSimpleUniverse)
import ALife.Creatur.Genetics.BRGCBool (put, runWriter,
runDiploidReader)
import Control.Monad.State.Lazy (evalStateT)
main :: IO ()
main = do
let u = mkSimpleUniverse "Chapter8" "chapter8"
-- Create some Bugs and save them in the population directory.
let g1 = runWriter (put Male >> put Green)
let (Right b1) = runDiploidReader (buildBug "Bugsy") (g1,g1)
evalStateT (store b1) u
let g2 = runWriter (put Male >> put Purple)
let (Right b2) = runDiploidReader (buildBug "Mel") (g2,g2)
evalStateT (store b2) u
let g3 = runWriter (put Female >> put Green)
let (Right b3) = runDiploidReader (buildBug "Flo") (g3, g3)
evalStateT (store b3) u
let g4 = runWriter (put Male >> put Purple)
let (Right b4) = runDiploidReader (buildBug "Buzz") (g4, g4)
evalStateT (store b4) u
|
mhwombat/creatur-examples
|
src/Tutorial/Chapter8/GeneratePopulation.hs
|
Haskell
|
bsd-3-clause
| 925
|
module Main where
import Control.Monad
import System.Exit (exitFailure)
import System.Environment
import L2.AbsL
import L2.ParL
import L2.ErrM
import Liveness.Liveness
main :: IO ()
main = do
args <- getArgs
when (length args /= 1) $ do
putStrLn "usage: filename"
exitFailure
ts <- liftM myLexer $ readFile (head args)
case pParenListInstruction ts of
Bad s -> do
putStrLn "\nParse Failed...\n"
putStrLn "Tokens:"
print ts
putStrLn s
Ok (PLI is) -> putStrLn . displayLiveArray . liveness $ is
|
mhuesch/scheme_compiler
|
src/Liveness/Main.hs
|
Haskell
|
bsd-3-clause
| 585
|
module Matterhorn.Events.ChannelListOverlay
( onEventChannelListOverlay
, channelListOverlayKeybindings
, channelListOverlayKeyHandlers
)
where
import Prelude ()
import Matterhorn.Prelude
import qualified Graphics.Vty as Vty
import Matterhorn.Events.Keybindings
import Matterhorn.State.ChannelListOverlay
import Matterhorn.State.ListOverlay
import Matterhorn.Types
onEventChannelListOverlay :: Vty.Event -> MH ()
onEventChannelListOverlay =
void . onEventListOverlay (csCurrentTeam.tsChannelListOverlay) channelListOverlayKeybindings
-- | The keybindings we want to use while viewing a channel list overlay
channelListOverlayKeybindings :: KeyConfig -> KeyHandlerMap
channelListOverlayKeybindings = mkKeybindings channelListOverlayKeyHandlers
channelListOverlayKeyHandlers :: [KeyEventHandler]
channelListOverlayKeyHandlers =
[ mkKb CancelEvent "Close the channel search list" (exitListOverlay (csCurrentTeam.tsChannelListOverlay))
, mkKb SearchSelectUpEvent "Select the previous channel" channelListSelectUp
, mkKb SearchSelectDownEvent "Select the next channel" channelListSelectDown
, mkKb PageDownEvent "Page down in the channel list" channelListPageDown
, mkKb PageUpEvent "Page up in the channel list" channelListPageUp
, mkKb ActivateListItemEvent "Join the selected channel" (listOverlayActivateCurrent (csCurrentTeam.tsChannelListOverlay))
]
|
matterhorn-chat/matterhorn
|
src/Matterhorn/Events/ChannelListOverlay.hs
|
Haskell
|
bsd-3-clause
| 1,458
|
{-# LANGUAGE NoMonomorphismRestriction #-}
import Diagrams.Prelude
import Diagrams.Backend.Cairo.CmdLine
import System.Environment
main = withArgs [ "-o", "test4.png", "-w", "400", "-h", "400" ] $ defaultMain $ ((text "ABCDEFGHabcdefgh" # fontSize 2 # translateX 8 <> rect 10 1 # lw 0.1) # translateX (-5)) <> rect 12 12 # lw 0.2
|
diagrams/diagrams-test
|
misc/av-font.hs
|
Haskell
|
bsd-3-clause
| 332
|
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE RecordWildCards #-}
module LDrive.Platforms where
-- ( testPlatformParser
-- , ColoredLEDs(..)
-- , TestUART(..)
-- , TestSPI(..)
-- , TestCAN(..)
-- , TestDMA(..)
-- , TestPlatform(..)
-- , testplatform_clockconfig
-- , odrive
-- , drv8301
-- , drv8301_en_gate
-- , m1_ncs
-- , pinOut
-- ) where
import Ivory.Language
import Ivory.Tower.Config
import Data.Char (toUpper)
import qualified Ivory.BSP.STM32F405.ADC as F405
import qualified Ivory.BSP.STM32F405.ATIM18 as F405
import qualified Ivory.BSP.STM32F405.CAN as F405
import qualified Ivory.BSP.STM32F405.UART as F405
import qualified Ivory.BSP.STM32F405.GPIO as F405
import qualified Ivory.BSP.STM32F405.GPIO.AF as F405
import qualified Ivory.BSP.STM32F405.SPI as F405
import qualified Ivory.BSP.STM32F405.RNG as F405
import qualified Ivory.BSP.STM32F405.GTIM2345 as F405
import qualified Ivory.BSP.STM32F405.Interrupt as F405
import Ivory.BSP.STM32.Peripheral.ADC
import Ivory.BSP.STM32.Peripheral.CAN
import Ivory.BSP.STM32.Peripheral.GPIOF4
import Ivory.BSP.STM32.Peripheral.UART
import Ivory.BSP.STM32.Peripheral.SPI as SPI -- hiding (ActiveHigh, ActiveLow)
import Ivory.BSP.STM32.Peripheral.RNG
import Ivory.BSP.STM32.Peripheral.UART.DMA
import Ivory.BSP.STM32.ClockConfig
import Ivory.BSP.STM32.Config
import Ivory.BSP.STM32.Interrupt
import LDrive.LED as LED
import Ivory.Tower.Drivers.PWM.ATIM
testPlatformParser :: ConfigParser TestPlatform
testPlatformParser = do
p <- subsection "args" $ subsection "platform" string
case map toUpper p of
"ODRIVE" -> result odrive
"CAN4DISCO" -> result c4d
_ -> fail ("no such platform " ++ p)
where
result platform = do
conf <- stm32ConfigParser (testplatform_stm32 platform)
return platform { testplatform_stm32 = conf }
data ColoredLEDs =
ColoredLEDs
{ redLED :: LED
, greenLED :: LED
}
data TestUART =
TestUART
{ testUARTPeriph :: UART
, testUARTPins :: UARTPins
}
data TestSPI =
TestSPI
{ testSPIPeriph :: SPIPeriph
, testSPIPins :: SPIPins
-- TODO FIXME: move CS pins for test devices into TestSPI
}
data TestCAN =
TestCAN
{ testCAN :: CANPeriph
, testCANRX :: GPIOPin
, testCANTX :: GPIOPin
, testCANFilters :: CANPeriphFilters
}
data TestDMA =
TestDMA
{ testDMAUARTPeriph :: DMAUART
, testDMAUARTPins :: UARTPins
}
data ADC = ADC {
adcId :: Uint8
, adcPeriph :: ADCPeriph
, adcChan :: (Uint8, GPIOPin)
, adcInjChan :: (Uint8, GPIOPin)
, adcInt :: HasSTM32Interrupt
}
data Enc = EncTimer {
encTim :: F405.GTIM16
, encChan1 :: GPIOPin
, encChan2 :: GPIOPin
, encAf :: GPIO_AF
}
data ExtInt =
ExtInt
{ extInt :: HasSTM32Interrupt,
extPin :: GPIOPin
}
type ADCs = (ADC, ADC, ADC)
data TestPlatform =
TestPlatform
{ testplatform_leds :: ColoredLEDs
, testplatform_uart :: TestUART
, testplatform_spi :: TestSPI
, testplatform_can :: TestCAN
, testplatform_rng :: RNG
, testplatform_stm32 :: STM32Config
, testplatform_enc :: Enc
, testplatform_pwm :: PWMTimer
, testplatform_adc1 :: ADC
, testplatform_adc2 :: ADC
, testplatform_adc3 :: ADC
, testplatform_adcs :: ADCs
}
testplatform_clockconfig :: TestPlatform -> ClockConfig
testplatform_clockconfig = stm32config_clock . testplatform_stm32
--testExti :: ExtInt
--testExti = ExtInt (HasSTM32Interrupt F405.EXTI0) F405.pinD1
testExti :: ExtInt
testExti = ExtInt (HasSTM32Interrupt F405.EXTI4) gpio3
adcint :: HasSTM32Interrupt
adcint = HasSTM32Interrupt F405.ADC
adc1, adc2, adc3 :: ADC
adc1 = ADC 1 F405.adc1 (5, F405.pinA5) (0, F405.pinA0) adcint
adc2 = ADC 2 F405.adc2 (13, F405.pinC3) (10, F405.pinC0) adcint
adc3 = ADC 3 F405.adc3 (12, F405.pinC2) (11, F405.pinC1) adcint
spi3_pins :: SPIPins
spi3_pins = SPIPins
{ spiPinMiso = F405.pinC12
, spiPinMosi = F405.pinC11
, spiPinSck = F405.pinC10
, spiPinAF = F405.gpio_af_spi3
}
gpio1, gpio2, gpio3, gpio4 :: GPIOPin
gpio1 = F405.pinB2
gpio2 = F405.pinA5
gpio3 = F405.pinA4
gpio4 = F405.pinA3
drv8301_en_gate :: GPIOPin
drv8301_en_gate = F405.pinB12
m0_dc_cal, m1_dc_cal :: GPIOPin
m0_dc_cal = F405.pinC9
m1_dc_cal = F405.pinC15
m0_nCS :: GPIOPin
m0_nCS = F405.pinC13
m1_nCS :: GPIOPin
m1_nCS = F405.pinC14
enc0 :: Enc
enc0 = EncTimer F405.tim3 F405.pinB4 F405.pinB5 F405.gpio_af_tim3
enc0Z0 :: GPIOPin
enc0Z0 = F405.pinA15
enc1 :: Enc
enc1 = EncTimer F405.tim4 F405.pinB6 F405.pinB7 F405.gpio_af_tim4
enc1Z0 :: GPIOPin
enc1Z0 = F405.pinB3
pwm0 :: PWMTimer
pwm0 = PWMTimer F405.tim1
F405.pinA8 F405.pinA9 F405.pinA10
F405.pinB13 F405.pinB14 F405.pinB15
F405.gpio_af_tim1 0 tim_period_clocks
pwm1 :: PWMTimer
pwm1 = PWMTimer F405.tim8
F405.pinC6 F405.pinC7 F405.pinC8
F405.pinA7 F405.pinB0 F405.pinB1
F405.gpio_af_tim8 0 tim_period_clocks
drv8301M0 :: SPIDevice
drv8301M0 = SPIDevice
{ spiDevPeripheral = F405.spi3
, spiDevCSPin = m0_nCS
, spiDevClockHz = 500000
, spiDevCSActive = SPI.ActiveLow
, spiDevClockPolarity = ClockPolarityLow
, spiDevClockPhase = ClockPhase2
, spiDevBitOrder = MSBFirst
, spiDevName = "drv8301m0"
}
drv8301M1 :: SPIDevice
drv8301M1 = SPIDevice
{ spiDevPeripheral = F405.spi3
, spiDevCSPin = m1_nCS
, spiDevClockHz = 500000
, spiDevCSActive = SPI.ActiveLow
, spiDevClockPolarity = ClockPolarityLow
, spiDevClockPhase = ClockPhase2
, spiDevBitOrder = MSBFirst
, spiDevName = "drv8301m1"
}
tim_period_clocks :: Uint16
tim_period_clocks = 8192
currentMeasPeriod :: ClockConfig -> IFloat
currentMeasPeriod cc = (2 * (safeCast tim_period_clocks) / (fromIntegral pclkhz))
where
pclkbus = PClk2
pclkhz = clockPClkHz pclkbus cc
currentMeasHz :: ClockConfig -> IFloat
currentMeasHz cc = (fromIntegral pclkhz) / (safeCast $ 2 * tim_period_clocks)
where
pclkbus = PClk2
pclkhz = clockPClkHz pclkbus cc
odrive :: TestPlatform
odrive = TestPlatform
{ testplatform_leds = ColoredLEDs
{ redLED = LED gpio1 LED.ActiveHigh
, greenLED = LED gpio2 LED.ActiveHigh
}
, testplatform_uart = TestUART
{ testUARTPeriph = F405.uart1
, testUARTPins = UARTPins
{ uartPinTx = F405.pinB6
, uartPinRx = F405.pinB7
, uartPinAF = F405.gpio_af_uart1
}
}
, testplatform_spi = TestSPI
{ testSPIPeriph = F405.spi3
, testSPIPins = spi3_pins
}
, testplatform_can = TestCAN
{ testCAN = F405.can1
, testCANRX = F405.pinB8
, testCANTX = F405.pinB9
, testCANFilters = F405.canFilters
}
, testplatform_rng = F405.rng
, testplatform_enc = enc0
, testplatform_pwm = pwm0
, testplatform_adc1 = adc1
, testplatform_adc2 = adc2
, testplatform_adc3 = adc3
, testplatform_adcs = (adc1, adc2, adc3)
, testplatform_stm32 = odriveSTMConfig 8
}
c4d :: TestPlatform
c4d = TestPlatform
{ testplatform_leds = ColoredLEDs
{ redLED = LED F405.pinD14 LED.ActiveHigh
, greenLED = LED F405.pinD15 LED.ActiveHigh
}
, testplatform_uart = TestUART
{ testUARTPeriph = F405.uart2
, testUARTPins = UARTPins
{ uartPinTx = F405.pinA2
, uartPinRx = F405.pinA3
, uartPinAF = F405.gpio_af_uart2
}
}
, testplatform_spi = TestSPI
{ testSPIPeriph = F405.spi3
, testSPIPins = spi3_pins
}
, testplatform_can = TestCAN
{ testCAN = F405.can1
, testCANRX = F405.pinB8
, testCANTX = F405.pinB9
, testCANFilters = F405.canFilters
}
, testplatform_rng = F405.rng
, testplatform_enc = enc0
, testplatform_pwm = pwm0
, testplatform_adc1 = adc1
, testplatform_adc2 = adc2
, testplatform_adc3 = adc3
, testplatform_adcs = (adc1, adc2, adc3)
, testplatform_stm32 = odriveSTMConfig 8
}
--- XXX: clock hackery, suggest upstream
data Divs = Divs {
div_hclk :: Integer
, div_pclk1 :: Integer
, div_pclk2 :: Integer
}
externalXtalDivs :: Integer -> Integer -> Divs -> ClockConfig
externalXtalDivs xtal_mhz sysclk_mhz Divs{..} = ClockConfig
{ clockconfig_source = External (xtal_mhz * 1000 * 1000)
, clockconfig_pll = PLLFactor
{ pll_m = xtal_mhz
, pll_n = sysclk_mhz * 2
, pll_p = 2
, pll_q = 7
}
, clockconfig_hclk_divider = div_hclk
, clockconfig_pclk1_divider = div_pclk1
, clockconfig_pclk2_divider = div_pclk2
}
-- STM32F405RGT6
odriveSTMConfig :: Integer -> STM32Config
odriveSTMConfig xtal_mhz = STM32Config
{ stm32config_processor = STM32F405
, stm32config_px4version = Nothing
, stm32config_clock = externalXtalDivs xtal_mhz 168 divs
-- XXX: this is 192 in total (112+16+64)
-- 64 is CCM (core coupled memory)
-- + 4kb additional backup sram
-- , stm32config_sram = 128 * 1024
, stm32config_sram = 164 * 1024
}
where
divs = Divs
{ div_hclk = 1
, div_pclk1 = 2
, div_pclk2 = 1
}
|
sorki/odrive
|
src/LDrive/Platforms.hs
|
Haskell
|
bsd-3-clause
| 9,381
|
module Main
(
main
) where
import qualified Data.ByteString.Lazy.Char8 as L
import qualified Data.Attoparsec.Char8 as P
import Data.Attoparsec.Lazy hiding (skipWhile,take)
import Data.List (intercalate,transpose)
import NanoUtils.Container (normalizeByMax)
import System.IO
main = do
xss <- parseFile
let xss' = transpose.map normalizeByMax.transpose $ xss
contents = intercalate "\n".map (intercalate "\t".map show) $ xss'
writeFile "temp" contents
parseFile = do
contents <- L.readFile "data/allnodes_notnormalized.tab"
let (Done _ lst) = parse docParser contents
return lst
docParser = (P.double `P.sepBy` skipTab) `P.sepBy` P.endOfLine
skipTab = P.skipWhile (=='\t')
|
nanonaren/Reducer
|
Normalize.hs
|
Haskell
|
bsd-3-clause
| 706
|
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances,
PatternGuards #-}
module Idris.Core.Evaluate(normalise, normaliseTrace, normaliseC, normaliseAll,
rt_simplify, simplify, specialise, hnf, convEq, convEq',
Def(..), CaseInfo(..), CaseDefs(..),
Accessibility(..), Totality(..), PReason(..), MetaInformation(..),
Context, initContext, ctxtAlist, uconstraints, next_tvar,
addToCtxt, setAccess, setTotal, setMetaInformation, addCtxtDef, addTyDecl,
addDatatype, addCasedef, simplifyCasedef, addOperator,
lookupNames, lookupTy, lookupP, lookupDef, lookupDefAcc, lookupVal,
mapDefCtxt,
lookupTotal, lookupNameTotal, lookupMetaInformation, lookupTyEnv, isDConName, isTConName, isConName, isFnName,
Value(..), Quote(..), initEval, uniqueNameCtxt) where
import Debug.Trace
import Control.Monad.State -- not Strict!
import qualified Data.Binary as B
import Data.Binary hiding (get, put)
import Idris.Core.TT
import Idris.Core.CaseTree
data EvalState = ES { limited :: [(Name, Int)],
nexthole :: Int }
deriving Show
type Eval a = State EvalState a
data EvalOpt = Spec
| HNF
| Simplify
| AtREPL
| RunTT
deriving (Show, Eq)
initEval = ES [] 0
-- VALUES (as HOAS) ---------------------------------------------------------
-- | A HOAS representation of values
data Value = VP NameType Name Value
| VV Int
-- True for Bool indicates safe to reduce
| VBind Bool Name (Binder Value) (Value -> Eval Value)
-- For frozen let bindings when simplifying
| VBLet Int Name Value Value Value
| VApp Value Value
| VType UExp
| VErased
| VImpossible
| VConstant Const
| VProj Value Int
-- | VLazy Env [Value] Term
| VTmp Int
instance Show Value where
show x = show $ evalState (quote 100 x) initEval
instance Show (a -> b) where
show x = "<<fn>>"
-- THE EVALUATOR ------------------------------------------------------------
-- The environment is assumed to be "locally named" - i.e., not de Bruijn
-- indexed.
-- i.e. it's an intermediate environment that we have while type checking or
-- while building a proof.
-- | Normalise fully type checked terms (so, assume all names/let bindings resolved)
normaliseC :: Context -> Env -> TT Name -> TT Name
normaliseC ctxt env t
= evalState (do val <- eval False ctxt [] env t []
quote 0 val) initEval
normaliseAll :: Context -> Env -> TT Name -> TT Name
normaliseAll ctxt env t
= evalState (do val <- eval False ctxt [] env t [AtREPL]
quote 0 val) initEval
normalise :: Context -> Env -> TT Name -> TT Name
normalise = normaliseTrace False
normaliseTrace :: Bool -> Context -> Env -> TT Name -> TT Name
normaliseTrace tr ctxt env t
= evalState (do val <- eval tr ctxt [] (map finalEntry env) (finalise t) []
quote 0 val) initEval
specialise :: Context -> Env -> [(Name, Int)] -> TT Name -> TT Name
specialise ctxt env limits t
= evalState (do val <- eval False ctxt []
(map finalEntry env) (finalise t)
[Spec]
quote 0 val) (initEval { limited = limits })
-- | Like normalise, but we only reduce functions that are marked as okay to
-- inline (and probably shouldn't reduce lets?)
-- 20130908: now only used to reduce for totality checking. Inlining should
-- be done elsewhere.
simplify :: Context -> Env -> TT Name -> TT Name
simplify ctxt env t
= evalState (do val <- eval False ctxt [(sUN "lazy", 0),
(sUN "assert_smaller", 0),
(sUN "par", 0),
(sUN "prim__syntactic_eq", 0),
(sUN "fork", 0)]
(map finalEntry env) (finalise t)
[Simplify]
quote 0 val) initEval
-- | Simplify for run-time (i.e. basic inlining)
rt_simplify :: Context -> Env -> TT Name -> TT Name
rt_simplify ctxt env t
= evalState (do val <- eval False ctxt [(sUN "lazy", 0),
(sUN "assert_smaller", 0),
(sUN "par", 0),
(sUN "prim__syntactic_eq", 0),
(sUN "prim_fork", 0)]
(map finalEntry env) (finalise t)
[RunTT]
quote 0 val) initEval
-- | Reduce a term to head normal form
hnf :: Context -> Env -> TT Name -> TT Name
hnf ctxt env t
= evalState (do val <- eval False ctxt []
(map finalEntry env)
(finalise t) [HNF]
quote 0 val) initEval
-- unbindEnv env (quote 0 (eval ctxt (bindEnv env t)))
finalEntry :: (Name, Binder (TT Name)) -> (Name, Binder (TT Name))
finalEntry (n, b) = (n, fmap finalise b)
bindEnv :: EnvTT n -> TT n -> TT n
bindEnv [] tm = tm
bindEnv ((n, Let t v):bs) tm = Bind n (NLet t v) (bindEnv bs tm)
bindEnv ((n, b):bs) tm = Bind n b (bindEnv bs tm)
unbindEnv :: EnvTT n -> TT n -> TT n
unbindEnv [] tm = tm
unbindEnv (_:bs) (Bind n b sc) = unbindEnv bs sc
usable :: Bool -- specialising
-> Name -> [(Name, Int)] -> Eval (Bool, [(Name, Int)])
-- usable _ _ ns@((MN 0 "STOP", _) : _) = return (False, ns)
usable False n [] = return (True, [])
usable True n ns
= do ES ls num <- get
case lookup n ls of
Just 0 -> return (False, ns)
Just i -> return (True, ns)
_ -> return (False, ns)
usable False n ns
= case lookup n ns of
Just 0 -> return (False, ns)
Just i -> return $ (True, (n, abs (i-1)) : filter (\ (n', _) -> n/=n') ns)
_ -> return $ (True, (n, 100) : filter (\ (n', _) -> n/=n') ns)
deduct :: Name -> Eval ()
deduct n = do ES ls num <- get
case lookup n ls of
Just i -> do put $ ES ((n, (i-1)) :
filter (\ (n', _) -> n/=n') ls) num
_ -> return ()
-- | Evaluate in a context of locally named things (i.e. not de Bruijn indexed,
-- such as we might have during construction of a proof)
-- The (Name, Int) pair in the arguments is the maximum depth of unfolding of
-- a name. The corresponding pair in the state is the maximum number of
-- unfoldings overall.
eval :: Bool -> Context -> [(Name, Int)] -> Env -> TT Name ->
[EvalOpt] -> Eval Value
eval traceon ctxt ntimes genv tm opts = ev ntimes [] True [] tm where
spec = Spec `elem` opts
simpl = Simplify `elem` opts
runtime = RunTT `elem` opts
atRepl = AtREPL `elem` opts
hnf = HNF `elem` opts
-- returns 'True' if the function should block
-- normal evaluation should return false
blockSimplify (CaseInfo inl dict) n stk
| RunTT `elem` opts
= not (inl || dict) || elem n stk
| Simplify `elem` opts
= (not (inl || dict) || elem n stk)
|| (n == sUN "prim__syntactic_eq")
| otherwise = False
getCases cd | simpl = cases_totcheck cd
| runtime = cases_runtime cd
| otherwise = cases_compiletime cd
ev ntimes stk top env (P _ n ty)
| Just (Let t v) <- lookup n genv = ev ntimes stk top env v
ev ntimes_in stk top env (P Ref n ty)
| not top && hnf = liftM (VP Ref n) (ev ntimes stk top env ty)
| otherwise
= do (u, ntimes) <- usable spec n ntimes_in
if u then
do let val = lookupDefAcc n (spec || atRepl) ctxt
case val of
[(Function _ tm, Public)] ->
ev ntimes (n:stk) True env tm
[(Function _ tm, Hidden)] ->
ev ntimes (n:stk) True env tm
[(TyDecl nt ty, _)] -> do vty <- ev ntimes stk True env ty
return $ VP nt n vty
[(CaseOp ci _ _ _ _ cd, acc)]
| (acc /= Frozen) &&
null (fst (cases_totcheck cd)) -> -- unoptimised version
let (ns, tree) = getCases cd in
if blockSimplify ci n stk
then liftM (VP Ref n) (ev ntimes stk top env ty)
else -- traceWhen runtime (show (n, ns, tree)) $
do c <- evCase ntimes n (n:stk) top env ns [] tree
case c of
(Nothing, _) -> liftM (VP Ref n) (ev ntimes stk top env ty)
(Just v, _) -> return v
_ -> liftM (VP Ref n) (ev ntimes stk top env ty)
else liftM (VP Ref n) (ev ntimes stk top env ty)
ev ntimes stk top env (P nt n ty)
= liftM (VP nt n) (ev ntimes stk top env ty)
ev ntimes stk top env (V i)
| i < length env && i >= 0 = return $ snd (env !! i)
| otherwise = return $ VV i
ev ntimes stk top env (Bind n (Let t v) sc)
= do v' <- ev ntimes stk top env v --(finalise v)
sc' <- ev ntimes stk top ((n, v') : env) sc
wknV (-1) sc'
-- | otherwise
-- = do t' <- ev ntimes stk top env t
-- v' <- ev ntimes stk top env v --(finalise v)
-- -- use Tmp as a placeholder, then make it a variable reference
-- -- again when evaluation finished
-- hs <- get
-- let vd = nexthole hs
-- put (hs { nexthole = vd + 1 })
-- sc' <- ev ntimes stk top (VP Bound (MN vd "vlet") VErased : env) sc
-- return $ VBLet vd n t' v' sc'
ev ntimes stk top env (Bind n (NLet t v) sc)
= do t' <- ev ntimes stk top env (finalise t)
v' <- ev ntimes stk top env (finalise v)
sc' <- ev ntimes stk top ((n, v') : env) sc
return $ VBind True n (Let t' v') (\x -> return sc')
ev ntimes stk top env (Bind n b sc)
= do b' <- vbind env b
let n' = uniqueName n (map fst env)
return $ VBind True -- (vinstances 0 sc < 2)
n' b' (\x -> ev ntimes stk False ((n, x):env) sc)
where vbind env t
-- | simpl
-- = fmapMB (\tm -> ev ((MN 0 "STOP", 0) : ntimes)
-- stk top env (finalise tm)) t
-- | otherwise
= fmapMB (\tm -> ev ntimes stk top env (finalise tm)) t
ev ntimes stk top env (App f a)
= do f' <- ev ntimes stk False env f
a' <- ev ntimes stk False env a
evApply ntimes stk top env [a'] f'
ev ntimes stk top env (Proj t i)
= do -- evaluate dictionaries if it means the projection works
t' <- ev ntimes stk top env t
-- tfull' <- reapply ntimes stk top env t' []
return (doProj t' (getValArgs t'))
where doProj t' (VP (DCon _ _) _ _, args)
| i >= 0 && i < length args = args!!i
doProj t' _ = VProj t' i
ev ntimes stk top env (Constant c) = return $ VConstant c
ev ntimes stk top env Erased = return VErased
ev ntimes stk top env Impossible = return VImpossible
ev ntimes stk top env (TType i) = return $ VType i
evApply ntimes stk top env args (VApp f a)
= evApply ntimes stk top env (a:args) f
evApply ntimes stk top env args f
= apply ntimes stk top env f args
reapply ntimes stk top env f@(VP Ref n ty) args
= let val = lookupDefAcc n (spec || atRepl) ctxt in
case val of
[(CaseOp ci _ _ _ _ cd, acc)] ->
let (ns, tree) = getCases cd in
do c <- evCase ntimes n (n:stk) top env ns args tree
case c of
(Nothing, _) -> return $ unload env (VP Ref n ty) args
(Just v, rest) -> evApply ntimes stk top env rest v
_ -> case args of
(a : as) -> return $ unload env f (a : as)
[] -> return f
reapply ntimes stk top env (VApp f a) args
= reapply ntimes stk top env f (a : args)
reapply ntimes stk top env v args = return v
apply ntimes stk top env (VBind True n (Lam t) sc) (a:as)
= do a' <- sc a
app <- apply ntimes stk top env a' as
wknV (-1) app
apply ntimes_in stk top env f@(VP Ref n ty) args
| not top && hnf = case args of
[] -> return f
_ -> return $ unload env f args
| otherwise
= do (u, ntimes) <- usable spec n ntimes_in
if u then
do let val = lookupDefAcc n (spec || atRepl) ctxt
case val of
[(CaseOp ci _ _ _ _ cd, acc)]
| acc /= Frozen -> -- unoptimised version
let (ns, tree) = getCases cd in
if blockSimplify ci n stk
then return $ unload env (VP Ref n ty) args
else -- traceWhen runtime (show (n, ns, tree)) $
do c <- evCase ntimes n (n:stk) top env ns args tree
case c of
(Nothing, _) -> return $ unload env (VP Ref n ty) args
(Just v, rest) -> evApply ntimes stk top env rest v
[(Operator _ i op, _)] ->
if (i <= length args)
then case op (take i args) of
Nothing -> return $ unload env (VP Ref n ty) args
Just v -> evApply ntimes stk top env (drop i args) v
else return $ unload env (VP Ref n ty) args
_ -> case args of
[] -> return f
_ -> return $ unload env f args
else case args of
(a : as) -> return $ unload env f (a:as)
[] -> return f
apply ntimes stk top env f (a:as) = return $ unload env f (a:as)
apply ntimes stk top env f [] = return f
-- specApply stk env f@(VP Ref n ty) args
-- = case lookupCtxt n statics of
-- [as] -> if or as
-- then trace (show (n, map fst (filter (\ (_, s) -> s) (zip args as)))) $
-- return $ unload env f args
-- else return $ unload env f args
-- _ -> return $ unload env f args
-- specApply stk env f args = return $ unload env f args
unload :: [(Name, Value)] -> Value -> [Value] -> Value
unload env f [] = f
unload env f (a:as) = unload env (VApp f a) as
evCase ntimes n stk top env ns args tree
| length ns <= length args
= do let args' = take (length ns) args
let rest = drop (length ns) args
when spec $ deduct n -- successful, so deduct usages
t <- evTree ntimes stk top env (zip ns args') tree
-- (zipWith (\n , t) -> (n, t)) ns args') tree
return (t, rest)
| otherwise = return (Nothing, args)
evTree :: [(Name, Int)] -> [Name] -> Bool ->
[(Name, Value)] -> [(Name, Value)] -> SC -> Eval (Maybe Value)
evTree ntimes stk top env amap (UnmatchedCase str) = return Nothing
evTree ntimes stk top env amap (STerm tm)
= do let etm = pToVs (map fst amap) tm
etm' <- ev ntimes stk (not (conHeaded tm))
(amap ++ env) etm
return $ Just etm'
evTree ntimes stk top env amap (ProjCase t alts)
= do t' <- ev ntimes stk top env t
doCase ntimes stk top env amap t' alts
evTree ntimes stk top env amap (Case n alts)
= case lookup n amap of
Just v -> doCase ntimes stk top env amap v alts
_ -> return Nothing
evTree ntimes stk top env amap ImpossibleCase = return Nothing
doCase ntimes stk top env amap v alts =
do c <- chooseAlt env v (getValArgs v) alts amap
case c of
Just (altmap, sc) -> evTree ntimes stk top env altmap sc
_ -> do c' <- chooseAlt' ntimes stk env v (getValArgs v) alts amap
case c' of
Just (altmap, sc) -> evTree ntimes stk top env altmap sc
_ -> return Nothing
conHeaded tm@(App _ _)
| (P (DCon _ _) _ _, args) <- unApply tm = True
conHeaded t = False
chooseAlt' ntimes stk env _ (f, args) alts amap
= do f' <- apply ntimes stk True env f args
chooseAlt env f' (getValArgs f')
alts amap
chooseAlt :: [(Name, Value)] -> Value -> (Value, [Value]) -> [CaseAlt] ->
[(Name, Value)] ->
Eval (Maybe ([(Name, Value)], SC))
chooseAlt env _ (VP (DCon i a) _ _, args) alts amap
| Just (ns, sc) <- findTag i alts = return $ Just (updateAmap (zip ns args) amap, sc)
| Just v <- findDefault alts = return $ Just (amap, v)
chooseAlt env _ (VP (TCon i a) _ _, args) alts amap
| Just (ns, sc) <- findTag i alts
= return $ Just (updateAmap (zip ns args) amap, sc)
| Just v <- findDefault alts = return $ Just (amap, v)
chooseAlt env _ (VConstant c, []) alts amap
| Just v <- findConst c alts = return $ Just (amap, v)
| Just (n', sub, sc) <- findSuc c alts
= return $ Just (updateAmap [(n',sub)] amap, sc)
| Just v <- findDefault alts = return $ Just (amap, v)
chooseAlt env _ (VP _ n _, args) alts amap
| Just (ns, sc) <- findFn n alts = return $ Just (updateAmap (zip ns args) amap, sc)
chooseAlt env _ (VBind _ _ (Pi s) t, []) alts amap
| Just (ns, sc) <- findFn (sUN "->") alts
= do t' <- t (VV 0) -- we know it's not in scope or it's not a pattern
return $ Just (updateAmap (zip ns [s, t']) amap, sc)
chooseAlt _ _ _ alts amap
| Just v <- findDefault alts
= if (any fnCase alts)
then return $ Just (amap, v)
else return Nothing
| otherwise = return Nothing
fnCase (FnCase _ _ _) = True
fnCase _ = False
-- Replace old variable names in the map with new matches
-- (This is possibly unnecessary since we make unique names and don't
-- allow repeated variables...?)
updateAmap newm amap
= newm ++ filter (\ (x, _) -> not (elem x (map fst newm))) amap
findTag i [] = Nothing
findTag i (ConCase n j ns sc : xs) | i == j = Just (ns, sc)
findTag i (_ : xs) = findTag i xs
findFn fn [] = Nothing
findFn fn (FnCase n ns sc : xs) | fn == n = Just (ns, sc)
findFn fn (_ : xs) = findFn fn xs
findDefault [] = Nothing
findDefault (DefaultCase sc : xs) = Just sc
findDefault (_ : xs) = findDefault xs
findSuc c [] = Nothing
findSuc (BI val) (SucCase n sc : _)
| val /= 0 = Just (n, VConstant (BI (val - 1)), sc)
findSuc c (_ : xs) = findSuc c xs
findConst c [] = Nothing
findConst c (ConstCase c' v : xs) | c == c' = Just v
findConst (AType (ATInt ITNative)) (ConCase n 1 [] v : xs) = Just v
findConst (AType ATFloat) (ConCase n 2 [] v : xs) = Just v
findConst (AType (ATInt ITChar)) (ConCase n 3 [] v : xs) = Just v
findConst StrType (ConCase n 4 [] v : xs) = Just v
findConst PtrType (ConCase n 5 [] v : xs) = Just v
findConst (AType (ATInt ITBig)) (ConCase n 6 [] v : xs) = Just v
findConst (AType (ATInt (ITFixed ity))) (ConCase n tag [] v : xs)
| tag == 7 + fromEnum ity = Just v
findConst (AType (ATInt (ITVec ity count))) (ConCase n tag [] v : xs)
| tag == (fromEnum ity + 1) * 1000 + count = Just v
findConst c (_ : xs) = findConst c xs
getValArgs tm = getValArgs' tm []
getValArgs' (VApp f a) as = getValArgs' f (a:as)
getValArgs' f as = (f, as)
-- tmpToV i vd (VLetHole j) | vd == j = return $ VV i
-- tmpToV i vd (VP nt n v) = liftM (VP nt n) (tmpToV i vd v)
-- tmpToV i vd (VBind n b sc) = do b' <- fmapMB (tmpToV i vd) b
-- let sc' = \x -> do x' <- sc x
-- tmpToV (i + 1) vd x'
-- return (VBind n b' sc')
-- tmpToV i vd (VApp f a) = liftM2 VApp (tmpToV i vd f) (tmpToV i vd a)
-- tmpToV i vd x = return x
instance Eq Value where
(==) x y = getTT x == getTT y
where getTT v = evalState (quote 0 v) initEval
class Quote a where
quote :: Int -> a -> Eval (TT Name)
instance Quote Value where
quote i (VP nt n v) = liftM (P nt n) (quote i v)
quote i (VV x) = return $ V x
quote i (VBind _ n b sc) = do sc' <- sc (VTmp i)
b' <- quoteB b
liftM (Bind n b') (quote (i+1) sc')
where quoteB t = fmapMB (quote i) t
quote i (VBLet vd n t v sc)
= do sc' <- quote i sc
t' <- quote i t
v' <- quote i v
let sc'' = pToV (sMN vd "vlet") (addBinder sc')
return (Bind n (Let t' v') sc'')
quote i (VApp f a) = liftM2 App (quote i f) (quote i a)
quote i (VType u) = return $ TType u
quote i VErased = return $ Erased
quote i VImpossible = return $ Impossible
quote i (VProj v j) = do v' <- quote i v
return (Proj v' j)
quote i (VConstant c) = return $ Constant c
quote i (VTmp x) = return $ V (i - x - 1)
wknV :: Int -> Value -> Eval Value
wknV i (VV x) = return $ VV (x + i)
wknV i (VBind red n b sc) = do b' <- fmapMB (wknV i) b
return $ VBind red n b' (\x -> do x' <- sc x
wknV i x')
wknV i (VApp f a) = liftM2 VApp (wknV i f) (wknV i a)
wknV i t = return t
convEq' ctxt x y = evalStateT (convEq ctxt x y) (0, [])
convEq :: Context -> TT Name -> TT Name -> StateT UCs (TC' Err) Bool
convEq ctxt = ceq [] where
ceq :: [(Name, Name)] -> TT Name -> TT Name -> StateT UCs (TC' Err) Bool
ceq ps (P xt x _) (P yt y _)
| x == y || (x, y) `elem` ps || (y,x) `elem` ps = return True
| otherwise = sameDefs ps x y
ceq ps x (Bind n (Lam t) (App y (V 0))) = ceq ps x y
ceq ps (Bind n (Lam t) (App x (V 0))) y = ceq ps x y
ceq ps x (Bind n (Lam t) (App y (P Bound n' _)))
| n == n' = ceq ps x y
ceq ps (Bind n (Lam t) (App x (P Bound n' _))) y
| n == n' = ceq ps x y
ceq ps (V x) (V y) = return (x == y)
ceq ps (Bind _ xb xs) (Bind _ yb ys)
= liftM2 (&&) (ceqB ps xb yb) (ceq ps xs ys)
where
ceqB ps (Let v t) (Let v' t') = liftM2 (&&) (ceq ps v v') (ceq ps t t')
ceqB ps (Guess v t) (Guess v' t') = liftM2 (&&) (ceq ps v v') (ceq ps t t')
ceqB ps b b' = ceq ps (binderTy b) (binderTy b')
ceq ps (App fx ax) (App fy ay) = liftM2 (&&) (ceq ps fx fy) (ceq ps ax ay)
ceq ps (Constant x) (Constant y) = return (x == y)
ceq ps (TType x) (TType y) = do (v, cs) <- get
put (v, ULE x y : cs)
return True
ceq ps Erased _ = return True
ceq ps _ Erased = return True
ceq ps _ _ = return False
caseeq ps (Case n cs) (Case n' cs') = caseeqA ((n,n'):ps) cs cs'
where
caseeqA ps (ConCase x i as sc : rest) (ConCase x' i' as' sc' : rest')
= do q1 <- caseeq (zip as as' ++ ps) sc sc'
q2 <- caseeqA ps rest rest'
return $ x == x' && i == i' && q1 && q2
caseeqA ps (ConstCase x sc : rest) (ConstCase x' sc' : rest')
= do q1 <- caseeq ps sc sc'
q2 <- caseeqA ps rest rest'
return $ x == x' && q1 && q2
caseeqA ps (DefaultCase sc : rest) (DefaultCase sc' : rest')
= liftM2 (&&) (caseeq ps sc sc') (caseeqA ps rest rest')
caseeqA ps [] [] = return True
caseeqA ps _ _ = return False
caseeq ps (STerm x) (STerm y) = ceq ps x y
caseeq ps (UnmatchedCase _) (UnmatchedCase _) = return True
caseeq ps _ _ = return False
sameDefs ps x y = case (lookupDef x ctxt, lookupDef y ctxt) of
([Function _ xdef], [Function _ ydef])
-> ceq ((x,y):ps) xdef ydef
([CaseOp _ _ _ _ _ xd],
[CaseOp _ _ _ _ _ yd])
-> let (_, xdef) = cases_compiletime xd
(_, ydef) = cases_compiletime yd in
caseeq ((x,y):ps) xdef ydef
_ -> return False
-- SPECIALISATION -----------------------------------------------------------
-- We need too much control to be able to do this by tweaking the main
-- evaluator
spec :: Context -> Ctxt [Bool] -> Env -> TT Name -> Eval (TT Name)
spec ctxt statics genv tm = error "spec undefined"
-- CONTEXTS -----------------------------------------------------------------
{-| A definition is either a simple function (just an expression with a type),
a constant, which could be a data or type constructor, an axiom or as an
yet undefined function, or an Operator.
An Operator is a function which explains how to reduce.
A CaseOp is a function defined by a simple case tree -}
data Def = Function !Type !Term
| TyDecl NameType !Type
| Operator Type Int ([Value] -> Maybe Value)
| CaseOp CaseInfo
!Type
![Type] -- argument types
![Either Term (Term, Term)] -- original definition
![([Name], Term, Term)] -- simplified for totality check definition
!CaseDefs
-- [Name] SC -- Compile time case definition
-- [Name] SC -- Run time cae definitions
data CaseDefs = CaseDefs {
cases_totcheck :: !([Name], SC),
cases_compiletime :: !([Name], SC),
cases_inlined :: !([Name], SC),
cases_runtime :: !([Name], SC)
}
data CaseInfo = CaseInfo {
case_inlinable :: Bool,
tc_dictionary :: Bool
}
{-!
deriving instance Binary Def
!-}
{-!
deriving instance Binary CaseInfo
!-}
{-!
deriving instance Binary CaseDefs
!-}
instance Show Def where
show (Function ty tm) = "Function: " ++ show (ty, tm)
show (TyDecl nt ty) = "TyDecl: " ++ show nt ++ " " ++ show ty
show (Operator ty _ _) = "Operator: " ++ show ty
show (CaseOp (CaseInfo inlc inlr) ty atys ps_in ps cd)
= let (ns, sc) = cases_compiletime cd
(ns_t, sc_t) = cases_totcheck cd
(ns', sc') = cases_runtime cd in
"Case: " ++ show ty ++ " " ++ show ps ++ "\n" ++
"TOTALITY CHECK TIME:\n\n" ++
show ns_t ++ " " ++ show sc_t ++ "\n\n" ++
"COMPILE TIME:\n\n" ++
show ns ++ " " ++ show sc ++ "\n\n" ++
"RUN TIME:\n\n" ++
show ns' ++ " " ++ show sc' ++ "\n\n" ++
if inlc then "Inlinable\n" else "Not inlinable\n"
-------
-- Frozen => doesn't reduce
-- Hidden => doesn't reduce and invisible to type checker
data Accessibility = Public | Frozen | Hidden
deriving (Show, Eq)
-- | The result of totality checking
data Totality = Total [Int] -- ^ well-founded arguments
| Productive -- ^ productive
| Partial PReason
| Unchecked
deriving Eq
-- | Reasons why a function may not be total
data PReason = Other [Name] | Itself | NotCovering | NotPositive | UseUndef Name
| BelieveMe | Mutual [Name] | NotProductive
deriving (Show, Eq)
instance Show Totality where
show (Total args)= "Total" -- ++ show args ++ " decreasing arguments"
show Productive = "Productive" -- ++ show args ++ " decreasing arguments"
show Unchecked = "not yet checked for totality"
show (Partial Itself) = "possibly not total as it is not well founded"
show (Partial NotCovering) = "not total as there are missing cases"
show (Partial NotPositive) = "not strictly positive"
show (Partial NotProductive) = "not productive"
show (Partial BelieveMe) = "not total due to use of believe_me in proof"
show (Partial (Other ns)) = "possibly not total due to: " ++ showSep ", " (map show ns)
show (Partial (Mutual ns)) = "possibly not total due to recursive path " ++
showSep " --> " (map show ns)
{-!
deriving instance Binary Accessibility
!-}
{-!
deriving instance Binary Totality
!-}
{-!
deriving instance Binary PReason
!-}
-- Possible attached meta-information for a definition in context
data MetaInformation =
EmptyMI -- ^ No meta-information
| DataMI [Int] -- ^ Meta information for a data declaration with position of parameters
deriving (Eq, Show)
-- | Contexts used for global definitions and for proof state. They contain
-- universe constraints and existing definitions.
data Context = MkContext {
uconstraints :: [UConstraint],
next_tvar :: Int,
definitions :: Ctxt (Def, Accessibility, Totality, MetaInformation)
} deriving Show
-- | The initial empty context
initContext = MkContext [] 0 emptyContext
mapDefCtxt :: (Def -> Def) -> Context -> Context
mapDefCtxt f (MkContext c t defs) = MkContext c t (mapCtxt f' defs)
where f' (d, a, t, m) = f' (f d, a, t, m)
-- | Get the definitions from a context
ctxtAlist :: Context -> [(Name, Def)]
ctxtAlist ctxt = map (\(n, (d, a, t, m)) -> (n, d)) $ toAlist (definitions ctxt)
veval ctxt env t = evalState (eval False ctxt [] env t []) initEval
addToCtxt :: Name -> Term -> Type -> Context -> Context
addToCtxt n tm ty uctxt
= let ctxt = definitions uctxt
ctxt' = addDef n (Function ty tm, Public, Unchecked, EmptyMI) ctxt in
uctxt { definitions = ctxt' }
setAccess :: Name -> Accessibility -> Context -> Context
setAccess n a uctxt
= let ctxt = definitions uctxt
ctxt' = updateDef n (\ (d, _, t, m) -> (d, a, t, m)) ctxt in
uctxt { definitions = ctxt' }
setTotal :: Name -> Totality -> Context -> Context
setTotal n t uctxt
= let ctxt = definitions uctxt
ctxt' = updateDef n (\ (d, a, _, m) -> (d, a, t, m)) ctxt in
uctxt { definitions = ctxt' }
setMetaInformation :: Name -> MetaInformation -> Context -> Context
setMetaInformation n m uctxt
= let ctxt = definitions uctxt
ctxt' = updateDef n (\ (d, a, t, _) -> (d, a, t, m)) ctxt in
uctxt { definitions = ctxt' }
addCtxtDef :: Name -> Def -> Context -> Context
addCtxtDef n d c = let ctxt = definitions c
ctxt' = addDef n (d, Public, Unchecked, EmptyMI) $! ctxt in
c { definitions = ctxt' }
addTyDecl :: Name -> NameType -> Type -> Context -> Context
addTyDecl n nt ty uctxt
= let ctxt = definitions uctxt
ctxt' = addDef n (TyDecl nt ty, Public, Unchecked, EmptyMI) ctxt in
uctxt { definitions = ctxt' }
addDatatype :: Datatype Name -> Context -> Context
addDatatype (Data n tag ty cons) uctxt
= let ctxt = definitions uctxt
ty' = normalise uctxt [] ty
ctxt' = addCons 0 cons (addDef n
(TyDecl (TCon tag (arity ty')) ty, Public, Unchecked, EmptyMI) ctxt) in
uctxt { definitions = ctxt' }
where
addCons tag [] ctxt = ctxt
addCons tag ((n, ty) : cons) ctxt
= let ty' = normalise uctxt [] ty in
addCons (tag+1) cons (addDef n
(TyDecl (DCon tag (arity ty')) ty, Public, Unchecked, EmptyMI) ctxt)
-- FIXME: Too many arguments! Refactor all these Bools.
addCasedef :: Name -> CaseInfo -> Bool -> Bool -> Bool -> Bool ->
[Type] -> -- argument types
[Either Term (Term, Term)] ->
[([Name], Term, Term)] -> -- totality
[([Name], Term, Term)] -> -- compile time
[([Name], Term, Term)] -> -- inlined
[([Name], Term, Term)] -> -- run time
Type -> Context -> Context
addCasedef n ci@(CaseInfo alwaysInline tcdict)
tcase covering reflect asserted argtys
ps_in ps_tot ps_inl ps_ct ps_rt ty uctxt
= let ctxt = definitions uctxt
access = case lookupDefAcc n False uctxt of
[(_, acc)] -> acc
_ -> Public
ctxt' = case (simpleCase tcase covering reflect CompileTime emptyFC argtys ps_tot,
simpleCase tcase covering reflect CompileTime emptyFC argtys ps_ct,
simpleCase tcase covering reflect CompileTime emptyFC argtys ps_inl,
simpleCase tcase covering reflect RunTime emptyFC argtys ps_rt) of
(OK (CaseDef args_tot sc_tot _),
OK (CaseDef args_ct sc_ct _),
OK (CaseDef args_inl sc_inl _),
OK (CaseDef args_rt sc_rt _)) ->
let inl = alwaysInline -- tcdict
inlc = (inl || small n args_ct sc_ct) && (not asserted)
inlr = inl || small n args_rt sc_rt
cdef = CaseDefs (args_tot, sc_tot)
(args_ct, sc_ct)
(args_inl, sc_inl)
(args_rt, sc_rt) in
addDef n (CaseOp (ci { case_inlinable = inlc })
ty argtys ps_in ps_tot cdef,
access, Unchecked, EmptyMI) ctxt in
uctxt { definitions = ctxt' }
-- simplify a definition for totality checking
simplifyCasedef :: Name -> Context -> Context
simplifyCasedef n uctxt
= let ctxt = definitions uctxt
ctxt' = case lookupCtxt n ctxt of
[(CaseOp ci ty atys [] ps _, acc, tot, metainf)] ->
ctxt -- nothing to simplify (or already done...)
[(CaseOp ci ty atys ps_in ps cd, acc, tot, metainf)] ->
let ps_in' = map simpl ps_in
pdef = map debind ps_in' in
case simpleCase False True False CompileTime emptyFC atys pdef of
OK (CaseDef args sc _) ->
addDef n (CaseOp ci
ty atys ps_in' ps (cd { cases_totcheck = (args, sc) }),
acc, tot, metainf) ctxt
Error err -> error (show err)
_ -> ctxt in
uctxt { definitions = ctxt' }
where
depat acc (Bind n (PVar t) sc)
= depat (n : acc) (instantiate (P Bound n t) sc)
depat acc x = (acc, x)
debind (Right (x, y)) = let (vs, x') = depat [] x
(_, y') = depat [] y in
(vs, x', y')
debind (Left x) = let (vs, x') = depat [] x in
(vs, x', Impossible)
simpl (Right (x, y)) = Right (x, simplify uctxt [] y)
simpl t = t
addOperator :: Name -> Type -> Int -> ([Value] -> Maybe Value) ->
Context -> Context
addOperator n ty a op uctxt
= let ctxt = definitions uctxt
ctxt' = addDef n (Operator ty a op, Public, Unchecked, EmptyMI) ctxt in
uctxt { definitions = ctxt' }
tfst (a, _, _, _) = a
lookupNames :: Name -> Context -> [Name]
lookupNames n ctxt
= let ns = lookupCtxtName n (definitions ctxt) in
map fst ns
lookupTy :: Name -> Context -> [Type]
lookupTy n ctxt
= do def <- lookupCtxt n (definitions ctxt)
case tfst def of
(Function ty _) -> return ty
(TyDecl _ ty) -> return ty
(Operator ty _ _) -> return ty
(CaseOp _ ty _ _ _ _) -> return ty
isConName :: Name -> Context -> Bool
isConName n ctxt = isTConName n ctxt || isDConName n ctxt
isTConName :: Name -> Context -> Bool
isTConName n ctxt
= or $ do def <- lookupCtxt n (definitions ctxt)
case tfst def of
(TyDecl (TCon _ _) _) -> return True
_ -> return False
isDConName :: Name -> Context -> Bool
isDConName n ctxt
= or $ do def <- lookupCtxt n (definitions ctxt)
case tfst def of
(TyDecl (DCon _ _) _) -> return True
_ -> return False
isFnName :: Name -> Context -> Bool
isFnName n ctxt
= or $ do def <- lookupCtxt n (definitions ctxt)
case tfst def of
(Function _ _) -> return True
(Operator _ _ _) -> return True
(CaseOp _ _ _ _ _ _) -> return True
_ -> return False
lookupP :: Name -> Context -> [Term]
lookupP n ctxt
= do def <- lookupCtxt n (definitions ctxt)
p <- case def of
(Function ty tm, a, _, _) -> return (P Ref n ty, a)
(TyDecl nt ty, a, _, _) -> return (P nt n ty, a)
(CaseOp _ ty _ _ _ _, a, _, _) -> return (P Ref n ty, a)
(Operator ty _ _, a, _, _) -> return (P Ref n ty, a)
case snd p of
Hidden -> []
_ -> return (fst p)
lookupDef :: Name -> Context -> [Def]
lookupDef n ctxt = map tfst $ lookupCtxt n (definitions ctxt)
lookupDefAcc :: Name -> Bool -> Context ->
[(Def, Accessibility)]
lookupDefAcc n mkpublic ctxt
= map mkp $ lookupCtxt n (definitions ctxt)
-- io_bind a special case for REPL prettiness
where mkp (d, a, _, _) = if mkpublic && (not (n == sUN "io_bind" || n == sUN "io_return"))
then (d, Public) else (d, a)
lookupTotal :: Name -> Context -> [Totality]
lookupTotal n ctxt = map mkt $ lookupCtxt n (definitions ctxt)
where mkt (d, a, t, m) = t
lookupMetaInformation :: Name -> Context -> [MetaInformation]
lookupMetaInformation n ctxt = map mkm $ lookupCtxt n (definitions ctxt)
where mkm (d, a, t, m) = m
lookupNameTotal :: Name -> Context -> [(Name, Totality)]
lookupNameTotal n = map (\(n, (_, _, t, _)) -> (n, t)) . lookupCtxtName n . definitions
lookupVal :: Name -> Context -> [Value]
lookupVal n ctxt
= do def <- lookupCtxt n (definitions ctxt)
case tfst def of
(Function _ htm) -> return (veval ctxt [] htm)
(TyDecl nt ty) -> return (VP nt n (veval ctxt [] ty))
lookupTyEnv :: Name -> Env -> Maybe (Int, Type)
lookupTyEnv n env = li n 0 env where
li n i [] = Nothing
li n i ((x, b): xs)
| n == x = Just (i, binderTy b)
| otherwise = li n (i+1) xs
-- | Create a unique name given context and other existing names
uniqueNameCtxt :: Context -> Name -> [Name] -> Name
uniqueNameCtxt ctxt n hs
| n `elem` hs = uniqueNameCtxt ctxt (nextName n) hs
| [_] <- lookupTy n ctxt = uniqueNameCtxt ctxt (nextName n) hs
| otherwise = n
|
ctford/Idris-Elba-dev
|
src/Idris/Core/Evaluate.hs
|
Haskell
|
bsd-3-clause
| 40,466
|
{-| Implementation of the primitives of instance allocation
-}
{-
Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.HTools.Cluster.AllocatePrimitives
( allocateOnSingle
, allocateOnPair
) where
import Ganeti.HTools.AlgorithmParams (AlgorithmOptions(..))
import Ganeti.HTools.Cluster.AllocationSolution (AllocElement)
import Ganeti.HTools.Cluster.Metrics ( compCV, compCVfromStats
, updateClusterStatisticsTwice)
import Ganeti.HTools.Cluster.Moves (setInstanceLocationScore)
import qualified Ganeti.HTools.Container as Container
import qualified Ganeti.HTools.Instance as Instance
import qualified Ganeti.HTools.Node as Node
import Ganeti.HTools.Types
import Ganeti.Utils.Statistics
-- | Tries to allocate an instance on one given node.
allocateOnSingle :: AlgorithmOptions
-> Node.List -> Instance.Instance -> Ndx
-> OpResult AllocElement
allocateOnSingle opts nl inst new_pdx =
let p = Container.find new_pdx nl
new_inst = Instance.setBoth inst new_pdx Node.noSecondary
force = algIgnoreSoftErrors opts
in do
Instance.instMatchesPolicy inst (Node.iPolicy p) (Node.exclStorage p)
new_p <- Node.addPriEx force p inst
let new_nl = Container.add new_pdx new_p nl
new_score = compCV new_nl
return (new_nl, new_inst, [new_p], new_score)
-- | Tries to allocate an instance on a given pair of nodes.
allocateOnPair :: AlgorithmOptions
-> [Statistics]
-> Node.List -> Instance.Instance -> Ndx -> Ndx
-> OpResult AllocElement
allocateOnPair opts stats nl inst new_pdx new_sdx =
let tgt_p = Container.find new_pdx nl
tgt_s = Container.find new_sdx nl
force = algIgnoreSoftErrors opts
in do
Instance.instMatchesPolicy inst (Node.iPolicy tgt_p)
(Node.exclStorage tgt_p)
let new_inst = Instance.setBoth (setInstanceLocationScore inst tgt_p
(Just tgt_s))
new_pdx new_sdx
new_p <- Node.addPriEx force tgt_p new_inst
new_s <- Node.addSec tgt_s new_inst new_pdx
let new_nl = Container.addTwo new_pdx new_p new_sdx new_s nl
new_stats = updateClusterStatisticsTwice stats
(tgt_p, new_p) (tgt_s, new_s)
return (new_nl, new_inst, [new_p, new_s], compCVfromStats new_stats)
|
mbakke/ganeti
|
src/Ganeti/HTools/Cluster/AllocatePrimitives.hs
|
Haskell
|
bsd-2-clause
| 3,665
|
-- |
-- Module : Foundation.Tuple
-- License : BSD-style
-- Maintainer : Vincent Hanquez <vincent@snarc.org>
-- Stability : experimental
-- Portability : portable
--
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
module Foundation.Tuple
( Tuple2(..)
, Tuple3(..)
, Tuple4(..)
, Fstable(..)
, Sndable(..)
, Thdable(..)
) where
import Basement.Compat.Base
import Basement.Compat.Bifunctor
import Foundation.Primitive
-- | Strict tuple (a,b)
data Tuple2 a b = Tuple2 !a !b
deriving (Show,Eq,Ord,Typeable,Data,Generic)
instance (NormalForm a, NormalForm b) => NormalForm (Tuple2 a b) where
toNormalForm (Tuple2 a b) = toNormalForm a `seq` toNormalForm b
instance Bifunctor Tuple2 where
bimap f g (Tuple2 a b) = Tuple2 (f a) (g b)
-- | Strict tuple (a,b,c)
data Tuple3 a b c = Tuple3 !a !b !c
deriving (Show,Eq,Ord,Typeable,Data,Generic)
instance (NormalForm a, NormalForm b, NormalForm c) => NormalForm (Tuple3 a b c) where
toNormalForm (Tuple3 a b c) = toNormalForm a `seq` toNormalForm b `seq` toNormalForm c
-- | Strict tuple (a,b,c,d)
data Tuple4 a b c d = Tuple4 !a !b !c !d
deriving (Show,Eq,Ord,Typeable,Data,Generic)
instance (NormalForm a, NormalForm b, NormalForm c, NormalForm d)
=> NormalForm (Tuple4 a b c d) where
toNormalForm (Tuple4 a b c d) = toNormalForm a `seq` toNormalForm b `seq` toNormalForm c `seq` toNormalForm d
-- | Class of product types that have a first element
class Fstable a where
type ProductFirst a
fst :: a -> ProductFirst a
-- | Class of product types that have a second element
class Sndable a where
type ProductSecond a
snd :: a -> ProductSecond a
-- | Class of product types that have a third element
class Thdable a where
type ProductThird a
thd :: a -> ProductThird a
instance Fstable (a,b) where
type ProductFirst (a,b) = a
fst (a,_) = a
instance Fstable (a,b,c) where
type ProductFirst (a,b,c) = a
fst (a,_,_) = a
instance Fstable (a,b,c,d) where
type ProductFirst (a,b,c,d) = a
fst (a,_,_,_) = a
instance Fstable (Tuple2 a b) where
type ProductFirst (Tuple2 a b) = a
fst (Tuple2 a _) = a
instance Fstable (Tuple3 a b c) where
type ProductFirst (Tuple3 a b c) = a
fst (Tuple3 a _ _) = a
instance Fstable (Tuple4 a b c d) where
type ProductFirst (Tuple4 a b c d) = a
fst (Tuple4 a _ _ _) = a
instance Sndable (a,b) where
type ProductSecond (a,b) = b
snd (_,b) = b
instance Sndable (a,b,c) where
type ProductSecond (a,b,c) = b
snd (_,b,_) = b
instance Sndable (a,b,c,d) where
type ProductSecond (a,b,c,d) = b
snd (_,b,_,_) = b
instance Sndable (Tuple2 a b) where
type ProductSecond (Tuple2 a b) = b
snd (Tuple2 _ b) = b
instance Sndable (Tuple3 a b c) where
type ProductSecond (Tuple3 a b c) = b
snd (Tuple3 _ b _) = b
instance Sndable (Tuple4 a b c d) where
type ProductSecond (Tuple4 a b c d) = b
snd (Tuple4 _ b _ _) = b
instance Thdable (a,b,c) where
type ProductThird (a,b,c) = c
thd (_,_,c) = c
instance Thdable (a,b,c,d) where
type ProductThird (a,b,c,d) = c
thd (_,_,c,_) = c
instance Thdable (Tuple3 a b c) where
type ProductThird (Tuple3 a b c) = c
thd (Tuple3 _ _ c) = c
instance Thdable (Tuple4 a b c d) where
type ProductThird (Tuple4 a b c d) = c
thd (Tuple4 _ _ c _) = c
|
vincenthz/hs-foundation
|
foundation/Foundation/Tuple.hs
|
Haskell
|
bsd-3-clause
| 3,381
|
{-# LANGUAGE TemplateHaskell #-}
module Version where
import Version.TH
import Data.Version (showVersion)
import qualified Paths_birch as P
version :: String
version = showVersion P.version ++ "-" ++ $(getCommitHash)
|
hithroc/hsvkbot
|
src/Version.hs
|
Haskell
|
bsd-3-clause
| 218
|
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE GADTs #-}
module Llvm.Pass.RewriteUse where
import Control.Monad
import Data.Maybe
import Prelude hiding (succ)
import qualified Compiler.Hoopl as H
import Llvm.Data.Ir
import Llvm.Util.Monadic (maybeM)
import Debug.Trace
type MaybeChange a = a -> Maybe a
f2 :: (a -> Maybe a) -> (a, a) -> Maybe (a, a)
f2 f (a1, a2) = case (f a1, f a2) of
(Nothing, Nothing) -> Nothing
(a1', a2') -> Just (fromMaybe a1 a1', fromMaybe a2 a2')
f3 :: (a -> Maybe a) -> (a, a, a) -> Maybe (a, a, a)
f3 f (a1, a2, a3) = case (f a1, f a2, f a3) of
(Nothing, Nothing, Nothing) -> Nothing
(a1', a2', a3') -> Just (fromMaybe a1 a1', fromMaybe a2 a2', fromMaybe a3 a3')
fs :: Eq a => (a -> Maybe a) -> [a] -> Maybe [a]
fs f ls = let ls' = map (\x -> (fromMaybe x (f x))) ls
in if ls == ls' then Nothing else Just ls'
rwIbinExpr :: MaybeChange a -> MaybeChange (IbinExpr a)
rwIbinExpr f e = let (v1, v2) = operandOfIbinExpr e
t = typeOfIbinExpr e
in do { (v1', v2') <- f2 f (v1, v2)
; return $ newBinExpr t v1' v2'
}
where newBinExpr t v1 v2 =
case e of
Add nw _ _ _ -> Add nw t v1 v2
Sub nw _ _ _ -> Sub nw t v1 v2
Mul nw _ _ _ -> Mul nw t v1 v2
Udiv nw _ _ _ -> Udiv nw t v1 v2
Sdiv nw _ _ _ -> Sdiv nw t v1 v2
Urem _ _ _ -> Urem t v1 v2
Srem _ _ _ -> Srem t v1 v2
Shl nw _ _ _ -> Shl nw t v1 v2
Lshr nw _ _ _ -> Lshr nw t v1 v2
Ashr nw _ _ _ -> Ashr nw t v1 v2
And _ _ _ -> And t v1 v2
Or _ _ _ -> Or t v1 v2
Xor _ _ _ -> Xor t v1 v2
rwFbinExpr :: MaybeChange a -> MaybeChange (FbinExpr a)
rwFbinExpr f e = let (v1, v2) = operandOfFbinExpr e
t = typeOfFbinExpr e
in do { (v1', v2') <- f2 f (v1, v2)
; return $ newBinExpr t v1' v2'
}
where newBinExpr t v1 v2 =
case e of
Fadd fg _ _ _ -> Fadd fg t v1 v2
Fsub fg _ _ _ -> Fsub fg t v1 v2
Fmul fg _ _ _ -> Fmul fg t v1 v2
Fdiv fg _ _ _ -> Fdiv fg t v1 v2
Frem fg _ _ _ -> Frem fg t v1 v2
rwBinExpr :: MaybeChange a -> MaybeChange (BinExpr a)
rwBinExpr f (Ie e) = liftM Ie (rwIbinExpr f e)
rwBinExpr f (Fe e) = liftM Fe (rwFbinExpr f e)
rwConversion :: MaybeChange a -> MaybeChange (Conversion a)
rwConversion f (Conversion co tv1 t) = do { tv1' <- f tv1
; return $ Conversion co tv1' t
}
rwGetElemPtr :: Eq a => MaybeChange a -> MaybeChange (GetElemPtr a)
rwGetElemPtr f (GetElemPtr b tv1 indices) = do { tv1' <- f tv1
; indices' <- fs f indices
; return $ GetElemPtr b tv1' indices'
}
rwSelect :: MaybeChange a -> MaybeChange (Select a)
rwSelect f (Select tv1 tv2 tv3) = do { (tv1', tv2', tv3') <- f3 f (tv1, tv2, tv3)
; return $ Select tv1' tv2' tv3'
}
rwIcmp :: MaybeChange a -> MaybeChange (Icmp a)
rwIcmp f (Icmp op t v1 v2) = do { (v1', v2') <- f2 f (v1, v2)
; return $ Icmp op t v1' v2'
}
rwFcmp :: MaybeChange a -> MaybeChange (Fcmp a)
rwFcmp f (Fcmp op t v1 v2) = do { (v1', v2') <- f2 f (v1, v2)
; return $ Fcmp op t v1' v2'
}
tv2v :: MaybeChange Value -> MaybeChange (Typed Value)
tv2v f (TypedData t x) = liftM (TypedData t) (f x)
tp2p :: MaybeChange Value -> MaybeChange (Typed Pointer)
tp2p f x | trace ("tp2p " ++ (show x)) False = undefined
tp2p f (TypedData t (Pointer x)) = liftM (\p -> TypedData t (Pointer p)) (f x)
rwExpr :: MaybeChange Value -> MaybeChange Expr
rwExpr f (EgEp gep) = rwGetElemPtr (tv2v f) gep >>= return . EgEp
rwExpr f (EiC a) = rwIcmp f a >>= return . EiC
rwExpr f (EfC a) = rwFcmp f a >>= return . EfC
rwExpr f (Eb a) = rwBinExpr f a >>= return . Eb
rwExpr f (Ec a) = rwConversion (tv2v f) a >>= return . Ec
rwExpr f (Es a) = rwSelect (tv2v f) a >>= return . Es
rwExpr f (Ev x) = (tv2v f x) >>= return . Ev
rwMemOp :: MaybeChange Value -> MaybeChange Rhs
rwMemOp f x | trace ("rwMemOp " ++ (show x)) False = undefined
rwMemOp f (RmO (Allocate m t ms ma)) = do { ms' <- maybeM (tv2v f) ms
; return $ RmO $ Allocate m t ms' ma
}
rwMemOp f (RmO (Load x ptr a1 a2 a3 a4)) =
do { tp <- (tp2p f) ptr
; traceM $ "tp:" ++ show tp
; return $ RmO (Load x tp a1 a2 a3 a4)
}
rwMemOp f (RmO (LoadAtomic _ _ (TypedData (Tpointer t _) ptr) _)) = do { tv <- (tv2v f) (TypedData t (Deref ptr))
; return $ Re $ Ev tv
}
-- rwMemOp f (RmO (Free tv)) = (tv2v f) tv >>= return . RmO . Free
rwMemOp f (RmO (Store a tv1 tv2 ma nt)) = do { tv1' <- (tv2v f) tv1
; return $ RmO $ Store a tv1' tv2 ma nt
}
rwMemOp f (RmO (StoreAtomic at a tv1 tv2 ma)) = do { tv1' <- (tv2v f) tv1
; return $ RmO $ StoreAtomic at a tv1' tv2 ma
}
rwMemOp f (RmO (CmpXchg wk b ptr v1 v2 b2 fe ff)) = do { (v1', v2') <- f2 (tv2v f) (v1, v2)
; return $ RmO $ CmpXchg wk b ptr v1' v2' b2 fe ff
}
rwMemOp f (RmO (AtomicRmw b ao ptr v1 b2 fe)) = do { v1' <- (tv2v f) v1
; return $ RmO $ AtomicRmw b ao ptr v1' b2 fe
}
rwMemOp _ _ = error "impossible case"
rwShuffleVector :: MaybeChange a -> MaybeChange (ShuffleVector a)
rwShuffleVector f (ShuffleVector tv1 tv2 tv3) = do { (tv1', tv2', tv3') <- f3 f (tv1, tv2, tv3)
; return $ ShuffleVector tv1' tv2' tv3'
}
rwExtractValue :: MaybeChange a -> MaybeChange (ExtractValue a)
rwExtractValue f (ExtractValue tv1 s) = f tv1 >>= \tv1' -> return $ ExtractValue tv1' s
rwInsertValue :: MaybeChange a -> MaybeChange (InsertValue a)
rwInsertValue f (InsertValue tv1 tv2 s) = do { (tv1', tv2') <- f2 f (tv1, tv2)
; return $ InsertValue tv1' tv2' s
}
rwExtractElem :: MaybeChange a -> MaybeChange (ExtractElem a)
rwExtractElem f (ExtractElem tv1 tv2) = do { (tv1', tv2') <- f2 f (tv1, tv2)
; return $ ExtractElem tv1' tv2'
}
rwInsertElem :: MaybeChange a -> MaybeChange (InsertElem a)
rwInsertElem f (InsertElem tv1 tv2 tv3) = do { (tv1', tv2', tv3') <- f3 f (tv1, tv2, tv3)
; return $ InsertElem tv1' tv2' tv3'
}
rwRhs :: MaybeChange Value -> MaybeChange Rhs
rwRhs f (RmO a) = rwMemOp f (RmO a)
rwRhs _ (Call _ _) = Nothing
rwRhs f (Re a) = rwExpr f a >>= return . Re
rwRhs f (ReE a) = rwExtractElem (tv2v f) a >>= return . ReE
rwRhs f (RiE a) = rwInsertElem (tv2v f) a >>= return . RiE
rwRhs f (RsV a) = rwShuffleVector (tv2v f) a >>= return . RsV
rwRhs f (ReV a) = rwExtractValue (tv2v f) a >>= return . ReV
rwRhs f (RiV a) = rwInsertValue (tv2v f) a >>= return . RiV
rwRhs f (VaArg tv t) = (tv2v f) tv >>= \tv' -> return $ VaArg tv' t
rwRhs _ (LandingPad _ _ _ _ _) = Nothing
rwComputingInst :: MaybeChange Value -> MaybeChange ComputingInst
rwComputingInst f (ComputingInst lhs rhs) = rwRhs f rhs >>= return . (ComputingInst lhs)
rwComputingInstWithDbg :: MaybeChange Value -> MaybeChange ComputingInstWithDbg
rwComputingInstWithDbg f (ComputingInstWithDbg cinst dbgs) =
rwComputingInst f cinst >>= \cinst' -> return $ ComputingInstWithDbg cinst' dbgs
rwCinst :: MaybeChange Value -> MaybeChange (Node e x)
rwCinst f (Cinst c) = rwComputingInstWithDbg f c >>= return . Cinst
rwCinst _ _ = Nothing
rwTerminatorInst :: MaybeChange Value -> MaybeChange TerminatorInst
rwTerminatorInst f (Return ls) = do { ls' <- fs (tv2v f) ls
; return $ Return ls'
}
rwTerminatorInst f (Cbr v tl fl) = do { v' <- f v
; return $ Cbr v' tl fl
}
rwTerminatorInst _ _ = Nothing
-- rwTerminatorInst f e = error ("unhandled case " ++ (show e))
rwTerminatorInstWithDbg :: MaybeChange Value -> MaybeChange TerminatorInstWithDbg
rwTerminatorInstWithDbg f (TerminatorInstWithDbg cinst dbgs) =
rwTerminatorInst f cinst >>= \cinst' -> return $ TerminatorInstWithDbg cinst' dbgs
rwTinst :: MaybeChange Value -> MaybeChange (Node e x)
rwTinst f (Tinst c) = rwTerminatorInstWithDbg f c >>= return . Tinst
rwTinst _ _ = Nothing
rwNode :: MaybeChange Value -> MaybeChange (Node e x)
rwNode f n@(Cinst _) = rwCinst f n
rwNode f n@(Tinst _) = rwTinst f n
rwNode _ _ = Nothing
nodeToGraph :: Node e x -> H.Graph Node e x
nodeToGraph n@(Nlabel _) = H.mkFirst n
nodeToGraph n@(Pinst _) = H.mkMiddle n
nodeToGraph n@(Cinst _) = H.mkMiddle n
nodeToGraph n@(Tinst _) = H.mkLast n
|
mlite/hLLVM
|
src/Llvm/Pass/RewriteUse.hs
|
Haskell
|
bsd-3-clause
| 10,153
|
--------------------------------------------------------------------
-- |
-- Module : Text.XML.Light.Cursor
-- Copyright : (c) Galois, Inc. 2008
-- License : BSD3
--
-- Maintainer: Iavor S. Diatchki <diatchki@galois.com>
-- Stability : provisional
-- Portability: portable
--
-- XML cursors for working XML content withing the context of
-- an XML document. This implementation is based on the general
-- tree zipper written by Krasimir Angelov and Iavor S. Diatchki.
--
module Text.XML.Light.Cursor
( Tag(..), getTag, setTag, fromTag
, Cursor(..), Path
-- * Conversions
, fromContent
, fromElement
, fromForest
, toForest
, toTree
-- * Moving around
, parent
, root
, getChild
, firstChild
, lastChild
, left
, right
, nextDF
-- ** Searching
, findChild
, findLeft
, findRight
, findRec
-- * Node classification
, isRoot
, isFirst
, isLast
, isLeaf
, isChild
, hasChildren
, getNodeIndex
-- * Updates
, setContent
, modifyContent
, modifyContentM
-- ** Inserting content
, insertLeft
, insertRight
, insertGoLeft
, insertGoRight
-- ** Removing content
, removeLeft
, removeRight
, removeGoLeft
, removeGoRight
, removeGoUp
) where
import Text.XML.Light.Types
import Data.Maybe(isNothing)
import Control.Monad(mplus)
data Tag = Tag { tagName :: QName
, tagAttribs :: [Attr]
, tagLine :: Maybe Line
} deriving (Show)
getTag :: Element -> Tag
getTag e = Tag { tagName = elName e
, tagAttribs = elAttribs e
, tagLine = elLine e
}
setTag :: Tag -> Element -> Element
setTag t e = fromTag t (elContent e)
fromTag :: Tag -> [Content] -> Element
fromTag t cs = Element { elName = tagName t
, elAttribs = tagAttribs t
, elLine = tagLine t
, elContent = cs
}
type Path = [([Content],Tag,[Content])]
-- | The position of a piece of content in an XML document.
data Cursor = Cur
{ current :: Content -- ^ The currently selected content.
, lefts :: [Content] -- ^ Siblings on the left, closest first.
, rights :: [Content] -- ^ Siblings on the right, closest first.
, parents :: Path -- ^ The contexts of the parent elements of this location.
} deriving (Show)
-- Moving around ---------------------------------------------------------------
-- | The parent of the given location.
parent :: Cursor -> Maybe Cursor
parent loc =
case parents loc of
(pls,v,prs) : ps -> Just
Cur { current = Elem
(fromTag v
(combChildren (lefts loc) (current loc) (rights loc)))
, lefts = pls, rights = prs, parents = ps
}
[] -> Nothing
-- | The top-most parent of the given location.
root :: Cursor -> Cursor
root loc = maybe loc root (parent loc)
-- | The left sibling of the given location.
left :: Cursor -> Maybe Cursor
left loc =
case lefts loc of
t : ts -> Just loc { current = t, lefts = ts
, rights = current loc : rights loc }
[] -> Nothing
-- | The right sibling of the given location.
right :: Cursor -> Maybe Cursor
right loc =
case rights loc of
t : ts -> Just loc { current = t, lefts = current loc : lefts loc
, rights = ts }
[] -> Nothing
-- | The first child of the given location.
firstChild :: Cursor -> Maybe Cursor
firstChild loc =
do (t : ts, ps) <- downParents loc
return Cur { current = t, lefts = [], rights = ts , parents = ps }
-- | The last child of the given location.
lastChild :: Cursor -> Maybe Cursor
lastChild loc =
do (ts, ps) <- downParents loc
case reverse ts of
l : ls -> return Cur { current = l, lefts = ls, rights = []
, parents = ps }
[] -> Nothing
-- | Find the next left sibling that satisfies a predicate.
findLeft :: (Cursor -> Bool) -> Cursor -> Maybe Cursor
findLeft p loc = do loc1 <- left loc
if p loc1 then return loc1 else findLeft p loc1
-- | Find the next right sibling that satisfies a predicate.
findRight :: (Cursor -> Bool) -> Cursor -> Maybe Cursor
findRight p loc = do loc1 <- right loc
if p loc1 then return loc1 else findRight p loc1
-- | The first child that satisfies a predicate.
findChild :: (Cursor -> Bool) -> Cursor -> Maybe Cursor
findChild p loc =
do loc1 <- firstChild loc
if p loc1 then return loc1 else findRight p loc1
-- | The next position in a left-to-right depth-first traversal of a document:
-- either the first child, right sibling, or the right sibling of a parent that
-- has one.
nextDF :: Cursor -> Maybe Cursor
nextDF c = firstChild c `mplus` up c
where up x = right x `mplus` (up =<< parent x)
-- | Perform a depth first search for a descendant that satisfies the
-- given predicate.
findRec :: (Cursor -> Bool) -> Cursor -> Maybe Cursor
findRec p c = if p c then Just c else findRec p =<< nextDF c
-- | The child with the given index (starting from 0).
getChild :: Int -> Cursor -> Maybe Cursor
getChild n loc =
do (ts,ps) <- downParents loc
(ls,t,rs) <- splitChildren ts n
return Cur { current = t, lefts = ls, rights = rs, parents = ps }
-- | private: computes the parent for "down" operations.
downParents :: Cursor -> Maybe ([Content], Path)
downParents loc =
case current loc of
Elem e -> Just ( elContent e
, (lefts loc, getTag e, rights loc) : parents loc
)
_ -> Nothing
-- Conversions -----------------------------------------------------------------
-- | A cursor for the given content.
fromContent :: Content -> Cursor
fromContent t = Cur { current = t, lefts = [], rights = [], parents = [] }
-- | A cursor for the given element.
fromElement :: Element -> Cursor
fromElement e = fromContent (Elem e)
-- | The location of the first tree in a forest.
fromForest :: [Content] -> Maybe Cursor
fromForest (t:ts) = Just Cur { current = t, lefts = [], rights = ts
, parents = [] }
fromForest [] = Nothing
-- | Computes the tree containing this location.
toTree :: Cursor -> Content
toTree loc = current (root loc)
-- | Computes the forest containing this location.
toForest :: Cursor -> [Content]
toForest loc = let r = root loc in combChildren (lefts r) (current r) (rights r)
-- Queries ---------------------------------------------------------------------
-- | Are we at the top of the document?
isRoot :: Cursor -> Bool
isRoot loc = null (parents loc)
-- | Are we at the left end of the the document?
isFirst :: Cursor -> Bool
isFirst loc = null (lefts loc)
-- | Are we at the right end of the document?
isLast :: Cursor -> Bool
isLast loc = null (rights loc)
-- | Are we at the bottom of the document?
isLeaf :: Cursor -> Bool
isLeaf loc = isNothing (downParents loc)
-- | Do we have a parent?
isChild :: Cursor -> Bool
isChild loc = not (isRoot loc)
-- | Get the node index inside the sequence of children
getNodeIndex :: Cursor -> Int
getNodeIndex loc = length (lefts loc)
-- | Do we have children?
hasChildren :: Cursor -> Bool
hasChildren loc = not (isLeaf loc)
-- Updates ---------------------------------------------------------------------
-- | Change the current content.
setContent :: Content -> Cursor -> Cursor
setContent t loc = loc { current = t }
-- | Modify the current content.
modifyContent :: (Content -> Content) -> Cursor -> Cursor
modifyContent f loc = setContent (f (current loc)) loc
-- | Modify the current content, allowing for an effect.
modifyContentM :: Monad m => (Content -> m Content) -> Cursor -> m Cursor
modifyContentM f loc = do x <- f (current loc)
return (setContent x loc)
-- | Insert content to the left of the current position.
insertLeft :: Content -> Cursor -> Cursor
insertLeft t loc = loc { lefts = t : lefts loc }
-- | Insert content to the right of the current position.
insertRight :: Content -> Cursor -> Cursor
insertRight t loc = loc { rights = t : rights loc }
-- | Remove the content on the left of the current position, if any.
removeLeft :: Cursor -> Maybe (Content,Cursor)
removeLeft loc = case lefts loc of
l : ls -> return (l,loc { lefts = ls })
[] -> Nothing
-- | Remove the content on the right of the current position, if any.
removeRight :: Cursor -> Maybe (Content,Cursor)
removeRight loc = case rights loc of
l : ls -> return (l,loc { rights = ls })
[] -> Nothing
-- | Insert content to the left of the current position.
-- The new content becomes the current position.
insertGoLeft :: Content -> Cursor -> Cursor
insertGoLeft t loc = loc { current = t, rights = current loc : rights loc }
-- | Insert content to the right of the current position.
-- The new content becomes the current position.
insertGoRight :: Content -> Cursor -> Cursor
insertGoRight t loc = loc { current = t, lefts = current loc : lefts loc }
-- | Remove the current element.
-- The new position is the one on the left.
removeGoLeft :: Cursor -> Maybe Cursor
removeGoLeft loc = case lefts loc of
l : ls -> Just loc { current = l, lefts = ls }
[] -> Nothing
-- | Remove the current element.
-- The new position is the one on the right.
removeGoRight :: Cursor -> Maybe Cursor
removeGoRight loc = case rights loc of
l : ls -> Just loc { current = l, rights = ls }
[] -> Nothing
-- | Remove the current element.
-- The new position is the parent of the old position.
removeGoUp :: Cursor -> Maybe Cursor
removeGoUp loc =
case parents loc of
(pls,v,prs) : ps -> Just
Cur { current = Elem (fromTag v (reverse (lefts loc) ++ rights loc))
, lefts = pls, rights = prs, parents = ps
}
[] -> Nothing
-- | private: Gets the given element of a list.
-- Also returns the preceding elements (reversed) and the following elements.
splitChildren :: [a] -> Int -> Maybe ([a],a,[a])
splitChildren _ n | n < 0 = Nothing
splitChildren cs pos = loop [] cs pos
where loop acc (x:xs) 0 = Just (acc,x,xs)
loop acc (x:xs) n = loop (x:acc) xs $! n-1
loop _ _ _ = Nothing
-- | private: combChildren ls x ys = reverse ls ++ [x] ++ ys
combChildren :: [a] -> a -> [a] -> [a]
combChildren ls t rs = foldl (flip (:)) (t:rs) ls
|
amremam2004/vxmlizer
|
Text/XML/Light/Cursor.hs
|
Haskell
|
bsd-3-clause
| 10,568
|
module Usage.Usage where
import qualified Definition.Definition as D.D
test :: Int
test = D.D.s<caret>even + 1
|
charleso/intellij-haskforce
|
tests/gold/codeInsight/QualifiedImportMultipleLevels_AsPartConsistsOfMultipleCons/Usage/Usage.hs
|
Haskell
|
apache-2.0
| 115
|
{-# OPTIONS_GHC -fwarn-safe #-}
-- | Basic test to see if Safe warning flags compile
-- Warn if module is inferred safe
-- In this test the warning _shouldn't_ fire
module SafeFlags23 where
import System.IO.Unsafe
f :: Int
f = 1
|
sdiehl/ghc
|
testsuite/tests/safeHaskell/flags/SafeFlags24.hs
|
Haskell
|
bsd-3-clause
| 232
|
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="hr-HR">
<title>Directory List v2.3</title>
<maps>
<homeID>directorylistv2_3</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
thc202/zap-extensions
|
addOns/directorylistv2_3/src/main/javahelp/help_hr_HR/helpset_hr_HR.hs
|
Haskell
|
apache-2.0
| 978
|
{-
Parser.hs: Parser for the Flounder interface definition language
Part of Flounder: a strawman device definition DSL for Barrelfish
Copyright (c) 2009, ETH Zurich.
All rights reserved.
This file is distributed under the terms in the attached LICENSE file.
If you do not find this file, copies can be found by writing to:
ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group.
-}
module Parser where
import Syntax
import Prelude
import Text.ParserCombinators.Parsec as Parsec
import Text.ParserCombinators.Parsec.Expr
import Text.ParserCombinators.Parsec.Pos
import qualified Text.ParserCombinators.Parsec.Token as P
import Text.ParserCombinators.Parsec.Language( javaStyle )
import Data.Char
import Numeric
import Data.List
import Text.Printf
parse_intf predefDecls filename = parseFromFile (intffile predefDecls) filename
parse_include predefDecls filename = parseFromFile (includefile predefDecls) filename
lexer = P.makeTokenParser (javaStyle
{ P.reservedNames = [ "interface",
"message",
"rpc",
"in",
"out"
]
, P.reservedOpNames = ["*","/","+","-"]
, P.commentStart = "/*"
, P.commentEnd = "*/"
})
whiteSpace = P.whiteSpace lexer
reserved = P.reserved lexer
identifier = P.identifier lexer
stringLit = P.stringLiteral lexer
comma = P.comma lexer
commaSep = P.commaSep lexer
commaSep1 = P.commaSep1 lexer
parens = P.parens lexer
braces = P.braces lexer
squares = P.squares lexer
semiSep = P.semiSep lexer
symbol = P.symbol lexer
natural = P.natural lexer
builtinTypes = map show [UInt8 ..] ++ ["int"] -- int is legacy -AB
-- identifyBuiltin :: [(String, Declaration)] -> String -> TypeRef
identifyBuiltin typeDcls typeName =
do {
if typeName `elem` builtinTypes then
return $ Builtin $ (read typeName::TypeBuiltin)
else
case typeName `lookup` typeDcls of
Just (Typedef (TAliasT new orig)) -> return $ TypeAlias new orig
Just _ -> return $ TypeVar typeName
Nothing ->
do {
; pos <- getPosition
-- This is ugly, I agree:
; return $ error ("Use of undeclared type '" ++ typeName ++ "' in "
++ show (sourceName pos) ++ " at l. "
++ show (sourceLine pos) ++ " col. "
++ show (sourceColumn pos))
}
}
intffile predefDecls = do { whiteSpace
; i <- iface predefDecls
; return i
}
includefile predefDecls = do { whiteSpace
; typeDecls <- typeDeclaration predefDecls
; return typeDecls
}
iface predefDecls = do { reserved "interface"
; name <- identifier
; descr <- option name stringLit
; decls <- braces $ do {
; typeDecls <- typeDeclaration predefDecls
; msgDecls <- many1 $ mesg typeDecls
; return ((map snd typeDecls) ++ msgDecls)
}
; symbol ";" <?> " ';' missing from end of " ++ name ++ " interface specification"
; return (Interface name (Just descr) decls)
}
typeDeclaration typeDcls = do {
; decl <- try (do {
; x <- transparentAlias
; return $ Just x
})
<|> try (do {
; x <- typedefinition typeDcls
; return $ Just x
})
<|> return Nothing
; case decl of
Nothing -> return typeDcls
Just x -> typeDeclaration (x : typeDcls)
}
mesg typeDcls = do { bckArgs <- many backendParams
; def <- msg typeDcls bckArgs <|> rpc typeDcls bckArgs
; return $ Messagedef def
}
msg typeDcls bckArgs = do { t <- msgtype
; i <- identifier
; a <- parens $ commaSep (marg typeDcls)
; symbol ";"
; return $ Message t i a bckArgs
}
rpc typeDcls bckArgs= do { _ <- rpctype
; i <- identifier
; a <- parens $ commaSep (rpcArg typeDcls)
; symbol ";"
; return $ RPC i a bckArgs
}
rpctype = do { reserved "rpc"
; return () }
rpcArg typeDcls = do { reserved "in"
; Arg b n <- marg typeDcls
; return $ RPCArgIn b n
}
<|> do { reserved "out"
; Arg b n <- marg typeDcls
; return $ RPCArgOut b n
}
backendParams = do { char '@'
; i <- identifier
; p <- parens $ commaSep backendParam
; return (i, p)
}
backendParam = do { name <- identifier
; symbol "="
; do { num <- natural ; return $ (name, BackendInt num) }
<|> do { arg <- identifier ; return $ (name, BackendMsgArg arg) }
}
msgtype = do { reserved "message"; return MMessage }
<|> do { reserved "call"; return MCall }
<|> do { reserved "response"; return MResponse }
marg typeDcls = try (marg_array typeDcls)
<|> (marg_simple typeDcls)
marg_simple typeDcls = do { t <- identifier
; n <- identifier
; b <- identifyBuiltin typeDcls t
; return (Arg b (Name n))
}
marg_array typeDcls = do { t <- identifier
; n <- identifier
; symbol "["
; l <- identifier
; symbol "]"
; bType <- identifyBuiltin typeDcls t
; return (Arg bType (DynamicArray n l))
}
transparentAlias = do { whiteSpace
; reserved "alias"
; newType <- identifier
; originType <- identifier
; symbol ";"
; return (newType, Typedef $ TAliasT newType
(read originType::TypeBuiltin))
}
typedefinition typeDcls = do { whiteSpace
; reserved "typedef"
; (name, typeDef) <- typedef_body typeDcls
; symbol ";"
; return (name, Typedef typeDef)
}
typedef_body typeDcls = try (struct_typedef typeDcls)
<|> try (array_typedef typeDcls)
<|> try enum_typedef
<|> (alias_typedef typeDcls)
struct_typedef typeDcls = do { reserved "struct"
; f <- braces $ many1 (struct_field typeDcls)
; i <- identifier
; return (i, (TStruct i f))
}
struct_field typeDcls = do { t <- identifier
; i <- identifier
; symbol ";"
; b <- identifyBuiltin typeDcls t
; return (TStructField b i)
}
array_typedef typeDcls = do { t <- identifier
; i <- identifier
; symbol "["
; sz <- integer
; symbol "]"
; b <- identifyBuiltin typeDcls t
; return (i, (TArray b i sz))
}
enum_typedef = do { reserved "enum"
; v <- braces $ commaSep1 identifier
; i <- identifier
; return (i, (TEnum i v))
}
alias_typedef typeDcls = do { t <- identifier
; i <- identifier
; b <- identifyBuiltin typeDcls t
; return (i, (TAlias i b))
}
integer = P.integer lexer
|
joe9/barrelfish
|
tools/flounder/Parser.hs
|
Haskell
|
mit
| 9,137
|
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeOperators #-}
module T15361 where
import Data.Kind
import Data.Type.Equality
-- Don't report (* ~ *) here
foo :: forall (a :: Type) (b :: Type) (c :: Type).
a :~~: b -> a :~~: c
foo HRefl = HRefl
data Chumbawamba :: Type -> Type where
IGetKnockedDown :: (Eq a, Ord a) => a -> Chumbawamba a
-- Don't report (Eq a) here
goo :: Chumbawamba a -> String
goo (IGetKnockedDown x) = show x
|
sdiehl/ghc
|
testsuite/tests/typecheck/should_fail/T15361.hs
|
Haskell
|
bsd-3-clause
| 495
|
import qualified Data.Vector as U
import Data.Bits
main = print . U.maximumBy (\x y -> GT) . U.map (*2) . U.map (`shiftL` 2) $ U.replicate (100000000 :: Int) (5::Int)
|
hvr/vector
|
old-testsuite/microsuite/maximumBy.hs
|
Haskell
|
bsd-3-clause
| 168
|
import Data.Bits ((.&.))
flags :: Int -> Int
flags x
| x .&. 128 > 0 = 12
| otherwise = 13
{-# NOINLINE flags #-}
main :: IO ()
main = print (flags 255)
|
ezyang/ghc
|
testsuite/tests/codeGen/should_run/T13425.hs
|
Haskell
|
bsd-3-clause
| 159
|
-- !!! Check the Read instance for Array
-- [Not strictly a 'deriving' issue]
module Main( main ) where
import Data.Array
bds :: ((Int,Int),(Int,Int))
bds = ((1,4),(2,5))
type MyArr = Array (Int,Int) Int
a :: MyArr
a = array bds [ ((i,j), i+j) | (i,j) <- range bds ]
main = do { putStrLn (show a) ;
let { b :: MyArr ;
b = read (show a) } ;
putStrLn (show b)
}
|
olsner/ghc
|
testsuite/tests/deriving/should_run/drvrun009.hs
|
Haskell
|
bsd-3-clause
| 418
|
-- !!! Test seeking
import System.IO
main = do
h <- openFile "hSeek001.in" ReadMode
True <- hIsSeekable h
hSeek h SeekFromEnd (-1)
z <- hGetChar h
putStr (z:"\n")
hSeek h SeekFromEnd (-3)
x <- hGetChar h
putStr (x:"\n")
hSeek h RelativeSeek (-2)
w <- hGetChar h
putStr (w:"\n")
hSeek h RelativeSeek 2
z <- hGetChar h
putStr (z:"\n")
hSeek h AbsoluteSeek (0)
a <- hGetChar h
putStr (a:"\n")
hSeek h AbsoluteSeek (10)
k <- hGetChar h
putStr (k:"\n")
hSeek h AbsoluteSeek (25)
z <- hGetChar h
putStr (z:"\n")
hClose h
|
urbanslug/ghc
|
libraries/base/tests/IO/hSeek001.hs
|
Haskell
|
bsd-3-clause
| 614
|
{-# LANGUAGE JavaScriptFFI #-}
module Doppler.GHCJS.VirtualDOM.VDom (
VDom, requireVDom
) where
import GHCJS.Types (JSVal)
newtype VDom = VDom JSVal
foreign import javascript interruptible "require(['virtual-dom'], $c);"
requireVDom :: IO VDom
|
oinuar/doppler
|
src/Doppler/GHCJS/VirtualDOM/VDom.hs
|
Haskell
|
mit
| 254
|
import Data.List
import Data.Text hiding (intercalate, map)
import System.Hclip
import Text.ParserCombinators.Parsec
-- | Strip, with Strings instead of Text for arguments
trim :: String -> String
trim = unpack . strip . pack
-- | A single cell of a matrix
body :: Parser String
body = many1 $ noneOf "&\\"
-- | A single row of the matrix
row :: Parser [String]
row = sepBy body (char '&')
-- | A matrix parser (excluding wrappers)
matrix :: Parser [[String]]
matrix = sepBy row (try (string "\\\\"))
-- | A wrapped matrix parser
wrappedMatrix :: Parser [[String]]
wrappedMatrix = do
optional (try $ string "\\begin{bmatrix}")
mat <- matrix
optional (try $ string "\\end{bmatrix}")
return mat
-- | Trim every element of the matrix
cleanUp :: [[String]] -> [[String]]
cleanUp (x : xs) = map trim x : cleanUp xs
cleanUp [] = []
-- | Generate a wolfram array from an array of arrays of strings
wolfram :: [[String]] -> String
wolfram x = "{" ++ wolfram' ++ "}"
where
wolfram' = intercalate ",\n " (map row x)
row y = "{" ++ row' y ++ "}"
row' y = intercalate ", " y
main :: IO ()
main = do
input <- getClipboard
putStrLn $ "Got input: \n" ++ input ++ "\n"
let result = parse wrappedMatrix "matrix" $ trim input
case result of
Left e -> putStrLn $ "Failed to parse input:\n" ++ show e
Right mat -> do
let s = wolfram $ cleanUp mat
setClipboard s
putStrLn $ "Success! Copied result to clipboard:\n" ++ s
|
mystor/matrix-detex
|
MatrixDetex.hs
|
Haskell
|
mit
| 1,604
|
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE CPP #-}
module Test.Hspec.Wai.Internal (
WaiExpectation
, WaiSession(..)
, runWaiSession
, runWithState
, withApplication
, getApp
, getState
, formatHeader
) where
import Control.Monad.IO.Class
import Control.Monad.Trans.Class
import Control.Monad.Trans.Reader
import Network.Wai (Application)
import Network.Wai.Test hiding (request)
import Test.Hspec.Core.Spec
import Test.Hspec.Wai.Util (formatHeader)
#if MIN_VERSION_base(4,9,0)
import Control.Monad.Fail
#endif
-- | An expectation in the `WaiSession` monad. Failing expectations are
-- communicated through exceptions (similar to `Test.Hspec.Expectations.Expectation` and
-- `Test.HUnit.Base.Assertion`).
type WaiExpectation st = WaiSession st ()
-- | A <http://www.yesodweb.com/book/web-application-interface WAI> test
-- session that carries the `Application` under test and some client state.
newtype WaiSession st a = WaiSession {unWaiSession :: ReaderT st Session a}
deriving (Functor, Applicative, Monad, MonadIO
#if MIN_VERSION_base(4,9,0)
, MonadFail
#endif
)
runWaiSession :: WaiSession () a -> Application -> IO a
runWaiSession action app = runWithState action ((), app)
runWithState :: WaiSession st a -> (st, Application) -> IO a
runWithState action (st, app) = runSession (flip runReaderT st $ unWaiSession action) app
withApplication :: Application -> WaiSession () a -> IO a
withApplication = flip runWaiSession
instance Example (WaiExpectation st) where
type Arg (WaiExpectation st) = (st, Application)
evaluateExample e p action = evaluateExample (action $ runWithState e) p ($ ())
getApp :: WaiSession st Application
getApp = WaiSession (lift ask)
getState :: WaiSession st st
getState = WaiSession ask
|
hspec/hspec-wai
|
src/Test/Hspec/Wai/Internal.hs
|
Haskell
|
mit
| 1,937
|
{-# LANGUAGE PatternSynonyms #-}
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module JSDOM.Generated.SQLTransactionErrorCallback
(newSQLTransactionErrorCallback,
newSQLTransactionErrorCallbackSync,
newSQLTransactionErrorCallbackAsync, SQLTransactionErrorCallback)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SQLTransactionErrorCallback Mozilla SQLTransactionErrorCallback documentation>
newSQLTransactionErrorCallback ::
(MonadDOM m) =>
(SQLError -> JSM ()) -> m SQLTransactionErrorCallback
newSQLTransactionErrorCallback callback
= liftDOM
(SQLTransactionErrorCallback . Callback <$>
function
(\ _ _ [error] ->
fromJSValUnchecked error >>= \ error' -> callback error'))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SQLTransactionErrorCallback Mozilla SQLTransactionErrorCallback documentation>
newSQLTransactionErrorCallbackSync ::
(MonadDOM m) =>
(SQLError -> JSM ()) -> m SQLTransactionErrorCallback
newSQLTransactionErrorCallbackSync callback
= liftDOM
(SQLTransactionErrorCallback . Callback <$>
function
(\ _ _ [error] ->
fromJSValUnchecked error >>= \ error' -> callback error'))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SQLTransactionErrorCallback Mozilla SQLTransactionErrorCallback documentation>
newSQLTransactionErrorCallbackAsync ::
(MonadDOM m) =>
(SQLError -> JSM ()) -> m SQLTransactionErrorCallback
newSQLTransactionErrorCallbackAsync callback
= liftDOM
(SQLTransactionErrorCallback . Callback <$>
asyncFunction
(\ _ _ [error] ->
fromJSValUnchecked error >>= \ error' -> callback error'))
|
ghcjs/jsaddle-dom
|
src/JSDOM/Generated/SQLTransactionErrorCallback.hs
|
Haskell
|
mit
| 2,755
|
module Instructions where
import Text.ParserCombinators.Parsec
import Control.Applicative hiding (many, (<|>))
type Coordinate = (Integer, Integer)
type Region = (Coordinate, Coordinate)
data Instruction = Instruction Task Region
deriving (Show)
data Task = TurnOn | Toggle | TurnOff
deriving (Show)
instructions = many instruction <* eof
instruction :: GenParser Char st Instruction
instruction =
Instruction <$> task
<* space
<*> region
<* eol
task = try (TurnOn <$ string "turn on") <|>
try (TurnOff <$ string "turn off") <|>
(Toggle <$ string "toggle")
region = (,) <$> coord
<* string " through "
<*> coord
coord = (,) <$> integer
<* char ','
<*> integer
integer = rd <$> many1 digit
where rd = read :: String -> Integer
eol = (char '\n' <|> (char '\r' >> option '\n' (char '\n'))) >> return ()
|
corajr/adventofcode2015
|
6/Instructions.hs
|
Haskell
|
mit
| 947
|
module Main where
import Lib
import Text.Printf
import Data.Time.Clock.POSIX
n = 4::Int
main :: IO ()
main = do
startTime <- getPOSIXTime
printf "Maximum product of %d values taken in a straight line from array 'values':\n\t%d"
n $ maxStraightProduct n
stopTime <- getPOSIXTime
printf "\t(%s sec)\n" $ show (stopTime - startTime)
|
JohnL4/ProjectEuler
|
Haskell/Problem011/app/Main.hs
|
Haskell
|
mit
| 349
|
-- | This module describes the interface (as a data tyep) that some variant
-- should implement. See `Variant`.
--
{-# LANGUAGE OverloadedStrings #-}
module NetHack.Data.Variant
( Variant()
, monster
, allMonsterNames
, commandPrefix
, variant
, loadVariant )
where
import Control.Applicative
import Control.Monad.IO.Class
import qualified Data.ByteString as B
import Data.List ( find )
import qualified Data.Text as T
import Data.Yaml
import qualified NetHack.Data.Monster as MD
-- | Export a function that returns one of these to add a variant to the bot.
-- See `variant`.
data Variant = Variant { monster :: !(T.Text -> Maybe MD.Monster)
, allMonsterNames :: ![T.Text]
, commandPrefix :: T.Text }
instance FromJSON Variant where
parseJSON (Object v) = do
prefix <- v .: "prefix"
monsters <- v .: "monsters"
return Variant
{
commandPrefix = prefix
, allMonsterNames = fmap MD.moName monsters
, monster = \name -> find ((==) name . MD.moName) monsters
}
parseJSON _ = empty
-- Builds a `Variant` out of three properties.
variant :: (T.Text -> Maybe MD.Monster) -- ^ Return a monster with the given
-- name or `Nothing` if there is no
-- such monster.
-> [T.Text] -- ^ The list of all monster names.
-> T.Text -- ^ The command prefix for the IRC
-- bot. E.g. "u" for UnNetHack.
-> Variant
variant = Variant
-- Loads a variant from a YAML file.
loadVariant :: MonadIO m => FilePath -> m Variant
loadVariant fpath = liftIO $ do
bs <- B.readFile fpath
case decodeEither bs of
Left err -> error err
Right var -> return var
|
UnNetHack/pinobot
|
lib/NetHack/Data/Variant.hs
|
Haskell
|
mit
| 1,915
|
module Euler.E9 where
euler9 :: Int -> Int
euler9 n = x*y*z
where
(x,y,z) = findTriple n
genTriples :: Int -> [(Int, Int, Int)]
genTriples n = [(x,y,z) | x <- [1..n], y <- [x..n], z <- [y..n], x+y+z == n]
isPythTriple :: (Int,Int,Int) -> Bool
isPythTriple (x,y,z) = or
[ x*x + y*y == z*z
, x*x + z*z == y*y
, y*y + z*z == x*x
]
findTriple :: Int -> (Int,Int,Int)
findTriple n = head $ filter isPythTriple $ genTriples n
main :: IO ()
main = print $ euler9 1000
|
D4r1/project-euler
|
Euler/E9.hs
|
Haskell
|
mit
| 472
|
module SyntheticWeb.Client.Executor
( executeTask
) where
import Control.Concurrent (threadDelay)
import Control.Concurrent.STM (atomically)
import Data.Time (NominalDiffTime)
import SyntheticWeb.Client.Http (get, post, put)
import SyntheticWeb.Client.TimedAction (timedAction)
import SyntheticWeb.Counter ( ByteCounter
, activatePattern
, updateByteCount
, updateLatencyTime
, updatePatternTime
, updateSleepTime )
import SyntheticWeb.Client.ExecM ( ExecM
, getCounters
, getActivities
, getGenerator
, liftIO )
import SyntheticWeb.Plan.Types ( Activity (..)
, Duration (..) )
import SyntheticWeb.Statistical (Statistical (Exactly), sample)
-- | Execute one task.
executeTask :: ExecM ()
executeTask = do
((), timeItTook) <-
timedAction $ do
doActivatePattern
mapM_ executeActivity =<< getActivities
doUpdatePatternTime timeItTook
-- | Execute one client activity. Counters related to the activity -
-- timings and byte counters - shall be updated.
executeActivity :: Activity -> ExecM ()
-- | Delay the task worker thread for the specified duration.
executeActivity (SLEEP duration) = do
delay <- sampleDelayTime duration
((), timeItTook) <- timedAction $ liftIO (threadDelay delay)
doUpdateSleepTime timeItTook
-- | Fetch a resource with the specfied size.
executeActivity (GET headers download _) = do
((_, byteCount), timeItTook) <- timedAction (get download headers)
doUpdateByteCountAndLatencyTime byteCount timeItTook
-- | Upload to a resource with the specified size.
executeActivity (PUT headers upload) = do
((_, byteCount), timeItTook) <- timedAction (put upload headers)
doUpdateByteCountAndLatencyTime byteCount timeItTook
-- | Perform a post (upload and download) with the specicied sizes.
executeActivity (POST headers upload download _) = do
((_, byteCount), timeItTook) <- timedAction (post upload download headers)
doUpdateByteCountAndLatencyTime byteCount timeItTook
sampleDelayTime :: Duration -> ExecM Int
sampleDelayTime (Usec stat) = do
Exactly t <- sample stat =<< getGenerator
return t
sampleDelayTime (Msec stat) = do
Exactly t <- sample stat =<< getGenerator
return (t * 1000)
sampleDelayTime (Sec stat) = do
Exactly t <- sample stat =<< getGenerator
return (t * 1000000)
doActivatePattern :: ExecM ()
doActivatePattern = do
c <- getCounters
liftIO $ atomically (activatePattern c)
doUpdateByteCountAndLatencyTime :: ByteCounter -> NominalDiffTime -> ExecM ()
doUpdateByteCountAndLatencyTime bc t = do
c <- getCounters
liftIO $ atomically $ do
updateByteCount bc c
updateLatencyTime t c
doUpdatePatternTime :: NominalDiffTime -> ExecM ()
doUpdatePatternTime t = do
c <- getCounters
liftIO $ atomically (updatePatternTime t c)
doUpdateSleepTime :: NominalDiffTime -> ExecM ()
doUpdateSleepTime t = do
c <- getCounters
liftIO $ atomically (updateSleepTime t c)
|
kosmoskatten/synthetic-web
|
src/SyntheticWeb/Client/Executor.hs
|
Haskell
|
mit
| 3,191
|
module AI where
import Control.Monad
import Data.Array.MArray
import Data.Array.IO
import Data.Word
import System.Random
type Index = Int
type Value = Int
type Weight = Value
type Neurons = IOArray Index Value
type Synapses = [(Index, Index, Weight)] -- src, dst, weight
type Goals = [Index]
type Brain = (Neurons, Synapses, Goals)
type Score = Int
type Population = [(Score, Brain)]
newRandomBrain :: Int -> Int -> Goals -> IO Brain
newRandomBrain nbNeurons nbSynapses goals = do
neurons <- newArray (0, nbNeurons) 0
synapses <- replicateM nbSynapses $ do
source <- randomRIO (0, nbNeurons)
destination <- randomRIO (0, nbNeurons)
weight <- randomRIO (minBound, maxBound)
return (source, destination, weight)
return (neurons, synapses, goals)
think :: Brain -> [Value] -> IO [Value]
think (neurons, synapses, goals) inputs = do
-- Clear existing neurons
(l, h) <- getBounds neurons
forM_ [l..h] $ \i -> do
writeArray neurons i 0
-- Write inputs
forM_ (zip [1..] inputs) $ \(i, v) -> do
writeArray neurons i v
-- Fire the synapses again
forM_ synapses $ \(src, dst, weight) -> do
result <- readArray neurons src
writeArray neurons dst (result + weight)
-- Yield goals
forM goals $ \i -> do
readArray neurons i
createPopulation :: Int -> Int -> Int -> Goals -> IO Population
createPopulation amount nbNeurons nbSynapses goals = replicateM amount $ do
brain <- newRandomBrain nbNeurons nbSynapses goals
return (0, brain)
testPopulation :: Population -> ([Value] -> IO Score) -> [Value] -> IO Population
testPopulation population fitness inputs = forM population $ \(oldScore, brain) -> do
outputs <- think brain inputs
score <- fitness outputs
return (oldScore + score, brain)
|
nitrix/ai
|
src/AI.hs
|
Haskell
|
mit
| 1,853
|
import Data.List
isTriangular threeNumbers = x + y > z
where
[x, y, z] = sort threeNumbers
countTrue = length . filter id
parseInputLine = map (read :: String -> Integer) . words
main = do
input <- getContents
print . countTrue . map (isTriangular . parseInputLine) . lines $ input
|
lzlarryli/advent_of_code_2016
|
day3/part1.hs
|
Haskell
|
mit
| 297
|
module Y2017.M03.D16.Solution where
import Data.Maybe (fromMaybe)
import Data.Set (Set)
import qualified Data.Set as Set
-- below imports available from 1HaskellADay git respository
import Analytics.Theory.Number.Prime
import Y2017.M03.D15.Solution (uniqueValuesUpTo)
{--
So, yesterday, when we solved the Exercise imported above, we saw that we had
614 unique values with the max value being Just 126410606437752. That max value
is quite the spicy meatball, however. But a help here is that we are looking
for prime-square-free numbers, or, that is to say more precisely, numbers that
are not divisible by the squares of the primes. So, let's winnow down our list
a bit.
--}
squareFreed :: Prime -> Set Integer -> Set Integer
squareFreed prime = Set.filter ((/= 0) . (`mod` (prime ^ 2)))
{--
How many values in uniqueValuesUpTo 51 when that list is squareFreed of the
first Prime, 2? (remember to square 2 as the factor to check against)o
>>> length (squareFreed (uniqueValuesUpTo 51) (head primes))
286
>>> fst <$> Set.maxView (squareFreed (head primes) (uniqueValuesUpTo 51))
Just 18053528883775
Boom! A marked improvement! Let's do the same for the next prime, 3. First,
assign smr0 to the squareFreed 2 value:
>>> let smr0 = squareFreed (head primes) (uniqueValuesUpTo 51)
and repeat the above for the next prime (head (tail primes)). What is the new
length and new max value you get for your newly filtered set from smr0?
assign smr1 to that newer smaller subset.
>>> let smr1 = squareFreed (head (tail primes)) smr0
>>> length smr1
185
>>> fst <$> Set.maxView smr1
Just 18053528883775
No change to the max, let's go a bit further. Now how about for the next prime?
>>> let smr2 = squareFreed (head (drop 2 primes)) smr1
>>> length smr2
162
>>> fst <$> Set.maxView smr2
Just 9762479679106
>>> sqrt . fromIntegral <$> it
Just 3124496.708128527
This shows after filtering out only 3 prime-squares we've significantly reduced
the number of values we need to test against AND the maximum value prime we need
to compute to test.
So.
Today's Haskell problem. Using the above algorithm, filter the unique values
of the Pascal's Triangle up to row 51 down to only the square-free numbers,
then sum the resulting set. What is the value you get?
--}
sqFreeSieve :: Set Integer -> Set Integer
sqFreeSieve = sfs primes
sfs :: [Prime] -> Set Integer -> Set Integer
sfs (p:rimes) uniq =
if fromMaybe 0 (fst <$> Set.maxView uniq) < p * p then uniq
else sfs rimes (squareFreed p uniq)
{--
>>> length (sqFreeSieve (uniqueValuesUpTo 51))
158
Eheh! We found only four more beasties for all that work?!? ;)
>>> sum (sqFreeSieve (uniqueValuesUpTo 51))
... some value
--}
|
geophf/1HaskellADay
|
exercises/HAD/Y2017/M03/D16/Solution.hs
|
Haskell
|
mit
| 2,693
|
{-# LANGUAGE Haskell2010 #-}
module Deprecated where
-- | Docs for something deprecated
deprecated :: Int
deprecated = 1
{-# DEPRECATED deprecated "Don't use this" #-}
|
haskell/haddock
|
latex-test/src/Deprecated/Deprecated.hs
|
Haskell
|
bsd-2-clause
| 170
|
-- http://www.codewars.com/kata/54d6abf84a35017d30000b26
module Data.Complex.Gaussian.Prime where
import Data.Complex.Gaussian (Gaussian (..), norm)
isGaussianPrime :: Gaussian -> Bool
isGaussianPrime z@(Gaussian x y)
= n==2
|| n`mod`4==1 && isPrime n
|| y==0 && abs x `mod` 4==3 && isPrime (abs x)
|| x==0 && abs y `mod` 4==3 && isPrime (abs y)
where
n = norm z
isPrime m = m > 1 && foldr (\p r -> p*p > m || ((m `rem` p) /= 0 && r)) True primes
primes = 2 : filter isPrime [3,5..]
|
Bodigrim/katas
|
src/haskell/B-Gaussian-primes.hs
|
Haskell
|
bsd-2-clause
| 516
|
{-# LANGUAGE Haskell2010 #-}
module Operators where
(+++) :: [a] -> [a] -> [a]
a +++ b = a ++ b ++ a
($$$) :: [a] -> [a] -> [a]
a $$$ b = b +++ a
(***) :: [a] -> [a] -> [a]
(***) a [] = a
(***) a (_:b) = a +++ (a *** b)
(*/\*) :: [[a]] -> [a] -> [a]
a */\* b = concatMap (*** b) a
(**/\**) :: [[a]] -> [[a]] -> [[a]]
a **/\** b = zipWith (*/\*) [a +++ b] (a $$$ b)
(#.#) :: a -> b -> (c -> (a, b))
a #.# b = const $ (a, b)
|
haskell/haddock
|
hypsrc-test/src/Operators.hs
|
Haskell
|
bsd-2-clause
| 431
|
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE ExistentialQuantification #-}
module Ivory.Language.Proc where
import Ivory.Language.Monad
import Ivory.Language.Proxy
import Ivory.Language.Type
import Ivory.Language.Effects
import qualified Ivory.Language.Effects as E
import qualified Ivory.Language.Syntax as AST
-- Function Type ---------------------------------------------------------------
-- | The kind of procedures.
data Proc k = [k] :-> k
-- | Typeclass for procedure types, parametrized over the C procedure's
-- signature, to produce a value representing their signature.
class ProcType (sig :: Proc *) where
-- | Turn a type-level description of the signature into a (return
-- type, [argument types]) value.
procType :: Proxy sig -> (AST.Type,[AST.Type])
-- Base case: C procedure taking no arguments and returning an
-- 'IvoryType'.
instance IvoryType r => ProcType ('[] :-> r) where
procType _ = (ivoryType (Proxy :: Proxy r),[])
-- Inductive case: Anything in 'ProcType' is still in 'ProcType' if it
-- has another 'IvoryType' argument prepended to its signature.
instance (IvoryType a, ProcType (args :-> r))
=> ProcType ((a ': args) :-> r) where
procType _ = (r, ivoryType (Proxy :: Proxy a) : args)
where
(r,args) = procType (Proxy :: Proxy (args :-> r))
-- Function Pointers -----------------------------------------------------------
-- | Procedure pointers
newtype ProcPtr (sig :: Proc *) = ProcPtr { getProcPtr :: AST.Name }
instance ProcType proc => IvoryType (ProcPtr proc) where
ivoryType _ = AST.TyProc r args
where
(r,args) = procType (Proxy :: Proxy proc)
instance ProcType proc => IvoryVar (ProcPtr proc) where
wrapVar = ProcPtr . AST.NameVar
unwrapExpr ptr = case getProcPtr ptr of
AST.NameSym sym -> AST.ExpSym sym
AST.NameVar var -> AST.ExpVar var
procPtr :: ProcType sig => Def sig -> ProcPtr sig
procPtr = ProcPtr . defSymbol
-- Function Symbols ------------------------------------------------------------
-- | Procedure definitions.
data Def (proc :: Proc *)
= DefProc AST.Proc
| DefImport AST.Import
deriving (Show, Eq, Ord)
defSymbol :: Def proc -> AST.Name
defSymbol def = case def of
DefProc p -> AST.NameSym (AST.procSym p)
DefImport i -> AST.NameSym (AST.importSym i)
instance ProcType proc => IvoryType (Def proc) where
ivoryType _ = AST.TyProc r args
where
(r,args) = procType (Proxy :: Proxy proc)
-- Procedure Definition --------------------------------------------------------
-- | Procedure definition.
proc :: forall proc impl. IvoryProcDef proc impl => AST.Sym -> impl -> Def proc
proc name impl = defproc
where
(r,args) = procType (Proxy :: Proxy proc)
(vars,def) = procDef initialClosure Proxy impl
defproc = case def of
Defined block -> DefProc $
AST.Proc { AST.procSym = name
, AST.procRetTy = r
, AST.procArgs = zipWith AST.Typed args vars
, AST.procBody = blockStmts block
, AST.procRequires = blockRequires block
, AST.procEnsures = blockEnsures block
}
Imported header reqs ens -> DefImport $
AST.Import { AST.importSym = name
, AST.importFile = header
, AST.importRetTy = r
, AST.importArgs = zipWith AST.Typed args vars
, AST.importRequires = reqs
, AST.importEnsures = ens
}
-- | Type inference can usually determine the argument types of an Ivory
-- procedure, but for void procedures there's often nothing to constrain
-- the return type. This function is a type-constrained version of
-- 'proc' that just forces the return type to be '()'.
voidProc :: IvoryProcDef (args :-> ()) impl =>
AST.Sym -> impl -> Def (args :-> ())
voidProc = proc
newtype Body r = Body
{ runBody :: forall s . Ivory (E.ProcEffects s r) ()
}
class WrapIvory m where
type Return m
wrap :: (forall s . Ivory (E.ProcEffects s r) (Return m)) -> m r
unwrap :: m r -> (forall s . Ivory (E.ProcEffects s r) (Return m))
instance WrapIvory Body where
type Return Body = ()
wrap = Body
unwrap = runBody
body :: IvoryType r
=> (forall s . Ivory (E.ProcEffects s r) ())
-> Body r
body m = Body m
data Definition = Defined CodeBlock
| Imported FilePath [AST.Require] [AST.Ensure]
-- | Typeclass for an Ivory procedure definition to produce ;
-- the type is parametrized over:
--
-- * The procedure type 'proc', encoding the C procedure's signature
-- via the 'Proc' kind,
-- * The implementation type 'impl' - either 'Body' for the return
-- value, or else a Haskell function type whose arguments correspond
-- to the C arguments and whose return type is @Body r@ on the return
-- type @r@.
class ProcType proc => IvoryProcDef (proc :: Proc *) impl | impl -> proc where
procDef :: Closure -> Proxy proc -> impl -> ([AST.Var], Definition)
-- Base case: No arguments in C signature
instance IvoryType ret => IvoryProcDef ('[] :-> ret) (Body ret) where
procDef env _ b = (getEnv env, Defined (snd (primRunIvory (runBody b))))
-- Inductive case: Remove first argument from C signature, and
-- parametrize 'impl' over another argument of the same type.
instance (IvoryVar a, IvoryProcDef (args :-> ret) k)
=> IvoryProcDef ((a ': args) :-> ret) (a -> k) where
procDef env _ k = procDef env' (Proxy :: Proxy (args :-> ret)) (k arg)
where
(var,env') = genVar env
arg = wrapVar var
-- | A variable name supply, and the typed values that have been generated.
data Closure = Closure
{ closSupply :: [AST.Var]
, closEnv :: [AST.Var]
}
-- | Initial closure, with no environment and a large supply of names.
initialClosure :: Closure
initialClosure = Closure
{ closSupply = [ AST.VarName ("var" ++ show (n :: Int)) | n <- [0 ..] ]
, closEnv = []
}
-- | Given a type and a closure, generate a typed variable, and a new closure
-- with that typed variable in it's environment.
genVar :: Closure -> (AST.Var, Closure)
genVar clos = (var, clos')
where
var = head (closSupply clos)
clos' = Closure
{ closSupply = tail (closSupply clos)
, closEnv = var : closEnv clos
}
-- | Retrieve the environment from a closure.
getEnv :: Closure -> [AST.Var]
getEnv = reverse . closEnv
-- Imported Functions ----------------------------------------------------------
-- | Import a function from a C header.
importProc :: forall proc. ProcType proc => AST.Sym -> String -> Def proc
importProc sym file = DefImport AST.Import
{ AST.importSym = sym
, AST.importFile = file
, AST.importRetTy = retTy
, AST.importArgs = args
, AST.importRequires = []
, AST.importEnsures = []
}
where
(retTy, argTys) = procType (Proxy :: Proxy proc)
args = zipWith AST.Typed argTys (closSupply initialClosure)
newtype ImportFrom r = ImportFrom
{ runImportFrom :: forall s . Ivory (E.ProcEffects s r) FilePath
}
instance WrapIvory ImportFrom where
type Return ImportFrom = FilePath
wrap = ImportFrom
unwrap = runImportFrom
importFrom :: String -> ImportFrom a
importFrom h = ImportFrom (return h)
instance IvoryType ret => IvoryProcDef ('[] :-> ret) (ImportFrom ret) where
procDef env _ b = (getEnv env, Imported header reqs ens)
where
(header, block) = primRunIvory (runImportFrom b)
reqs = blockRequires block
ens = blockEnsures block
-- Call ------------------------------------------------------------------------
-- | Direct calls.
call :: forall proc eff impl. IvoryCall proc eff impl => Def proc -> impl
call def = callAux (defSymbol def) (Proxy :: Proxy proc) []
-- | Indirect calls.
indirect :: forall proc eff impl. IvoryCall proc eff impl
=> ProcPtr proc -> impl
indirect ptr = callAux (getProcPtr ptr) (Proxy :: Proxy proc) []
-- | Typeclass for something callable in Ivory (and returning a
-- result). Parameter 'proc' is the procedure type (encoding the
-- arguments and return of the C procedure via the 'Proc' kind, as in
-- 'IvoryProcDef'), parameter 'eff' is the effect context (which
-- remains unchanged through the calls here), and parameter 'impl', as
-- in 'IvoryProcDef', is the implementation type.
class IvoryCall (proc :: Proc *) (eff :: E.Effects) impl
| proc eff -> impl, impl -> eff where
-- | Recursive helper call. 'proc' encodes a C procedure type, and
-- this call has two main parts:
--
-- * If 'proc' contains arguments, then 'impl' must be a function
-- type causing this whole call to expect an Ivory value that was
-- passed in to apply to the C procedure. In this case, 'proc' is
-- reduced by removing the first C argument from the type itself,
-- and the argument to 'impl' is accumulated onto the list of
-- typed expressions.
-- * If 'proc' contains no arguments, then this returns the Ivory
-- effect which calls the function with all the arguments in the
-- list applied to it, and captures and returns the result.
callAux :: AST.Name -> Proxy proc -> [AST.Typed AST.Expr] -> impl
instance IvoryVar r => IvoryCall ('[] :-> r) eff (Ivory eff r) where
-- Base case ('proc' takes no arguments, 'impl' is just an Ivory
-- effect):
callAux sym _ args = do
r <- freshVar "r"
emit (AST.Call (ivoryType (Proxy :: Proxy r)) (Just r) sym (reverse args))
return (wrapVar r)
instance (IvoryVar a, IvoryVar r, IvoryCall (args :-> r) eff impl)
=> IvoryCall ((a ': args) :-> r) eff (a -> impl) where
-- Inductive case: note that 'proc' reduces from ((a ': args) :-> r)
-- down to (args :-> r) in the proxy, and that 'impl' is (a -> impl)
-- and we put that 'a' onto the list of arguments.
callAux sym _ args a = callAux sym rest args'
where
rest = Proxy :: Proxy (args :-> r)
args' = typedExpr a : args
-- Call_ -----------------------------------------------------------------------
-- | Direct calls, ignoring the result.
call_ :: forall proc eff impl. IvoryCall_ proc eff impl => Def proc -> impl
call_ def = callAux_ (defSymbol def) (Proxy :: Proxy proc) []
-- | Indirect calls, ignoring the result.
indirect_ :: forall proc eff impl. IvoryCall_ proc eff impl
=> ProcPtr proc -> impl
indirect_ ptr = callAux_ (getProcPtr ptr) (Proxy :: Proxy proc) []
-- | Typeclass for something callable in Ivory without a return value
-- needed. This is otherwise identical to 'IvoryCall'.
class IvoryCall_ (proc :: Proc *) (eff :: E.Effects) impl
| proc eff -> impl, impl -> eff
where
callAux_ :: AST.Name -> Proxy proc -> [AST.Typed AST.Expr] -> impl
instance IvoryType r => IvoryCall_ ('[] :-> r) eff (Ivory eff ()) where
callAux_ sym _ args = do
emit (AST.Call (ivoryType (Proxy :: Proxy r)) Nothing sym (reverse args))
instance (IvoryVar a, IvoryType r, IvoryCall_ (args :-> r) eff impl)
=> IvoryCall_ ((a ': args) :-> r) eff (a -> impl) where
callAux_ sym _ args a = callAux_ sym rest args'
where
rest = Proxy :: Proxy (args :-> r)
args' = typedExpr a : args
-- Return ----------------------------------------------------------------------
-- | Primitive return from function.
ret :: (GetReturn eff ~ Returns r, IvoryVar r) => r -> Ivory eff ()
ret r = emit (AST.Return (typedExpr r))
-- | Primitive void return from function.
retVoid :: (GetReturn eff ~ Returns ()) => Ivory eff ()
retVoid = emit AST.ReturnVoid
|
Hodapp87/ivory
|
ivory/src/Ivory/Language/Proc.hs
|
Haskell
|
bsd-3-clause
| 11,895
|
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE LambdaCase #-}
module Development.Cake3.Ext.UrWeb where
import Data.Data
import Data.Char
import Data.Typeable
import Data.Generics
import Data.Maybe
import Data.Monoid
import Data.List ()
import qualified Data.List as L
import Data.Set (Set)
import qualified Data.Set as S
import Data.Foldable (Foldable(..), foldl')
import qualified Data.Foldable as F
import Data.ByteString.Char8 (ByteString(..))
import qualified Data.ByteString.Char8 as BS
import qualified Data.Text as T
import Data.String
import Control.Monad.Trans
import Control.Monad.State
import Control.Monad.Writer
import Control.Monad.Error
import Language.JavaScript.Parser as JS
import Network.Mime (defaultMimeLookup)
import Text.Printf
import Text.Parsec as P hiding (string)
import Text.Parsec.Token as P hiding(lexeme, symbol)
import qualified Text.Parsec.Token as P
import Text.Parsec.ByteString as P
import qualified System.FilePath as F
import System.Directory
import System.IO as IO
import System.FilePath.Wrapper
import Development.Cake3.Monad
import Development.Cake3 hiding (many, (<|>))
data UrpAllow = UrpMime | UrpUrl | UrpResponseHeader | UrpEnvVar | UrpHeader
deriving(Show,Data,Typeable)
data UrpRewrite = UrpStyle | UrpAll | UrpTable
deriving(Show,Data,Typeable)
data UrpHdrToken = UrpDatabase String
| UrpSql File
| UrpAllow UrpAllow String
| UrpRewrite UrpRewrite String
| UrpLibrary File
| UrpDebug
| UrpInclude File
| UrpLink (Either File String)
| UrpSrc File String String
| UrpPkgConfig String
| UrpFFI File
| UrpJSFunc String String String -- ^ Module name, UrWeb name, JavaScript name
| UrpSafeGet String
| UrpScript String
| UrpClientOnly String
deriving(Show,Data,Typeable)
data UrpModToken
= UrpModule1 File
| UrpModule2 File File
| UrpModuleSys String
deriving(Show,Data,Typeable)
data Urp = Urp {
urp :: File
, uexe :: Maybe File
, uhdr :: [UrpHdrToken]
, umod :: [UrpModToken]
} deriving(Show,Data,Typeable)
newtype UWLib = UWLib Urp
deriving (Show,Data,Typeable)
newtype UWExe = UWExe Urp
deriving (Show,Data,Typeable)
instance (MonadAction a m) => RefInput a m UWLib where
refInput (UWLib u) = refInput (urp u)
instance (MonadAction a m) => RefInput a m UWExe where
refInput (UWExe u) = refInput (urpExe u)
class UrpLike x where
toUrp :: x -> Urp
tempfiles :: x -> [File]
tempfiles = (\x -> (urpObjs x) ++ maybeToList (urpSql' x) ++ maybeToList (urpExe' x)) . toUrp
instance UrpLike Urp where
toUrp = id
instance UrpLike UWLib where
toUrp (UWLib x) = x
instance UrpLike UWExe where
toUrp (UWExe x) = x
urpDeps :: Urp -> [File]
urpDeps (Urp _ _ hdr mod) = foldl' scan2 (foldl' scan1 mempty hdr) mod where
scan1 a (UrpLink (Left f)) = f:a
scan1 a (UrpSrc f _ _) = (f.="o"):a
scan1 a (UrpInclude f) = f:a
scan1 a _ = a
scan2 a (UrpModule1 f) = f:a
scan2 a (UrpModule2 f1 f2) = f1:f2:a
scan2 a _ = a
urpSql' :: Urp -> Maybe File
urpSql' (Urp _ _ hdr _) = find hdr where
find [] = Nothing
find ((UrpSql f):hs) = Just f
find (h:hs) = find hs
urpSql :: Urp -> File
urpSql u = case urpSql' u of
Nothing -> error "ur project defines no SQL file"
Just sql -> sql
urpSrcs (Urp _ _ hdr _) = foldl' scan [] hdr where
scan a (UrpSrc f cfl lfl) = (f,cfl):a
scan a _ = a
urpObjs (Urp _ _ hdr _) = foldl' scan [] hdr where
scan a (UrpSrc f _ lfl) = (f.="o"):a
scan a (UrpLink (Left f)) = (f):a
scan a _ = a
urpLibs (Urp _ _ hdr _) = foldl' scan [] hdr where
scan a (UrpLibrary f) = f:a
scan a _ = a
urpExe' = uexe
urpExe u = case uexe u of
Nothing -> error "ur project defines no EXE file"
Just exe -> exe
urpPkgCfg (Urp _ _ hdr _) = foldl' scan [] hdr where
scan a (UrpPkgConfig s) = s:a
scan a _ = a
data UrpState = UrpState {
urpst :: Urp
, urautogen :: File
} deriving (Show)
defState urp = UrpState (Urp urp Nothing [] []) (fromFilePath "autogen")
class ToUrpWord a where
toUrpWord :: a -> String
instance ToUrpWord UrpAllow where
toUrpWord (UrpMime) = "mime"
toUrpWord (UrpHeader) = "requestHeader"
toUrpWord (UrpUrl) = "url"
toUrpWord (UrpEnvVar) = "env"
toUrpWord (UrpResponseHeader) = "responseHeader"
instance ToUrpWord UrpRewrite where
toUrpWord (UrpStyle) = "style"
toUrpWord (UrpAll) = "all"
toUrpWord (UrpTable) = "table"
class ToUrpLine a where
toUrpLine :: FilePath -> a -> String
maskPkgCfg s = "%" ++ (map toUpper s) ++ "%"
instance ToUrpLine UrpHdrToken where
toUrpLine up (UrpDatabase dbs) = printf "database %s" dbs
toUrpLine up (UrpSql f) = printf "sql %s" (up </> toFilePath f)
toUrpLine up (UrpAllow a s) = printf "allow %s %s" (toUrpWord a) s
toUrpLine up (UrpRewrite a s) = printf "rewrite %s %s" (toUrpWord a) s
toUrpLine up (UrpLibrary f)
| (takeFileName f) == "lib.urp" = printf "library %s" (up </> toFilePath (takeDirectory f))
| otherwise = printf "library %s" (up </> toFilePath (dropExtension f))
toUrpLine up (UrpDebug) = printf "debug"
toUrpLine up (UrpInclude f) = printf "include %s" (up </> toFilePath f)
toUrpLine up (UrpLink (Left f)) = printf "link %s" (up </> toFilePath f)
toUrpLine up (UrpLink (Right lfl)) = printf "link %s" lfl
toUrpLine up (UrpSrc f _ _) = printf "link %s" (up </> toFilePath (f.="o"))
toUrpLine up (UrpPkgConfig s) = printf "link %s" (maskPkgCfg s)
toUrpLine up (UrpFFI s) = printf "ffi %s" (up </> toFilePath (dropExtensions s))
toUrpLine up (UrpSafeGet s) = printf "safeGet %s" (dropExtensions s)
toUrpLine up (UrpJSFunc s1 s2 s3) = printf "jsFunc %s.%s = %s" s1 s2 s3
toUrpLine up (UrpScript s) = printf "script %s" s
toUrpLine up (UrpClientOnly s) = printf "clientOnly %s" s
toUrpLine up e = error $ "toUrpLine: unhandled case " ++ (show e)
instance ToUrpLine UrpModToken where
toUrpLine up (UrpModule1 f) = up </> toFilePath (dropExtensions f)
toUrpLine up (UrpModule2 f _) = up </> toFilePath (dropExtensions f)
toUrpLine up (UrpModuleSys s) = printf "$/%s" s
newtype UrpGen m a = UrpGen { unUrpGen :: StateT UrpState m a }
deriving(Functor, Applicative, Monad, MonadState UrpState, MonadMake, MonadIO)
toFile f' wr = liftIO $ do
let f = toFilePath f'
createDirectoryIfMissing True (takeDirectory f)
writeFile f $ execWriter $ wr
tempPrefix :: File -> String
tempPrefix f = concat $ map (map nodot) $ splitDirectories f where
nodot '.' = '_'
nodot '/' = '_'
nodot a = a
mkFileRule pfx wr = genFile (tmp_file pfx) $ execWriter $ wr
line :: (MonadWriter String m) => String -> m ()
line s = tell (s++"\n")
uwlib :: File -> UrpGen (Make' IO) () -> Make UWLib
uwlib urpfile m = do
((),s) <- runStateT (unUrpGen m) (defState urpfile)
let u@(Urp _ _ hdr mod) = urpst s
let pkgcfg = (urpPkgCfg u)
forM_ (urpSrcs u) $ \(c,fl) -> do
let flags = concat $ fl : map (\p -> printf "$(shell pkg-config --cflags %s) " p) (urpPkgCfg u)
let i = makevar "URINCL" "-I$(shell urweb -print-cinclude) "
let cc = makevar "URCC" "$(shell $(shell urweb -print-ccompiler) -print-prog-name=gcc)"
let cpp = makevar "URCPP" "$(shell $(shell urweb -print-ccompiler) -print-prog-name=g++)"
let incfl = extvar "UR_CFLAGS"
rule' $ do
case takeExtension c of
".cpp" -> shell [cmd| $cpp -c $incfl $i $(string flags) -o @(c .= "o") $(c) |]
".c" -> shell [cmd| $cc -c $i $incfl $(string flags) -o @(c .= "o") $(c) |]
e -> error ("Unknown C-source extension " ++ e)
inp_in <- mkFileRule (tempPrefix (urpfile .= "in")) $ do
forM hdr (line . toUrpLine (urpUp urpfile))
line ""
forM mod (line . toUrpLine (urpUp urpfile))
rule' $ do
let cpy = [cmd|cat $inp_in|] :: CommandGen' (Make' IO)
let l = foldl' (\a p -> do
let l = makevar (map toUpper $ printf "lib%s" p) (printf "$(shell pkg-config --libs %s)" p)
[cmd| $a | sed 's@@$(string $ maskPkgCfg p)@@$l@@' |]
) cpy pkgcfg
shell [cmd| $l > @urpfile |]
depend (urpDeps u)
depend (urpLibs u)
return $ UWLib u
uwapp :: String -> File -> UrpGen (Make' IO) () -> Make UWExe
uwapp opts urpfile m = do
(UWLib u') <- uwlib urpfile m
let u = u' { uexe = Just (urpfile .= "exe") }
rule $ do
depend urpfile
produce (urpExe u)
case urpSql' u of
Nothing -> return ()
Just sql -> produce sql
depend (makevar "URVERSION" "$(shell urweb -version)")
unsafeShell [cmd|urweb $(string opts) $((takeDirectory urpfile)</>(takeBaseName urpfile))|]
return $ UWExe u
setAutogenDir d = modify $ \s -> s { urautogen = d }
addHdr h = modify $ \s -> let u = urpst s in s { urpst = u { uhdr = (uhdr u) ++ [h] } }
addMod m = modify $ \s -> let u = urpst s in s { urpst = u { umod = (umod u) ++ [m] } }
database :: (MonadMake m) => String -> UrpGen m ()
database dbs = addHdr $ UrpDatabase dbs
allow :: (MonadMake m) => UrpAllow -> String -> UrpGen m ()
allow a s = addHdr $ UrpAllow a s
rewrite :: (MonadMake m) => UrpRewrite -> String -> UrpGen m ()
rewrite a s = addHdr $ UrpRewrite a s
urpUp :: File -> FilePath
urpUp f = F.joinPath $ map (const "..") $ filter (/= ".") $ F.splitDirectories $ F.takeDirectory $ toFilePath f
class LibraryLike x where
library :: (MonadMake m) => x -> UrpGen m ()
instance LibraryLike [File] where
library ls = do
forM_ ls $ \l -> do
when ((takeExtension l) /= ".urp") $ do
fail $ printf "library declaration '%s' should ends with '.urp'" (toFilePath l)
addHdr $ UrpLibrary l
instance LibraryLike UWLib where
library (UWLib u) = library [urp u]
instance LibraryLike x => LibraryLike (Make x) where
library ml = liftMake ml >>= library
-- | Build a file using external Makefile facility.
externalMake3 ::
File -- ^ External Makefile
-> File -- ^ External file to refer to
-> String -- ^ The name of the target to run
-> Make [File]
externalMake3 mk f tgt = do
prebuildS [cmd|$(make) -C $(string $ toFilePath $ takeDirectory mk) -f $(string $ takeFileName mk) $(string tgt) |]
return [f]
-- | Build a file using external Makefile facility.
externalMake' ::
File -- ^ External Makefile
-> File -- ^ External file to refer to
-> Make [File]
externalMake' mk f = do
prebuildS [cmd|$(make) -C $(string $ toFilePath $ takeDirectory mk) -f $(string $ takeFileName mk)|]
return [f]
-- | Build a file from external project. It is expected, that this project has a
-- 'Makwfile' in it's root directory. Call Makefile with the default target
externalMake ::
File -- ^ File from the external project to build
-> Make [File]
externalMake f = externalMake3 (takeDirectory f </> "Makefile") f ""
-- | Build a file from external project. It is expected, that this project has a
-- 'Makwfile' in it's root directory
externalMakeTarget ::
File -- ^ File from the external project to build
-> String
-> Make [File]
externalMakeTarget f tgt = externalMake3 (takeDirectory f </> "Makefile") f tgt
-- | Build a file from external project. It is expected, that this project has a
-- fiel.mk (a Makefile with an unusual name) in it's root directory
externalMake2 :: File -> Make [File]
externalMake2 f = externalMake' ((takeDirectory f </> takeFileName f) .= "mk") f
ur, module_ :: (MonadMake m) => UrpModToken -> UrpGen m ()
module_ = addMod
ur = addMod
pair f = UrpModule2 (f.="ur") (f.="urs")
single f = UrpModule1 f
sys s = UrpModuleSys s
debug :: (MonadMake m) => UrpGen m ()
debug = addHdr $ UrpDebug
include :: (MonadMake m) => File -> UrpGen m ()
include f = addHdr $ UrpInclude f
link' :: (MonadMake m) => File -> String -> UrpGen m ()
link' f fl = do
addHdr $ UrpLink (Left f)
when (fl /= "") $ do
addHdr $ UrpLink (Right fl)
link :: (MonadMake m) => File -> UrpGen m ()
link f = link' f []
csrc' :: (MonadMake m) => File -> String -> String -> UrpGen m ()
csrc' f cfl lfl = do
addHdr $ UrpSrc f cfl lfl
when (lfl /= "") $ do
addHdr $ UrpLink (Right lfl)
csrc :: (MonadMake m) => File -> UrpGen m ()
csrc f = csrc' f [] []
ffi :: (MonadMake m) => File -> UrpGen m ()
ffi s = addHdr $ UrpFFI s
sql :: (MonadMake m) => File -> UrpGen m ()
sql f = addHdr $ UrpSql f
jsFunc m u j = addHdr $ UrpJSFunc m u j
safeGet' :: (MonadMake m) => String -> UrpGen m ()
safeGet' uri
| otherwise = addHdr $ UrpSafeGet uri
safeGet :: (MonadMake m) => File -> String -> UrpGen m ()
safeGet m fn
| (takeExtension m) /= ".ur" = fail (printf "safeGet: not an Ur/Web module name specified (%s)" (toFilePath m))
| otherwise = safeGet' (printf "%s/%s" (takeBaseName m) fn)
url = UrpUrl
mime = UrpMime
style = UrpStyle
all = UrpAll
table = UrpTable
env = UrpEnvVar
hdr = UrpHeader
requestHeader = UrpHeader
responseHeader = UrpResponseHeader
script :: (MonadMake m) => String -> UrpGen m ()
script s = addHdr $ UrpScript s
guessMime inf = fixup $ BS.unpack (defaultMimeLookup (fromString inf)) where
fixup "application/javascript" = "text/javascript"
fixup m = m
pkgconfig :: (MonadMake m) => String -> UrpGen m ()
pkgconfig l = addHdr $ UrpPkgConfig l
type BinOptions = [ BinOption ]
data BinOption = NoScan | UseUrembed deriving(Show, Eq)
bin :: (MonadIO m, MonadMake m) => File -> BinOptions -> UrpGen m ()
bin src bo = do
let ds = if NoScan `elem` bo then "--dont-scan" else ""
case UseUrembed `elem` bo of
False -> do
c <- readFileForMake src
bin' (toFilePath src) c bo
True -> do
a <- urautogen `liftM` get
library $ do
rule $ shell [cmd|urembed -o @(a </> (takeFileName src .="urp")) $(string ds) $src|]
bin' :: (MonadIO m, MonadMake m) => FilePath -> BS.ByteString -> BinOptions -> UrpGen m ()
bin' src_name src_contents' bo = do
dir <- urautogen `liftM` get
let mm = guessMime src_name
let mn = (mkname src_name)
let wrapmod ext = (dir </> mn) .= ext
let binmod ext = (dir </> (mn ++ "_c")) .= ext
let jsmod ext = (dir </> (mn ++ "_js")) .= ext
(src_contents, nurls) <-
if not (NoScan `elem` bo) then
if ((takeExtension src_name) == ".css") then do
(e,urls) <- return $ runWriter $ parse_css src_contents' $ \x -> do
let (url, query) = span (\c -> not $ elem c "?#") x
let mn = modname (const (fromFilePath $ mkname url))
tell [ mn ]
return $ "/" ++ mn ++ "/blobpage" ++ query
case e of
Left e -> do
fail $ printf "Error while parsing css %s: %s" src_name (show e)
Right b -> do
return (b, L.nub urls)
else
return (src_contents', [])
else
return (src_contents', [])
-- Binary module
let binfunc = printf "uw_%s_binary" (modname binmod)
let textfunc = printf "uw_%s_text" (modname binmod)
toFile (binmod ".c") $ do
line $ "/* Thanks, http://stupefydeveloper.blogspot.ru/2008/08/cc-embed-binary-data-into-elf.html */"
line $ "#include <urweb.h>"
line $ "#include <stdio.h>"
line $ printf "#define BLOBSZ %d" (BS.length src_contents)
line $ "static char blob[BLOBSZ];"
line $ "uw_Basis_blob " ++ binfunc ++ " (uw_context ctx, uw_unit unit)"
line $ "{"
line $ " uw_Basis_blob uwblob;"
line $ " uwblob.data = &blob[0];"
line $ " uwblob.size = BLOBSZ;"
line $ " return uwblob;"
line $ "}"
line $ ""
line $ "uw_Basis_string " ++ textfunc ++ " (uw_context ctx, uw_unit unit) {"
line $ " char* data = &blob[0];"
line $ " size_t size = sizeof(blob);"
line $ " char * c = uw_malloc(ctx, size+1);"
line $ " char * write = c;"
line $ " int i;"
line $ " for (i = 0; i < size; i++) {"
line $ " *write = data[i];"
line $ " if (*write == '\\0')"
line $ " *write = '\\n';"
line $ " *write++;"
line $ " }"
line $ " *write=0;"
line $ " return c;"
line $ " }"
line $ ""
let append f wr = liftIO $ BS.appendFile f $ execWriter $ wr
append (toFilePath (binmod ".c")) $ do
let line s = tell ((BS.pack s)`mappend`(BS.pack "\n"))
line $ ""
line $ "static char blob[BLOBSZ] = {"
let buf = reverse $ BS.foldl (\a c -> (BS.pack (printf "0x%02X ," c)) : a) [] src_contents
tell (BS.concat buf)
line $ "};"
line $ ""
toFile (binmod ".h") $ do
line $ "#include <urweb.h>"
line $ "uw_Basis_blob " ++ binfunc ++ " (uw_context ctx, uw_unit unit);"
line $ "uw_Basis_string " ++ textfunc ++ " (uw_context ctx, uw_unit unit);"
toFile (binmod ".urs") $ do
line $ "val binary : unit -> transaction blob"
line $ "val text : unit -> transaction string"
include (binmod ".h")
csrc (binmod ".c")
ffi (binmod ".urs")
-- JavaScript FFI Module
(jstypes,jsdecls) <-
if not (NoScan `elem` bo) then
if ((takeExtension src_name) == ".js") then do
e <- liftMake $ parse_js src_contents
case e of
Left e -> do
fail $ printf "Error while parsing javascript %s: %s" src_name e
Right decls -> do
return decls
else
return ([],[])
else
return ([],[])
forM_ jsdecls $ \decl -> do
addHdr $ UrpJSFunc (modname jsmod) (urname decl) (jsname decl)
addHdr $ UrpClientOnly $ (modname jsmod) ++ "." ++ (urname decl)
toFile (jsmod ".urs") $ do
forM_ jstypes $ \decl -> line (urtdecl decl)
forM_ jsdecls $ \decl -> line (urdecl decl)
ffi (jsmod ".urs")
-- Wrapper module
toFile (wrapmod ".urs") $ do
line $ "val binary : unit -> transaction blob"
line $ "val text : unit -> transaction string"
line $ "val blobpage : unit -> transaction page"
line $ "val geturl : url"
forM_ jstypes $ \decl -> line (urtdecl decl)
forM_ jsdecls $ \d -> line (urdecl d)
line $ "val propagated_urls : list url"
toFile (wrapmod ".ur") $ do
line $ "val binary = " ++ modname binmod ++ ".binary"
line $ "val text = " ++ modname binmod ++ ".text"
forM_ jsdecls $ \d ->
line $ printf "val %s = %s.%s" (urname d) (modname jsmod) (urname d)
line $ printf "fun blobpage {} = b <- binary () ; returnBlob b (blessMime \"%s\")" mm
line $ "val geturl = url(blobpage {})"
line $ "val propagated_urls = "
forM_ nurls $ \u -> do
line $ " " ++ u ++ ".geturl ::"
line $ " []"
allow mime mm
safeGet (wrapmod ".ur") "blobpage"
safeGet (wrapmod ".ur") "blob"
module_ (pair $ wrapmod ".ur")
where
mkname :: FilePath -> String
mkname = upper1 . notnum . map under . takeFileName where
under c | c`elem`"_-. /" = '_'
| otherwise = c
upper1 [] = []
upper1 (x:xs) = (toUpper x) : xs
notnum n@(x:xs) | isDigit x = "f" ++ n
| otherwise = n
modname :: (String -> File) -> String
modname f = upper1 . takeBaseName $ f ".urs" where
upper1 [] = []
upper1 (x:xs) = (toUpper x) : xs
{-
- Content parsing helpers
-}
data JSFunc = JSFunc {
urdecl :: String -- ^ URS declaration for this function
, urname :: String -- ^ UrWeb name of this function
, jsname :: String -- ^ JavaScript name of this function
} deriving(Show)
data JSType = JSType {
urtdecl :: String
} deriving(Show)
-- | Parse the JavaScript file, extract top-level functions, convert their
-- signatures into Ur/Web format, return them as the list of strings
parse_js :: BS.ByteString -> Make (Either String ([JSType],[JSFunc]))
parse_js contents = do
runErrorT $ do
c <- either fail return (JS.parse (BS.unpack contents) "<urembed_input>")
f <- concat <$> (forM (findTopLevelFunctions c) $ \f@(fn:_) -> (do
ts <- mapM extractEmbeddedType (f`zip`(False:repeat True))
let urdecl_ = urs_line ts
let urname_ = (fst (head ts))
let jsname_ = fn
return [JSFunc urdecl_ urname_ jsname_]
) `catchError` (\(e::String) -> do
err $ printf "ignoring function %s, reason:\n\t%s" fn e
return []))
t <- concat <$> (forM (findTopLevelVars c) $ \vn -> (do
(n,t) <- extractEmbeddedType (vn,False)
return [JSType $ printf "type %s" t]
)`catchError` (\(e::String) -> do
err $ printf "ignoring variable %s, reason:\n\t%s" vn e
return []))
return (t,f)
where
urs_line :: [(String,String)] -> String
urs_line [] = error "wrong function signature"
urs_line ((n,nt):args) = printf "val %s : %s" n (fmtargs args) where
fmtargs :: [(String,String)] -> String
fmtargs ((an,at):as) = printf "%s -> %s" at (fmtargs as)
fmtargs [] = let pf = L.stripPrefix "pure_" nt in
case pf of
Just p -> p
Nothing -> printf "transaction %s" nt
extractEmbeddedType :: (Monad m) => (String,Bool) -> m (String,String)
extractEmbeddedType ([],_) = error "BUG: empty identifier"
extractEmbeddedType (name,fallback) = check (msum [span2 "__" name , span2 "_as_" name]) where
check (Just (n,t)) = return (n,t)
check _ | fallback == True = return (name,name)
| fallback == False = fail $ printf "Can't extract the type from the identifier '%s'" name
findTopLevelFunctions :: JSNode -> [[String]]
findTopLevelFunctions top = map decls $ listify is_func top where
is_func n@(JSFunction a b c d e f) = True
is_func _ = False
decls (JSFunction a b c d e f) = (identifiers b) ++ (identifiersC d)
findTopLevelVars :: JSNode -> [String]
findTopLevelVars top = map decls $ listify is_var top where
is_var n@(JSVarDecl a []) = True
is_var _ = False
decls (JSVarDecl a _) = (head $ identifiers a);
identifiersC x = map name $ listify ids x where
ids i@(NT (JSIdentifier s) _ com) = True
ids _ = False
name (NT (JSIdentifier n) _ com)
| not $ null $ comglue = n ++ "_as_" ++ comglue
| otherwise = n
where
comglue = concat $ map
(\c ->
case c of
CommentA _ c -> unwords $ filter (\c -> c /= "/*" && c /= "*/") $ words c
_ -> "") com
identifiers x = map name $ listify ids x where
ids i@(JSIdentifier s) = True
ids _ = False
name (JSIdentifier n) = n
err,out :: (MonadIO m) => String -> m ()
err = hio stderr
out = hio stdout
span2 :: String -> String -> Maybe (String,String)
span2 inf s = span' [] s where
span' _ [] = Nothing
span' acc (c:cs)
| L.isPrefixOf inf (c:cs) = Just (acc, drop (length inf) (c:cs))
| otherwise = span' (acc++[c]) cs
hio :: (MonadIO m) => Handle -> String -> m ()
hio h = liftIO . hPutStrLn h
transform_css :: (Stream s m Char) => ParsecT s u m [Either ByteString [Char]]
transform_css = do
l1 <- map Left <$> blabla
l2 <- map Right <$> funs
e <- try (eof >> return True) <|> (return False)
case e of
True -> return (l1++l2)
False -> do
l <- transform_css
return (l1 ++ l2 ++ l)
where
symbol = P.symbol l
lexeme = P.lexeme l
string = lexeme (
between (char '\'') (char '\'') (strchars '\'') <|>
between (char '"') (char '"') (strchars '"')) <|>
manyTill anyChar (try (char ')'))
where
strchars e = many $ satisfy (/=e)
fun1 = lexeme $ do
symbol "url"
symbol "("
s <- string
symbol ")"
return s
blabla = do
l <- manyTill anyChar (eof <|> (try (lookAhead fun1) >> return ()))
case null l of
True -> return []
False -> return [BS.pack l]
funs = many (try fun1)
l = P.makeTokenParser $ P.LanguageDef
{ P.commentStart = "/*"
, P.commentEnd = "*/"
, P.commentLine = "//"
, P.nestedComments = True
, P.identStart = P.letter
, P.identLetter = P.alphaNum <|> oneOf "_@-"
, P.reservedNames = []
, P.reservedOpNames = []
, P.caseSensitive = False
, P.opStart = l
, P.opLetter = l
}
where l = oneOf ":!#$%&*+./<=>?@\\^|-~"
parse_css :: (Monad m) => BS.ByteString -> (String -> m String) -> m (Either P.ParseError BS.ByteString)
parse_css inp f = do
case P.runParser transform_css () "-" inp of
Left e -> return $ Left e
Right pr -> do
b <- forM pr $ \i -> do
case i of
Left bs -> return bs
Right u -> do
u' <- f u
return (BS.pack $ "url('" ++ u' ++ "')")
return $ Right $ BS.concat b
|
grwlf/cake3
|
src/Development/Cake3/Ext/UrWeb1.hs
|
Haskell
|
bsd-3-clause
| 24,818
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ViewPatterns #-}
-- | Build project(s).
module Stack.Build
(build
,clean)
where
import Control.Monad
import Control.Monad.Catch (MonadCatch, MonadMask)
import Control.Monad.IO.Class
import Control.Monad.Logger
import Control.Monad.Reader (MonadReader, asks)
import Control.Monad.Trans.Resource
import Data.Either
import Data.Function
import Data.Map.Strict (Map)
import qualified Data.Set as S
import Network.HTTP.Client.Conduit (HasHttpManager)
import Path.IO
import Prelude hiding (FilePath, writeFile)
import Stack.Build.ConstructPlan
import Stack.Build.Execute
import Stack.Build.Installed
import Stack.Build.Source
import Stack.Build.Types
import Stack.Constants
import Stack.Fetch as Fetch
import Stack.GhcPkg
import Stack.Package
import Stack.Types
import Stack.Types.Internal
{- EKB TODO: doc generation for stack-doc-server
#ifndef mingw32_HOST_OS
import System.Posix.Files (createSymbolicLink,removeLink)
#endif
--}
type M env m = (MonadIO m,MonadReader env m,HasHttpManager env,HasBuildConfig env,MonadLogger m,MonadBaseControl IO m,MonadCatch m,MonadMask m,HasLogLevel env)
-- | Build
build :: M env m => BuildOpts -> m ()
build bopts = do
menv <- getMinimalEnvOverride
cabalPkgVer <- getCabalPkgVer menv
(mbp, locals, sourceMap) <- loadSourceMap bopts
(installedMap, locallyRegistered) <- getInstalled menv profiling sourceMap
baseConfigOpts <- mkBaseConfigOpts bopts
let extraToBuild = either (const []) id $ boptsTargets bopts
plan <- withLoadPackage menv $ \loadPackage ->
constructPlan mbp baseConfigOpts locals extraToBuild locallyRegistered loadPackage sourceMap installedMap
if boptsDryrun bopts
then printPlan plan
else executePlan menv bopts baseConfigOpts cabalPkgVer locals plan
where
profiling = boptsLibProfile bopts || boptsExeProfile bopts
-- | Get the @BaseConfigOpts@ necessary for constructing configure options
mkBaseConfigOpts :: (MonadIO m, MonadReader env m, HasBuildConfig env, MonadThrow m)
=> BuildOpts -> m BaseConfigOpts
mkBaseConfigOpts bopts = do
snapDBPath <- packageDatabaseDeps
localDBPath <- packageDatabaseLocal
snapInstallRoot <- installationRootDeps
localInstallRoot <- installationRootLocal
return BaseConfigOpts
{ bcoSnapDB = snapDBPath
, bcoLocalDB = localDBPath
, bcoSnapInstallRoot = snapInstallRoot
, bcoLocalInstallRoot = localInstallRoot
, bcoBuildOpts = bopts
}
-- | Provide a function for loading package information from the package index
withLoadPackage :: M env m
=> EnvOverride
-> ((PackageName -> Version -> Map FlagName Bool -> IO Package) -> m a)
-> m a
withLoadPackage menv inner = do
bconfig <- asks getBuildConfig
withCabalLoader menv $ \cabalLoader ->
inner $ \name version flags -> do
bs <- cabalLoader $ PackageIdentifier name version -- TODO automatically update index the first time this fails
readPackageBS (depPackageConfig bconfig flags) bs
where
-- | Package config to be used for dependencies
depPackageConfig :: BuildConfig -> Map FlagName Bool -> PackageConfig
depPackageConfig bconfig flags = PackageConfig
{ packageConfigEnableTests = False
, packageConfigEnableBenchmarks = False
, packageConfigFlags = flags
, packageConfigGhcVersion = bcGhcVersion bconfig
, packageConfigPlatform = configPlatform (getConfig bconfig)
}
-- | Reset the build (remove Shake database and .gen files).
clean :: (M env m) => m ()
clean = do
bconfig <- asks getBuildConfig
menv <- getMinimalEnvOverride
cabalPkgVer <- getCabalPkgVer menv
forM_
(S.toList (bcPackages bconfig))
(distDirFromDir cabalPkgVer >=> removeTreeIfExists)
----------------------------------------------------------
-- DEAD CODE BELOW HERE
----------------------------------------------------------
{- EKB TODO: doc generation for stack-doc-server
(boptsFinalAction bopts == DoHaddock)
(buildDocIndex
(wanted pwd)
docLoc
packages
mgr
logLevel)
-}
{- EKB TODO: doc generation for stack-doc-server
-- | Build the haddock documentation index and contents.
buildDocIndex :: (Package -> Wanted)
-> Path Abs Dir
-> Set Package
-> Manager
-> LogLevel
-> Rules ()
buildDocIndex wanted docLoc packages mgr logLevel =
do runHaddock "--gen-contents" $(mkRelFile "index.html")
runHaddock "--gen-index" $(mkRelFile "doc-index.html")
combineHoogle
where
runWithLogging = runStackLoggingT mgr logLevel
runHaddock genOpt destFilename =
do let destPath = toFilePath (docLoc </> destFilename)
want [destPath]
destPath %> \_ ->
runWithLogging
(do needDeps
ifcOpts <- liftIO (fmap concat (mapM toInterfaceOpt (S.toList packages)))
runIn docLoc
"haddock"
mempty
(genOpt:ifcOpts)
Nothing)
toInterfaceOpt package =
do let pv = joinPkgVer (packageName package,packageVersion package)
srcPath = (toFilePath docLoc) ++ "/" ++
pv ++ "/" ++
packageNameString (packageName package) ++ "." ++
haddockExtension
exists <- doesFileExist srcPath
return (if exists
then ["-i"
,"../" ++
pv ++
"," ++
srcPath]
else [])
combineHoogle =
do let destHoogleDbLoc = hoogleDatabaseFile docLoc
destPath = toFilePath destHoogleDbLoc
want [destPath]
destPath %> \_ ->
runWithLogging
(do needDeps
srcHoogleDbs <- liftIO (fmap concat (mapM toSrcHoogleDb (S.toList packages)))
callProcess
"hoogle"
("combine" :
"-o" :
toFilePath destHoogleDbLoc :
srcHoogleDbs))
toSrcHoogleDb package =
do let srcPath = toFilePath docLoc ++ "/" ++
joinPkgVer (packageName package,packageVersion package) ++ "/" ++
packageNameString (packageName package) ++ "." ++
hoogleDbExtension
exists <- doesFileExist srcPath
return (if exists
then [srcPath]
else [])
needDeps =
need (concatMap (\package -> if wanted package == Wanted
then let dir = packageDir package
in [toFilePath (builtFileFromDir dir)]
else [])
(S.toList packages))
#ifndef mingw32_HOST_OS
-- | Remove existing links docs for package from @~/.shake/doc@.
removeDocLinks :: Path Abs Dir -> Package -> IO ()
removeDocLinks docLoc package =
do createDirectoryIfMissing True
(toFilePath docLoc)
userDocLs <-
fmap (map (toFilePath docLoc ++))
(getDirectoryContents (toFilePath docLoc))
forM_ userDocLs $
\docPath ->
do isDir <- doesDirectoryExist docPath
when isDir
(case breakPkgVer (FilePath.takeFileName docPath) of
Just (p,_) ->
when (p == packageName package)
(removeLink docPath)
Nothing -> return ())
-- | Add link for package to @~/.shake/doc@.
createDocLinks :: Path Abs Dir -> Package -> IO ()
createDocLinks docLoc package =
do let pkgVer =
joinPkgVer (packageName package,(packageVersion package))
pkgVerLoc <- liftIO (parseRelDir pkgVer)
let pkgDestDocLoc = docLoc </> pkgVerLoc
pkgDestDocPath =
FilePath.dropTrailingPathSeparator (toFilePath pkgDestDocLoc)
cabalDocLoc = parent docLoc </>
$(mkRelDir "share/doc/")
haddockLocs <-
do cabalDocExists <- doesDirectoryExist (toFilePath cabalDocLoc)
if cabalDocExists
then findFiles cabalDocLoc
(\fileLoc ->
FilePath.takeExtensions (toFilePath fileLoc) ==
"." ++ haddockExtension &&
dirname (parent fileLoc) ==
$(mkRelDir "html/") &&
toFilePath (dirname (parent (parent fileLoc))) ==
(pkgVer ++ "/"))
(\dirLoc ->
not (isHiddenDir dirLoc) &&
dirname (parent (parent dirLoc)) /=
$(mkRelDir "html/"))
else return []
case haddockLocs of
[haddockLoc] ->
case stripDir (parent docLoc)
haddockLoc of
Just relHaddockPath ->
do let srcRelPathCollapsed =
FilePath.takeDirectory (FilePath.dropTrailingPathSeparator (toFilePath relHaddockPath))
{-srcRelPath = "../" ++ srcRelPathCollapsed-}
createSymbolicLink (FilePath.dropTrailingPathSeparator srcRelPathCollapsed)
pkgDestDocPath
Nothing -> return ()
_ -> return ()
#endif /* not defined(mingw32_HOST_OS) */
-- | Get @-i@ arguments for haddock for dependencies.
haddockInterfaceOpts :: Path Abs Dir -> Package -> Set Package -> IO [String]
haddockInterfaceOpts userDocLoc package packages =
do mglobalDocLoc <- getGlobalDocPath
globalPkgVers <-
case mglobalDocLoc of
Nothing -> return M.empty
Just globalDocLoc -> getDocPackages globalDocLoc
let toInterfaceOpt pn =
case find (\dpi -> packageName dpi == pn) (S.toList packages) of
Nothing ->
return (case (M.lookup pn globalPkgVers,mglobalDocLoc) of
(Just (v:_),Just globalDocLoc) ->
["-i"
,"../" ++ joinPkgVer (pn,v) ++
"," ++
toFilePath globalDocLoc ++ "/" ++
joinPkgVer (pn,v) ++ "/" ++
packageNameString pn ++ "." ++
haddockExtension]
_ -> [])
Just dpi ->
do let destPath = (toFilePath userDocLoc ++ "/" ++
joinPkgVer (pn,packageVersion dpi) ++ "/" ++
packageNameString pn ++ "." ++
haddockExtension)
exists <- doesFileExist destPath
return (if exists
then ["-i"
,"../" ++
joinPkgVer (pn,packageVersion dpi) ++
"," ++
destPath]
else [])
--TODO: use not only direct dependencies, but dependencies of dependencies etc.
--(e.g. redis-fp doesn't include @text@ in its dependencies which means the 'Text'
--datatype isn't linked in its haddocks)
fmap concat (mapM toInterfaceOpt (S.toList (packageAllDeps package)))
--------------------------------------------------------------------------------
-- Paths
{- EKB TODO: doc generation for stack-doc-server
-- | Returns true for paths whose last directory component begins with ".".
isHiddenDir :: Path b Dir -> Bool
isHiddenDir = isPrefixOf "." . toFilePath . dirname
-}
--}
|
mietek/stack
|
src/Stack/Build.hs
|
Haskell
|
bsd-3-clause
| 12,655
|
{-# OPTIONS -Wall #-}
-- The pec embedded compiler
-- Copyright 2011-2012, Brett Letner
module Pec.LLVM (dModule) where
import Control.Concurrent
import Data.Char
import Data.Generics.Uniplate.Data
import Data.List
import Data.Maybe
import Development.Shake.FilePath
import Grm.Prims
import Language.LLVM.Abs
import Numeric
import Pec.IUtil
import qualified Language.Pir.Abs as I
data St = St
{ strings :: [(String,String)]
, free_vars :: [String]
, enums :: [(String,Integer)]
, fields :: [(String,Integer)]
, tydecls :: [(String,I.TyDecl)]
, defines :: [Define]
}
dModule :: FilePath -> I.Module -> IO ()
dModule outdir m@(I.Module a _ _) = do
xs <- readMVar gTyDecls
let st0 = St{ strings = ss
, enums = concatMap tyEnums $ universeBi xs
, free_vars = map vtvar ifvs
, fields = concatMap tyFields $ universeBi xs
, tydecls = [ (dTypeVar y, z) | (y, z) <- xs ]
, defines = []
}
let ds = map (dTypeD st0) xs
let st = st0{ defines = ds }
writeFileBinary (joinPath [outdir, fn]) $
ppShow $
transformBi elimNoOpS $
transformBi allocasAtStart $
Module $
map dStringD ss ++
ds ++
map dBuiltin builtinTbl ++
map (dDeclare st) ifvs ++
map (dDefine st) cs
where
I.Module _ _ cs = transformBi inlineAtoms m
ifvs = nub $ concatMap fvsIDefine cs
fn = n ++ ".ll"
n = case a of
"" -> error "unused:dModule"
_ -> init a
ss = [ (s, "@.str" ++ show i)
| (I.StringL s ,i) <- zip (nub $ sort $ universeBi m)
[ 0 :: Int .. ]]
dDeclare :: St -> I.TVar -> Define
dDeclare st x = case ty of
PtrT (FunT a bs) -> Declare a v bs
_ -> error $ "declare not a function type:" ++ ppShow x
where
TVar ty v = dTVar st x
dTypeD :: St -> (I.Type, I.TyDecl) -> Define
dTypeD st (x,y) = TypeD (dTypeVar x) $ dTyDecl st y
dTypeVar :: I.Type -> String
dTypeVar x0 = '%' : loop x0
where
loop x = case x of
I.Type a [] -> a
I.Type a xs ->
a ++ "$" ++ concat (intersperse "." $ map loop xs) ++ "$"
dTyDecl :: St -> I.TyDecl -> Type
dTyDecl st x = case x of
I.TyEnum bs -> lengthT bs
I.TyRecord bs -> StructT $ map dFieldT bs
I.TyTagged bs -> StructT
[ lengthT bs
, maximumBy (\a b -> compare (sizeT st a) (sizeT st b))
[ dType t | I.ConC _ t <- bs ]
]
lengthT :: [a] -> Type
lengthT = IntT . show . bitsToEncode . genericLength
sizeT :: St -> Type -> Integer
sizeT st x = case x of
VoidT -> 0
CharT -> 8
FloatT -> 32
DoubleT -> 64
PtrT{} -> sizeofptr
FunT{} -> sizeofptr
IntT a -> read a
StructT bs -> sum $ map (sizeT st) bs
ArrayT a b -> read a * (sizeT st b)
UserT a -> case lookup a $ tydecls st of
Just b -> sizeT st $ dTyDecl st b
Nothing -> error $ "unused:sizeT:UserT:" ++ ppShow x
VarArgsT -> error $ "unused:sizeT:VarArgsT:" ++ ppShow x
sizeofptr :: Integer
sizeofptr = 32
dFieldT :: I.FieldT -> Type
dFieldT (I.FieldT _ b) = dType b
dVar :: Bool -> String -> String
dVar is_free v = (if is_free then '@' else '%') : map f v
where
f c = case c of
'~' -> '$'
_ -> c
dDefine :: St -> I.Define -> Define
dDefine st (I.Define a b cs ds) =
Define (dType a) (dVar True b) (map (dTVar st) cs)
(concatMap (dStmt st) ds)
dStmt :: St -> I.Stmt -> [Stmt]
dStmt st x = case x of
I.LetS a b -> dExp st a b
I.StoreS a b -> [ StoreS (dAtom st b) (dTVar st a) ]
I.CallS a b -> [ CallS (dTVar st a) (map (dAtom st) b) ]
I.SwitchS a b cs -> concat
[ [ SwitchS (dAtom st a) l1 $ map (dSwitchAlt st) lcs ]
, [ LabelS l1 ]
, concatMap (dStmt st) b
, [ Br0S l0 ]
, concatMap (dSwitchAltBody st l0) lcs
, [ LabelS l0 ]
]
where
l0 = uLbl a
l1 = uLbl b
lcs = [ (uLbl c, c) | c <- cs ]
I.IfS a b c -> concat
[ [ BrS (duAtom st a) l1 l2 ]
, [ LabelS l1 ]
, concatMap (dStmt st) b
, [ Br0S l3 ]
, [ LabelS l2 ]
, concatMap (dStmt st) c
, [ Br0S l3 ]
, [ LabelS l3 ]
]
where
l1 = uLbl a
l2 = uLbl b
l3 = uLbl c
I.WhenS a b -> concat
[ [ BrS (duAtom st a) l1 l2 ]
, [ LabelS l1 ]
, concatMap (dStmt st) b
, [ Br0S l2 ]
, [ LabelS l2 ]
]
where
l1 = uLbl a
l2 = uLbl b
I.WhileS a b c -> concat
[ [ Br0S l0 ]
, [ LabelS l0 ]
, concatMap (dStmt st) a
, [ BrS (duAtom st b) l1 l2 ]
, [ LabelS l1 ]
, concatMap (dStmt st) c
, [ Br0S l0 ]
, [ LabelS l2 ]
]
where
l0 = uLbl a
l1 = uLbl b
l2 = uLbl c
I.ReturnS a -> [ ReturnS $ dAtom st a ]
I.NoOpS -> []
uLbl :: a -> String
uLbl a = uId a "Lbl"
dSwitchAlt :: St -> (String, I.SwitchAlt) -> SwitchAlt
dSwitchAlt st (lbl, I.SwitchAlt a _) = SwitchAlt tl lbl
where
tl = case dTLit st a of
TLit (PtrT (FunT b _)) c -> TLit b c -- BAL: Shouldn't base report the correct type here without the need for this fixup?
b -> b
dSwitchAltBody :: St -> String -> (String, I.SwitchAlt) -> [Stmt]
dSwitchAltBody st lbl0 (lbl, I.SwitchAlt _ b) = concat
[ [ LabelS lbl ]
, concatMap (dStmt st) b
, [ Br0S lbl0 ]
]
variantTypes :: St -> Exp -> (Type,Type)
variantTypes st x = case [ (a, b) | TypeD v (StructT [a,b]) <- defines st, v == v0 ] of
[y] -> y
_ -> error $ "unused:variantTypes:" ++ ppShow x
where
IdxE (TVar (PtrT (UserT v0)) _) _ = x
fldE :: TVar -> Integer -> Exp
fldE a i = IdxE a $ LitA $ TLit (IntT "32") $ NmbrL $ show i
bitcastE :: TVar -> Type -> Exp
bitcastE = CastE Bitcast
dExp :: St -> I.TVar -> I.Exp -> [Stmt]
dExp st tv@(I.TVar v t) x = case x of
I.CallE (I.TVar "tagv" _) [I.VarA b] ->
[ LetS v1 $ fldE (dTVar st b) 0, letS $ LoadE $ TVar (PtrT $ dType t) v1 ]
where
v1 = uId b "%.tag"
I.CallE (I.TVar "un" _) [_, I.VarA c] ->
[ LetS v1 e, letS $ bitcastE (TVar (PtrT ta) v1) tb ]
where
v1 = uId c "%.data"
e = fldE (dTVar st c) 1
(_,ta) = variantTypes st e
tb = dType t
I.CallE (I.TVar "mk" a) [I.LitA (I.TLit (I.StringL b) _)] -> fst $ dTag st tv a b
I.CallE (I.TVar "mk" a) [I.LitA (I.TLit (I.StringL b) _), c] ->
ss0 ++
[ LetS datap0 $ fldE tv1 1
, LetS datap1 $ bitcastE (TVar (PtrT tb) datap0) (PtrT tc)
, StoreS atomc (TVar (PtrT tc) datap1)
, s
]
where
(ss,(tv1,tb)) = dTag st tv a b
(ss0, s) = (init ss, last ss)
datap0 = uId c "%.data"
datap1 = uId datap0 "%.data"
atomc = dAtom st c
tc = tyAtom atomc
I.CallE a [I.VarA b] | isJust mi -> [ letS $ fldE (dTVar st b) $ fromJust mi ]
where mi = lookup (vtvar a) $ fields st
I.CallE (I.TVar "idx" _) [I.VarA b, c] -> [ letS $ IdxE (dTVar st b) $ dAtom st c ]
I.CallE a [b,c] | isBinOp a -> [ letS $ llvmBinOp st a b c ]
I.CallE a b -> [ letS $ CallE (dTVar st a) (map (dAtom st) b) ]
I.CastE a b -> [ letS $ CastE cast tva tb ]
where
tva@(TVar ta _) = dTVar st a
tb = dType b
y = ttvar a
sa = sizeT st ta
sb = sizeT st tb
cast
| isSigned y && isFloating b = Sitofp
| isUnsigned y && isFloating b = Uitofp
| isFloating y && isSigned b = Fptosi
| isFloating y && isUnsigned b = Fptoui
| isFloating y && isFloating b && sa < sb = Fpext
| isFloating y && isFloating b && sa > sb = Fptrunc
| isSigned y && isSigned b && sa < sb = Sext
| isSigned y && isSigned b && sa > sb = Trunc
| isUnsigned y && isUnsigned b && sa < sb = Zext
| isUnsigned y && isUnsigned b && sa > sb = Trunc
| otherwise = Bitcast
I.AllocaE a -> [ letS $ AllocaE $ dType a ]
I.LoadE a -> [ letS $ LoadE $ dTVar st a ]
I.AtomE a -> [ letS $ AtomE $ dAtom st a ]
where
letS = LetS (dVar False v)
dTag :: St -> I.TVar -> a -> String -> ([Stmt], (TVar, Type))
dTag st tv a b =
([ LetS v1 $ AllocaE t
, LetS tagp tagfld
, StoreS (LitA $ TLit ta $ dEnum st b) (TVar (PtrT ta) tagp)
, LetS v0 $ LoadE tv1
], (tv1,tb))
where
TVar t v0 = dTVar st tv
v1 = uId a "%.v"
tv1 = TVar (PtrT t) v1
tagp = uId b "%.tag"
tagfld = fldE tv1 0
(ta,tb) = variantTypes st tagfld
duAtom :: St -> I.Atom -> UAtom
duAtom st = uAtom . dAtom st
llvmBinOp :: St -> I.TVar -> I.Atom -> I.Atom -> Exp
llvmBinOp st a b c =
BinOpE (f ty) (dType ty) (duAtom st b) (duAtom st c)
where
f = fromJust $ lookup (vtvar a) binOpTbl
ty = tatom b
tyAtom :: Atom -> Type
tyAtom x = case x of
LitA (TLit a _) -> a
VarA (TVar a _) -> a
uAtom :: Atom -> UAtom
uAtom x = case x of
LitA (TLit _ b) -> LitUA b
VarA (TVar _ b) -> VarUA b
dAtom :: St -> I.Atom -> Atom
dAtom st x = case x of
I.LitA a -> LitA $ dTLit st a
I.VarA a -> VarA $ dTVar st a
dLit :: St -> I.Type -> I.Lit -> Lit
dLit st t x = case x of
I.StringL a -> case lookup a $ strings st of
Just v -> StringL (show $ length a + 1) v
Nothing -> error $ "unused:dLit:string"
I.NmbrL a
| isFloating t -> NmbrL $ show (readNumber a :: Double)
| isFloat a -> error $ "non-integral literal:" ++ a
| otherwise -> NmbrL $ show (readNumber a :: Integer)
I.CharL a -> NmbrL $ show $ ord a
I.EnumL a -> dEnum st a
I.VoidL -> VoidL
dEnum :: St -> String -> Lit
dEnum st x = case x of
"False_" -> FalseL
"True_" -> TrueL
_ -> case lookup x $ enums st of
Nothing -> error $ "unused:dEnum:" ++ ppShow (enums st, x)
Just i -> NmbrL $ show i
dTVar :: St -> I.TVar -> TVar
dTVar st (I.TVar a b) = case lookup a builtinTbl of
Just t -> TVar t (dVar True a)
Nothing -> TVar (dType b) (dVar (a `elem` (free_vars st ++ builtins)) a)
dBuiltin :: (String, Type) -> Define
dBuiltin (s, PtrT (FunT a bs)) = Declare a ('@':s) bs
dBuiltin x = error $ "unused:dBuiltin:" ++ ppShow x
builtinTbl :: [(String, Type)]
builtinTbl =
[ ("printf", PtrT (FunT VoidT [PtrT CharT, VarArgsT])) ]
dTLit :: St -> I.TLit -> TLit
dTLit st (I.TLit a b) = TLit (dType b) (dLit st b a)
dType :: I.Type -> Type
dType t@(I.Type a b) = case (a,b) of
("Ptr_", [c]) -> PtrT (dType c)
("Void_", []) -> VoidT
("I_",_) -> IntT $ nCnt b
("W_",_) -> IntT $ nCnt b
("Fun_", ts) -> PtrT (FunT (dType $ last ts) (map dType $ init ts))
("Array_", [c,d]) -> ArrayT (nCnt [c]) (dType d)
("Float_", []) -> FloatT
("Double_", []) -> DoubleT
("Char_", []) -> CharT
_ -> UserT $ dTypeVar t
fSOrU :: a -> a -> a -> I.Type -> a
fSOrU a b c t
| isFloating t = a
| isSigned t = b
| otherwise = c
fOrN :: a -> a -> I.Type -> a
fOrN a b t
| isFloating t = a
| otherwise = b
binOpTbl :: [(String, I.Type -> BinOp)]
binOpTbl =
[ ("eq", \_ -> Icmp Equ)
, ("ne", \_ -> Icmp Neq)
, ("gt", fSOrU (Fcmp Ogt) (Icmp Sgt) (Icmp Ugt))
, ("gte", fSOrU (Fcmp Oge) (Icmp Sge) (Icmp Uge))
, ("lt", fSOrU (Fcmp Olt) (Icmp Slt) (Icmp Ult))
, ("lte", fSOrU (Fcmp Ole) (Icmp Sle) (Icmp Ule))
, ("add", fOrN Fadd Add)
, ("sub", fOrN Fsub Sub)
, ("mul", fOrN Fmul Mul)
, ("div", fSOrU Fdiv Sdiv Udiv)
, ("rem", fSOrU Frem Srem Urem)
, ("shl", \_ -> Shl)
, ("shr", \_ -> Lshr)
, ("band", \_ -> And)
, ("bor", \_ -> Or)
, ("bxor", \_ -> Xor)
, ("bnot", \_ -> error $ "todo:implement binary not in LLVM") -- BAL
, ("and", \_ -> error $ "todo:implement boolean and in LLVM") -- BAL:doesn't this get desugared?
, ("or", \_ -> error $ "todo:implement boolean or in LLVM") -- BAL:doesn't this get desugared?
]
dStringD :: (String, Lident) -> Define
dStringD (s,v) = StringD v (show $ 1 + length s) $ concatMap const_char s
const_char :: Char -> String
const_char c
| c < ' ' || c > '~' || c == '\\' = encode_char c
| otherwise = [c]
encode_char :: Enum a => a -> String
encode_char c =
'\\' : (if i <= 0xf then "0" else "") ++ map toUpper (showHex i "")
where i = fromEnum c
allocasAtStart :: Define -> Define -- also removes unused allocas
allocasAtStart (Define a b cs ds) = Define a b cs $
[ s | s@(LetS v AllocaE{}) <- universeBi ds, v `elem` universeBi ds1 ]
++ ds1
where
ds1 = transformBi f ds
f :: Stmt -> Stmt
f s
| isAllocaS s = NoOpS
| otherwise = s
allocasAtStart x = x
isAllocaS :: Stmt -> Bool
isAllocaS (LetS _ AllocaE{}) = True
isAllocaS _ = False
elimNoOpS :: Module -> Module
elimNoOpS = transformBi (filter ((/=) NoOpS))
|
stevezhee/pec
|
Pec/LLVM.hs
|
Haskell
|
bsd-3-clause
| 12,321
|
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.EXT.PackedPixels
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.EXT.PackedPixels (
-- * Extension Support
glGetEXTPackedPixels,
gl_EXT_packed_pixels,
-- * Enums
pattern GL_UNSIGNED_BYTE_3_3_2_EXT,
pattern GL_UNSIGNED_INT_10_10_10_2_EXT,
pattern GL_UNSIGNED_INT_8_8_8_8_EXT,
pattern GL_UNSIGNED_SHORT_4_4_4_4_EXT,
pattern GL_UNSIGNED_SHORT_5_5_5_1_EXT
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
|
haskell-opengl/OpenGLRaw
|
src/Graphics/GL/EXT/PackedPixels.hs
|
Haskell
|
bsd-3-clause
| 816
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE MultiParamTypeClasses #-}
#if __GLASGOW_HASKELL__ >= 702 && __GLASGOW_HASKELL__ < 710
{-# LANGUAGE Trustworthy #-}
#endif
-----------------------------------------------------------------------------
-- |
-- Module : Control.Comonad.Density
-- Copyright : (C) 2008-2011 Edward Kmett
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : Edward Kmett <ekmett@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GADTs, MPTCs)
--
-- The 'Density' 'Comonad' for a 'Functor' (aka the 'Comonad generated by a 'Functor')
-- The 'Density' term dates back to Dubuc''s 1974 thesis. The term
-- 'Monad' genererated by a 'Functor' dates back to 1972 in Street''s
-- ''Formal Theory of Monads''.
--
-- The left Kan extension of a 'Functor' along itself (@'Lan' f f@) forms a 'Comonad'. This is
-- that 'Comonad'.
----------------------------------------------------------------------------
module Control.Comonad.Density
( Density(..)
, liftDensity
, densityToAdjunction, adjunctionToDensity
, densityToLan, lanToDensity
) where
import Control.Applicative
import Control.Comonad
import Control.Comonad.Trans.Class
import Data.Functor.Apply
import Data.Functor.Adjunction
import Data.Functor.Extend
import Data.Functor.Kan.Lan
data Density k a where
Density :: (k b -> a) -> k b -> Density k a
instance Functor (Density f) where
fmap f (Density g h) = Density (f . g) h
{-# INLINE fmap #-}
instance Extend (Density f) where
duplicated (Density f ws) = Density (Density f) ws
{-# INLINE duplicated #-}
instance Comonad (Density f) where
duplicate (Density f ws) = Density (Density f) ws
{-# INLINE duplicate #-}
extract (Density f a) = f a
{-# INLINE extract #-}
instance ComonadTrans Density where
lower (Density f c) = extend f c
{-# INLINE lower #-}
instance Apply f => Apply (Density f) where
Density kxf x <.> Density kya y =
Density (\k -> kxf (fmap fst k) (kya (fmap snd k))) ((,) <$> x <.> y)
{-# INLINE (<.>) #-}
instance Applicative f => Applicative (Density f) where
pure a = Density (const a) (pure ())
{-# INLINE pure #-}
Density kxf x <*> Density kya y =
Density (\k -> kxf (fmap fst k) (kya (fmap snd k))) (liftA2 (,) x y)
{-# INLINE (<*>) #-}
-- | The natural transformation from a @'Comonad' w@ to the 'Comonad' generated by @w@ (forwards).
--
-- This is merely a right-inverse (section) of 'lower', rather than a full inverse.
--
-- @
-- 'lower' . 'liftDensity' ≡ 'id'
-- @
liftDensity :: Comonad w => w a -> Density w a
liftDensity = Density extract
{-# INLINE liftDensity #-}
-- | The Density 'Comonad' of a left adjoint is isomorphic to the 'Comonad' formed by that 'Adjunction'.
--
-- This isomorphism is witnessed by 'densityToAdjunction' and 'adjunctionToDensity'.
--
-- @
-- 'densityToAdjunction' . 'adjunctionToDensity' ≡ 'id'
-- 'adjunctionToDensity' . 'densityToAdjunction' ≡ 'id'
-- @
densityToAdjunction :: Adjunction f g => Density f a -> f (g a)
densityToAdjunction (Density f v) = fmap (leftAdjunct f) v
{-# INLINE densityToAdjunction #-}
adjunctionToDensity :: Adjunction f g => f (g a) -> Density f a
adjunctionToDensity = Density counit
{-# INLINE adjunctionToDensity #-}
-- | The 'Density' 'Comonad' of a 'Functor' @f@ is obtained by taking the left Kan extension
-- ('Lan') of @f@ along itself. This isomorphism is witnessed by 'lanToDensity' and 'densityToLan'
--
-- @
-- 'lanToDensity' . 'densityToLan' ≡ 'id'
-- 'densityToLan' . 'lanToDensity' ≡ 'id'
-- @
lanToDensity :: Lan f f a -> Density f a
lanToDensity (Lan f v) = Density f v
{-# INLINE lanToDensity #-}
densityToLan :: Density f a -> Lan f f a
densityToLan (Density f v) = Lan f v
{-# INLINE densityToLan #-}
|
xuwei-k/kan-extensions
|
src/Control/Comonad/Density.hs
|
Haskell
|
bsd-3-clause
| 3,776
|
{-# LANGUAGE TemplateHaskell #-}
------------------------------------------------------------------------------
-- | This module defines our application's state type and an alias for its
-- handler monad.
--
module Application where
------------------------------------------------------------------------------
import Control.Lens
import Snap.Snaplet
import Snap.Snaplet.Auth
import Snap.Snaplet.Heist
import Snap.Snaplet.I18N
import Snap.Snaplet.MongoDB.Core
import Snap.Snaplet.Session
------------------------------------------------------------------------------
data App = App
{ _heist :: Snaplet (Heist App)
, _i18n :: Snaplet I18N
, _appSession :: Snaplet SessionManager
, _appMongoDB :: Snaplet MongoDB
, _appAuth :: Snaplet (AuthManager App)
, _adminRole :: Role -- ^ Role for admin user. keep it simple for now.
}
makeLenses ''App
instance HasHeist App where
heistLens = subSnaplet heist
instance HasI18N App where
i18nLens = i18n
instance HasMongoDB App where
getMongoDB app = app ^. (appMongoDB . snapletValue)
-- getMongoDB = (^& (appMongoDB . snapletValue))
------------------------------------------------------------------------------
type AppHandler = Handler App App
|
HaskellCNOrg/snap-web
|
src/Application.hs
|
Haskell
|
bsd-3-clause
| 1,347
|
{-
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
\section[RnExpr]{Renaming of expressions}
Basically dependency analysis.
Handles @Match@, @GRHSs@, @HsExpr@, and @Qualifier@ datatypes. In
general, all of these functions return a renamed thing, and a set of
free variables.
-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE MultiWayIf #-}
module RnExpr (
rnLExpr, rnExpr, rnStmts
) where
#include "HsVersions.h"
import RnBinds ( rnLocalBindsAndThen, rnLocalValBindsLHS, rnLocalValBindsRHS,
rnMatchGroup, rnGRHS, makeMiniFixityEnv)
import HsSyn
import TcRnMonad
import Module ( getModule )
import RnEnv
import RnSplice ( rnBracket, rnSpliceExpr, checkThLocalName )
import RnTypes
import RnPat
import DynFlags
import PrelNames
import BasicTypes
import Name
import NameSet
import RdrName
import UniqSet
import Data.List
import Util
import ListSetOps ( removeDups )
import ErrUtils
import Outputable
import SrcLoc
import FastString
import Control.Monad
import TysWiredIn ( nilDataConName )
import qualified GHC.LanguageExtensions as LangExt
import Data.Ord
import Data.Array
{-
************************************************************************
* *
\subsubsection{Expressions}
* *
************************************************************************
-}
rnExprs :: [LHsExpr RdrName] -> RnM ([LHsExpr Name], FreeVars)
rnExprs ls = rnExprs' ls emptyUniqSet
where
rnExprs' [] acc = return ([], acc)
rnExprs' (expr:exprs) acc =
do { (expr', fvExpr) <- rnLExpr expr
-- Now we do a "seq" on the free vars because typically it's small
-- or empty, especially in very long lists of constants
; let acc' = acc `plusFV` fvExpr
; (exprs', fvExprs) <- acc' `seq` rnExprs' exprs acc'
; return (expr':exprs', fvExprs) }
-- Variables. We look up the variable and return the resulting name.
rnLExpr :: LHsExpr RdrName -> RnM (LHsExpr Name, FreeVars)
rnLExpr = wrapLocFstM rnExpr
rnExpr :: HsExpr RdrName -> RnM (HsExpr Name, FreeVars)
finishHsVar :: Located Name -> RnM (HsExpr Name, FreeVars)
-- Separated from rnExpr because it's also used
-- when renaming infix expressions
finishHsVar (L l name)
= do { this_mod <- getModule
; when (nameIsLocalOrFrom this_mod name) $
checkThLocalName name
; return (HsVar (L l name), unitFV name) }
rnUnboundVar :: RdrName -> RnM (HsExpr Name, FreeVars)
rnUnboundVar v
= do { if isUnqual v
then -- Treat this as a "hole"
-- Do not fail right now; instead, return HsUnboundVar
-- and let the type checker report the error
return (HsUnboundVar (rdrNameOcc v), emptyFVs)
else -- Fail immediately (qualified name)
do { n <- reportUnboundName v
; return (HsVar (noLoc n), emptyFVs) } }
rnExpr (HsVar (L l v))
= do { opt_DuplicateRecordFields <- xoptM LangExt.DuplicateRecordFields
; mb_name <- lookupOccRn_overloaded opt_DuplicateRecordFields v
; case mb_name of {
Nothing -> rnUnboundVar v ;
Just (Left name)
| name == nilDataConName -- Treat [] as an ExplicitList, so that
-- OverloadedLists works correctly
-> rnExpr (ExplicitList placeHolderType Nothing [])
| otherwise
-> finishHsVar (L l name) ;
Just (Right [f@(FieldOcc (L _ fn) s)]) ->
return (HsRecFld (ambiguousFieldOcc (FieldOcc (L l fn) s))
, unitFV (selectorFieldOcc f)) ;
Just (Right fs@(_:_:_)) -> return (HsRecFld (Ambiguous (L l v)
PlaceHolder)
, mkFVs (map selectorFieldOcc fs));
Just (Right []) -> error "runExpr/HsVar" } }
rnExpr (HsIPVar v)
= return (HsIPVar v, emptyFVs)
rnExpr (HsOverLabel v)
= return (HsOverLabel v, emptyFVs)
rnExpr (HsLit lit@(HsString src s))
= do { opt_OverloadedStrings <- xoptM LangExt.OverloadedStrings
; if opt_OverloadedStrings then
rnExpr (HsOverLit (mkHsIsString src s placeHolderType))
else do {
; rnLit lit
; return (HsLit lit, emptyFVs) } }
rnExpr (HsLit lit)
= do { rnLit lit
; return (HsLit lit, emptyFVs) }
rnExpr (HsOverLit lit)
= do { (lit', fvs) <- rnOverLit lit
; return (HsOverLit lit', fvs) }
rnExpr (HsApp fun arg)
= do { (fun',fvFun) <- rnLExpr fun
; (arg',fvArg) <- rnLExpr arg
; return (HsApp fun' arg', fvFun `plusFV` fvArg) }
rnExpr (HsAppType fun arg)
= do { (fun',fvFun) <- rnLExpr fun
; (arg',fvArg) <- rnHsWcType HsTypeCtx arg
; return (HsAppType fun' arg', fvFun `plusFV` fvArg) }
rnExpr (OpApp e1 op _ e2)
= do { (e1', fv_e1) <- rnLExpr e1
; (e2', fv_e2) <- rnLExpr e2
; (op', fv_op) <- rnLExpr op
-- Deal with fixity
-- When renaming code synthesised from "deriving" declarations
-- we used to avoid fixity stuff, but we can't easily tell any
-- more, so I've removed the test. Adding HsPars in TcGenDeriv
-- should prevent bad things happening.
; fixity <- case op' of
L _ (HsVar (L _ n)) -> lookupFixityRn n
L _ (HsRecFld f) -> lookupFieldFixityRn f
_ -> return (Fixity (show minPrecedence) minPrecedence InfixL)
-- c.f. lookupFixity for unbound
; final_e <- mkOpAppRn e1' op' fixity e2'
; return (final_e, fv_e1 `plusFV` fv_op `plusFV` fv_e2) }
rnExpr (NegApp e _)
= do { (e', fv_e) <- rnLExpr e
; (neg_name, fv_neg) <- lookupSyntaxName negateName
; final_e <- mkNegAppRn e' neg_name
; return (final_e, fv_e `plusFV` fv_neg) }
------------------------------------------
-- Template Haskell extensions
-- Don't ifdef-GHCI them because we want to fail gracefully
-- (not with an rnExpr crash) in a stage-1 compiler.
rnExpr e@(HsBracket br_body) = rnBracket e br_body
rnExpr (HsSpliceE splice) = rnSpliceExpr splice
---------------------------------------------
-- Sections
-- See Note [Parsing sections] in Parser.y
rnExpr (HsPar (L loc (section@(SectionL {}))))
= do { (section', fvs) <- rnSection section
; return (HsPar (L loc section'), fvs) }
rnExpr (HsPar (L loc (section@(SectionR {}))))
= do { (section', fvs) <- rnSection section
; return (HsPar (L loc section'), fvs) }
rnExpr (HsPar e)
= do { (e', fvs_e) <- rnLExpr e
; return (HsPar e', fvs_e) }
rnExpr expr@(SectionL {})
= do { addErr (sectionErr expr); rnSection expr }
rnExpr expr@(SectionR {})
= do { addErr (sectionErr expr); rnSection expr }
---------------------------------------------
rnExpr (HsCoreAnn src ann expr)
= do { (expr', fvs_expr) <- rnLExpr expr
; return (HsCoreAnn src ann expr', fvs_expr) }
rnExpr (HsSCC src lbl expr)
= do { (expr', fvs_expr) <- rnLExpr expr
; return (HsSCC src lbl expr', fvs_expr) }
rnExpr (HsTickPragma src info srcInfo expr)
= do { (expr', fvs_expr) <- rnLExpr expr
; return (HsTickPragma src info srcInfo expr', fvs_expr) }
rnExpr (HsLam matches)
= do { (matches', fvMatch) <- rnMatchGroup LambdaExpr rnLExpr matches
; return (HsLam matches', fvMatch) }
rnExpr (HsLamCase _arg matches)
= do { (matches', fvs_ms) <- rnMatchGroup CaseAlt rnLExpr matches
-- ; return (HsLamCase arg matches', fvs_ms) }
; return (HsLamCase placeHolderType matches', fvs_ms) }
rnExpr (HsCase expr matches)
= do { (new_expr, e_fvs) <- rnLExpr expr
; (new_matches, ms_fvs) <- rnMatchGroup CaseAlt rnLExpr matches
; return (HsCase new_expr new_matches, e_fvs `plusFV` ms_fvs) }
rnExpr (HsLet (L l binds) expr)
= rnLocalBindsAndThen binds $ \binds' _ -> do
{ (expr',fvExpr) <- rnLExpr expr
; return (HsLet (L l binds') expr', fvExpr) }
rnExpr (HsDo do_or_lc (L l stmts) _)
= do { ((stmts', _), fvs) <-
rnStmtsWithPostProcessing do_or_lc rnLExpr
postProcessStmtsForApplicativeDo stmts
(\ _ -> return ((), emptyFVs))
; return ( HsDo do_or_lc (L l stmts') placeHolderType, fvs ) }
rnExpr (ExplicitList _ _ exps)
= do { opt_OverloadedLists <- xoptM LangExt.OverloadedLists
; (exps', fvs) <- rnExprs exps
; if opt_OverloadedLists
then do {
; (from_list_n_name, fvs') <- lookupSyntaxName fromListNName
; return (ExplicitList placeHolderType (Just from_list_n_name) exps'
, fvs `plusFV` fvs') }
else
return (ExplicitList placeHolderType Nothing exps', fvs) }
rnExpr (ExplicitPArr _ exps)
= do { (exps', fvs) <- rnExprs exps
; return (ExplicitPArr placeHolderType exps', fvs) }
rnExpr (ExplicitTuple tup_args boxity)
= do { checkTupleSection tup_args
; checkTupSize (length tup_args)
; (tup_args', fvs) <- mapAndUnzipM rnTupArg tup_args
; return (ExplicitTuple tup_args' boxity, plusFVs fvs) }
where
rnTupArg (L l (Present e)) = do { (e',fvs) <- rnLExpr e
; return (L l (Present e'), fvs) }
rnTupArg (L l (Missing _)) = return (L l (Missing placeHolderType)
, emptyFVs)
rnExpr (RecordCon { rcon_con_name = con_id
, rcon_flds = rec_binds@(HsRecFields { rec_dotdot = dd }) })
= do { con_lname@(L _ con_name) <- lookupLocatedOccRn con_id
; (flds, fvs) <- rnHsRecFields (HsRecFieldCon con_name) mk_hs_var rec_binds
; (flds', fvss) <- mapAndUnzipM rn_field flds
; let rec_binds' = HsRecFields { rec_flds = flds', rec_dotdot = dd }
; return (RecordCon { rcon_con_name = con_lname, rcon_flds = rec_binds'
, rcon_con_expr = noPostTcExpr, rcon_con_like = PlaceHolder }
, fvs `plusFV` plusFVs fvss `addOneFV` con_name) }
where
mk_hs_var l n = HsVar (L l n)
rn_field (L l fld) = do { (arg', fvs) <- rnLExpr (hsRecFieldArg fld)
; return (L l (fld { hsRecFieldArg = arg' }), fvs) }
rnExpr (RecordUpd { rupd_expr = expr, rupd_flds = rbinds })
= do { (expr', fvExpr) <- rnLExpr expr
; (rbinds', fvRbinds) <- rnHsRecUpdFields rbinds
; return (RecordUpd { rupd_expr = expr', rupd_flds = rbinds'
, rupd_cons = PlaceHolder, rupd_in_tys = PlaceHolder
, rupd_out_tys = PlaceHolder, rupd_wrap = PlaceHolder }
, fvExpr `plusFV` fvRbinds) }
rnExpr (ExprWithTySig expr pty)
= do { (pty', fvTy) <- rnHsSigWcType ExprWithTySigCtx pty
; (expr', fvExpr) <- bindSigTyVarsFV (hsWcScopedTvs pty') $
rnLExpr expr
; return (ExprWithTySig expr' pty', fvExpr `plusFV` fvTy) }
rnExpr (HsIf _ p b1 b2)
= do { (p', fvP) <- rnLExpr p
; (b1', fvB1) <- rnLExpr b1
; (b2', fvB2) <- rnLExpr b2
; (mb_ite, fvITE) <- lookupIfThenElse
; return (HsIf mb_ite p' b1' b2', plusFVs [fvITE, fvP, fvB1, fvB2]) }
rnExpr (HsMultiIf _ty alts)
= do { (alts', fvs) <- mapFvRn (rnGRHS IfAlt rnLExpr) alts
-- ; return (HsMultiIf ty alts', fvs) }
; return (HsMultiIf placeHolderType alts', fvs) }
rnExpr (ArithSeq _ _ seq)
= do { opt_OverloadedLists <- xoptM LangExt.OverloadedLists
; (new_seq, fvs) <- rnArithSeq seq
; if opt_OverloadedLists
then do {
; (from_list_name, fvs') <- lookupSyntaxName fromListName
; return (ArithSeq noPostTcExpr (Just from_list_name) new_seq, fvs `plusFV` fvs') }
else
return (ArithSeq noPostTcExpr Nothing new_seq, fvs) }
rnExpr (PArrSeq _ seq)
= do { (new_seq, fvs) <- rnArithSeq seq
; return (PArrSeq noPostTcExpr new_seq, fvs) }
{-
These three are pattern syntax appearing in expressions.
Since all the symbols are reservedops we can simply reject them.
We return a (bogus) EWildPat in each case.
-}
rnExpr EWildPat = return (hsHoleExpr, emptyFVs) -- "_" is just a hole
rnExpr e@(EAsPat {}) =
patSynErr e (text "Did you mean to enable TypeApplications?")
rnExpr e@(EViewPat {}) = patSynErr e empty
rnExpr e@(ELazyPat {}) = patSynErr e empty
{-
************************************************************************
* *
Static values
* *
************************************************************************
For the static form we check that the free variables are all top-level
value bindings. This is done by checking that the name is external or
wired-in. See the Notes about the NameSorts in Name.hs.
-}
rnExpr e@(HsStatic expr) = do
target <- fmap hscTarget getDynFlags
case target of
-- SPT entries are expected to exist in object code so far, and this is
-- not the case in interpreted mode. See bug #9878.
HscInterpreted -> addErr $ sep
[ text "The static form is not supported in interpreted mode."
, text "Please use -fobject-code."
]
_ -> return ()
(expr',fvExpr) <- rnLExpr expr
stage <- getStage
case stage of
Brack _ _ -> return () -- Don't check names if we are inside brackets.
-- We don't want to reject cases like:
-- \e -> [| static $(e) |]
-- if $(e) turns out to produce a legal expression.
Splice _ -> addErr $ sep
[ text "static forms cannot be used in splices:"
, nest 2 $ ppr e
]
_ -> do
let isTopLevelName n = isExternalName n || isWiredInName n
case nameSetElems $ filterNameSet
(\n -> not (isTopLevelName n || isUnboundName n))
fvExpr of
[] -> return ()
fvNonGlobal -> addErr $ cat
[ text $ "Only identifiers of top-level bindings can "
++ "appear in the body of the static form:"
, nest 2 $ ppr e
, text "but the following identifiers were found instead:"
, nest 2 $ vcat $ map ppr fvNonGlobal
]
return (HsStatic expr', fvExpr)
{-
************************************************************************
* *
Arrow notation
* *
************************************************************************
-}
rnExpr (HsProc pat body)
= newArrowScope $
rnPat ProcExpr pat $ \ pat' -> do
{ (body',fvBody) <- rnCmdTop body
; return (HsProc pat' body', fvBody) }
-- Ideally, these would be done in parsing, but to keep parsing simple, we do it here.
rnExpr e@(HsArrApp {}) = arrowFail e
rnExpr e@(HsArrForm {}) = arrowFail e
rnExpr other = pprPanic "rnExpr: unexpected expression" (ppr other)
-- HsWrap
hsHoleExpr :: HsExpr id
hsHoleExpr = HsUnboundVar (mkVarOcc "_")
arrowFail :: HsExpr RdrName -> RnM (HsExpr Name, FreeVars)
arrowFail e
= do { addErr (vcat [ text "Arrow command found where an expression was expected:"
, nest 2 (ppr e) ])
-- Return a place-holder hole, so that we can carry on
-- to report other errors
; return (hsHoleExpr, emptyFVs) }
----------------------
-- See Note [Parsing sections] in Parser.y
rnSection :: HsExpr RdrName -> RnM (HsExpr Name, FreeVars)
rnSection section@(SectionR op expr)
= do { (op', fvs_op) <- rnLExpr op
; (expr', fvs_expr) <- rnLExpr expr
; checkSectionPrec InfixR section op' expr'
; return (SectionR op' expr', fvs_op `plusFV` fvs_expr) }
rnSection section@(SectionL expr op)
= do { (expr', fvs_expr) <- rnLExpr expr
; (op', fvs_op) <- rnLExpr op
; checkSectionPrec InfixL section op' expr'
; return (SectionL expr' op', fvs_op `plusFV` fvs_expr) }
rnSection other = pprPanic "rnSection" (ppr other)
{-
************************************************************************
* *
Arrow commands
* *
************************************************************************
-}
rnCmdArgs :: [LHsCmdTop RdrName] -> RnM ([LHsCmdTop Name], FreeVars)
rnCmdArgs [] = return ([], emptyFVs)
rnCmdArgs (arg:args)
= do { (arg',fvArg) <- rnCmdTop arg
; (args',fvArgs) <- rnCmdArgs args
; return (arg':args', fvArg `plusFV` fvArgs) }
rnCmdTop :: LHsCmdTop RdrName -> RnM (LHsCmdTop Name, FreeVars)
rnCmdTop = wrapLocFstM rnCmdTop'
where
rnCmdTop' (HsCmdTop cmd _ _ _)
= do { (cmd', fvCmd) <- rnLCmd cmd
; let cmd_names = [arrAName, composeAName, firstAName] ++
nameSetElems (methodNamesCmd (unLoc cmd'))
-- Generate the rebindable syntax for the monad
; (cmd_names', cmd_fvs) <- lookupSyntaxNames cmd_names
; return (HsCmdTop cmd' placeHolderType placeHolderType
(cmd_names `zip` cmd_names'),
fvCmd `plusFV` cmd_fvs) }
rnLCmd :: LHsCmd RdrName -> RnM (LHsCmd Name, FreeVars)
rnLCmd = wrapLocFstM rnCmd
rnCmd :: HsCmd RdrName -> RnM (HsCmd Name, FreeVars)
rnCmd (HsCmdArrApp arrow arg _ ho rtl)
= do { (arrow',fvArrow) <- select_arrow_scope (rnLExpr arrow)
; (arg',fvArg) <- rnLExpr arg
; return (HsCmdArrApp arrow' arg' placeHolderType ho rtl,
fvArrow `plusFV` fvArg) }
where
select_arrow_scope tc = case ho of
HsHigherOrderApp -> tc
HsFirstOrderApp -> escapeArrowScope tc
-- See Note [Escaping the arrow scope] in TcRnTypes
-- Before renaming 'arrow', use the environment of the enclosing
-- proc for the (-<) case.
-- Local bindings, inside the enclosing proc, are not in scope
-- inside 'arrow'. In the higher-order case (-<<), they are.
-- infix form
rnCmd (HsCmdArrForm op (Just _) [arg1, arg2])
= do { (op',fv_op) <- escapeArrowScope (rnLExpr op)
; let L _ (HsVar (L _ op_name)) = op'
; (arg1',fv_arg1) <- rnCmdTop arg1
; (arg2',fv_arg2) <- rnCmdTop arg2
-- Deal with fixity
; fixity <- lookupFixityRn op_name
; final_e <- mkOpFormRn arg1' op' fixity arg2'
; return (final_e, fv_arg1 `plusFV` fv_op `plusFV` fv_arg2) }
rnCmd (HsCmdArrForm op fixity cmds)
= do { (op',fvOp) <- escapeArrowScope (rnLExpr op)
; (cmds',fvCmds) <- rnCmdArgs cmds
; return (HsCmdArrForm op' fixity cmds', fvOp `plusFV` fvCmds) }
rnCmd (HsCmdApp fun arg)
= do { (fun',fvFun) <- rnLCmd fun
; (arg',fvArg) <- rnLExpr arg
; return (HsCmdApp fun' arg', fvFun `plusFV` fvArg) }
rnCmd (HsCmdLam matches)
= do { (matches', fvMatch) <- rnMatchGroup LambdaExpr rnLCmd matches
; return (HsCmdLam matches', fvMatch) }
rnCmd (HsCmdPar e)
= do { (e', fvs_e) <- rnLCmd e
; return (HsCmdPar e', fvs_e) }
rnCmd (HsCmdCase expr matches)
= do { (new_expr, e_fvs) <- rnLExpr expr
; (new_matches, ms_fvs) <- rnMatchGroup CaseAlt rnLCmd matches
; return (HsCmdCase new_expr new_matches, e_fvs `plusFV` ms_fvs) }
rnCmd (HsCmdIf _ p b1 b2)
= do { (p', fvP) <- rnLExpr p
; (b1', fvB1) <- rnLCmd b1
; (b2', fvB2) <- rnLCmd b2
; (mb_ite, fvITE) <- lookupIfThenElse
; return (HsCmdIf mb_ite p' b1' b2', plusFVs [fvITE, fvP, fvB1, fvB2]) }
rnCmd (HsCmdLet (L l binds) cmd)
= rnLocalBindsAndThen binds $ \ binds' _ -> do
{ (cmd',fvExpr) <- rnLCmd cmd
; return (HsCmdLet (L l binds') cmd', fvExpr) }
rnCmd (HsCmdDo (L l stmts) _)
= do { ((stmts', _), fvs) <-
rnStmts ArrowExpr rnLCmd stmts (\ _ -> return ((), emptyFVs))
; return ( HsCmdDo (L l stmts') placeHolderType, fvs ) }
rnCmd cmd@(HsCmdWrap {}) = pprPanic "rnCmd" (ppr cmd)
---------------------------------------------------
type CmdNeeds = FreeVars -- Only inhabitants are
-- appAName, choiceAName, loopAName
-- find what methods the Cmd needs (loop, choice, apply)
methodNamesLCmd :: LHsCmd Name -> CmdNeeds
methodNamesLCmd = methodNamesCmd . unLoc
methodNamesCmd :: HsCmd Name -> CmdNeeds
methodNamesCmd (HsCmdArrApp _arrow _arg _ HsFirstOrderApp _rtl)
= emptyFVs
methodNamesCmd (HsCmdArrApp _arrow _arg _ HsHigherOrderApp _rtl)
= unitFV appAName
methodNamesCmd (HsCmdArrForm {}) = emptyFVs
methodNamesCmd (HsCmdWrap _ cmd) = methodNamesCmd cmd
methodNamesCmd (HsCmdPar c) = methodNamesLCmd c
methodNamesCmd (HsCmdIf _ _ c1 c2)
= methodNamesLCmd c1 `plusFV` methodNamesLCmd c2 `addOneFV` choiceAName
methodNamesCmd (HsCmdLet _ c) = methodNamesLCmd c
methodNamesCmd (HsCmdDo (L _ stmts) _) = methodNamesStmts stmts
methodNamesCmd (HsCmdApp c _) = methodNamesLCmd c
methodNamesCmd (HsCmdLam match) = methodNamesMatch match
methodNamesCmd (HsCmdCase _ matches)
= methodNamesMatch matches `addOneFV` choiceAName
--methodNamesCmd _ = emptyFVs
-- Other forms can't occur in commands, but it's not convenient
-- to error here so we just do what's convenient.
-- The type checker will complain later
---------------------------------------------------
methodNamesMatch :: MatchGroup Name (LHsCmd Name) -> FreeVars
methodNamesMatch (MG { mg_alts = L _ ms })
= plusFVs (map do_one ms)
where
do_one (L _ (Match _ _ _ grhss)) = methodNamesGRHSs grhss
-------------------------------------------------
-- gaw 2004
methodNamesGRHSs :: GRHSs Name (LHsCmd Name) -> FreeVars
methodNamesGRHSs (GRHSs grhss _) = plusFVs (map methodNamesGRHS grhss)
-------------------------------------------------
methodNamesGRHS :: Located (GRHS Name (LHsCmd Name)) -> CmdNeeds
methodNamesGRHS (L _ (GRHS _ rhs)) = methodNamesLCmd rhs
---------------------------------------------------
methodNamesStmts :: [Located (StmtLR Name Name (LHsCmd Name))] -> FreeVars
methodNamesStmts stmts = plusFVs (map methodNamesLStmt stmts)
---------------------------------------------------
methodNamesLStmt :: Located (StmtLR Name Name (LHsCmd Name)) -> FreeVars
methodNamesLStmt = methodNamesStmt . unLoc
methodNamesStmt :: StmtLR Name Name (LHsCmd Name) -> FreeVars
methodNamesStmt (LastStmt cmd _ _) = methodNamesLCmd cmd
methodNamesStmt (BodyStmt cmd _ _ _) = methodNamesLCmd cmd
methodNamesStmt (BindStmt _ cmd _ _ _) = methodNamesLCmd cmd
methodNamesStmt (RecStmt { recS_stmts = stmts }) =
methodNamesStmts stmts `addOneFV` loopAName
methodNamesStmt (LetStmt {}) = emptyFVs
methodNamesStmt (ParStmt {}) = emptyFVs
methodNamesStmt (TransStmt {}) = emptyFVs
methodNamesStmt ApplicativeStmt{} = emptyFVs
-- ParStmt and TransStmt can't occur in commands, but it's not
-- convenient to error here so we just do what's convenient
{-
************************************************************************
* *
Arithmetic sequences
* *
************************************************************************
-}
rnArithSeq :: ArithSeqInfo RdrName -> RnM (ArithSeqInfo Name, FreeVars)
rnArithSeq (From expr)
= do { (expr', fvExpr) <- rnLExpr expr
; return (From expr', fvExpr) }
rnArithSeq (FromThen expr1 expr2)
= do { (expr1', fvExpr1) <- rnLExpr expr1
; (expr2', fvExpr2) <- rnLExpr expr2
; return (FromThen expr1' expr2', fvExpr1 `plusFV` fvExpr2) }
rnArithSeq (FromTo expr1 expr2)
= do { (expr1', fvExpr1) <- rnLExpr expr1
; (expr2', fvExpr2) <- rnLExpr expr2
; return (FromTo expr1' expr2', fvExpr1 `plusFV` fvExpr2) }
rnArithSeq (FromThenTo expr1 expr2 expr3)
= do { (expr1', fvExpr1) <- rnLExpr expr1
; (expr2', fvExpr2) <- rnLExpr expr2
; (expr3', fvExpr3) <- rnLExpr expr3
; return (FromThenTo expr1' expr2' expr3',
plusFVs [fvExpr1, fvExpr2, fvExpr3]) }
{-
************************************************************************
* *
\subsubsection{@Stmt@s: in @do@ expressions}
* *
************************************************************************
-}
-- | Rename some Stmts
rnStmts :: Outputable (body RdrName)
=> HsStmtContext Name
-> (Located (body RdrName) -> RnM (Located (body Name), FreeVars))
-- ^ How to rename the body of each statement (e.g. rnLExpr)
-> [LStmt RdrName (Located (body RdrName))]
-- ^ Statements
-> ([Name] -> RnM (thing, FreeVars))
-- ^ if these statements scope over something, this renames it
-- and returns the result.
-> RnM (([LStmt Name (Located (body Name))], thing), FreeVars)
rnStmts ctxt rnBody = rnStmtsWithPostProcessing ctxt rnBody noPostProcessStmts
-- | like 'rnStmts' but applies a post-processing step to the renamed Stmts
rnStmtsWithPostProcessing
:: Outputable (body RdrName)
=> HsStmtContext Name
-> (Located (body RdrName) -> RnM (Located (body Name), FreeVars))
-- ^ How to rename the body of each statement (e.g. rnLExpr)
-> (HsStmtContext Name
-> [(LStmt Name (Located (body Name)), FreeVars)]
-> RnM ([LStmt Name (Located (body Name))], FreeVars))
-- ^ postprocess the statements
-> [LStmt RdrName (Located (body RdrName))]
-- ^ Statements
-> ([Name] -> RnM (thing, FreeVars))
-- ^ if these statements scope over something, this renames it
-- and returns the result.
-> RnM (([LStmt Name (Located (body Name))], thing), FreeVars)
rnStmtsWithPostProcessing ctxt rnBody ppStmts stmts thing_inside
= do { ((stmts', thing), fvs) <-
rnStmtsWithFreeVars ctxt rnBody stmts thing_inside
; (pp_stmts, fvs') <- ppStmts ctxt stmts'
; return ((pp_stmts, thing), fvs `plusFV` fvs')
}
-- | maybe rearrange statements according to the ApplicativeDo transformation
postProcessStmtsForApplicativeDo
:: HsStmtContext Name
-> [(ExprLStmt Name, FreeVars)]
-> RnM ([ExprLStmt Name], FreeVars)
postProcessStmtsForApplicativeDo ctxt stmts
= do {
-- rearrange the statements using ApplicativeStmt if
-- -XApplicativeDo is on. Also strip out the FreeVars attached
-- to each Stmt body.
ado_is_on <- xoptM LangExt.ApplicativeDo
; let is_do_expr | DoExpr <- ctxt = True
| otherwise = False
; if ado_is_on && is_do_expr
then rearrangeForApplicativeDo ctxt stmts
else noPostProcessStmts ctxt stmts }
-- | strip the FreeVars annotations from statements
noPostProcessStmts
:: HsStmtContext Name
-> [(LStmt Name (Located (body Name)), FreeVars)]
-> RnM ([LStmt Name (Located (body Name))], FreeVars)
noPostProcessStmts _ stmts = return (map fst stmts, emptyNameSet)
rnStmtsWithFreeVars :: Outputable (body RdrName)
=> HsStmtContext Name
-> (Located (body RdrName) -> RnM (Located (body Name), FreeVars))
-> [LStmt RdrName (Located (body RdrName))]
-> ([Name] -> RnM (thing, FreeVars))
-> RnM ( ([(LStmt Name (Located (body Name)), FreeVars)], thing)
, FreeVars)
-- Each Stmt body is annotated with its FreeVars, so that
-- we can rearrange statements for ApplicativeDo.
--
-- Variables bound by the Stmts, and mentioned in thing_inside,
-- do not appear in the result FreeVars
rnStmtsWithFreeVars ctxt _ [] thing_inside
= do { checkEmptyStmts ctxt
; (thing, fvs) <- thing_inside []
; return (([], thing), fvs) }
rnStmtsWithFreeVars MDoExpr rnBody stmts thing_inside -- Deal with mdo
= -- Behave like do { rec { ...all but last... }; last }
do { ((stmts1, (stmts2, thing)), fvs)
<- rnStmt MDoExpr rnBody (noLoc $ mkRecStmt all_but_last) $ \ _ ->
do { last_stmt' <- checkLastStmt MDoExpr last_stmt
; rnStmt MDoExpr rnBody last_stmt' thing_inside }
; return (((stmts1 ++ stmts2), thing), fvs) }
where
Just (all_but_last, last_stmt) = snocView stmts
rnStmtsWithFreeVars ctxt rnBody (lstmt@(L loc _) : lstmts) thing_inside
| null lstmts
= setSrcSpan loc $
do { lstmt' <- checkLastStmt ctxt lstmt
; rnStmt ctxt rnBody lstmt' thing_inside }
| otherwise
= do { ((stmts1, (stmts2, thing)), fvs)
<- setSrcSpan loc $
do { checkStmt ctxt lstmt
; rnStmt ctxt rnBody lstmt $ \ bndrs1 ->
rnStmtsWithFreeVars ctxt rnBody lstmts $ \ bndrs2 ->
thing_inside (bndrs1 ++ bndrs2) }
; return (((stmts1 ++ stmts2), thing), fvs) }
----------------------
rnStmt :: Outputable (body RdrName)
=> HsStmtContext Name
-> (Located (body RdrName) -> RnM (Located (body Name), FreeVars))
-- ^ How to rename the body of the statement
-> LStmt RdrName (Located (body RdrName))
-- ^ The statement
-> ([Name] -> RnM (thing, FreeVars))
-- ^ Rename the stuff that this statement scopes over
-> RnM ( ([(LStmt Name (Located (body Name)), FreeVars)], thing)
, FreeVars)
-- Variables bound by the Stmt, and mentioned in thing_inside,
-- do not appear in the result FreeVars
rnStmt ctxt rnBody (L loc (LastStmt body noret _)) thing_inside
= do { (body', fv_expr) <- rnBody body
; (ret_op, fvs1) <- lookupStmtName ctxt returnMName
; (thing, fvs3) <- thing_inside []
; return (([(L loc (LastStmt body' noret ret_op), fv_expr)], thing),
fv_expr `plusFV` fvs1 `plusFV` fvs3) }
rnStmt ctxt rnBody (L loc (BodyStmt body _ _ _)) thing_inside
= do { (body', fv_expr) <- rnBody body
; (then_op, fvs1) <- lookupStmtName ctxt thenMName
; (guard_op, fvs2) <- if isListCompExpr ctxt
then lookupStmtName ctxt guardMName
else return (noSyntaxExpr, emptyFVs)
-- Only list/parr/monad comprehensions use 'guard'
-- Also for sub-stmts of same eg [ e | x<-xs, gd | blah ]
-- Here "gd" is a guard
; (thing, fvs3) <- thing_inside []
; return (([(L loc (BodyStmt body'
then_op guard_op placeHolderType), fv_expr)], thing),
fv_expr `plusFV` fvs1 `plusFV` fvs2 `plusFV` fvs3) }
rnStmt ctxt rnBody (L loc (BindStmt pat body _ _ _)) thing_inside
= do { (body', fv_expr) <- rnBody body
-- The binders do not scope over the expression
; (bind_op, fvs1) <- lookupStmtName ctxt bindMName
; xMonadFailEnabled <- fmap (xopt LangExt.MonadFailDesugaring) getDynFlags
; let failFunction | xMonadFailEnabled = failMName
| otherwise = failMName_preMFP
; (fail_op, fvs2) <- lookupSyntaxName failFunction
; rnPat (StmtCtxt ctxt) pat $ \ pat' -> do
{ (thing, fvs3) <- thing_inside (collectPatBinders pat')
; return (( [( L loc (BindStmt pat' body' bind_op fail_op PlaceHolder)
, fv_expr )]
, thing),
fv_expr `plusFV` fvs1 `plusFV` fvs2 `plusFV` fvs3) }}
-- fv_expr shouldn't really be filtered by the rnPatsAndThen
-- but it does not matter because the names are unique
rnStmt _ _ (L loc (LetStmt (L l binds))) thing_inside
= do { rnLocalBindsAndThen binds $ \binds' bind_fvs -> do
{ (thing, fvs) <- thing_inside (collectLocalBinders binds')
; return (([(L loc (LetStmt (L l binds')), bind_fvs)], thing), fvs) } }
rnStmt ctxt rnBody (L loc (RecStmt { recS_stmts = rec_stmts })) thing_inside
= do { (return_op, fvs1) <- lookupStmtName ctxt returnMName
; (mfix_op, fvs2) <- lookupStmtName ctxt mfixName
; (bind_op, fvs3) <- lookupStmtName ctxt bindMName
; let empty_rec_stmt = emptyRecStmtName { recS_ret_fn = return_op
, recS_mfix_fn = mfix_op
, recS_bind_fn = bind_op }
-- Step1: Bring all the binders of the mdo into scope
-- (Remember that this also removes the binders from the
-- finally-returned free-vars.)
-- And rename each individual stmt, making a
-- singleton segment. At this stage the FwdRefs field
-- isn't finished: it's empty for all except a BindStmt
-- for which it's the fwd refs within the bind itself
-- (This set may not be empty, because we're in a recursive
-- context.)
; rnRecStmtsAndThen rnBody rec_stmts $ \ segs -> do
{ let bndrs = nameSetElems $ foldr (unionNameSet . (\(ds,_,_,_) -> ds))
emptyNameSet segs
; (thing, fvs_later) <- thing_inside bndrs
; let (rec_stmts', fvs) = segmentRecStmts loc ctxt empty_rec_stmt segs fvs_later
-- We aren't going to try to group RecStmts with
-- ApplicativeDo, so attaching empty FVs is fine.
; return ( ((zip rec_stmts' (repeat emptyNameSet)), thing)
, fvs `plusFV` fvs1 `plusFV` fvs2 `plusFV` fvs3) } }
rnStmt ctxt _ (L loc (ParStmt segs _ _ _)) thing_inside
= do { (mzip_op, fvs1) <- lookupStmtNamePoly ctxt mzipName
; (bind_op, fvs2) <- lookupStmtName ctxt bindMName
; (return_op, fvs3) <- lookupStmtName ctxt returnMName
; ((segs', thing), fvs4) <- rnParallelStmts (ParStmtCtxt ctxt) return_op segs thing_inside
; return ( ([(L loc (ParStmt segs' mzip_op bind_op placeHolderType), fvs4)], thing)
, fvs1 `plusFV` fvs2 `plusFV` fvs3 `plusFV` fvs4) }
rnStmt ctxt _ (L loc (TransStmt { trS_stmts = stmts, trS_by = by, trS_form = form
, trS_using = using })) thing_inside
= do { -- Rename the 'using' expression in the context before the transform is begun
(using', fvs1) <- rnLExpr using
-- Rename the stmts and the 'by' expression
-- Keep track of the variables mentioned in the 'by' expression
; ((stmts', (by', used_bndrs, thing)), fvs2)
<- rnStmts (TransStmtCtxt ctxt) rnLExpr stmts $ \ bndrs ->
do { (by', fvs_by) <- mapMaybeFvRn rnLExpr by
; (thing, fvs_thing) <- thing_inside bndrs
; let fvs = fvs_by `plusFV` fvs_thing
used_bndrs = filter (`elemNameSet` fvs) bndrs
-- The paper (Fig 5) has a bug here; we must treat any free variable
-- of the "thing inside", **or of the by-expression**, as used
; return ((by', used_bndrs, thing), fvs) }
-- Lookup `return`, `(>>=)` and `liftM` for monad comprehensions
; (return_op, fvs3) <- lookupStmtName ctxt returnMName
; (bind_op, fvs4) <- lookupStmtName ctxt bindMName
; (fmap_op, fvs5) <- case form of
ThenForm -> return (noExpr, emptyFVs)
_ -> lookupStmtNamePoly ctxt fmapName
; let all_fvs = fvs1 `plusFV` fvs2 `plusFV` fvs3
`plusFV` fvs4 `plusFV` fvs5
bndr_map = used_bndrs `zip` used_bndrs
-- See Note [TransStmt binder map] in HsExpr
; traceRn (text "rnStmt: implicitly rebound these used binders:" <+> ppr bndr_map)
; return (([(L loc (TransStmt { trS_stmts = stmts', trS_bndrs = bndr_map
, trS_by = by', trS_using = using', trS_form = form
, trS_ret = return_op, trS_bind = bind_op
, trS_bind_arg_ty = PlaceHolder
, trS_fmap = fmap_op }), fvs2)], thing), all_fvs) }
rnStmt _ _ (L _ ApplicativeStmt{}) _ =
panic "rnStmt: ApplicativeStmt"
rnParallelStmts :: forall thing. HsStmtContext Name
-> SyntaxExpr Name
-> [ParStmtBlock RdrName RdrName]
-> ([Name] -> RnM (thing, FreeVars))
-> RnM (([ParStmtBlock Name Name], thing), FreeVars)
-- Note [Renaming parallel Stmts]
rnParallelStmts ctxt return_op segs thing_inside
= do { orig_lcl_env <- getLocalRdrEnv
; rn_segs orig_lcl_env [] segs }
where
rn_segs :: LocalRdrEnv
-> [Name] -> [ParStmtBlock RdrName RdrName]
-> RnM (([ParStmtBlock Name Name], thing), FreeVars)
rn_segs _ bndrs_so_far []
= do { let (bndrs', dups) = removeDups cmpByOcc bndrs_so_far
; mapM_ dupErr dups
; (thing, fvs) <- bindLocalNames bndrs' (thing_inside bndrs')
; return (([], thing), fvs) }
rn_segs env bndrs_so_far (ParStmtBlock stmts _ _ : segs)
= do { ((stmts', (used_bndrs, segs', thing)), fvs)
<- rnStmts ctxt rnLExpr stmts $ \ bndrs ->
setLocalRdrEnv env $ do
{ ((segs', thing), fvs) <- rn_segs env (bndrs ++ bndrs_so_far) segs
; let used_bndrs = filter (`elemNameSet` fvs) bndrs
; return ((used_bndrs, segs', thing), fvs) }
; let seg' = ParStmtBlock stmts' used_bndrs return_op
; return ((seg':segs', thing), fvs) }
cmpByOcc n1 n2 = nameOccName n1 `compare` nameOccName n2
dupErr vs = addErr (text "Duplicate binding in parallel list comprehension for:"
<+> quotes (ppr (head vs)))
lookupStmtName :: HsStmtContext Name -> Name -> RnM (SyntaxExpr Name, FreeVars)
-- Like lookupSyntaxName, but respects contexts
lookupStmtName ctxt n
| rebindableContext ctxt
= lookupSyntaxName n
| otherwise
= return (mkRnSyntaxExpr n, emptyFVs)
lookupStmtNamePoly :: HsStmtContext Name -> Name -> RnM (HsExpr Name, FreeVars)
lookupStmtNamePoly ctxt name
| rebindableContext ctxt
= do { rebindable_on <- xoptM LangExt.RebindableSyntax
; if rebindable_on
then do { fm <- lookupOccRn (nameRdrName name)
; return (HsVar (noLoc fm), unitFV fm) }
else not_rebindable }
| otherwise
= not_rebindable
where
not_rebindable = return (HsVar (noLoc name), emptyFVs)
-- | Is this a context where we respect RebindableSyntax?
-- but ListComp/PArrComp are never rebindable
-- Neither is ArrowExpr, which has its own desugarer in DsArrows
rebindableContext :: HsStmtContext Name -> Bool
rebindableContext ctxt = case ctxt of
ListComp -> False
PArrComp -> False
ArrowExpr -> False
PatGuard {} -> False
DoExpr -> True
MDoExpr -> True
MonadComp -> True
GhciStmtCtxt -> True -- I suppose?
ParStmtCtxt c -> rebindableContext c -- Look inside to
TransStmtCtxt c -> rebindableContext c -- the parent context
{-
Note [Renaming parallel Stmts]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Renaming parallel statements is painful. Given, say
[ a+c | a <- as, bs <- bss
| c <- bs, a <- ds ]
Note that
(a) In order to report "Defined but not used" about 'bs', we must
rename each group of Stmts with a thing_inside whose FreeVars
include at least {a,c}
(b) We want to report that 'a' is illegally bound in both branches
(c) The 'bs' in the second group must obviously not be captured by
the binding in the first group
To satisfy (a) we nest the segements.
To satisfy (b) we check for duplicates just before thing_inside.
To satisfy (c) we reset the LocalRdrEnv each time.
************************************************************************
* *
\subsubsection{mdo expressions}
* *
************************************************************************
-}
type FwdRefs = NameSet
type Segment stmts = (Defs,
Uses, -- May include defs
FwdRefs, -- A subset of uses that are
-- (a) used before they are bound in this segment, or
-- (b) used here, and bound in subsequent segments
stmts) -- Either Stmt or [Stmt]
-- wrapper that does both the left- and right-hand sides
rnRecStmtsAndThen :: Outputable (body RdrName) =>
(Located (body RdrName)
-> RnM (Located (body Name), FreeVars))
-> [LStmt RdrName (Located (body RdrName))]
-- assumes that the FreeVars returned includes
-- the FreeVars of the Segments
-> ([Segment (LStmt Name (Located (body Name)))]
-> RnM (a, FreeVars))
-> RnM (a, FreeVars)
rnRecStmtsAndThen rnBody s cont
= do { -- (A) Make the mini fixity env for all of the stmts
fix_env <- makeMiniFixityEnv (collectRecStmtsFixities s)
-- (B) Do the LHSes
; new_lhs_and_fv <- rn_rec_stmts_lhs fix_env s
-- ...bring them and their fixities into scope
; let bound_names = collectLStmtsBinders (map fst new_lhs_and_fv)
-- Fake uses of variables introduced implicitly (warning suppression, see #4404)
implicit_uses = lStmtsImplicits (map fst new_lhs_and_fv)
; bindLocalNamesFV bound_names $
addLocalFixities fix_env bound_names $ do
-- (C) do the right-hand-sides and thing-inside
{ segs <- rn_rec_stmts rnBody bound_names new_lhs_and_fv
; (res, fvs) <- cont segs
; warnUnusedLocalBinds bound_names (fvs `unionNameSet` implicit_uses)
; return (res, fvs) }}
-- get all the fixity decls in any Let stmt
collectRecStmtsFixities :: [LStmtLR RdrName RdrName body] -> [LFixitySig RdrName]
collectRecStmtsFixities l =
foldr (\ s -> \acc -> case s of
(L _ (LetStmt (L _ (HsValBinds (ValBindsIn _ sigs))))) ->
foldr (\ sig -> \ acc -> case sig of
(L loc (FixSig s)) -> (L loc s) : acc
_ -> acc) acc sigs
_ -> acc) [] l
-- left-hand sides
rn_rec_stmt_lhs :: Outputable body => MiniFixityEnv
-> LStmt RdrName body
-- rename LHS, and return its FVs
-- Warning: we will only need the FreeVars below in the case of a BindStmt,
-- so we don't bother to compute it accurately in the other cases
-> RnM [(LStmtLR Name RdrName body, FreeVars)]
rn_rec_stmt_lhs _ (L loc (BodyStmt body a b c))
= return [(L loc (BodyStmt body a b c), emptyFVs)]
rn_rec_stmt_lhs _ (L loc (LastStmt body noret a))
= return [(L loc (LastStmt body noret a), emptyFVs)]
rn_rec_stmt_lhs fix_env (L loc (BindStmt pat body a b t))
= do
-- should the ctxt be MDo instead?
(pat', fv_pat) <- rnBindPat (localRecNameMaker fix_env) pat
return [(L loc (BindStmt pat' body a b t),
fv_pat)]
rn_rec_stmt_lhs _ (L _ (LetStmt (L _ binds@(HsIPBinds _))))
= failWith (badIpBinds (text "an mdo expression") binds)
rn_rec_stmt_lhs fix_env (L loc (LetStmt (L l(HsValBinds binds))))
= do (_bound_names, binds') <- rnLocalValBindsLHS fix_env binds
return [(L loc (LetStmt (L l (HsValBinds binds'))),
-- Warning: this is bogus; see function invariant
emptyFVs
)]
-- XXX Do we need to do something with the return and mfix names?
rn_rec_stmt_lhs fix_env (L _ (RecStmt { recS_stmts = stmts })) -- Flatten Rec inside Rec
= rn_rec_stmts_lhs fix_env stmts
rn_rec_stmt_lhs _ stmt@(L _ (ParStmt {})) -- Syntactically illegal in mdo
= pprPanic "rn_rec_stmt" (ppr stmt)
rn_rec_stmt_lhs _ stmt@(L _ (TransStmt {})) -- Syntactically illegal in mdo
= pprPanic "rn_rec_stmt" (ppr stmt)
rn_rec_stmt_lhs _ stmt@(L _ (ApplicativeStmt {})) -- Shouldn't appear yet
= pprPanic "rn_rec_stmt" (ppr stmt)
rn_rec_stmt_lhs _ (L _ (LetStmt (L _ EmptyLocalBinds)))
= panic "rn_rec_stmt LetStmt EmptyLocalBinds"
rn_rec_stmts_lhs :: Outputable body => MiniFixityEnv
-> [LStmt RdrName body]
-> RnM [(LStmtLR Name RdrName body, FreeVars)]
rn_rec_stmts_lhs fix_env stmts
= do { ls <- concatMapM (rn_rec_stmt_lhs fix_env) stmts
; let boundNames = collectLStmtsBinders (map fst ls)
-- First do error checking: we need to check for dups here because we
-- don't bind all of the variables from the Stmt at once
-- with bindLocatedLocals.
; checkDupNames boundNames
; return ls }
-- right-hand-sides
rn_rec_stmt :: (Outputable (body RdrName)) =>
(Located (body RdrName) -> RnM (Located (body Name), FreeVars))
-> [Name]
-> (LStmtLR Name RdrName (Located (body RdrName)), FreeVars)
-> RnM [Segment (LStmt Name (Located (body Name)))]
-- Rename a Stmt that is inside a RecStmt (or mdo)
-- Assumes all binders are already in scope
-- Turns each stmt into a singleton Stmt
rn_rec_stmt rnBody _ (L loc (LastStmt body noret _), _)
= do { (body', fv_expr) <- rnBody body
; (ret_op, fvs1) <- lookupSyntaxName returnMName
; return [(emptyNameSet, fv_expr `plusFV` fvs1, emptyNameSet,
L loc (LastStmt body' noret ret_op))] }
rn_rec_stmt rnBody _ (L loc (BodyStmt body _ _ _), _)
= do { (body', fvs) <- rnBody body
; (then_op, fvs1) <- lookupSyntaxName thenMName
; return [(emptyNameSet, fvs `plusFV` fvs1, emptyNameSet,
L loc (BodyStmt body' then_op noSyntaxExpr placeHolderType))] }
rn_rec_stmt rnBody _ (L loc (BindStmt pat' body _ _ _), fv_pat)
= do { (body', fv_expr) <- rnBody body
; (bind_op, fvs1) <- lookupSyntaxName bindMName
; xMonadFailEnabled <- fmap (xopt LangExt.MonadFailDesugaring) getDynFlags
; let failFunction | xMonadFailEnabled = failMName
| otherwise = failMName_preMFP
; (fail_op, fvs2) <- lookupSyntaxName failFunction
; let bndrs = mkNameSet (collectPatBinders pat')
fvs = fv_expr `plusFV` fv_pat `plusFV` fvs1 `plusFV` fvs2
; return [(bndrs, fvs, bndrs `intersectNameSet` fvs,
L loc (BindStmt pat' body' bind_op fail_op PlaceHolder))] }
rn_rec_stmt _ _ (L _ (LetStmt (L _ binds@(HsIPBinds _))), _)
= failWith (badIpBinds (text "an mdo expression") binds)
rn_rec_stmt _ all_bndrs (L loc (LetStmt (L l (HsValBinds binds'))), _)
= do { (binds', du_binds) <- rnLocalValBindsRHS (mkNameSet all_bndrs) binds'
-- fixities and unused are handled above in rnRecStmtsAndThen
; let fvs = allUses du_binds
; return [(duDefs du_binds, fvs, emptyNameSet,
L loc (LetStmt (L l (HsValBinds binds'))))] }
-- no RecStmt case because they get flattened above when doing the LHSes
rn_rec_stmt _ _ stmt@(L _ (RecStmt {}), _)
= pprPanic "rn_rec_stmt: RecStmt" (ppr stmt)
rn_rec_stmt _ _ stmt@(L _ (ParStmt {}), _) -- Syntactically illegal in mdo
= pprPanic "rn_rec_stmt: ParStmt" (ppr stmt)
rn_rec_stmt _ _ stmt@(L _ (TransStmt {}), _) -- Syntactically illegal in mdo
= pprPanic "rn_rec_stmt: TransStmt" (ppr stmt)
rn_rec_stmt _ _ (L _ (LetStmt (L _ EmptyLocalBinds)), _)
= panic "rn_rec_stmt: LetStmt EmptyLocalBinds"
rn_rec_stmt _ _ stmt@(L _ (ApplicativeStmt {}), _)
= pprPanic "rn_rec_stmt: ApplicativeStmt" (ppr stmt)
rn_rec_stmts :: Outputable (body RdrName) =>
(Located (body RdrName) -> RnM (Located (body Name), FreeVars))
-> [Name]
-> [(LStmtLR Name RdrName (Located (body RdrName)), FreeVars)]
-> RnM [Segment (LStmt Name (Located (body Name)))]
rn_rec_stmts rnBody bndrs stmts
= do { segs_s <- mapM (rn_rec_stmt rnBody bndrs) stmts
; return (concat segs_s) }
---------------------------------------------
segmentRecStmts :: SrcSpan -> HsStmtContext Name
-> Stmt Name body
-> [Segment (LStmt Name body)] -> FreeVars
-> ([LStmt Name body], FreeVars)
segmentRecStmts loc ctxt empty_rec_stmt segs fvs_later
| null segs
= ([], fvs_later)
| MDoExpr <- ctxt
= segsToStmts empty_rec_stmt grouped_segs fvs_later
-- Step 4: Turn the segments into Stmts
-- Use RecStmt when and only when there are fwd refs
-- Also gather up the uses from the end towards the
-- start, so we can tell the RecStmt which things are
-- used 'after' the RecStmt
| otherwise
= ([ L loc $
empty_rec_stmt { recS_stmts = ss
, recS_later_ids = nameSetElems (defs `intersectNameSet` fvs_later)
, recS_rec_ids = nameSetElems (defs `intersectNameSet` uses) }]
, uses `plusFV` fvs_later)
where
(defs_s, uses_s, _, ss) = unzip4 segs
defs = plusFVs defs_s
uses = plusFVs uses_s
-- Step 2: Fill in the fwd refs.
-- The segments are all singletons, but their fwd-ref
-- field mentions all the things used by the segment
-- that are bound after their use
segs_w_fwd_refs = addFwdRefs segs
-- Step 3: Group together the segments to make bigger segments
-- Invariant: in the result, no segment uses a variable
-- bound in a later segment
grouped_segs = glomSegments ctxt segs_w_fwd_refs
----------------------------
addFwdRefs :: [Segment a] -> [Segment a]
-- So far the segments only have forward refs *within* the Stmt
-- (which happens for bind: x <- ...x...)
-- This function adds the cross-seg fwd ref info
addFwdRefs segs
= fst (foldr mk_seg ([], emptyNameSet) segs)
where
mk_seg (defs, uses, fwds, stmts) (segs, later_defs)
= (new_seg : segs, all_defs)
where
new_seg = (defs, uses, new_fwds, stmts)
all_defs = later_defs `unionNameSet` defs
new_fwds = fwds `unionNameSet` (uses `intersectNameSet` later_defs)
-- Add the downstream fwd refs here
{-
Note [Segmenting mdo]
~~~~~~~~~~~~~~~~~~~~~
NB. June 7 2012: We only glom segments that appear in an explicit mdo;
and leave those found in "do rec"'s intact. See
http://ghc.haskell.org/trac/ghc/ticket/4148 for the discussion
leading to this design choice. Hence the test in segmentRecStmts.
Note [Glomming segments]
~~~~~~~~~~~~~~~~~~~~~~~~
Glomming the singleton segments of an mdo into minimal recursive groups.
At first I thought this was just strongly connected components, but
there's an important constraint: the order of the stmts must not change.
Consider
mdo { x <- ...y...
p <- z
y <- ...x...
q <- x
z <- y
r <- x }
Here, the first stmt mention 'y', which is bound in the third.
But that means that the innocent second stmt (p <- z) gets caught
up in the recursion. And that in turn means that the binding for
'z' has to be included... and so on.
Start at the tail { r <- x }
Now add the next one { z <- y ; r <- x }
Now add one more { q <- x ; z <- y ; r <- x }
Now one more... but this time we have to group a bunch into rec
{ rec { y <- ...x... ; q <- x ; z <- y } ; r <- x }
Now one more, which we can add on without a rec
{ p <- z ;
rec { y <- ...x... ; q <- x ; z <- y } ;
r <- x }
Finally we add the last one; since it mentions y we have to
glom it together with the first two groups
{ rec { x <- ...y...; p <- z ; y <- ...x... ;
q <- x ; z <- y } ;
r <- x }
-}
glomSegments :: HsStmtContext Name
-> [Segment (LStmt Name body)]
-> [Segment [LStmt Name body]] -- Each segment has a non-empty list of Stmts
-- See Note [Glomming segments]
glomSegments _ [] = []
glomSegments ctxt ((defs,uses,fwds,stmt) : segs)
-- Actually stmts will always be a singleton
= (seg_defs, seg_uses, seg_fwds, seg_stmts) : others
where
segs' = glomSegments ctxt segs
(extras, others) = grab uses segs'
(ds, us, fs, ss) = unzip4 extras
seg_defs = plusFVs ds `plusFV` defs
seg_uses = plusFVs us `plusFV` uses
seg_fwds = plusFVs fs `plusFV` fwds
seg_stmts = stmt : concat ss
grab :: NameSet -- The client
-> [Segment a]
-> ([Segment a], -- Needed by the 'client'
[Segment a]) -- Not needed by the client
-- The result is simply a split of the input
grab uses dus
= (reverse yeses, reverse noes)
where
(noes, yeses) = span not_needed (reverse dus)
not_needed (defs,_,_,_) = not (intersectsNameSet defs uses)
----------------------------------------------------
segsToStmts :: Stmt Name body -- A RecStmt with the SyntaxOps filled in
-> [Segment [LStmt Name body]] -- Each Segment has a non-empty list of Stmts
-> FreeVars -- Free vars used 'later'
-> ([LStmt Name body], FreeVars)
segsToStmts _ [] fvs_later = ([], fvs_later)
segsToStmts empty_rec_stmt ((defs, uses, fwds, ss) : segs) fvs_later
= ASSERT( not (null ss) )
(new_stmt : later_stmts, later_uses `plusFV` uses)
where
(later_stmts, later_uses) = segsToStmts empty_rec_stmt segs fvs_later
new_stmt | non_rec = head ss
| otherwise = L (getLoc (head ss)) rec_stmt
rec_stmt = empty_rec_stmt { recS_stmts = ss
, recS_later_ids = nameSetElems used_later
, recS_rec_ids = nameSetElems fwds }
non_rec = isSingleton ss && isEmptyNameSet fwds
used_later = defs `intersectNameSet` later_uses
-- The ones needed after the RecStmt
{-
************************************************************************
* *
ApplicativeDo
* *
************************************************************************
Note [ApplicativeDo]
= Example =
For a sequence of statements
do
x <- A
y <- B x
z <- C
return (f x y z)
We want to transform this to
(\(x,y) z -> f x y z) <$> (do x <- A; y <- B x; return (x,y)) <*> C
It would be easy to notice that "y <- B x" and "z <- C" are
independent and do something like this:
do
x <- A
(y,z) <- (,) <$> B x <*> C
return (f x y z)
But this isn't enough! A and C were also independent, and this
transformation loses the ability to do A and C in parallel.
The algorithm works by first splitting the sequence of statements into
independent "segments", and a separate "tail" (the final statement). In
our example above, the segements would be
[ x <- A
, y <- B x ]
[ z <- C ]
and the tail is:
return (f x y z)
Then we take these segments and make an Applicative expression from them:
(\(x,y) z -> return (f x y z))
<$> do { x <- A; y <- B x; return (x,y) }
<*> C
Finally, we recursively apply the transformation to each segment, to
discover any nested parallelism.
= Syntax & spec =
expr ::= ... | do {stmt_1; ..; stmt_n} expr | ...
stmt ::= pat <- expr
| (arg_1 | ... | arg_n) -- applicative composition, n>=1
| ... -- other kinds of statement (e.g. let)
arg ::= pat <- expr
| {stmt_1; ..; stmt_n} {var_1..var_n}
(note that in the actual implementation,the expr in a do statement is
represented by a LastStmt as the final stmt, this is just a
representational issue and may change later.)
== Transformation to introduce applicative stmts ==
ado {} tail = tail
ado {pat <- expr} {return expr'} = (mkArg(pat <- expr)); return expr'
ado {one} tail = one : tail
ado stmts tail
| n == 1 = ado before (ado after tail)
where (before,after) = split(stmts_1)
| n > 1 = (mkArg(stmts_1) | ... | mkArg(stmts_n)); tail
where
{stmts_1 .. stmts_n} = segments(stmts)
segments(stmts) =
-- divide stmts into segments with no interdependencies
mkArg({pat <- expr}) = (pat <- expr)
mkArg({stmt_1; ...; stmt_n}) =
{stmt_1; ...; stmt_n} {vars(stmt_1) u .. u vars(stmt_n)}
split({stmt_1; ..; stmt_n) =
({stmt_1; ..; stmt_i}, {stmt_i+1; ..; stmt_n})
-- 1 <= i <= n
-- i is a good place to insert a bind
== Desugaring for do ==
dsDo {} expr = expr
dsDo {pat <- rhs; stmts} expr =
rhs >>= \pat -> dsDo stmts expr
dsDo {(arg_1 | ... | arg_n)} (return expr) =
(\argpat (arg_1) .. argpat(arg_n) -> expr)
<$> argexpr(arg_1)
<*> ...
<*> argexpr(arg_n)
dsDo {(arg_1 | ... | arg_n); stmts} expr =
join (\argpat (arg_1) .. argpat(arg_n) -> dsDo stmts expr)
<$> argexpr(arg_1)
<*> ...
<*> argexpr(arg_n)
-}
-- | rearrange a list of statements using ApplicativeDoStmt. See
-- Note [ApplicativeDo].
rearrangeForApplicativeDo
:: HsStmtContext Name
-> [(ExprLStmt Name, FreeVars)]
-> RnM ([ExprLStmt Name], FreeVars)
rearrangeForApplicativeDo _ [] = return ([], emptyNameSet)
rearrangeForApplicativeDo _ [(one,_)] = return ([one], emptyNameSet)
rearrangeForApplicativeDo ctxt stmts0 = do
optimal_ado <- goptM Opt_OptimalApplicativeDo
let stmt_tree | optimal_ado = mkStmtTreeOptimal stmts
| otherwise = mkStmtTreeHeuristic stmts
stmtTreeToStmts ctxt stmt_tree [last] last_fvs
where
(stmts,(last,last_fvs)) = findLast stmts0
findLast [] = error "findLast"
findLast [last] = ([],last)
findLast (x:xs) = (x:rest,last) where (rest,last) = findLast xs
-- | A tree of statements using a mixture of applicative and bind constructs.
data StmtTree a
= StmtTreeOne a
| StmtTreeBind (StmtTree a) (StmtTree a)
| StmtTreeApplicative [StmtTree a]
flattenStmtTree :: StmtTree a -> [a]
flattenStmtTree t = go t []
where
go (StmtTreeOne a) as = a : as
go (StmtTreeBind l r) as = go l (go r as)
go (StmtTreeApplicative ts) as = foldr go as ts
type ExprStmtTree = StmtTree (ExprLStmt Name, FreeVars)
type Cost = Int
-- | Turn a sequence of statements into an ExprStmtTree using a
-- heuristic algorithm. /O(n^2)/
mkStmtTreeHeuristic :: [(ExprLStmt Name, FreeVars)] -> ExprStmtTree
mkStmtTreeHeuristic [one] = StmtTreeOne one
mkStmtTreeHeuristic stmts =
case segments stmts of
[one] -> split one
segs -> StmtTreeApplicative (map split segs)
where
split [one] = StmtTreeOne one
split stmts =
StmtTreeBind (mkStmtTreeHeuristic before) (mkStmtTreeHeuristic after)
where (before, after) = splitSegment stmts
-- | Turn a sequence of statements into an ExprStmtTree optimally,
-- using dynamic programming. /O(n^3)/
mkStmtTreeOptimal :: [(ExprLStmt Name, FreeVars)] -> ExprStmtTree
mkStmtTreeOptimal stmts =
ASSERT(not (null stmts)) -- the empty case is handled by the caller;
-- we don't support empty StmtTrees.
fst (arr ! (0,n))
where
n = length stmts - 1
stmt_arr = listArray (0,n) stmts
-- lazy cache of optimal trees for subsequences of the input
arr :: Array (Int,Int) (ExprStmtTree, Cost)
arr = array ((0,0),(n,n))
[ ((lo,hi), tree lo hi)
| lo <- [0..n]
, hi <- [lo..n] ]
-- compute the optimal tree for the sequence [lo..hi]
tree lo hi
| hi == lo = (StmtTreeOne (stmt_arr ! lo), 1)
| otherwise =
case segments [ stmt_arr ! i | i <- [lo..hi] ] of
[] -> panic "mkStmtTree"
[_one] -> split lo hi
segs -> (StmtTreeApplicative trees, maximum costs)
where
bounds = scanl (\(_,hi) a -> (hi+1, hi + length a)) (0,lo-1) segs
(trees,costs) = unzip (map (uncurry split) (tail bounds))
-- find the best place to split the segment [lo..hi]
split :: Int -> Int -> (ExprStmtTree, Cost)
split lo hi
| hi == lo = (StmtTreeOne (stmt_arr ! lo), 1)
| otherwise = (StmtTreeBind before after, c1+c2)
where
-- As per the paper, for a sequence s1...sn, we want to find
-- the split with the minimum cost, where the cost is the
-- sum of the cost of the left and right subsequences.
--
-- As an optimisation (also in the paper) if the cost of
-- s1..s(n-1) is different from the cost of s2..sn, we know
-- that the optimal solution is the lower of the two. Only
-- in the case that these two have the same cost do we need
-- to do the exhaustive search.
--
((before,c1),(after,c2))
| hi - lo == 1
= ((StmtTreeOne (stmt_arr ! lo), 1),
(StmtTreeOne (stmt_arr ! hi), 1))
| left_cost < right_cost
= ((left,left_cost), (StmtTreeOne (stmt_arr ! hi), 1))
| otherwise -- left_cost > right_cost
= ((StmtTreeOne (stmt_arr ! lo), 1), (right,right_cost))
| otherwise = minimumBy (comparing cost) alternatives
where
(left, left_cost) = arr ! (lo,hi-1)
(right, right_cost) = arr ! (lo+1,hi)
cost ((_,c1),(_,c2)) = c1 + c2
alternatives = [ (arr ! (lo,k), arr ! (k+1,hi))
| k <- [lo .. hi-1] ]
-- | Turn the ExprStmtTree back into a sequence of statements, using
-- ApplicativeStmt where necessary.
stmtTreeToStmts
:: HsStmtContext Name
-> ExprStmtTree
-> [ExprLStmt Name] -- ^ the "tail"
-> FreeVars -- ^ free variables of the tail
-> RnM ( [ExprLStmt Name] -- ( output statements,
, FreeVars ) -- , things we needed
-- If we have a single bind, and we can do it without a join, transform
-- to an ApplicativeStmt. This corresponds to the rule
-- dsBlock [pat <- rhs] (return expr) = expr <$> rhs
-- In the spec, but we do it here rather than in the desugarer,
-- because we need the typechecker to typecheck the <$> form rather than
-- the bind form, which would give rise to a Monad constraint.
stmtTreeToStmts ctxt (StmtTreeOne (L _ (BindStmt pat rhs _ _ _),_))
tail _tail_fvs
| isIrrefutableHsPat pat, (False,tail') <- needJoin tail
-- WARNING: isIrrefutableHsPat on (HsPat Name) doesn't have enough info
-- to know which types have only one constructor. So only
-- tuples come out as irrefutable; other single-constructor
-- types, and newtypes, will not. See the code for
-- isIrrefuatableHsPat
= mkApplicativeStmt ctxt [ApplicativeArgOne pat rhs] False tail'
stmtTreeToStmts _ctxt (StmtTreeOne (s,_)) tail _tail_fvs =
return (s : tail, emptyNameSet)
stmtTreeToStmts ctxt (StmtTreeBind before after) tail tail_fvs = do
(stmts1, fvs1) <- stmtTreeToStmts ctxt after tail tail_fvs
let tail1_fvs = unionNameSets (tail_fvs : map snd (flattenStmtTree after))
(stmts2, fvs2) <- stmtTreeToStmts ctxt before stmts1 tail1_fvs
return (stmts2, fvs1 `plusFV` fvs2)
stmtTreeToStmts ctxt (StmtTreeApplicative trees) tail tail_fvs = do
pairs <- mapM (stmtTreeArg ctxt tail_fvs) trees
let (stmts', fvss) = unzip pairs
let (need_join, tail') = needJoin tail
(stmts, fvs) <- mkApplicativeStmt ctxt stmts' need_join tail'
return (stmts, unionNameSets (fvs:fvss))
where
stmtTreeArg _ctxt _tail_fvs (StmtTreeOne (L _ (BindStmt pat exp _ _ _), _)) =
return (ApplicativeArgOne pat exp, emptyFVs)
stmtTreeArg ctxt tail_fvs tree = do
let stmts = flattenStmtTree tree
pvarset = mkNameSet (concatMap (collectStmtBinders.unLoc.fst) stmts)
`intersectNameSet` tail_fvs
pvars = nameSetElems pvarset
pat = mkBigLHsVarPatTup pvars
tup = mkBigLHsVarTup pvars
(stmts',fvs2) <- stmtTreeToStmts ctxt tree [] pvarset
(mb_ret, fvs1) <-
if | L _ ApplicativeStmt{} <- last stmts' ->
return (unLoc tup, emptyNameSet)
| otherwise -> do
(ret,fvs) <- lookupStmtNamePoly ctxt returnMName
return (HsApp (noLoc ret) tup, fvs)
return ( ApplicativeArgMany stmts' mb_ret pat
, fvs1 `plusFV` fvs2)
-- | Divide a sequence of statements into segments, where no segment
-- depends on any variables defined by a statement in another segment.
segments
:: [(ExprLStmt Name, FreeVars)]
-> [[(ExprLStmt Name, FreeVars)]]
segments stmts = map fst $ merge $ reverse $ map reverse $ walk (reverse stmts)
where
allvars = mkNameSet (concatMap (collectStmtBinders.unLoc.fst) stmts)
-- We would rather not have a segment that just has LetStmts in
-- it, so combine those with an adjacent segment where possible.
merge [] = []
merge (seg : segs)
= case rest of
[] -> [(seg,all_lets)]
((s,s_lets):ss) | all_lets || s_lets
-> (seg ++ s, all_lets && s_lets) : ss
_otherwise -> (seg,all_lets) : rest
where
rest = merge segs
all_lets = all (isLetStmt . fst) seg
-- walk splits the statement sequence into segments, traversing
-- the sequence from the back to the front, and keeping track of
-- the set of free variables of the current segment. Whenever
-- this set of free variables is empty, we have a complete segment.
walk :: [(ExprLStmt Name, FreeVars)] -> [[(ExprLStmt Name, FreeVars)]]
walk [] = []
walk ((stmt,fvs) : stmts) = ((stmt,fvs) : seg) : walk rest
where (seg,rest) = chunter fvs' stmts
(_, fvs') = stmtRefs stmt fvs
chunter _ [] = ([], [])
chunter vars ((stmt,fvs) : rest)
| not (isEmptyNameSet vars)
= ((stmt,fvs) : chunk, rest')
where (chunk,rest') = chunter vars' rest
(pvars, evars) = stmtRefs stmt fvs
vars' = (vars `minusNameSet` pvars) `unionNameSet` evars
chunter _ rest = ([], rest)
stmtRefs stmt fvs
| isLetStmt stmt = (pvars, fvs' `minusNameSet` pvars)
| otherwise = (pvars, fvs')
where fvs' = fvs `intersectNameSet` allvars
pvars = mkNameSet (collectStmtBinders (unLoc stmt))
isLetStmt :: LStmt a b -> Bool
isLetStmt (L _ LetStmt{}) = True
isLetStmt _ = False
-- | Find a "good" place to insert a bind in an indivisible segment.
-- This is the only place where we use heuristics. The current
-- heuristic is to peel off the first group of independent statements
-- and put the bind after those.
splitSegment
:: [(ExprLStmt Name, FreeVars)]
-> ( [(ExprLStmt Name, FreeVars)]
, [(ExprLStmt Name, FreeVars)] )
splitSegment [one,two] = ([one],[two])
-- there is no choice when there are only two statements; this just saves
-- some work in a common case.
splitSegment stmts
| Just (lets,binds,rest) <- slurpIndependentStmts stmts
= if not (null lets)
then (lets, binds++rest)
else (lets++binds, rest)
| otherwise
= case stmts of
(x:xs) -> ([x],xs)
_other -> (stmts,[])
slurpIndependentStmts
:: [(LStmt Name (Located (body Name)), FreeVars)]
-> Maybe ( [(LStmt Name (Located (body Name)), FreeVars)] -- LetStmts
, [(LStmt Name (Located (body Name)), FreeVars)] -- BindStmts
, [(LStmt Name (Located (body Name)), FreeVars)] )
slurpIndependentStmts stmts = go [] [] emptyNameSet stmts
where
-- If we encounter a BindStmt that doesn't depend on a previous BindStmt
-- in this group, then add it to the group.
go lets indep bndrs ((L loc (BindStmt pat body bind_op fail_op ty), fvs) : rest)
| isEmptyNameSet (bndrs `intersectNameSet` fvs)
= go lets ((L loc (BindStmt pat body bind_op fail_op ty), fvs) : indep)
bndrs' rest
where bndrs' = bndrs `unionNameSet` mkNameSet (collectPatBinders pat)
-- If we encounter a LetStmt that doesn't depend on a BindStmt in this
-- group, then move it to the beginning, so that it doesn't interfere with
-- grouping more BindStmts.
-- TODO: perhaps we shouldn't do this if there are any strict bindings,
-- because we might be moving evaluation earlier.
go lets indep bndrs ((L loc (LetStmt binds), fvs) : rest)
| isEmptyNameSet (bndrs `intersectNameSet` fvs)
= go ((L loc (LetStmt binds), fvs) : lets) indep bndrs rest
go _ [] _ _ = Nothing
go _ [_] _ _ = Nothing
go lets indep _ stmts = Just (reverse lets, reverse indep, stmts)
-- | Build an ApplicativeStmt, and strip the "return" from the tail
-- if necessary.
--
-- For example, if we start with
-- do x <- E1; y <- E2; return (f x y)
-- then we get
-- do (E1[x] | E2[y]); f x y
--
-- the LastStmt in this case has the return removed, but we set the
-- flag on the LastStmt to indicate this, so that we can print out the
-- original statement correctly in error messages. It is easier to do
-- it this way rather than try to ignore the return later in both the
-- typechecker and the desugarer (I tried it that way first!).
mkApplicativeStmt
:: HsStmtContext Name
-> [ApplicativeArg Name Name] -- ^ The args
-> Bool -- ^ True <=> need a join
-> [ExprLStmt Name] -- ^ The body statements
-> RnM ([ExprLStmt Name], FreeVars)
mkApplicativeStmt ctxt args need_join body_stmts
= do { (fmap_op, fvs1) <- lookupStmtName ctxt fmapName
; (ap_op, fvs2) <- lookupStmtName ctxt apAName
; (mb_join, fvs3) <-
if need_join then
do { (join_op, fvs) <- lookupStmtName ctxt joinMName
; return (Just join_op, fvs) }
else
return (Nothing, emptyNameSet)
; let applicative_stmt = noLoc $ ApplicativeStmt
(zip (fmap_op : repeat ap_op) args)
mb_join
placeHolderType
; return ( applicative_stmt : body_stmts
, fvs1 `plusFV` fvs2 `plusFV` fvs3) }
-- | Given the statements following an ApplicativeStmt, determine whether
-- we need a @join@ or not, and remove the @return@ if necessary.
needJoin :: [ExprLStmt Name] -> (Bool, [ExprLStmt Name])
needJoin [] = (False, []) -- we're in an ApplicativeArg
needJoin [L loc (LastStmt e _ t)]
| Just arg <- isReturnApp e = (False, [L loc (LastStmt arg True t)])
needJoin stmts = (True, stmts)
-- | @Just e@, if the expression is @return e@, otherwise @Nothing@
isReturnApp :: LHsExpr Name -> Maybe (LHsExpr Name)
isReturnApp (L _ (HsPar expr)) = isReturnApp expr
isReturnApp (L _ (HsApp f arg))
| is_return f = Just arg
| otherwise = Nothing
where
is_return (L _ (HsPar e)) = is_return e
is_return (L _ (HsAppType e _)) = is_return e
is_return (L _ (HsVar (L _ r))) = r == returnMName || r == pureAName
-- TODO: I don't know how to get this right for rebindable syntax
is_return _ = False
isReturnApp _ = Nothing
{-
************************************************************************
* *
\subsubsection{Errors}
* *
************************************************************************
-}
checkEmptyStmts :: HsStmtContext Name -> RnM ()
-- We've seen an empty sequence of Stmts... is that ok?
checkEmptyStmts ctxt
= unless (okEmpty ctxt) (addErr (emptyErr ctxt))
okEmpty :: HsStmtContext a -> Bool
okEmpty (PatGuard {}) = True
okEmpty _ = False
emptyErr :: HsStmtContext Name -> SDoc
emptyErr (ParStmtCtxt {}) = text "Empty statement group in parallel comprehension"
emptyErr (TransStmtCtxt {}) = text "Empty statement group preceding 'group' or 'then'"
emptyErr ctxt = text "Empty" <+> pprStmtContext ctxt
----------------------
checkLastStmt :: Outputable (body RdrName) => HsStmtContext Name
-> LStmt RdrName (Located (body RdrName))
-> RnM (LStmt RdrName (Located (body RdrName)))
checkLastStmt ctxt lstmt@(L loc stmt)
= case ctxt of
ListComp -> check_comp
MonadComp -> check_comp
PArrComp -> check_comp
ArrowExpr -> check_do
DoExpr -> check_do
MDoExpr -> check_do
_ -> check_other
where
check_do -- Expect BodyStmt, and change it to LastStmt
= case stmt of
BodyStmt e _ _ _ -> return (L loc (mkLastStmt e))
LastStmt {} -> return lstmt -- "Deriving" clauses may generate a
-- LastStmt directly (unlike the parser)
_ -> do { addErr (hang last_error 2 (ppr stmt)); return lstmt }
last_error = (text "The last statement in" <+> pprAStmtContext ctxt
<+> text "must be an expression")
check_comp -- Expect LastStmt; this should be enforced by the parser!
= case stmt of
LastStmt {} -> return lstmt
_ -> pprPanic "checkLastStmt" (ppr lstmt)
check_other -- Behave just as if this wasn't the last stmt
= do { checkStmt ctxt lstmt; return lstmt }
-- Checking when a particular Stmt is ok
checkStmt :: HsStmtContext Name
-> LStmt RdrName (Located (body RdrName))
-> RnM ()
checkStmt ctxt (L _ stmt)
= do { dflags <- getDynFlags
; case okStmt dflags ctxt stmt of
IsValid -> return ()
NotValid extra -> addErr (msg $$ extra) }
where
msg = sep [ text "Unexpected" <+> pprStmtCat stmt <+> ptext (sLit "statement")
, text "in" <+> pprAStmtContext ctxt ]
pprStmtCat :: Stmt a body -> SDoc
pprStmtCat (TransStmt {}) = text "transform"
pprStmtCat (LastStmt {}) = text "return expression"
pprStmtCat (BodyStmt {}) = text "body"
pprStmtCat (BindStmt {}) = text "binding"
pprStmtCat (LetStmt {}) = text "let"
pprStmtCat (RecStmt {}) = text "rec"
pprStmtCat (ParStmt {}) = text "parallel"
pprStmtCat (ApplicativeStmt {}) = panic "pprStmtCat: ApplicativeStmt"
------------
emptyInvalid :: Validity -- Payload is the empty document
emptyInvalid = NotValid Outputable.empty
okStmt, okDoStmt, okCompStmt, okParStmt, okPArrStmt
:: DynFlags -> HsStmtContext Name
-> Stmt RdrName (Located (body RdrName)) -> Validity
-- Return Nothing if OK, (Just extra) if not ok
-- The "extra" is an SDoc that is appended to an generic error message
okStmt dflags ctxt stmt
= case ctxt of
PatGuard {} -> okPatGuardStmt stmt
ParStmtCtxt ctxt -> okParStmt dflags ctxt stmt
DoExpr -> okDoStmt dflags ctxt stmt
MDoExpr -> okDoStmt dflags ctxt stmt
ArrowExpr -> okDoStmt dflags ctxt stmt
GhciStmtCtxt -> okDoStmt dflags ctxt stmt
ListComp -> okCompStmt dflags ctxt stmt
MonadComp -> okCompStmt dflags ctxt stmt
PArrComp -> okPArrStmt dflags ctxt stmt
TransStmtCtxt ctxt -> okStmt dflags ctxt stmt
-------------
okPatGuardStmt :: Stmt RdrName (Located (body RdrName)) -> Validity
okPatGuardStmt stmt
= case stmt of
BodyStmt {} -> IsValid
BindStmt {} -> IsValid
LetStmt {} -> IsValid
_ -> emptyInvalid
-------------
okParStmt dflags ctxt stmt
= case stmt of
LetStmt (L _ (HsIPBinds {})) -> emptyInvalid
_ -> okStmt dflags ctxt stmt
----------------
okDoStmt dflags ctxt stmt
= case stmt of
RecStmt {}
| LangExt.RecursiveDo `xopt` dflags -> IsValid
| ArrowExpr <- ctxt -> IsValid -- Arrows allows 'rec'
| otherwise -> NotValid (text "Use RecursiveDo")
BindStmt {} -> IsValid
LetStmt {} -> IsValid
BodyStmt {} -> IsValid
_ -> emptyInvalid
----------------
okCompStmt dflags _ stmt
= case stmt of
BindStmt {} -> IsValid
LetStmt {} -> IsValid
BodyStmt {} -> IsValid
ParStmt {}
| LangExt.ParallelListComp `xopt` dflags -> IsValid
| otherwise -> NotValid (text "Use ParallelListComp")
TransStmt {}
| LangExt.TransformListComp `xopt` dflags -> IsValid
| otherwise -> NotValid (text "Use TransformListComp")
RecStmt {} -> emptyInvalid
LastStmt {} -> emptyInvalid -- Should not happen (dealt with by checkLastStmt)
ApplicativeStmt {} -> emptyInvalid
----------------
okPArrStmt dflags _ stmt
= case stmt of
BindStmt {} -> IsValid
LetStmt {} -> IsValid
BodyStmt {} -> IsValid
ParStmt {}
| LangExt.ParallelListComp `xopt` dflags -> IsValid
| otherwise -> NotValid (text "Use ParallelListComp")
TransStmt {} -> emptyInvalid
RecStmt {} -> emptyInvalid
LastStmt {} -> emptyInvalid -- Should not happen (dealt with by checkLastStmt)
ApplicativeStmt {} -> emptyInvalid
---------
checkTupleSection :: [LHsTupArg RdrName] -> RnM ()
checkTupleSection args
= do { tuple_section <- xoptM LangExt.TupleSections
; checkErr (all tupArgPresent args || tuple_section) msg }
where
msg = text "Illegal tuple section: use TupleSections"
---------
sectionErr :: HsExpr RdrName -> SDoc
sectionErr expr
= hang (text "A section must be enclosed in parentheses")
2 (text "thus:" <+> (parens (ppr expr)))
patSynErr :: HsExpr RdrName -> SDoc -> RnM (HsExpr Name, FreeVars)
patSynErr e explanation = do { addErr (sep [text "Pattern syntax in expression context:",
nest 4 (ppr e)] $$
explanation)
; return (EWildPat, emptyFVs) }
badIpBinds :: Outputable a => SDoc -> a -> SDoc
badIpBinds what binds
= hang (text "Implicit-parameter bindings illegal in" <+> what)
2 (ppr binds)
|
mcschroeder/ghc
|
compiler/rename/RnExpr.hs
|
Haskell
|
bsd-3-clause
| 78,620
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE NoStrict #-}
{-# LANGUAGE TupleSections #-}
module Data.IP.Builder
( -- * 'P.BoundedPrim' 'B.Builder's for general, IPv4 and IPv6 addresses.
ipBuilder
, ipv4Builder
, ipv6Builder
) where
import qualified Data.ByteString.Builder as B
import qualified Data.ByteString.Builder.Prim as P
import Data.ByteString.Builder.Prim ((>$<), (>*<))
import GHC.Exts
import GHC.Word (Word8(..), Word16(..), Word32(..))
import Data.IP.Addr
------------ IP builders
{-# INLINE ipBuilder #-}
-- | 'P.BoundedPrim' bytestring 'B.Builder' for general 'IP' addresses.
ipBuilder :: IP -> B.Builder
ipBuilder (IPv4 addr) = ipv4Builder addr
ipBuilder (IPv6 addr) = ipv6Builder addr
{-# INLINE ipv4Builder #-}
-- | 'P.BoundedPrim' bytestring 'B.Builder' for 'IPv4' addresses.
ipv4Builder :: IPv4 -> B.Builder
ipv4Builder addr = P.primBounded ipv4Bounded $! fromIPv4w addr
{-# INLINE ipv6Builder #-}
-- | 'P.BoundedPrim' bytestring 'B.Builder' for 'IPv6' addresses.
ipv6Builder :: IPv6 -> B.Builder
ipv6Builder addr = P.primBounded ipv6Bounded $! fromIPv6w addr
------------ Builder utilities
-- Convert fixed to bounded for fusion
toB :: P.FixedPrim a -> P.BoundedPrim a
toB = P.liftFixedToBounded
{-# INLINE toB #-}
ipv4Bounded :: P.BoundedPrim Word32
ipv4Bounded =
quads >$< ((P.word8Dec >*< dotsep) >*< (P.word8Dec >*< dotsep))
>*< ((P.word8Dec >*< dotsep) >*< P.word8Dec)
where
quads a = ((qdot 0o30# a, qdot 0o20# a), (qdot 0o10# a, qfin a))
{-# INLINE quads #-}
qdot s (W32# a) = (W8# (wordToWord8Compat# ((word32ToWordCompat# a `uncheckedShiftRL#` s) `and#` 0xff##)), ())
{-# INLINE qdot #-}
qfin (W32# a) = W8# (wordToWord8Compat# (word32ToWordCompat# a `and#` 0xff##))
{-# INLINE qfin #-}
dotsep = const 0x2e >$< toB P.word8
-- | For each 32-bit chunk of an IPv6 address, encode its display format in the
-- presentation form of the address, based on its location relative to the
-- "best gap", i.e. the left-most longest run of zeros. The "hi" (H) and/or
-- "lo" (L) 16 bits may be accompanied by colons (C) on the left and/or right.
--
data FF = CHL Word32 -- ^ :<h>:<l>
| HL Word32 -- ^ <h>:<l>
| NOP -- ^ nop
| COL -- ^ :
| CC -- ^ : :
| CLO Word32 -- ^ :<l>
| CHC Word32 -- ^ :<h>:
| HC Word32 -- ^ <h>:
-- Build an IPv6 address in conformance with
-- [RFC5952](http://tools.ietf.org/html/rfc5952 RFC 5952).
--
ipv6Bounded :: P.BoundedPrim (Word32, Word32, Word32, Word32)
ipv6Bounded =
P.condB generalCase
( genFields >$< output128 )
( P.condB v4mapped
( pairPair >$< (colsep >*< colsep)
>*< (ffff >*< (fstUnit >$< colsep >*< ipv4Bounded)) )
( pairPair >$< (P.emptyB >*< colsep) >*< (colsep >*< ipv4Bounded) ) )
where
-- The boundedPrim switches and predicates need to be inlined for best
-- performance, gaining a factor of ~2 in throughput in tests.
--
{-# INLINE output128 #-}
{-# INLINE output64 #-}
{-# INLINE generalCase #-}
{-# INLINE v4mapped #-}
{-# INLINE output32 #-}
generalCase :: (Word32, Word32, Word32, Word32) -> Bool
generalCase (w0, w1, w2, w3) =
w0 /= 0 || w1 /= 0 || (w2 /= 0xffff && (w2 /= 0 || w3 <= 0xffff))
--
v4mapped :: (Word32, Word32, Word32, Word32) -> Bool
v4mapped (w0, w1, w2, _) =
w0 == 0 && w1 == 0 && w2 == 0xffff
-- BoundedPrim for the full 128-bit IPv6 address given as
-- a pair of pairs of FF values, which encode the
-- output format of each of the 32-bit chunks.
--
output128 :: P.BoundedPrim ((FF, FF), (FF, FF))
output128 = output64 >*< output64
output64 = (output32 >*< output32)
--
-- And finally the per-word case-work.
--
output32 :: P.BoundedPrim FF
output32 =
P.condB (\case { CHL _ -> True; _ -> False }) build_CHL $ -- :hi:lo
P.condB (\case { HL _ -> True; _ -> False }) build_HL $ -- hi:lo
P.condB (\case { NOP -> True; _ -> False }) build_NOP $ --
P.condB (\case { COL -> True; _ -> False }) build_COL $ -- :
P.condB (\case { CC -> True; _ -> False }) build_CC $ -- : :
P.condB (\case { CLO _ -> True; _ -> False }) build_CLO $ -- :lo
P.condB (\case { CHC _ -> True; _ -> False }) build_CHC $ -- :hi:
build_HC -- hi:
-- encoders for the eight field format (FF) cases.
--
build_CHL = ( \ case CHL w -> ( fstUnit (hi16 w), fstUnit (lo16 w) )
_ -> undefined )
>$< (colsep >*< P.word16Hex)
>*< (colsep >*< P.word16Hex)
--
build_HL = ( \ case HL w -> ( hi16 w, fstUnit (lo16 w) )
_ -> undefined )
>$< P.word16Hex >*< colsep >*< P.word16Hex
--
build_NOP = P.emptyB
--
build_COL = const () >$< colsep
--
build_CC = const ((), ()) >$< colsep >*< colsep
--
build_CLO = ( \ case CLO w -> fstUnit (lo16 w)
_ -> undefined )
>$< colsep >*< P.word16Hex
--
build_CHC = ( \ case CHC w -> fstUnit (sndUnit (hi16 w))
_ -> undefined )
>$< colsep >*< P.word16Hex >*< colsep
--
build_HC = ( \ case HC w -> sndUnit (hi16 w)
_ -> undefined )
>$< P.word16Hex >*< colsep
-- static encoders
--
colsep :: P.BoundedPrim a
colsep = toB $ const 0x3a >$< P.word8
--
ffff :: P.BoundedPrim a
ffff = toB $ const 0xffff >$< P.word16HexFixed
-- | Helpers
hi16, lo16 :: Word32 -> Word16
hi16 !(W32# w) = W16# (wordToWord16Compat# (word32ToWordCompat# w `uncheckedShiftRL#` 16#))
lo16 !(W32# w) = W16# (wordToWord16Compat# (word32ToWordCompat# w `and#` 0xffff##))
--
fstUnit :: a -> ((), a)
fstUnit = ((), )
--
sndUnit :: a -> (a, ())
sndUnit = (, ())
--
pairPair (a, b, c, d) = ((a, b), (c, d))
-- Construct fields decorated with output format details
genFields (w0, w1, w2, w3) =
let !(!gapStart, !gapEnd) = bestgap w0 w1 w2 w3
!f0 = makeF0 gapStart gapEnd w0
!f1 = makeF12 gapStart gapEnd 2# 3# w1
!f2 = makeF12 gapStart gapEnd 4# 5# w2
!f3 = makeF3 gapStart gapEnd w3
in ((f0, f1), (f2, f3))
makeF0 (I# gapStart) (I# gapEnd) !w =
case (gapEnd ==# 0#) `orI#` (gapStart ># 1#) of
1# -> HL w
_ -> case gapStart ==# 0# of
1# -> COL
_ -> HC w
{-# INLINE makeF0 #-}
makeF12 (I# gapStart) (I# gapEnd) il ir !w =
case (gapEnd <=# il) `orI#` (gapStart ># ir) of
1# -> CHL w
_ -> case gapStart >=# il of
1# -> case gapStart ==# il of
1# -> COL
_ -> CHC w
_ -> case gapEnd ==# ir of
0# -> NOP
_ -> CLO w
{-# INLINE makeF12 #-}
makeF3 (I# gapStart) (I# gapEnd) !w =
case gapEnd <=# 6# of
1# -> CHL w
_ -> case gapStart ==# 6# of
0# -> case gapEnd ==# 8# of
1# -> COL
_ -> CLO w
_ -> CC
{-# INLINE makeF3 #-}
-- | Unrolled and inlined calculation of the first longest
-- run (gap) of 16-bit aligned zeros in the input address.
--
bestgap :: Word32 -> Word32 -> Word32 -> Word32 -> (Int, Int)
bestgap !(W32# a0) !(W32# a1) !(W32# a2) !(W32# a3) =
finalGap
(updateGap (0xffff## `and#` (word32ToWordCompat# a3))
(updateGap (0xffff0000## `and#` (word32ToWordCompat# a3))
(updateGap (0xffff## `and#` (word32ToWordCompat# a2))
(updateGap (0xffff0000## `and#` (word32ToWordCompat# a2))
(updateGap (0xffff## `and#` (word32ToWordCompat# a1))
(updateGap (0xffff0000## `and#` (word32ToWordCompat# a1))
(updateGap (0xffff## `and#` (word32ToWordCompat# a0))
(initGap (0xffff0000## `and#` (word32ToWordCompat# a0))))))))))
where
-- The state after the first input word is always i' = 7,
-- but if the input word is zero, then also g=z=1 and e'=7.
initGap :: Word# -> Int#
initGap w = case w of { 0## -> 0x1717#; _ -> 0x0707# }
-- Update the nibbles of g|e'|z|i' based on the next input
-- word. We always decrement i', reset z on non-zero input,
-- otherwise increment z and check for a new best gap, if so
-- we replace g|e' with z|i'.
updateGap :: Word# -> Int# -> Int#
updateGap w g = case w `neWord#` 0## of
1# -> (g +# 0xffff#) `andI#` 0xff0f# -- g, e, 0, --i
_ -> let old = g +# 0xf# -- ++z, --i
zi = old `andI#` 0xff#
new = (zi `uncheckedIShiftL#` 8#) `orI#` zi
in case new ># old of
1# -> new -- z, i, z, i
_ -> old -- g, e, z, i
-- Extract gap start and end from the nibbles of g|e'|z|i'
-- where g is the gap width and e' is 8 minus its end.
finalGap :: Int# -> (Int, Int)
finalGap i =
let g = i `uncheckedIShiftRL#` 12#
in case g <# 2# of
1# -> (0, 0)
_ -> let e = 8# -# ((i `uncheckedIShiftRL#` 8#) `andI#` 0xf#)
s = e -# g
in (I# s, I# e)
{-# INLINE bestgap #-}
#if MIN_VERSION_base(4,16,0)
word32ToWordCompat# :: Word32# -> Word#
word32ToWordCompat# = word32ToWord#
wordToWord8Compat# :: Word# -> Word8#
wordToWord8Compat# = wordToWord8#
wordToWord16Compat# :: Word# -> Word16#
wordToWord16Compat# = wordToWord16#
#else
word32ToWordCompat# :: Word# -> Word#
word32ToWordCompat# x = x
wordToWord8Compat# :: Word# -> Word#
wordToWord8Compat# x = x
wordToWord16Compat# :: Word# -> Word#
wordToWord16Compat# x = x
#endif
|
kazu-yamamoto/iproute
|
Data/IP/Builder.hs
|
Haskell
|
bsd-3-clause
| 10,407
|
{-# LANGUAGE ScopedTypeVariables #-}
-- | This module is unstable; functions are not guaranteed to be the same or even to exist in future versions
--
-- It is intended primarily for use by this library itself.
module Data.Bitmap.Util
( tablespoon
, subStr
, padByte
) where
import Control.Exception
import qualified Data.String.Class as S
import Data.Word
import System.IO.Unsafe (unsafePerformIO)
handlers :: [Handler (Either String a)]
handlers = [ Handler $ \(e :: ArithException) -> return . Left . show $ e
, Handler $ \(e :: ArrayException) -> return . Left . show $ e
, Handler $ \(e :: ErrorCall) -> return . Left . show $ e
, Handler $ \(e :: PatternMatchFail) -> return . Left . show $ e
, Handler $ \(e :: SomeException) -> throwIO e
]
-- | Hack to catch "pureish" asynchronous errors
--
-- This is only used as a workaround to the binary library's shortcoming of
-- using asynchronous errors instead of pure error handling, and also zlib's
-- same shortcoming.
--
-- This function is similar to the @spoon@ package's @teaspoon@ function,
-- except that it can return more information when an exception is caught.
tablespoon :: a -> Either String a
tablespoon x = unsafePerformIO $ (Right `fmap` evaluate x) `catches` handlers
-- | Return a substring
--
-- 'subStr' @index@ @length@ returns @length@ characters from the string
-- starting at @index@, which starts at 0.
--
-- > subStr 1 2 "abcd" == "bc"
subStr :: (S.StringCells s) => Int -> Int -> s -> s
subStr index length_ = S.take length_ . S.drop index
padByte :: Word8
padByte = 0x00
|
bairyn/bitmaps
|
src/Data/Bitmap/Util.hs
|
Haskell
|
bsd-3-clause
| 1,643
|
{-# LANGUAGE OverloadedStrings #-}
module Views.Common.SEO where
import Control.Monad
import qualified Data.Text as T
import Data.Text.Lazy(Text)
import Data.String (fromString)
import qualified Text.Printf as PF
import Network.URI
import Text.Blaze.Html5((!))
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
import qualified Utils.BlazeExtra.Attributes as EA
import Utils.URI.String
import Models.Schema
metaProperty p v =
H.meta ! property p ! A.content v
where
property = H.customAttribute "property"
metaName n v = H.meta ! A.name n ! A.content v
keywordsAndDescription keywords description = do
metaName "keywords" $ H.toValue keywords
metaName "description" $ H.toValue description
openGraph :: String -> String -> String -> H.Html
openGraph title url description = do
metaProperty "og:type" "website"
metaProperty "og:title" $ H.toValue title
metaProperty "og:url" $ H.toValue url
metaProperty "og:description" $ H.toValue description
canonical :: String -> H.Html
canonical url =
H.link ! A.rel "canonical" ! A.href ( H.toValue url)
gaEvent :: String-> String ->H.Attribute
gaEvent ev ct =
let
v = (PF.printf "ga('send', 'event', '%s', '%s');" ev ct) :: String
in
A.onclick $ H.toValue v
utmParams :: String -> String -> [(String,String)]
utmParams host name =
[("utm_source",host)
,("utm_campaign",name)
,("utm_medium","website")]
|
DavidAlphaFox/sblog
|
src/Views/Common/SEO.hs
|
Haskell
|
bsd-3-clause
| 1,437
|
{-# LANGUAGE Safe, TypeFamilies #-}
module Data.Logic.Atom (
Atom, atom, unit
) where
import Control.Monad.Predicate
import Data.Logic.Term
import Data.Logic.Var
-- |A constant term.
newtype Atom a s = Atom a
instance Eq a => Term (Atom a) where
type Collapse (Atom a) = a
collapse (Atom x) = return x
unify (Atom x) (Atom y) = bool (x == y)
occurs _ _ = return False
-- |Constructs an atom.
atom :: Eq a => a -> Var (Atom a) s
atom = bind . Atom
-- |Synonym for @atom ()@.
unit :: Var (Atom ()) s
unit = atom ()
|
YellPika/tlogic
|
src/Data/Logic/Atom.hs
|
Haskell
|
bsd-3-clause
| 539
|
{-|
Module : AERN2.Utils.Bench
Description : utilities for benchmarks
Copyright : (c) Michal Konecny
License : BSD3
Maintainer : mikkonecny@gmail.com
Stability : experimental
Portability : portable
-}
module AERN2.Utils.Bench
(
listFromGen
)
where
-- import Test.QuickCheck
import Test.QuickCheck.Random (mkQCGen)
import Test.QuickCheck.Gen (Gen(..))
import MixedTypesNumPrelude
-- import qualified Prelude as P
listFromGen :: Gen a -> [a]
listFromGen gen =
list
where
list =
concat $ map genSome [1..]
where
genSome size =
unGen (sequence $ replicate 10 gen) qcGen (int size)
qcGen = mkQCGen (int 148548830)
|
michalkonecny/aern2
|
aern2-mp/src/AERN2/Utils/Bench.hs
|
Haskell
|
bsd-3-clause
| 718
|
-- | The type of cave kinds. Every level in the game is an instantiated
-- cave kind.
module Game.LambdaHack.Content.CaveKind
( pattern DEFAULT_RANDOM
, CaveKind(..), InitSleep(..), makeData
#ifdef EXPOSE_INTERNAL
-- * Internal operations
, validateSingle, validateAll, mandatoryGroups
#endif
) where
import Prelude ()
import Game.LambdaHack.Core.Prelude
import qualified Data.Text as T
import Game.LambdaHack.Content.ItemKind (ItemKind)
import Game.LambdaHack.Content.PlaceKind (PlaceKind)
import qualified Game.LambdaHack.Content.RuleKind as RK
import Game.LambdaHack.Content.TileKind (TileKind)
import qualified Game.LambdaHack.Core.Dice as Dice
import Game.LambdaHack.Core.Random
import Game.LambdaHack.Definition.ContentData
import Game.LambdaHack.Definition.Defs
import Game.LambdaHack.Definition.DefsInternal
-- | Parameters for the generation of dungeon levels.
-- Warning: for efficiency, avoid embedded items in any of the common tiles.
data CaveKind = CaveKind
{ cname :: Text -- ^ short description
, cfreq :: Freqs CaveKind -- ^ frequency within groups
, cXminSize :: X -- ^ minimal X size of the whole cave
, cYminSize :: Y -- ^ minimal Y size of the whole cave
, ccellSize :: Dice.DiceXY -- ^ size of a map cell holding a place
, cminPlaceSize :: Dice.DiceXY -- ^ minimal size of places; for merging
, cmaxPlaceSize :: Dice.DiceXY -- ^ maximal size of places; for growing
, cdarkOdds :: Dice.Dice -- ^ the odds a place is dark
-- (level-scaled dice roll > 50)
, cnightOdds :: Dice.Dice -- ^ the odds the cave is dark
-- (level-scaled dice roll > 50)
, cauxConnects :: Rational -- ^ a proportion of extra connections
, cmaxVoid :: Rational
-- ^ at most this proportion of rooms may be void
, cdoorChance :: Chance -- ^ the chance of a door in an opening
, copenChance :: Chance -- ^ if there's a door, is it open?
, chidden :: Int -- ^ if not open, hidden one in n times
, cactorCoeff :: Int -- ^ the lower, the more monsters spawn
, cactorFreq :: Freqs ItemKind -- ^ actor groups to consider
, citemNum :: Dice.Dice -- ^ number of initial items in the cave
, citemFreq :: Freqs ItemKind -- ^ item groups to consider;
-- note that the groups are flattened; e.g., if an item is moved
-- to another included group with the same weight, the outcome
-- doesn't change
, cplaceFreq :: Freqs PlaceKind -- ^ place groups to consider
, cpassable :: Bool
-- ^ are passable default tiles permitted
, clabyrinth :: Bool -- ^ waste of time for AI to explore
, cdefTile :: GroupName TileKind -- ^ the default cave tile
, cdarkCorTile :: GroupName TileKind -- ^ the dark cave corridor tile
, clitCorTile :: GroupName TileKind -- ^ the lit cave corridor tile
, cwallTile :: GroupName TileKind -- ^ the tile used for @FWall@ fence
, ccornerTile :: GroupName TileKind -- ^ tile used for the fence corners
, cfenceTileN :: GroupName TileKind -- ^ the outer fence N wall
, cfenceTileE :: GroupName TileKind -- ^ the outer fence E wall
, cfenceTileS :: GroupName TileKind -- ^ the outer fence S wall
, cfenceTileW :: GroupName TileKind -- ^ the outer fence W wall
, cfenceApart :: Bool -- ^ are places touching fence banned
, cminStairDist :: Int -- ^ minimal distance between stairs
, cmaxStairsNum :: Dice.Dice -- ^ maximum number of stairs
, cescapeFreq :: Freqs PlaceKind -- ^ escape groups, if any
, cstairFreq :: Freqs PlaceKind -- ^ place groups for created stairs
, cstairAllowed :: Freqs PlaceKind -- ^ extra groups for inherited
, cskip :: [Int] -- ^ which faction starting positions to skip
, cinitSleep :: InitSleep -- ^ whether actors spawn sleeping
, cdesc :: Text -- ^ full cave description
}
deriving Show -- No Eq and Ord to make extending logically sound
data InitSleep = InitSleepAlways | InitSleepPermitted | InitSleepBanned
deriving (Show, Eq)
-- | Catch caves with not enough space for all the places. Check the size
-- of the cave descriptions to make sure they fit on screen. Etc.
validateSingle :: RK.RuleContent -> CaveKind -> [Text]
validateSingle corule CaveKind{..} =
let (minCellSizeX, minCellSizeY) = Dice.infDiceXY ccellSize
(maxCellSizeX, maxCellSizeY) = Dice.supDiceXY ccellSize
(minMinSizeX, minMinSizeY) = Dice.infDiceXY cminPlaceSize
(maxMinSizeX, maxMinSizeY) = Dice.supDiceXY cminPlaceSize
(minMaxSizeX, minMaxSizeY) = Dice.infDiceXY cmaxPlaceSize
in [ "cname longer than 25" | T.length cname > 25 ]
++ [ "cXminSize > RK.rWidthMax" | cXminSize > RK.rWidthMax corule ]
++ [ "cYminSize > RK.rHeightMax" | cYminSize > RK.rHeightMax corule ]
++ [ "cXminSize < 8" | cXminSize < 8 ]
++ [ "cYminSize < 8" | cYminSize < 8 ] -- see @focusArea@
++ [ "cXminSize - 2 < maxCellSizeX" | cXminSize - 2 < maxCellSizeX ]
++ [ "cYminSize - 2 < maxCellSizeY" | cYminSize - 2 < maxCellSizeY ]
++ [ "minCellSizeX < 2" | minCellSizeX < 2 ]
++ [ "minCellSizeY < 2" | minCellSizeY < 2 ]
++ [ "minCellSizeX < 4 and stairs"
| minCellSizeX < 4 && not (null cstairFreq) ]
++ [ "minCellSizeY < 4 and stairs"
| minCellSizeY < 4 && not (null cstairFreq) ]
-- The following four are heuristics, so not too restrictive:
++ [ "minCellSizeX < 6 && non-trivial stairs"
| minCellSizeX < 6 && not (length cstairFreq <= 1 && null cescapeFreq) ]
++ [ "minCellSizeY < 4 && non-trivial stairs"
| minCellSizeY < 4 && not (length cstairFreq <= 1 && null cescapeFreq) ]
++ [ "minMinSizeX < 5 && non-trivial stairs"
| minMinSizeX < 5 && not (length cstairFreq <= 1 && null cescapeFreq) ]
++ [ "minMinSizeY < 3 && non-trivial stairs"
| minMinSizeY < 3 && not (length cstairFreq <= 1 && null cescapeFreq) ]
++ [ "minMinSizeX < 1" | minMinSizeX < 1 ]
++ [ "minMinSizeY < 1" | minMinSizeY < 1 ]
++ [ "minMaxSizeX < maxMinSizeX" | minMaxSizeX < maxMinSizeX ]
++ [ "minMaxSizeY < maxMinSizeY" | minMaxSizeY < maxMinSizeY ]
++ [ "chidden < 0" | chidden < 0 ]
++ [ "cactorCoeff < 0" | cactorCoeff < 0 ]
++ [ "citemNum < 0" | Dice.infDice citemNum < 0 ]
++ [ "cmaxStairsNum < 0" | Dice.infDice cmaxStairsNum < 0 ]
++ [ "stairs suggested, but not defined"
| Dice.supDice cmaxStairsNum > 0 && null cstairFreq ]
-- | Validate all cave kinds.
-- Note that names don't have to be unique: we can have several variants
-- of a cave with a given name.
validateAll :: [CaveKind] -> ContentData CaveKind -> [Text]
validateAll _ _ = [] -- so far, always valid
-- * Mandatory item groups
mandatoryGroups :: [GroupName CaveKind]
mandatoryGroups =
[DEFAULT_RANDOM]
pattern DEFAULT_RANDOM :: GroupName CaveKind
pattern DEFAULT_RANDOM = GroupName "default random"
makeData :: RK.RuleContent
-> [CaveKind] -> [GroupName CaveKind] -> [GroupName CaveKind]
-> ContentData CaveKind
makeData corule content groupNamesSingleton groupNames =
makeContentData "CaveKind" cname cfreq (validateSingle corule) validateAll
content
groupNamesSingleton
(mandatoryGroups ++ groupNames)
|
LambdaHack/LambdaHack
|
definition-src/Game/LambdaHack/Content/CaveKind.hs
|
Haskell
|
bsd-3-clause
| 7,660
|
-- |
-- Module : Data.Semiring.Properties
-- Copyright : Sebastian Fischer <mailto:mail@sebfisch.de>
-- License : BSD3
--
-- This library provides properties for the 'Semiring' type class that
-- can be checked using libraries like QuickCheck or SmallCheck.
--
module Data.Semiring.Properties (
module Data.Semiring, module Data.Semiring.Properties
) where
import Data.Semiring
-- | > a .+. b == b .+. a
plus'comm :: Semiring s => s -> s -> Bool
plus'comm a b = a .+. b == b .+. a
-- | > zero .+. a == a
left'zero :: Semiring s => s -> Bool
left'zero a = zero .+. a == a
-- | > (a .+. b) .+. c == a .+. (b .+. c)
add'assoc :: Semiring s => s -> s -> s -> Bool
add'assoc a b c = (a .+. b) .+. c == a .+. (b .+. c)
-- | > one .*. a == a
left'one :: Semiring s => s -> Bool
left'one a = one .*. a == a
-- | > a .*. one == a
right'one :: Semiring s => s -> Bool
right'one a = a .*. one == a
-- | > (a .*. b) .*. c == a .*. (b .*. c)
mul'assoc :: Semiring s => s -> s -> s -> Bool
mul'assoc a b c = (a .*. b) .*. c == a .*. (b .*. c)
-- | > a .*. (b .+. c) == (a .*. b) .+. (a .*. c)
left'distr :: Semiring s => s -> s -> s -> Bool
left'distr a b c = a .*. (b .+. c) == (a .*. b) .+. (a .*. c)
-- | > (a .+. b) .*. c == (a .*. c) .+. (b .*. c)
right'distr :: Semiring s => s -> s -> s -> Bool
right'distr a b c = (a .+. b) .*. c == (a .*. c) .+. (b .*. c)
-- | > zero .*. a == zero
left'ann :: Semiring s => s -> Bool
left'ann a = zero .*. a == zero
-- | > a .*. zero == zero
right'ann :: Semiring s => s -> Bool
right'ann a = a .*. zero == zero
|
sebfisch/haskell-regexp
|
src/Data/Semiring/Properties.hs
|
Haskell
|
bsd-3-clause
| 1,632
|
module Test.Cache(main) where
import Development.Shake
import Development.Shake.FilePath
import System.Directory
import Data.Char
import Test.Type
main = testBuild test $ do
vowels <- newCache $ \file -> do
src <- readFile' file
liftIO $ appendFile "trace.txt" "1"
pure $ length $ filter isDigit src
"*.out*" %> \x ->
writeFile' x . show =<< vowels (dropExtension x <.> "txt")
startCompiler <- newCache $ \() -> do
liftIO $ writeFile "compiler.txt" "on"
runAfter $ writeFile "compiler.txt" "off"
"*.lang" %> \out -> do
startCompiler ()
liftIO $ copyFile "compiler.txt" out
-- Bug fixed in https://github.com/ndmitchell/shake/pull/796
bug796_2 <- newCache $ \() -> do
readFile' "bug796.2"
"bug796" %> \out -> do
a <- readFile' "bug796.1"
b <- bug796_2 ()
writeFile' out $ a ++ b
test build = do
build ["clean"]
writeFile "trace.txt" ""
writeFile "vowels.txt" "abc123a"
build ["vowels.out1","vowels.out2","-j3","--sleep"]
assertContents "trace.txt" "1"
assertContents "vowels.out1" "3"
assertContents "vowels.out2" "3"
build ["vowels.out2","-j3"]
assertContents "trace.txt" "1"
assertContents "vowels.out1" "3"
writeFile "vowels.txt" "12xyz34"
build ["vowels.out2","-j3","--sleep"]
assertContents "trace.txt" "11"
assertContents "vowels.out2" "4"
build ["vowels.out1","-j3","--sleep"]
assertContents "trace.txt" "111"
assertContents "vowels.out1" "4"
build ["foo.lang","bar.lang"]
assertContents "foo.lang" "on"
assertContents "compiler.txt" "off"
writeFile "compiler.txt" "unstarted"
build ["foo.lang","bar.lang"]
assertContents "compiler.txt" "unstarted"
writeFile "bug796.1" "a"
writeFile "bug796.2" "b"
build ["bug796", "--sleep"]
assertContents "bug796" "ab"
writeFile "bug796.1" "A"
build ["bug796", "--sleep"]
assertContents "bug796" "Ab"
writeFile "bug796.2" "B"
build ["bug796", "--sleep"]
assertContents "bug796" "AB"
|
ndmitchell/shake
|
src/Test/Cache.hs
|
Haskell
|
bsd-3-clause
| 2,096
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
-- |
-- Module: $HEADER$
-- Description: TODO
-- Copyright: (c) 2016 Peter Trško
-- License: BSD3
--
-- Stability: experimental
-- Portability: GHC specific language extensions.
--
-- TODO
module Data.DHT.DKS.Type.Message.UpdateSuccessorAck
( UpdateSuccessorAck(..)
)
where
import Data.Eq (Eq)
import Data.Typeable (Typeable)
import GHC.Generics (Generic)
import Text.Show (Show)
import Data.Default.Class (Default(def))
import Data.OverloadedRecords.TH (overloadedRecord)
import Data.DHT.DKS.Type.Hash (DksHash)
data UpdateSuccessorAck = UpdateSuccessorAck
{ _requester :: !DksHash
, _oldSuccessor :: !DksHash
, _successor :: !DksHash
}
deriving (Eq, Generic, Show, Typeable)
overloadedRecord def ''UpdateSuccessorAck
|
FPBrno/dht-dks
|
src/Data/DHT/DKS/Type/Message/UpdateSuccessorAck.hs
|
Haskell
|
bsd-3-clause
| 1,039
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.