_id
stringlengths 64
64
| repository
stringlengths 6
84
| name
stringlengths 4
110
| content
stringlengths 0
248k
| license
null | download_url
stringlengths 89
454
| language
stringclasses 7
values | comments
stringlengths 0
74.6k
| code
stringlengths 0
248k
|
---|---|---|---|---|---|---|---|---|
88d28cf4f12d2a51959b0283c4c302079e68dfbd2df5aa7625d93c2d83f7efa6 | bobatkey/CS316-2022 | Week01.hs | # OPTIONS_GHC -fwarn - incomplete - patterns #
module Week01 where
import Prelude hiding (take, drop, Left, Right, Maybe (..), reverse, length)
CS316 2022/23 : Week 1
DATA AND FUNCTIONS
We start the course with an introduction to the two fundamental
concepts of functional programming in Haskell :
1 . Defining the datatypes we use to represent problems .
2 . Transforming data by pattern matching functions .
Almost all of what you will learn in this course is an elaboration
of these two key points . Over the weeks of this course , we will see
many different ways of representing problems using datatypes , and
several different ways to design functions to transform data .
DATA AND FUNCTIONS
We start the course with an introduction to the two fundamental
concepts of functional programming in Haskell:
1. Defining the datatypes we use to represent problems.
2. Transforming data by pattern matching functions.
Almost all of what you will learn in this course is an elaboration
of these two key points. Over the weeks of this course, we will see
many different ways of representing problems using datatypes, and
several different ways to design functions to transform data. -}
Part 1.1 : DEFINING DATATYPES AND FUNCTIONS
Examples of ( built in ) data values in Haskell are :
- Integers : 1 , 2 , 3 , 100 , -10
- Strings : " hello " , " Haskell " , " rainbow "
- Characters : ' a ' , ' b ' , ' x ' , ' y ' , ' z '
- Booleans : True , False
Every data value is also a ( short ) program that computes
itself as its result . Which means that if we give the
program ' 1 ' , it will evaluate to ' 1 ' .
Let 's try that in GHCi , the interactive " Read - Eval - Print - Loop "
( REPL ) for ...
* Week01 > 1
1
* Week01 > 2
2
* Week01 > " hello "
" hello "
* Week01 > True
True
Data values in Haskell are classified by their types . We can ask
GHCi what the types of values are by using the ' : t ' command :
* Week01 > : t True
True : : Bool
This notation says " True " " has type " " Bool " . The double colon is
read as " has type " .
The built in datatypes are useful , but one of the most useful
aspects of is the ability to define new datatypes .
It is often better to define our own datatypes for the problem we
want to solve , rather than using existing types . This is so that we
can be more precise in our modelling of the problem . The design of
our datatypes drives the design of our programs , helping us write
the programs too .
Let 's say we want to write programs that manipulate the directions
up , down , left , and right . We can define a data type in Haskell to
do this by the following declaration :
Examples of (built in) data values in Haskell are:
- Integers: 1, 2, 3, 100, -10
- Strings: "hello", "Haskell", "rainbow"
- Characters: 'a', 'b', 'x', 'y', 'z'
- Booleans: True, False
Every data value is also a (short) Haskell program that computes
itself as its result. Which means that if we give Haskell the
program '1', it will evaluate to '1'.
Let's try that in GHCi, the interactive "Read-Eval-Print-Loop"
(REPL) for Haskell...
*Week01> 1
1
*Week01> 2
2
*Week01> "hello"
"hello"
*Week01> True
True
Data values in Haskell are classified by their types. We can ask
GHCi what the types of values are by using the ':t' command:
*Week01> :t True
True :: Bool
This notation says "True" "has type" "Bool". The double colon is
read as "has type".
The built in datatypes are useful, but one of the most useful
aspects of Haskell is the ability to define new datatypes.
It is often better to define our own datatypes for the problem we
want to solve, rather than using existing types. This is so that we
can be more precise in our modelling of the problem. The design of
our datatypes drives the design of our programs, helping us write
the programs too.
Let's say we want to write programs that manipulate the directions
up, down, left, and right. We can define a data type in Haskell to
do this by the following declaration: -}
data Direction = Up | Down | Left | Right
deriving Show
In English , we read this declaration as :
A ' Direction ' is either
- ' Up ' ; or
- ' Down ' ; or
- ' Left ' ; or
- ' Right '
The keyword ' data ' means that this is a datatype . The symbol ' | ' is
read as ' or ' . Another way to read this declaration is : " a Direction
is either Up , Down , Left , or Right " .
Terminology :
- ' Direction ' is the name of the data type . Data type names always
start with a capital letter ( apart from some special built - in
cases ) .
- ' Up ' , ' Down ' , ' Left ' , and ' Right ' are names of * constructors * of
the values of the data type ' Direction ' . Constructors always
start with capital letters ( again , apart from some special
built - in cases ) .
NOTE : the ' deriving Show ' is an instruction to the
compiler to generate a function for converting ' Direction 's to
strings , so they can be printed out . Think of this as
auto - generating something similar to Java 's ' toString ( ) ' methods .
Now that we have defined a datatype , we can make some value
definitions . Here is a value definition :
A 'Direction' is either
- 'Up'; or
- 'Down'; or
- 'Left'; or
- 'Right'
The keyword 'data' means that this is a datatype. The symbol '|' is
read as 'or'. Another way to read this declaration is: "a Direction
is either Up, Down, Left, or Right".
Terminology:
- 'Direction' is the name of the data type. Data type names always
start with a capital letter (apart from some special built-in
cases).
- 'Up', 'Down', 'Left', and 'Right' are names of *constructors* of
the values of the data type 'Direction'. Constructors always
start with capital letters (again, apart from some special
built-in cases).
NOTE: the 'deriving Show' is an instruction to the Haskell
compiler to generate a function for converting 'Direction's to
strings, so they can be printed out. Think of this as
auto-generating something similar to Java's 'toString()' methods.
Now that we have defined a datatype, we can make some value
definitions. Here is a value definition: -}
whereIsTheCeiling :: Direction
whereIsTheCeiling = Up
This value definition consists of two lines :
1 . The first line tells us the name of the value we are defining
( ' whereIsTheCeiling ' ) and what type it is ( ' Direction ' ) .
2 . The second line repeats the name and gives the actual
definition , after an ' = ' . In this case , we are defining
' whereIsTheCeiling ' to be ' Up ' .
We can now use the name ' whereIsTheCeiling ' to stand for ' Up ' .
The first line specifying what the type is often optional . The
Haskell compiler is able to deduce the type from the value
itself . So we can make another value definition ' whereIsTheFloor '
by just giving the definition itself :
1. The first line tells us the name of the value we are defining
('whereIsTheCeiling') and what type it is ('Direction').
2. The second line repeats the name and gives the actual
definition, after an '='. In this case, we are defining
'whereIsTheCeiling' to be 'Up'.
We can now use the name 'whereIsTheCeiling' to stand for 'Up'.
The first line specifying what the type is often optional. The
Haskell compiler is able to deduce the type from the value
itself. So we can make another value definition 'whereIsTheFloor'
by just giving the definition itself: -}
whereIsTheFloor = Down
( NOTE : if you are reading this in VSCode with the integration
turned on , it will insert the inferred type just above the
definition . )
Even though we can often omit types , it is good practice to always
give them for definitions we make . It makes code much more
readable , and improves the error messages that you get back from
the compiler .
turned on, it will insert the inferred type just above the
definition.)
Even though we can often omit types, it is good practice to always
give them for definitions we make. It makes code much more
readable, and improves the error messages that you get back from
the compiler. -}
Making definitions like this is not very useful by itself . All we can
do is give names to existing values . More usefully , we can define
functions that transform data .
Roughly speaking , a function in Haskell takes in some data , looks
at it to decide what to do , and then returns some new data .
Here is an example that transforms directions by flipping them
vertically :
do is give names to existing values. More usefully, we can define
functions that transform data.
Roughly speaking, a function in Haskell takes in some data, looks
at it to decide what to do, and then returns some new data.
Here is an example that transforms directions by flipping them
vertically: -}
flipVertically :: Direction -> Direction
flipVertically Up = Down
flipVertically Down = Up
flipVertically Left = Left
flipVertically Right = Right
This definition looks more complex , but is similar to the two above .
The first line tells us ( and the compiler ) what type
' flipVertically ' has . It is a function type ' Direction - >
Direction ' , meaning that it is a function that takes ' Direction 's
as input , and returns ' Direction 's as output .
The other four lines define what happens for each of the four
different ' Direction 's : the two vertical directions are flipped ,
and the two horizontal directions remain the same .
This style of writing functions by enumerating possible cases is
called " pattern matching " -- each line of the definition specifies
a pattern of input that it recognises , and defines what to do on
the right hand side of the equals sign .
Functions need not only translate values into values of the same
type . For example , we can write a function by pattern matching that
returns ' True ' if the input is a vertical direction , and ' False ' if
is a horizontal direction :
The first line tells us (and the Haskell compiler) what type
'flipVertically' has. It is a function type 'Direction ->
Direction', meaning that it is a function that takes 'Direction's
as input, and returns 'Direction's as output.
The other four lines define what happens for each of the four
different 'Direction's: the two vertical directions are flipped,
and the two horizontal directions remain the same.
This style of writing functions by enumerating possible cases is
called "pattern matching" -- each line of the definition specifies
a pattern of input that it recognises, and defines what to do on
the right hand side of the equals sign.
Functions need not only translate values into values of the same
type. For example, we can write a function by pattern matching that
returns 'True' if the input is a vertical direction, and 'False' if
is a horizontal direction: -}
isVertical :: Direction -> Bool
isVertical Up = True
isVertical Down = True
isVertical Left = False
isVertical Right = False
We can also match on more than one input at a time . Here is a
function that takes two ' Direction 's as input and returns ' True ' if
they are the same , and ' False ' otherwise .
This definition also introduces a new kind of pattern : " wildcard "
patterns , written using an underscore ' _ ' . These patterns stand for
any input that was n't matched by the previous patterns .
function that takes two 'Direction's as input and returns 'True' if
they are the same, and 'False' otherwise.
This definition also introduces a new kind of pattern: "wildcard"
patterns, written using an underscore '_'. These patterns stand for
any input that wasn't matched by the previous patterns. -}
equalDirection :: Direction -> Direction -> Bool
equalDirection Up Up = True
equalDirection Down Down = True
equalDirection Left Left = True
equalDirection Right Right = True
equalDirection _ _ = False
The type of ' equalDirection ' is ' Direction - > Direction - > Bool ' ,
indicating that it takes two ' Direction 's as input , and returns a
' Bool'ean . The next four lines define the ' True ' cases : when the
two input ' Direction 's are the same . The final line says that
" whenever none of the previous cases applies , return ' False ' " . Note
that patterns are matched in order , from top to bottom .
indicating that it takes two 'Direction's as input, and returns a
'Bool'ean. The next four lines define the 'True' cases: when the
two input 'Direction's are the same. The final line says that
"whenever none of the previous cases applies, return 'False'". Note
that patterns are matched in order, from top to bottom. -}
Part 1.2 : STRUCTURED DATA
We have seen how to define a datatype that consist of several
options : a Direction can be any of Up , Down , Left , or Right . But
what if we want to represent how far up , down , left or right ?
To solve problems like this , datatypes can also have additional
data attached to each constructor . We do this by writing the types
of the data we want to attach after the constructor name in the
' data ' declaration .
Here is an example that defines a datatype called
' DirectionWithDistance ' . It has the same number of constructors as
' Direction ' , but now they all have an ' Integer ' attached .
We have seen how to define a datatype that consist of several
options: a Direction can be any of Up, Down, Left, or Right. But
what if we want to represent how far up, down, left or right?
To solve problems like this, datatypes can also have additional
data attached to each constructor. We do this by writing the types
of the data we want to attach after the constructor name in the
'data' declaration.
Here is an example that defines a datatype called
'DirectionWithDistance'. It has the same number of constructors as
'Direction', but now they all have an 'Integer' attached. -}
data DirectionWithDistance
= UpD Integer
| DownD Integer
| LeftD Integer
| RightD Integer
deriving Show
The effect of this declaration is to define a new datatype
' DirectionWithDistance ' with four constructors ' UpD ' , ' DownD ' ,
' LeftD ' and ' RightD ' . The difference with the previous constructors
that these now take parameters :
* Week01 > UpD 100
UpD 100
* > LeftD 300
LeftD 300
If we try to type ' UpD ' by itself , we get an error message :
* Week01 > UpD
< interactive>:6:1 : error :
• No instance for ( Show ( Integer - > DirectionWithDistance ) )
arising from a use of ‘ print ’
( maybe you have n't applied a function to enough arguments ? )
• In a stmt of an interactive GHCi command : print it
This error message is saying that the thing we typed in ( ' UpD ' ) has
type ' Integer - > DirectionWithDistance ' , and that this type has no
' Show ' instance . We will cover what it means to have a ' Show '
instance later in the course , but in essence it means that
does n't know how to print out functions .
This error message has revealed that ' UpD ' is in fact a
function . We can see this by asking the type :
* Week01 > : t UpD
UpD : : Integer - > DirectionWithDistance
Writing an integer after ' UpD ' yields a complete
' DirectionWithDistance ' :
* Week01 > : t UpD 100
UpD 100 : : DirectionWithDistance
Now that we know how to construct values of
' DirectionWithDistance ' , we can write a function to construct them
for us .
The following function takes a ' Direction ' and an ' Integer ' and
puts them together to create a ' DirectionWithDistance ' :
'DirectionWithDistance' with four constructors 'UpD', 'DownD',
'LeftD' and 'RightD'. The difference with the previous constructors
that these now take parameters:
*Week01> UpD 100
UpD 100
*Week01> LeftD 300
LeftD 300
If we try to type 'UpD' by itself, we get an error message:
*Week01> UpD
<interactive>:6:1: error:
• No instance for (Show (Integer -> DirectionWithDistance))
arising from a use of ‘print’
(maybe you haven't applied a function to enough arguments?)
• In a stmt of an interactive GHCi command: print it
This error message is saying that the thing we typed in ('UpD') has
type 'Integer -> DirectionWithDistance', and that this type has no
'Show' instance. We will cover what it means to have a 'Show'
instance later in the course, but in essence it means that Haskell
doesn't know how to print out functions.
This error message has revealed that 'UpD' is in fact a
function. We can see this by asking the type:
*Week01> :t UpD
UpD :: Integer -> DirectionWithDistance
Writing an integer after 'UpD' yields a complete
'DirectionWithDistance':
*Week01> :t UpD 100
UpD 100 :: DirectionWithDistance
Now that we know how to construct values of
'DirectionWithDistance', we can write a function to construct them
for us.
The following function takes a 'Direction' and an 'Integer' and
puts them together to create a 'DirectionWithDistance': -}
withDistance :: Direction -> Integer -> DirectionWithDistance
withDistance Up d = UpD d
withDistance Down d = DownD d
withDistance Left d = LeftD d
withDistance Right d = RightD d
This definition introduces a feature we have n't seen yet : using
variables in patterns to stand for any value .
In each line the 'd ' before the ' = ' sign is a pattern that stands
for any ' Integer ' that is passed to the function . So if we call it
like so :
* Week01 > withDistance Up 100
then the first line is used , with 'd ' set to ' 100 ' . And we get the
response :
UpD 100
In general , we can put variables anyway in patterns on the left
hand side of the equals where we would put a concrete value , and it
will be set to whatever matches at that point in the input .
We can see variables in action when we try to match against values
of type ' DirectionWithDistance ' . The following function takes
' DirectionWithDistance ' values as input , and extracts the ' Integer '
part :
variables in patterns to stand for any value.
In each line the 'd' before the '=' sign is a pattern that stands
for any 'Integer' that is passed to the function. So if we call it
like so:
*Week01> withDistance Up 100
then the first line is used, with 'd' set to '100'. And we get the
response:
UpD 100
In general, we can put variables anyway in patterns on the left
hand side of the equals where we would put a concrete value, and it
will be set to whatever matches at that point in the input.
We can see variables in action when we try to match against values
of type 'DirectionWithDistance'. The following function takes
'DirectionWithDistance' values as input, and extracts the 'Integer'
part: -}
getDistance :: DirectionWithDistance -> Integer
getDistance (UpD d) = d
getDistance (DownD d) = d
getDistance (LeftD d) = d
getDistance (RightD d) = d
So if we call this function with ' RightD 300 ' as input , then the
fourth line matches with 'd ' set to ' 300 ' :
* ( RightD 300 )
300
Similarly , we can write a function that extracts the ' Direction '
from a ' DirectionWithDistance ' :
fourth line matches with 'd' set to '300':
*Week01> getDistance (RightD 300)
300
Similarly, we can write a function that extracts the 'Direction'
from a 'DirectionWithDistance': -}
getDirection :: DirectionWithDistance -> Direction
getDirection (UpD d) = Up
getDirection (DownD d) = Down
getDirection (LeftD d) = Left
getDirection (RightD d) = Right
We are not limited to only one parameter on each constructor .
The ' DirectionWithDistance ' type can be thought of as representing
pairs of ' Direction 's and distances . We can make this explicit by
defining a datatype with a single constructor with two parameters :
the ' Direction ' and the ' Integer ' distance :
The 'DirectionWithDistance' type can be thought of as representing
pairs of 'Direction's and distances. We can make this explicit by
defining a datatype with a single constructor with two parameters:
the 'Direction' and the 'Integer' distance: -}
data DirectionWithDistance2
= DirectionWithDistance Direction Integer
deriving Show
( I have had to call this ' DirectionWithDistance2 ' because we can not
have two datatypes with the same name in the same module . Similarly
for the ' getDirection ' and ' ' functions below . )
With this datatype , it is much easier to write the ' getDistance '
and ' getDirection ' functions . We no longer have to write a case for
each direction :
have two datatypes with the same name in the same module. Similarly
for the 'getDirection' and 'getDistance' functions below.)
With this datatype, it is much easier to write the 'getDistance'
and 'getDirection' functions. We no longer have to write a case for
each direction: -}
getDistance2 :: DirectionWithDistance2 -> Integer
getDistance2 (DirectionWithDistance dir dist) = dist
getDirection2 :: DirectionWithDistance2 -> Direction
getDirection2 (DirectionWithDistance dir dist) = dir
The ' DirectionWithDistance ' and ' DirectionWithDistance2 ' datatypes
both represent the same information , in different ways . We can
demonstrate this relationship by writing functions that convert
back and forth . This will give us our first examples of using
functions within the definitions of other functions :
both represent the same information, in different ways. We can
demonstrate this relationship by writing functions that convert
back and forth. This will give us our first examples of using
functions within the definitions of other functions: -}
convertDirection :: DirectionWithDistance -> DirectionWithDistance2
convertDirection dwd = DirectionWithDistance (getDirection dwd) (getDistance dwd)
convertDirectionBack :: DirectionWithDistance2 -> DirectionWithDistance
convertDirectionBack (DirectionWithDistance dir dist) = withDistance dir dist
In the first function , we get a ' DirectionWithDistance ' called
' dwd ' . Then we construct a new ' DirectionWithDistance2 ' by using
its constructor . For the two parameters , we use ' getDirection ' to
extract the direction from ' dwd ' and ' ' to extract the
distance .
In the second function , we pattern match on the single constructor
of ' DirectionWithDistance2 ' , and then use the ' withDistance '
function defined above to construct a ' DirectionWithDistance ' .
'dwd'. Then we construct a new 'DirectionWithDistance2' by using
its constructor. For the two parameters, we use 'getDirection' to
extract the direction from 'dwd' and 'getDistance' to extract the
distance.
In the second function, we pattern match on the single constructor
of 'DirectionWithDistance2', and then use the 'withDistance'
function defined above to construct a 'DirectionWithDistance'. -}
! Part 1.3 : DATATYPES AND FUNCTIONS WITH TYPE PARAMETERS
We defined the datatype ' DirectionWithDistance2 ' to represent
directions with distances as pairs , and defined two functions
' getDirection ' and ' ' to extract the two parts .
But generally speaking , having pairs of things seems like a useful
thing to have for any pair of types , not just ' Direction 's and
' Integer 's .
To accomplish this , we can parameterise datatype definitions by
types , to get a generic datatype that can be specialised to any
particular type . Here is how we can define a generic pair type :
We defined the datatype 'DirectionWithDistance2' to represent
directions with distances as pairs, and defined two functions
'getDirection' and 'getDistance' to extract the two parts.
But generally speaking, having pairs of things seems like a useful
thing to have for any pair of types, not just 'Direction's and
'Integer's.
To accomplish this, we can parameterise datatype definitions by
types, to get a generic datatype that can be specialised to any
particular type. Here is how we can define a generic pair type: -}
data Pair a b = MkPair a b
deriving Show
The new thing here is the ' a ' and ' b ' between the name of the
datatype and the ' equals ' . This indicates that this datatype takes
two type parameters called ' a ' and ' b ' . These are then used in the
constructor ' MkPair ' where we used concrete type names before .
We can now use the ' MkPair ' constructor to construct pairs of any
types of values :
* 1 2
MkPair 1 2
* Week01 > MkPair Up Left
MkPair Up Left
* Week01 > MkPair ' a ' ' b '
MkPair ' a ' ' b '
* Week01 > MkPair Up ' a '
MkPair Up ' a '
and we can ask what their types are , showing us that have different
' Pair 's of different types of values :
* Week01 > : t MkPair Up Left
MkPair Up Left : : Pair Direction Direction
* > : t MkPair Up ' a '
MkPair Up ' a ' : : Pair Direction Char
Using ' Pair ' we can build another way of representing pairs of
' Direction 's and distances :
datatype and the 'equals'. This indicates that this datatype takes
two type parameters called 'a' and 'b'. These are then used in the
constructor 'MkPair' where we used concrete type names before.
We can now use the 'MkPair' constructor to construct pairs of any
types of values:
*Week01> MkPair 1 2
MkPair 1 2
*Week01> MkPair Up Left
MkPair Up Left
*Week01> MkPair 'a' 'b'
MkPair 'a' 'b'
*Week01> MkPair Up 'a'
MkPair Up 'a'
and we can ask what their types are, showing us that have different
'Pair's of different types of values:
*Week01> :t MkPair Up Left
MkPair Up Left :: Pair Direction Direction
*Week01> :t MkPair Up 'a'
MkPair Up 'a' :: Pair Direction Char
Using 'Pair' we can build another way of representing pairs of
'Direction's and distances: -}
type DirectionWithDistance3 = Pair Direction Integer
The keyword ' type ' means that we are defining a " type synonym " , that
is , an alternative name for a type . This definition says that we
will use the name ' DirectionWithDistance3 ' to stand for the type
' Pair Direction Integer ' .
is, an alternative name for a type. This definition says that we
will use the name 'DirectionWithDistance3' to stand for the type
'Pair Direction Integer'. -}
To define functions that manipulate ' Pair 's , we need to write types
with parameters as well . We do this by writing them with type
variables ' a ' , ' b ' , etc . where there would be concrete types . The
following two functions have similar definitions to ' getDistance2 '
and ' getDirection2 ' above , but work for any types ' a ' and ' b ' :
with parameters as well. We do this by writing them with type
variables 'a', 'b', etc. where there would be concrete types. The
following two functions have similar definitions to 'getDistance2'
and 'getDirection2' above, but work for any types 'a' and 'b': -}
getFirst :: Pair a b -> a
getFirst (MkPair a b) = a
getSecond :: Pair a b -> b
getSecond (MkPair a b) = b
{- Since 'Pair's can be constructed for any types 'a' and 'b', we can
write functions that move them around. For example, swapping the
components of a pair: -}
swap :: Pair a b -> Pair b a
swap (MkPair a b) = MkPair b a
We have seen several features of datatypes now : multiple
constructors , value parameters , and type parameters . The following
extremely useful type mixes the all together in one use :
constructors, value parameters, and type parameters. The following
extremely useful type mixes the all together in one use: -}
data Maybe a
= Nothing
| Just a
deriving Show
The ' Maybe ' type is useful for representing values that may or may
not be present . If a value is present , then we can write ' Just 1 '
( for example ) . If there is no sensible value to give , then we write
' Nothing ' . The ' Maybe ' type is similar to the use of ' null ' in a
language like Java , except that the possible absence of a value is
made explicit in the type .
Here is an example of the use of ' Maybe ' . The function
' verticalDistance ' is expected to return the vertical distance
associated with a pair of a ' Direction ' and a distance . In the
cases when the direction is ' Left ' or ' Right ' , however , there is
nothing sensible to return ( the direction is horizontal ) . So we
return ' Nothing ' :
not be present. If a value is present, then we can write 'Just 1'
(for example). If there is no sensible value to give, then we write
'Nothing'. The 'Maybe' type is similar to the use of 'null' in a
language like Java, except that the possible absence of a value is
made explicit in the type.
Here is an example of the use of 'Maybe'. The function
'verticalDistance' is expected to return the vertical distance
associated with a pair of a 'Direction' and a distance. In the
cases when the direction is 'Left' or 'Right', however, there is
nothing sensible to return (the direction is horizontal). So we
return 'Nothing': -}
verticalDistance :: Pair Direction Integer -> Maybe Integer
verticalDistance (MkPair Up dist) = Just dist
verticalDistance (MkPair Down dist) = Just dist
verticalDistance (MkPair Left dist) = Nothing
verticalDistance (MkPair Right dist) = Nothing
{- We will see the 'Maybe' type many times in this course. -}
! Part 1.4 : RECURSIVE DATATYPES AND FUNCTIONS
The datatypes we have seen so far only allow us to represent fixed
amounts of data . However , most programs we want to write will use
arbitrarily sized amounts of data .
To do this in Haskell , we use datatypes that refer to themselves
recursively . Here is an example , used for representing lists :
The datatypes we have seen so far only allow us to represent fixed
amounts of data. However, most programs we want to write will use
arbitrarily sized amounts of data.
To do this in Haskell, we use datatypes that refer to themselves
recursively. Here is an example, used for representing lists: -}
data List a
= Nil
| Cons a (List a)
deriving Show
The ' List ' datatype takes a type parameter ' a ' standing for the type
of data stored in the list .
There are two constructors :
1 . ' Nil ' represents the empty list . It does not have any parameters .
2 . ' Cons ' represents an element followed by more list .
To represent lists , we start from ' Nil ' , and build up the list by
adding things to the front :
of data stored in the list.
There are two constructors:
1. 'Nil' represents the empty list. It does not have any parameters.
2. 'Cons' represents an element followed by more list.
To represent lists, we start from 'Nil', and build up the list by
adding things to the front: -}
empty :: List Integer
empty = Nil
three :: List Integer
three = Cons 3 empty
twothree :: List Integer
twothree = Cons 2 three
onetwothree :: List Integer
onetwothree = Cons 1 twothree
Now if we evaluate ' onetwothree ' , we can see the whole list laid out :
* Week01 > onetwothree
Cons 1 ( Cons 2 ( Cons 3 Nil ) )
Pattern matching on lists works as before :
*Week01> onetwothree
Cons 1 (Cons 2 (Cons 3 Nil))
Pattern matching on lists works as before: -}
isNil :: List a -> Bool
isNil Nil = True
isNil (Cons _ _) = False
{- We can construct lists in functions by using the constructors: -}
singleton :: a -> List a
singleton a = Cons a Nil
listPair :: a -> a -> List a
listPair a1 a2 = Cons a1 (Cons a2 Nil)
Lists are so useful in Haskell ( possibly they are * over*used ) that
they have a special built in syntax .
The list type is written ' [ a ] ' to stand for " a list of elements of
type ' a ' " .
The empty list ' Nil ' is written ' [ ] ' .
To add an element to the head of a list , we write ' 1 : [ ] ' , instead
of using ' Cons ' . Note that ' : ' is still pronouced ' Cons ' ( short for
' Construct ' ) .
To write out full lists , we can use square brackets and commas ,
like so :
[ 1,2,3,4 ]
is shorthand for
1 : 2 : 3 : 4 : [ ]
When prints out lists it always uses the brackets and
commas form . However , it is important to remember that lists are
really formed from the constructors ' : ' and ' [ ] ' .
We can rewrite the two list construction functions above in terms
of the built - in syntax :
they have a special built in syntax.
The list type is written '[a]' to stand for "a list of elements of
type 'a'".
The empty list 'Nil' is written '[]'.
To add an element to the head of a list, we write '1 : []', instead
of using 'Cons'. Note that ':' is still pronouced 'Cons' (short for
'Construct').
To write out full lists, we can use square brackets and commas,
like so:
[1,2,3,4]
is shorthand for
1 : 2 : 3 : 4 : []
When Haskell prints out lists it always uses the brackets and
commas form. However, it is important to remember that lists are
really formed from the constructors ':' and '[]'.
We can rewrite the two list construction functions above in terms
of the built-in syntax: -}
singleton2 :: a -> [a]
singleton2 a = [a]
listPair2 :: a -> a -> [a]
listPair2 a b = [a,b]
Pattern matching on lists uses the ' : ' and ' [ ] ' syntax too . These two
functions extract the head or tail of a list , provided it exists . I
have used the ' Maybe ' type to account for the fact that the empty
list ( ' [ ] ' ) has no head or tail .
functions extract the head or tail of a list, provided it exists. I
have used the 'Maybe' type to account for the fact that the empty
list ('[]') has no head or tail. -}
getHead :: [a] -> Maybe a
getHead [] = Nothing
getHead (x:xs) = Just x
getTail :: [a] -> Maybe [a]
getTail [] = Nothing
getTail (x:xs) = Just xs
These definitions illustrate a piece of " culture " : it is
common to use single letter variable names like ' x ' for these kinds
of generic functions where it really can stand for anything . Also ,
it is common to ' pluralise ' the name used for the head of the list
for the tail . So in these definitions , we have the head ' x ' and the
tail ' xs ' ( ) .
Since lists may be of arbitrary size , we need a way to write
functions on them that can handle arbitrary size inputs . Just as we
did this in the type definition by making ' List ' refer to itself
recursively , we do this in functions by making them refer to
themselves recursively .
Here is a function that computes the length of a list :
common to use single letter variable names like 'x' for these kinds
of generic functions where it really can stand for anything. Also,
it is common to 'pluralise' the name used for the head of the list
for the tail. So in these definitions, we have the head 'x' and the
tail 'xs' (Eck-es).
Since lists may be of arbitrary size, we need a way to write
functions on them that can handle arbitrary size inputs. Just as we
did this in the type definition by making 'List' refer to itself
recursively, we do this in functions by making them refer to
themselves recursively.
Here is a function that computes the length of a list: -}
length :: [a] -> Integer
length [] = 0
length (x:xs) = 1 + length xs
The first case , ' length [ ] ' states that the length of the empty list
is ' 0 ' .
The second case states that the length of a list with a head and a
tail is ' 1 ' plus the length of the tail .
We can see how this works by writing out the steps involved in computing the length of a short list :
length [ 1,2,3 ]
= length ( 1:2:3 : [ ] )
= 1 + length ( 2:3 : [ ] )
= 1 + 1 + length ( 3 : [ ] )
= 1 + 1 + 1 + length [ ]
= 1 + 1 + 1 + 0
= 3
In this first line , I translated from the syntatic sugar for lists
to the " real " representation using ' : ' and ' [ ] ' . I then
systematically applied the rules of the ' length ' function to get to
some arithmetic to be evaluated , which evaluates to the length of
the list .
is '0'.
The second case states that the length of a list with a head and a
tail is '1' plus the length of the tail.
We can see how this works by writing out the steps involved in computing the length of a short list:
length [1,2,3]
= length (1:2:3:[])
= 1 + length (2:3:[])
= 1 + 1 + length (3:[])
= 1 + 1 + 1 + length []
= 1 + 1 + 1 + 0
= 3
In this first line, I translated from the syntatic sugar for lists
to the "real" representation using ':' and '[]'. I then
systematically applied the rules of the 'length' function to get to
some arithmetic to be evaluated, which evaluates to the length of
the list. -}
{- A similar function is one that computes the 'sum' of a list: -}
sumList :: [Integer] -> Integer
sumList [] = 0
sumList (x:xs) = x + sumList xs
Writing out the steps involved has a similar structure , but with
different values :
sumList [ 1,2,3 ]
= sumList ( 1:2:3 : [ ] )
= 1 + sumList ( 2:3 : [ ] )
= 1 + 2 + sumList ( 3 : [ ] )
= 1 + 2 + 3 + sumList [ ]
= 1 + 2 + 3 + 0
= 6
different values:
sumList [1,2,3]
= sumList (1:2:3:[])
= 1 + sumList (2:3:[])
= 1 + 2 + sumList (3:[])
= 1 + 2 + 3 + sumList []
= 1 + 2 + 3 + 0
= 6
-}
! Part 1.5 : APPENDING AND REVERSING LISTS
Two useful functions on lists are ' append ' and ' reverse ' . These will
also give us an opporuntity to see how to use multiple functions to
accomplish a task .
' append ' is intended to put two lists one after the other . So we
should have :
append [ 1,2 ] [ 3,4 ]
evaluates to
[ 1,2,3,4 ]
To define this function , we think in terms of what we ought to do
for all possible cases of input list .
When the first list is empty , we have :
append [ ] ys
Appending the empty list with ' ys ' ought to give us ' ys ' .
When the first list has a head and a tail , we have :
append ( x : xs ) ys
If we assume that we know how to append ' xs ' and ' ys ' , then we are
left with the problem of what to do with the ' x ' . Since it was at
the head of the first list , and the first list is going on the front
of the second list , a reasonable thing to do is to put it on the
head of the final list :
x : append xs ys
Putting this together , we get the following recursive definition :
Two useful functions on lists are 'append' and 'reverse'. These will
also give us an opporuntity to see how to use multiple functions to
accomplish a task.
'append' is intended to put two lists one after the other. So we
should have:
append [1,2] [3,4]
evaluates to
[1,2,3,4]
To define this function, we think in terms of what we ought to do
for all possible cases of input list.
When the first list is empty, we have:
append [] ys
Appending the empty list with 'ys' ought to give us 'ys'.
When the first list has a head and a tail, we have:
append (x:xs) ys
If we assume that we know how to append 'xs' and 'ys', then we are
left with the problem of what to do with the 'x'. Since it was at
the head of the first list, and the first list is going on the front
of the second list, a reasonable thing to do is to put it on the
head of the final list:
x : append xs ys
Putting this together, we get the following recursive definition: -}
append :: [a] -> [a] -> [a]
append [] ys = ys
append (x:xs) ys = x : append xs ys
We can check this does the right thing by stepping through the
function for an example input :
append [ 1,2 ] [ 3,4 ]
= append ( 1:2 : [ ] ) [ 3,4 ]
= 1 : append [ 2 ] [ 3,4 ]
= 1 : 2 : append [ ] [ 3,4 ]
= 1 : 2 : [ 3,4 ]
= [ 1,2,3,4 ]
Of course , we can also just run the function :
* Week01 > append [ 1,2 ] [ 3,4 ]
[ 1,2,3,4 ]
function for an example input:
append [1,2] [3,4]
= append (1:2:[]) [3,4]
= 1 : append [2] [3,4]
= 1 : 2 : append [] [3,4]
= 1 : 2 : [3,4]
= [1,2,3,4]
Of course, we can also just run the function:
*Week01> append [1,2] [3,4]
[1,2,3,4]
-}
{- Another useful function on lists is 'reverse'. Reversing a list takes
a list as input and produces a list, so the type is: -}
reverse :: [a] -> [a]
We look at the empty list case first . Reversing the empty list ought
to just be the empty list :
to just be the empty list: -}
reverse [] = []
Reversing a list with something in it is a bit more complex . Let 's
look at two examples :
reverse [ 1,2,3 ] = [ 3,2,1 ]
reverse [ 4,5,6,7 ] = [ 7,6,5,4 ]
Bearing in mind the reasoning we used in the append definition ,
let 's look carefully at what happens to the value at the head of
the input lists . In both cases , it moved to the end . Similarly , the
next element is moved to the position just before the end , and so
on . We can decompose both examples into the following structure ,
using a very informal ( non Haskell ) notation :
reverse ( x : xs ) = " reversed xs " + x at the end
Translating this definition into poses a problem : how do we
put a value at the end of a list ? The answer is to use the ' append '
function to append it on the end :
look at two examples:
reverse [1,2,3] = [3,2,1]
reverse [4,5,6,7] = [7,6,5,4]
Bearing in mind the reasoning we used in the append definition,
let's look carefully at what happens to the value at the head of
the input lists. In both cases, it moved to the end. Similarly, the
next element is moved to the position just before the end, and so
on. We can decompose both examples into the following structure,
using a very informal (non Haskell) notation:
reverse (x : xs) = "reversed xs" + x at the end
Translating this definition into Haskell poses a problem: how do we
put a value at the end of a list? The answer is to use the 'append'
function to append it on the end: -}
reverse (x:xs) = append (reverse xs) [x]
We can check our working by stepping through the definition of
reverse on a small input list :
reverse [ 1,2,3 ]
= reverse ( 1:2:3 : [ ] )
= append ( reverse ( 2:3 : [ ] ) [ 1 ]
= append ( append ( reverse ( 3 : [ ] ) [ 2 ] ) [ 1 ]
= append ( append ( append ( reverse [ ] ) [ 3 ] ) [ 2 ] ) [ 1 ]
= append ( append ( append [ ] [ 3 ] ) [ 2 ] ) [ 1 ]
= [ 3,2,1 ]
And again , we can test it by running it :
* Week01 > reverse [ 1,2,3 ]
[ 3,2,1 ]
reverse on a small input list:
reverse [1,2,3]
= reverse (1:2:3:[])
= append (reverse (2:3:[]) [1]
= append (append (reverse (3:[]) [2]) [1]
= append (append (append (reverse []) [3]) [2]) [1]
= append (append (append [] [3]) [2]) [1]
= [3,2,1]
And again, we can test it by running it:
*Week01> reverse [1,2,3]
[3,2,1]
-}
Looking at the trace of ' reverse ' , we can see that it has a flaw . It
builds up a tower of ' append 's . Evaluating an ' append ' takes time
proportional to the length of the first list . So if we do ' append 's
for every element in the input list we take time :
1 + 2 + 3 + 4 + ... + n = n*(n-1)/2
So the time taken is proportional to the square of the length of
the input list . But we should be able to reverse a list in time
proportional to just the length of the list ! How can we do this ?
The answer is to rewrite ' reverse ' by using an accumulator
parameter that stores the reversed list are building as we
go . Let 's see how this works .
We first define a function called ' fastReverseHelper ' . This takes
two arguments : the list to reverse , and an accumulator that
represents the list that has already been reversed :
builds up a tower of 'append's. Evaluating an 'append' takes time
proportional to the length of the first list. So if we do 'append's
for every element in the input list we take time:
1 + 2 + 3 + 4 + ... + n = n*(n-1)/2
So the time taken is proportional to the square of the length of
the input list. But we should be able to reverse a list in time
proportional to just the length of the list! How can we do this?
The answer is to rewrite 'reverse' by using an accumulator
parameter that stores the reversed list are building as we
go. Let's see how this works.
We first define a function called 'fastReverseHelper'. This takes
two arguments: the list to reverse, and an accumulator that
represents the list that has already been reversed: -}
fastReverseHelper :: [a] -> [a] -> [a]
fastReverseHelper [] accum = accum
fastReverseHelper (x:xs) accum = fastReverseHelper xs (x:accum)
This definition may be a little obscure at first , but it helps to
look at the a trace of how it works on a short list . We start with
the list [ 1,2 ] to reverse , and the empty ' accum'ulator parameter :
fastReverseHelper [ 1,2 ] [ ]
= fastReverseHelper [ 2 ] ( 1 : [ ] )
= fastReverseHelper [ ] ( 2:1 : [ ] )
= [ 2,1 ]
To reverse a list , we write ' ' that calls
' fastReverseHelper ' an empty initial accumulator :
look at the a trace of how it works on a short list. We start with
the list [1,2] to reverse, and the empty 'accum'ulator parameter:
fastReverseHelper [1,2] []
= fastReverseHelper [2] (1:[])
= fastReverseHelper [] (2:1:[])
= [2,1]
To reverse a list, we write 'fastReverse' that calls
'fastReverseHelper' an empty initial accumulator: -}
fastReverse :: [a] -> [a]
fastReverse xs = fastReverseHelper xs []
And we can test it :
* Week01 > fastReverse [ 1,2,3 ]
[ 3,2,1 ]
* Week01 > fastReverse [ 5,4,3,2,1 ]
[ 1,2,3,4,5 ]
*Week01> fastReverse [1,2,3]
[3,2,1]
*Week01> fastReverse [5,4,3,2,1]
[1,2,3,4,5]
-}
! Part 1.6 : TAKE , DROP AND CHUNK
Finally for this week , we 'll look at two more useful list functions ,
and how to put them together . This will also naturally lead to the
idea of nested lists of lists .
The first function is ' take ' , which takes a number of elements from
the front of a list . It is defined by pattern matching on the number
of elements remaining to be taken :
Finally for this week, we'll look at two more useful list functions,
and how to put them together. This will also naturally lead to the
idea of nested lists of lists.
The first function is 'take', which takes a number of elements from
the front of a list. It is defined by pattern matching on the number
of elements remaining to be taken: -}
take :: Integer -> [a] -> [a]
take 0 xs = []
take n [] = []
take n (x:xs) = x : take (n-1) xs
{- So, when we 'take 0' we always return the empty list. If we 'take n',
where 'n' is not 0, we look at the list. If the list is empty, then
we just return the empty list. If the list is not empty, we return
a list with 'x' at the head, and the result of 'take (n-1)' for the
tail.
A similar function is 'drop', which drops 'n' elements from the
front of a list: -}
drop :: Integer -> [a] -> [a]
drop 0 xs = xs
drop n [] = []
drop n (x:xs) = drop (n-1) xs
{- We can put these together to write a function that turns a list into
a list of "chunks". We will write a function with the following
type: -}
chunk :: Integer -> [a] -> [[a]]
The function ' chunk ' takes an ' Integer ' , which is the chunk size , and
a list of ' a 's . It returns a list of lists of ' a 's ( note the * two *
pairs of square brackets , meaning a list of lists ) .
The idea is that ' chunk n xs ' will split ' xs ' into chunks of size
' n ' . For example :
chunk 2 [ 1,2,3,4,5 ]
should return
[ [ 1,2],[3,4],[5 ] ]
( notice how there was n't enough to fill the last chunk , so we
return a partial chunk . )
We now think about how we will write this function . First , we think
about the empty list case . Turning the empty list into a list of
chunks yields ... the empty list of chunks :
a list of 'a's. It returns a list of lists of 'a's (note the *two*
pairs of square brackets, meaning a list of lists).
The idea is that 'chunk n xs' will split 'xs' into chunks of size
'n'. For example:
chunk 2 [1,2,3,4,5]
should return
[[1,2],[3,4],[5]]
(notice how there wasn't enough to fill the last chunk, so we
return a partial chunk.)
We now think about how we will write this function. First, we think
about the empty list case. Turning the empty list into a list of
chunks yields ... the empty list of chunks: -}
chunk n [] = []
If the list is n't empty , then we create a new list element ( using
' :') . In the head position , we place the new chunk made by ' take n '
to get the first ' n ' elements of the list . The tail of the output
list is constructed by calling chunk recursively on the result of
dropping the first ' n ' elements :
':'). In the head position, we place the new chunk made by 'take n'
to get the first 'n' elements of the list. The tail of the output
list is constructed by calling chunk recursively on the result of
dropping the first 'n' elements: -}
chunk n xs = take n xs : chunk n (drop n xs)
To understand this function , try writing out what it does step by
step on some small examples . I 'll start you off by showing an
example where it does n't work so well . If the chunk size is ' 0 ' ,
then it generates the empty chunk over and over again , forever :
chunk 0 [ 1,2,3,4,5 ]
= take 0 [ 1,2,3,4,5 ] : chunk 0 ( drop 0 [ 1,2,3,4,5 ] )
= [ ] : chunk 0 [ 1,2,3,4,5 ]
= [ ] : [ ] : [ ] : [ ] : ...
step on some small examples. I'll start you off by showing an
example where it doesn't work so well. If the chunk size is '0',
then it generates the empty chunk over and over again, forever:
chunk 0 [1,2,3,4,5]
= take 0 [1,2,3,4,5] : chunk 0 (drop 0 [1,2,3,4,5])
= [] : chunk 0 [1,2,3,4,5]
= [] : [] : [] : [] : ...
-}
| null | https://raw.githubusercontent.com/bobatkey/CS316-2022/e26930b695191ed9cf6acadfc673d4a1ee7849b2/lecture-notes/Week01.hs | haskell | each line of the definition specifies
each line of the definition specifies
Since 'Pair's can be constructed for any types 'a' and 'b', we can
write functions that move them around. For example, swapping the
components of a pair:
We will see the 'Maybe' type many times in this course.
We can construct lists in functions by using the constructors:
A similar function is one that computes the 'sum' of a list:
Another useful function on lists is 'reverse'. Reversing a list takes
a list as input and produces a list, so the type is:
So, when we 'take 0' we always return the empty list. If we 'take n',
where 'n' is not 0, we look at the list. If the list is empty, then
we just return the empty list. If the list is not empty, we return
a list with 'x' at the head, and the result of 'take (n-1)' for the
tail.
A similar function is 'drop', which drops 'n' elements from the
front of a list:
We can put these together to write a function that turns a list into
a list of "chunks". We will write a function with the following
type: | # OPTIONS_GHC -fwarn - incomplete - patterns #
module Week01 where
import Prelude hiding (take, drop, Left, Right, Maybe (..), reverse, length)
CS316 2022/23 : Week 1
DATA AND FUNCTIONS
We start the course with an introduction to the two fundamental
concepts of functional programming in Haskell :
1 . Defining the datatypes we use to represent problems .
2 . Transforming data by pattern matching functions .
Almost all of what you will learn in this course is an elaboration
of these two key points . Over the weeks of this course , we will see
many different ways of representing problems using datatypes , and
several different ways to design functions to transform data .
DATA AND FUNCTIONS
We start the course with an introduction to the two fundamental
concepts of functional programming in Haskell:
1. Defining the datatypes we use to represent problems.
2. Transforming data by pattern matching functions.
Almost all of what you will learn in this course is an elaboration
of these two key points. Over the weeks of this course, we will see
many different ways of representing problems using datatypes, and
several different ways to design functions to transform data. -}
Part 1.1 : DEFINING DATATYPES AND FUNCTIONS
Examples of ( built in ) data values in Haskell are :
- Integers : 1 , 2 , 3 , 100 , -10
- Strings : " hello " , " Haskell " , " rainbow "
- Characters : ' a ' , ' b ' , ' x ' , ' y ' , ' z '
- Booleans : True , False
Every data value is also a ( short ) program that computes
itself as its result . Which means that if we give the
program ' 1 ' , it will evaluate to ' 1 ' .
Let 's try that in GHCi , the interactive " Read - Eval - Print - Loop "
( REPL ) for ...
* Week01 > 1
1
* Week01 > 2
2
* Week01 > " hello "
" hello "
* Week01 > True
True
Data values in Haskell are classified by their types . We can ask
GHCi what the types of values are by using the ' : t ' command :
* Week01 > : t True
True : : Bool
This notation says " True " " has type " " Bool " . The double colon is
read as " has type " .
The built in datatypes are useful , but one of the most useful
aspects of is the ability to define new datatypes .
It is often better to define our own datatypes for the problem we
want to solve , rather than using existing types . This is so that we
can be more precise in our modelling of the problem . The design of
our datatypes drives the design of our programs , helping us write
the programs too .
Let 's say we want to write programs that manipulate the directions
up , down , left , and right . We can define a data type in Haskell to
do this by the following declaration :
Examples of (built in) data values in Haskell are:
- Integers: 1, 2, 3, 100, -10
- Strings: "hello", "Haskell", "rainbow"
- Characters: 'a', 'b', 'x', 'y', 'z'
- Booleans: True, False
Every data value is also a (short) Haskell program that computes
itself as its result. Which means that if we give Haskell the
program '1', it will evaluate to '1'.
Let's try that in GHCi, the interactive "Read-Eval-Print-Loop"
(REPL) for Haskell...
*Week01> 1
1
*Week01> 2
2
*Week01> "hello"
"hello"
*Week01> True
True
Data values in Haskell are classified by their types. We can ask
GHCi what the types of values are by using the ':t' command:
*Week01> :t True
True :: Bool
This notation says "True" "has type" "Bool". The double colon is
read as "has type".
The built in datatypes are useful, but one of the most useful
aspects of Haskell is the ability to define new datatypes.
It is often better to define our own datatypes for the problem we
want to solve, rather than using existing types. This is so that we
can be more precise in our modelling of the problem. The design of
our datatypes drives the design of our programs, helping us write
the programs too.
Let's say we want to write programs that manipulate the directions
up, down, left, and right. We can define a data type in Haskell to
do this by the following declaration: -}
data Direction = Up | Down | Left | Right
deriving Show
In English , we read this declaration as :
A ' Direction ' is either
- ' Up ' ; or
- ' Down ' ; or
- ' Left ' ; or
- ' Right '
The keyword ' data ' means that this is a datatype . The symbol ' | ' is
read as ' or ' . Another way to read this declaration is : " a Direction
is either Up , Down , Left , or Right " .
Terminology :
- ' Direction ' is the name of the data type . Data type names always
start with a capital letter ( apart from some special built - in
cases ) .
- ' Up ' , ' Down ' , ' Left ' , and ' Right ' are names of * constructors * of
the values of the data type ' Direction ' . Constructors always
start with capital letters ( again , apart from some special
built - in cases ) .
NOTE : the ' deriving Show ' is an instruction to the
compiler to generate a function for converting ' Direction 's to
strings , so they can be printed out . Think of this as
auto - generating something similar to Java 's ' toString ( ) ' methods .
Now that we have defined a datatype , we can make some value
definitions . Here is a value definition :
A 'Direction' is either
- 'Up'; or
- 'Down'; or
- 'Left'; or
- 'Right'
The keyword 'data' means that this is a datatype. The symbol '|' is
read as 'or'. Another way to read this declaration is: "a Direction
is either Up, Down, Left, or Right".
Terminology:
- 'Direction' is the name of the data type. Data type names always
start with a capital letter (apart from some special built-in
cases).
- 'Up', 'Down', 'Left', and 'Right' are names of *constructors* of
the values of the data type 'Direction'. Constructors always
start with capital letters (again, apart from some special
built-in cases).
NOTE: the 'deriving Show' is an instruction to the Haskell
compiler to generate a function for converting 'Direction's to
strings, so they can be printed out. Think of this as
auto-generating something similar to Java's 'toString()' methods.
Now that we have defined a datatype, we can make some value
definitions. Here is a value definition: -}
whereIsTheCeiling :: Direction
whereIsTheCeiling = Up
This value definition consists of two lines :
1 . The first line tells us the name of the value we are defining
( ' whereIsTheCeiling ' ) and what type it is ( ' Direction ' ) .
2 . The second line repeats the name and gives the actual
definition , after an ' = ' . In this case , we are defining
' whereIsTheCeiling ' to be ' Up ' .
We can now use the name ' whereIsTheCeiling ' to stand for ' Up ' .
The first line specifying what the type is often optional . The
Haskell compiler is able to deduce the type from the value
itself . So we can make another value definition ' whereIsTheFloor '
by just giving the definition itself :
1. The first line tells us the name of the value we are defining
('whereIsTheCeiling') and what type it is ('Direction').
2. The second line repeats the name and gives the actual
definition, after an '='. In this case, we are defining
'whereIsTheCeiling' to be 'Up'.
We can now use the name 'whereIsTheCeiling' to stand for 'Up'.
The first line specifying what the type is often optional. The
Haskell compiler is able to deduce the type from the value
itself. So we can make another value definition 'whereIsTheFloor'
by just giving the definition itself: -}
whereIsTheFloor = Down
( NOTE : if you are reading this in VSCode with the integration
turned on , it will insert the inferred type just above the
definition . )
Even though we can often omit types , it is good practice to always
give them for definitions we make . It makes code much more
readable , and improves the error messages that you get back from
the compiler .
turned on, it will insert the inferred type just above the
definition.)
Even though we can often omit types, it is good practice to always
give them for definitions we make. It makes code much more
readable, and improves the error messages that you get back from
the compiler. -}
Making definitions like this is not very useful by itself . All we can
do is give names to existing values . More usefully , we can define
functions that transform data .
Roughly speaking , a function in Haskell takes in some data , looks
at it to decide what to do , and then returns some new data .
Here is an example that transforms directions by flipping them
vertically :
do is give names to existing values. More usefully, we can define
functions that transform data.
Roughly speaking, a function in Haskell takes in some data, looks
at it to decide what to do, and then returns some new data.
Here is an example that transforms directions by flipping them
vertically: -}
flipVertically :: Direction -> Direction
flipVertically Up = Down
flipVertically Down = Up
flipVertically Left = Left
flipVertically Right = Right
This definition looks more complex , but is similar to the two above .
The first line tells us ( and the compiler ) what type
' flipVertically ' has . It is a function type ' Direction - >
Direction ' , meaning that it is a function that takes ' Direction 's
as input , and returns ' Direction 's as output .
The other four lines define what happens for each of the four
different ' Direction 's : the two vertical directions are flipped ,
and the two horizontal directions remain the same .
This style of writing functions by enumerating possible cases is
a pattern of input that it recognises , and defines what to do on
the right hand side of the equals sign .
Functions need not only translate values into values of the same
type . For example , we can write a function by pattern matching that
returns ' True ' if the input is a vertical direction , and ' False ' if
is a horizontal direction :
The first line tells us (and the Haskell compiler) what type
'flipVertically' has. It is a function type 'Direction ->
Direction', meaning that it is a function that takes 'Direction's
as input, and returns 'Direction's as output.
The other four lines define what happens for each of the four
different 'Direction's: the two vertical directions are flipped,
and the two horizontal directions remain the same.
This style of writing functions by enumerating possible cases is
a pattern of input that it recognises, and defines what to do on
the right hand side of the equals sign.
Functions need not only translate values into values of the same
type. For example, we can write a function by pattern matching that
returns 'True' if the input is a vertical direction, and 'False' if
is a horizontal direction: -}
isVertical :: Direction -> Bool
isVertical Up = True
isVertical Down = True
isVertical Left = False
isVertical Right = False
We can also match on more than one input at a time . Here is a
function that takes two ' Direction 's as input and returns ' True ' if
they are the same , and ' False ' otherwise .
This definition also introduces a new kind of pattern : " wildcard "
patterns , written using an underscore ' _ ' . These patterns stand for
any input that was n't matched by the previous patterns .
function that takes two 'Direction's as input and returns 'True' if
they are the same, and 'False' otherwise.
This definition also introduces a new kind of pattern: "wildcard"
patterns, written using an underscore '_'. These patterns stand for
any input that wasn't matched by the previous patterns. -}
equalDirection :: Direction -> Direction -> Bool
equalDirection Up Up = True
equalDirection Down Down = True
equalDirection Left Left = True
equalDirection Right Right = True
equalDirection _ _ = False
The type of ' equalDirection ' is ' Direction - > Direction - > Bool ' ,
indicating that it takes two ' Direction 's as input , and returns a
' Bool'ean . The next four lines define the ' True ' cases : when the
two input ' Direction 's are the same . The final line says that
" whenever none of the previous cases applies , return ' False ' " . Note
that patterns are matched in order , from top to bottom .
indicating that it takes two 'Direction's as input, and returns a
'Bool'ean. The next four lines define the 'True' cases: when the
two input 'Direction's are the same. The final line says that
"whenever none of the previous cases applies, return 'False'". Note
that patterns are matched in order, from top to bottom. -}
Part 1.2 : STRUCTURED DATA
We have seen how to define a datatype that consist of several
options : a Direction can be any of Up , Down , Left , or Right . But
what if we want to represent how far up , down , left or right ?
To solve problems like this , datatypes can also have additional
data attached to each constructor . We do this by writing the types
of the data we want to attach after the constructor name in the
' data ' declaration .
Here is an example that defines a datatype called
' DirectionWithDistance ' . It has the same number of constructors as
' Direction ' , but now they all have an ' Integer ' attached .
We have seen how to define a datatype that consist of several
options: a Direction can be any of Up, Down, Left, or Right. But
what if we want to represent how far up, down, left or right?
To solve problems like this, datatypes can also have additional
data attached to each constructor. We do this by writing the types
of the data we want to attach after the constructor name in the
'data' declaration.
Here is an example that defines a datatype called
'DirectionWithDistance'. It has the same number of constructors as
'Direction', but now they all have an 'Integer' attached. -}
data DirectionWithDistance
= UpD Integer
| DownD Integer
| LeftD Integer
| RightD Integer
deriving Show
The effect of this declaration is to define a new datatype
' DirectionWithDistance ' with four constructors ' UpD ' , ' DownD ' ,
' LeftD ' and ' RightD ' . The difference with the previous constructors
that these now take parameters :
* Week01 > UpD 100
UpD 100
* > LeftD 300
LeftD 300
If we try to type ' UpD ' by itself , we get an error message :
* Week01 > UpD
< interactive>:6:1 : error :
• No instance for ( Show ( Integer - > DirectionWithDistance ) )
arising from a use of ‘ print ’
( maybe you have n't applied a function to enough arguments ? )
• In a stmt of an interactive GHCi command : print it
This error message is saying that the thing we typed in ( ' UpD ' ) has
type ' Integer - > DirectionWithDistance ' , and that this type has no
' Show ' instance . We will cover what it means to have a ' Show '
instance later in the course , but in essence it means that
does n't know how to print out functions .
This error message has revealed that ' UpD ' is in fact a
function . We can see this by asking the type :
* Week01 > : t UpD
UpD : : Integer - > DirectionWithDistance
Writing an integer after ' UpD ' yields a complete
' DirectionWithDistance ' :
* Week01 > : t UpD 100
UpD 100 : : DirectionWithDistance
Now that we know how to construct values of
' DirectionWithDistance ' , we can write a function to construct them
for us .
The following function takes a ' Direction ' and an ' Integer ' and
puts them together to create a ' DirectionWithDistance ' :
'DirectionWithDistance' with four constructors 'UpD', 'DownD',
'LeftD' and 'RightD'. The difference with the previous constructors
that these now take parameters:
*Week01> UpD 100
UpD 100
*Week01> LeftD 300
LeftD 300
If we try to type 'UpD' by itself, we get an error message:
*Week01> UpD
<interactive>:6:1: error:
• No instance for (Show (Integer -> DirectionWithDistance))
arising from a use of ‘print’
(maybe you haven't applied a function to enough arguments?)
• In a stmt of an interactive GHCi command: print it
This error message is saying that the thing we typed in ('UpD') has
type 'Integer -> DirectionWithDistance', and that this type has no
'Show' instance. We will cover what it means to have a 'Show'
instance later in the course, but in essence it means that Haskell
doesn't know how to print out functions.
This error message has revealed that 'UpD' is in fact a
function. We can see this by asking the type:
*Week01> :t UpD
UpD :: Integer -> DirectionWithDistance
Writing an integer after 'UpD' yields a complete
'DirectionWithDistance':
*Week01> :t UpD 100
UpD 100 :: DirectionWithDistance
Now that we know how to construct values of
'DirectionWithDistance', we can write a function to construct them
for us.
The following function takes a 'Direction' and an 'Integer' and
puts them together to create a 'DirectionWithDistance': -}
withDistance :: Direction -> Integer -> DirectionWithDistance
withDistance Up d = UpD d
withDistance Down d = DownD d
withDistance Left d = LeftD d
withDistance Right d = RightD d
This definition introduces a feature we have n't seen yet : using
variables in patterns to stand for any value .
In each line the 'd ' before the ' = ' sign is a pattern that stands
for any ' Integer ' that is passed to the function . So if we call it
like so :
* Week01 > withDistance Up 100
then the first line is used , with 'd ' set to ' 100 ' . And we get the
response :
UpD 100
In general , we can put variables anyway in patterns on the left
hand side of the equals where we would put a concrete value , and it
will be set to whatever matches at that point in the input .
We can see variables in action when we try to match against values
of type ' DirectionWithDistance ' . The following function takes
' DirectionWithDistance ' values as input , and extracts the ' Integer '
part :
variables in patterns to stand for any value.
In each line the 'd' before the '=' sign is a pattern that stands
for any 'Integer' that is passed to the function. So if we call it
like so:
*Week01> withDistance Up 100
then the first line is used, with 'd' set to '100'. And we get the
response:
UpD 100
In general, we can put variables anyway in patterns on the left
hand side of the equals where we would put a concrete value, and it
will be set to whatever matches at that point in the input.
We can see variables in action when we try to match against values
of type 'DirectionWithDistance'. The following function takes
'DirectionWithDistance' values as input, and extracts the 'Integer'
part: -}
getDistance :: DirectionWithDistance -> Integer
getDistance (UpD d) = d
getDistance (DownD d) = d
getDistance (LeftD d) = d
getDistance (RightD d) = d
So if we call this function with ' RightD 300 ' as input , then the
fourth line matches with 'd ' set to ' 300 ' :
* ( RightD 300 )
300
Similarly , we can write a function that extracts the ' Direction '
from a ' DirectionWithDistance ' :
fourth line matches with 'd' set to '300':
*Week01> getDistance (RightD 300)
300
Similarly, we can write a function that extracts the 'Direction'
from a 'DirectionWithDistance': -}
getDirection :: DirectionWithDistance -> Direction
getDirection (UpD d) = Up
getDirection (DownD d) = Down
getDirection (LeftD d) = Left
getDirection (RightD d) = Right
We are not limited to only one parameter on each constructor .
The ' DirectionWithDistance ' type can be thought of as representing
pairs of ' Direction 's and distances . We can make this explicit by
defining a datatype with a single constructor with two parameters :
the ' Direction ' and the ' Integer ' distance :
The 'DirectionWithDistance' type can be thought of as representing
pairs of 'Direction's and distances. We can make this explicit by
defining a datatype with a single constructor with two parameters:
the 'Direction' and the 'Integer' distance: -}
data DirectionWithDistance2
= DirectionWithDistance Direction Integer
deriving Show
( I have had to call this ' DirectionWithDistance2 ' because we can not
have two datatypes with the same name in the same module . Similarly
for the ' getDirection ' and ' ' functions below . )
With this datatype , it is much easier to write the ' getDistance '
and ' getDirection ' functions . We no longer have to write a case for
each direction :
have two datatypes with the same name in the same module. Similarly
for the 'getDirection' and 'getDistance' functions below.)
With this datatype, it is much easier to write the 'getDistance'
and 'getDirection' functions. We no longer have to write a case for
each direction: -}
getDistance2 :: DirectionWithDistance2 -> Integer
getDistance2 (DirectionWithDistance dir dist) = dist
getDirection2 :: DirectionWithDistance2 -> Direction
getDirection2 (DirectionWithDistance dir dist) = dir
The ' DirectionWithDistance ' and ' DirectionWithDistance2 ' datatypes
both represent the same information , in different ways . We can
demonstrate this relationship by writing functions that convert
back and forth . This will give us our first examples of using
functions within the definitions of other functions :
both represent the same information, in different ways. We can
demonstrate this relationship by writing functions that convert
back and forth. This will give us our first examples of using
functions within the definitions of other functions: -}
convertDirection :: DirectionWithDistance -> DirectionWithDistance2
convertDirection dwd = DirectionWithDistance (getDirection dwd) (getDistance dwd)
convertDirectionBack :: DirectionWithDistance2 -> DirectionWithDistance
convertDirectionBack (DirectionWithDistance dir dist) = withDistance dir dist
In the first function , we get a ' DirectionWithDistance ' called
' dwd ' . Then we construct a new ' DirectionWithDistance2 ' by using
its constructor . For the two parameters , we use ' getDirection ' to
extract the direction from ' dwd ' and ' ' to extract the
distance .
In the second function , we pattern match on the single constructor
of ' DirectionWithDistance2 ' , and then use the ' withDistance '
function defined above to construct a ' DirectionWithDistance ' .
'dwd'. Then we construct a new 'DirectionWithDistance2' by using
its constructor. For the two parameters, we use 'getDirection' to
extract the direction from 'dwd' and 'getDistance' to extract the
distance.
In the second function, we pattern match on the single constructor
of 'DirectionWithDistance2', and then use the 'withDistance'
function defined above to construct a 'DirectionWithDistance'. -}
! Part 1.3 : DATATYPES AND FUNCTIONS WITH TYPE PARAMETERS
We defined the datatype ' DirectionWithDistance2 ' to represent
directions with distances as pairs , and defined two functions
' getDirection ' and ' ' to extract the two parts .
But generally speaking , having pairs of things seems like a useful
thing to have for any pair of types , not just ' Direction 's and
' Integer 's .
To accomplish this , we can parameterise datatype definitions by
types , to get a generic datatype that can be specialised to any
particular type . Here is how we can define a generic pair type :
We defined the datatype 'DirectionWithDistance2' to represent
directions with distances as pairs, and defined two functions
'getDirection' and 'getDistance' to extract the two parts.
But generally speaking, having pairs of things seems like a useful
thing to have for any pair of types, not just 'Direction's and
'Integer's.
To accomplish this, we can parameterise datatype definitions by
types, to get a generic datatype that can be specialised to any
particular type. Here is how we can define a generic pair type: -}
data Pair a b = MkPair a b
deriving Show
The new thing here is the ' a ' and ' b ' between the name of the
datatype and the ' equals ' . This indicates that this datatype takes
two type parameters called ' a ' and ' b ' . These are then used in the
constructor ' MkPair ' where we used concrete type names before .
We can now use the ' MkPair ' constructor to construct pairs of any
types of values :
* 1 2
MkPair 1 2
* Week01 > MkPair Up Left
MkPair Up Left
* Week01 > MkPair ' a ' ' b '
MkPair ' a ' ' b '
* Week01 > MkPair Up ' a '
MkPair Up ' a '
and we can ask what their types are , showing us that have different
' Pair 's of different types of values :
* Week01 > : t MkPair Up Left
MkPair Up Left : : Pair Direction Direction
* > : t MkPair Up ' a '
MkPair Up ' a ' : : Pair Direction Char
Using ' Pair ' we can build another way of representing pairs of
' Direction 's and distances :
datatype and the 'equals'. This indicates that this datatype takes
two type parameters called 'a' and 'b'. These are then used in the
constructor 'MkPair' where we used concrete type names before.
We can now use the 'MkPair' constructor to construct pairs of any
types of values:
*Week01> MkPair 1 2
MkPair 1 2
*Week01> MkPair Up Left
MkPair Up Left
*Week01> MkPair 'a' 'b'
MkPair 'a' 'b'
*Week01> MkPair Up 'a'
MkPair Up 'a'
and we can ask what their types are, showing us that have different
'Pair's of different types of values:
*Week01> :t MkPair Up Left
MkPair Up Left :: Pair Direction Direction
*Week01> :t MkPair Up 'a'
MkPair Up 'a' :: Pair Direction Char
Using 'Pair' we can build another way of representing pairs of
'Direction's and distances: -}
type DirectionWithDistance3 = Pair Direction Integer
The keyword ' type ' means that we are defining a " type synonym " , that
is , an alternative name for a type . This definition says that we
will use the name ' DirectionWithDistance3 ' to stand for the type
' Pair Direction Integer ' .
is, an alternative name for a type. This definition says that we
will use the name 'DirectionWithDistance3' to stand for the type
'Pair Direction Integer'. -}
To define functions that manipulate ' Pair 's , we need to write types
with parameters as well . We do this by writing them with type
variables ' a ' , ' b ' , etc . where there would be concrete types . The
following two functions have similar definitions to ' getDistance2 '
and ' getDirection2 ' above , but work for any types ' a ' and ' b ' :
with parameters as well. We do this by writing them with type
variables 'a', 'b', etc. where there would be concrete types. The
following two functions have similar definitions to 'getDistance2'
and 'getDirection2' above, but work for any types 'a' and 'b': -}
getFirst :: Pair a b -> a
getFirst (MkPair a b) = a
getSecond :: Pair a b -> b
getSecond (MkPair a b) = b
swap :: Pair a b -> Pair b a
swap (MkPair a b) = MkPair b a
We have seen several features of datatypes now : multiple
constructors , value parameters , and type parameters . The following
extremely useful type mixes the all together in one use :
constructors, value parameters, and type parameters. The following
extremely useful type mixes the all together in one use: -}
data Maybe a
= Nothing
| Just a
deriving Show
The ' Maybe ' type is useful for representing values that may or may
not be present . If a value is present , then we can write ' Just 1 '
( for example ) . If there is no sensible value to give , then we write
' Nothing ' . The ' Maybe ' type is similar to the use of ' null ' in a
language like Java , except that the possible absence of a value is
made explicit in the type .
Here is an example of the use of ' Maybe ' . The function
' verticalDistance ' is expected to return the vertical distance
associated with a pair of a ' Direction ' and a distance . In the
cases when the direction is ' Left ' or ' Right ' , however , there is
nothing sensible to return ( the direction is horizontal ) . So we
return ' Nothing ' :
not be present. If a value is present, then we can write 'Just 1'
(for example). If there is no sensible value to give, then we write
'Nothing'. The 'Maybe' type is similar to the use of 'null' in a
language like Java, except that the possible absence of a value is
made explicit in the type.
Here is an example of the use of 'Maybe'. The function
'verticalDistance' is expected to return the vertical distance
associated with a pair of a 'Direction' and a distance. In the
cases when the direction is 'Left' or 'Right', however, there is
nothing sensible to return (the direction is horizontal). So we
return 'Nothing': -}
verticalDistance :: Pair Direction Integer -> Maybe Integer
verticalDistance (MkPair Up dist) = Just dist
verticalDistance (MkPair Down dist) = Just dist
verticalDistance (MkPair Left dist) = Nothing
verticalDistance (MkPair Right dist) = Nothing
! Part 1.4 : RECURSIVE DATATYPES AND FUNCTIONS
The datatypes we have seen so far only allow us to represent fixed
amounts of data . However , most programs we want to write will use
arbitrarily sized amounts of data .
To do this in Haskell , we use datatypes that refer to themselves
recursively . Here is an example , used for representing lists :
The datatypes we have seen so far only allow us to represent fixed
amounts of data. However, most programs we want to write will use
arbitrarily sized amounts of data.
To do this in Haskell, we use datatypes that refer to themselves
recursively. Here is an example, used for representing lists: -}
data List a
= Nil
| Cons a (List a)
deriving Show
The ' List ' datatype takes a type parameter ' a ' standing for the type
of data stored in the list .
There are two constructors :
1 . ' Nil ' represents the empty list . It does not have any parameters .
2 . ' Cons ' represents an element followed by more list .
To represent lists , we start from ' Nil ' , and build up the list by
adding things to the front :
of data stored in the list.
There are two constructors:
1. 'Nil' represents the empty list. It does not have any parameters.
2. 'Cons' represents an element followed by more list.
To represent lists, we start from 'Nil', and build up the list by
adding things to the front: -}
empty :: List Integer
empty = Nil
three :: List Integer
three = Cons 3 empty
twothree :: List Integer
twothree = Cons 2 three
onetwothree :: List Integer
onetwothree = Cons 1 twothree
Now if we evaluate ' onetwothree ' , we can see the whole list laid out :
* Week01 > onetwothree
Cons 1 ( Cons 2 ( Cons 3 Nil ) )
Pattern matching on lists works as before :
*Week01> onetwothree
Cons 1 (Cons 2 (Cons 3 Nil))
Pattern matching on lists works as before: -}
isNil :: List a -> Bool
isNil Nil = True
isNil (Cons _ _) = False
singleton :: a -> List a
singleton a = Cons a Nil
listPair :: a -> a -> List a
listPair a1 a2 = Cons a1 (Cons a2 Nil)
Lists are so useful in Haskell ( possibly they are * over*used ) that
they have a special built in syntax .
The list type is written ' [ a ] ' to stand for " a list of elements of
type ' a ' " .
The empty list ' Nil ' is written ' [ ] ' .
To add an element to the head of a list , we write ' 1 : [ ] ' , instead
of using ' Cons ' . Note that ' : ' is still pronouced ' Cons ' ( short for
' Construct ' ) .
To write out full lists , we can use square brackets and commas ,
like so :
[ 1,2,3,4 ]
is shorthand for
1 : 2 : 3 : 4 : [ ]
When prints out lists it always uses the brackets and
commas form . However , it is important to remember that lists are
really formed from the constructors ' : ' and ' [ ] ' .
We can rewrite the two list construction functions above in terms
of the built - in syntax :
they have a special built in syntax.
The list type is written '[a]' to stand for "a list of elements of
type 'a'".
The empty list 'Nil' is written '[]'.
To add an element to the head of a list, we write '1 : []', instead
of using 'Cons'. Note that ':' is still pronouced 'Cons' (short for
'Construct').
To write out full lists, we can use square brackets and commas,
like so:
[1,2,3,4]
is shorthand for
1 : 2 : 3 : 4 : []
When Haskell prints out lists it always uses the brackets and
commas form. However, it is important to remember that lists are
really formed from the constructors ':' and '[]'.
We can rewrite the two list construction functions above in terms
of the built-in syntax: -}
singleton2 :: a -> [a]
singleton2 a = [a]
listPair2 :: a -> a -> [a]
listPair2 a b = [a,b]
Pattern matching on lists uses the ' : ' and ' [ ] ' syntax too . These two
functions extract the head or tail of a list , provided it exists . I
have used the ' Maybe ' type to account for the fact that the empty
list ( ' [ ] ' ) has no head or tail .
functions extract the head or tail of a list, provided it exists. I
have used the 'Maybe' type to account for the fact that the empty
list ('[]') has no head or tail. -}
getHead :: [a] -> Maybe a
getHead [] = Nothing
getHead (x:xs) = Just x
getTail :: [a] -> Maybe [a]
getTail [] = Nothing
getTail (x:xs) = Just xs
These definitions illustrate a piece of " culture " : it is
common to use single letter variable names like ' x ' for these kinds
of generic functions where it really can stand for anything . Also ,
it is common to ' pluralise ' the name used for the head of the list
for the tail . So in these definitions , we have the head ' x ' and the
tail ' xs ' ( ) .
Since lists may be of arbitrary size , we need a way to write
functions on them that can handle arbitrary size inputs . Just as we
did this in the type definition by making ' List ' refer to itself
recursively , we do this in functions by making them refer to
themselves recursively .
Here is a function that computes the length of a list :
common to use single letter variable names like 'x' for these kinds
of generic functions where it really can stand for anything. Also,
it is common to 'pluralise' the name used for the head of the list
for the tail. So in these definitions, we have the head 'x' and the
tail 'xs' (Eck-es).
Since lists may be of arbitrary size, we need a way to write
functions on them that can handle arbitrary size inputs. Just as we
did this in the type definition by making 'List' refer to itself
recursively, we do this in functions by making them refer to
themselves recursively.
Here is a function that computes the length of a list: -}
length :: [a] -> Integer
length [] = 0
length (x:xs) = 1 + length xs
The first case , ' length [ ] ' states that the length of the empty list
is ' 0 ' .
The second case states that the length of a list with a head and a
tail is ' 1 ' plus the length of the tail .
We can see how this works by writing out the steps involved in computing the length of a short list :
length [ 1,2,3 ]
= length ( 1:2:3 : [ ] )
= 1 + length ( 2:3 : [ ] )
= 1 + 1 + length ( 3 : [ ] )
= 1 + 1 + 1 + length [ ]
= 1 + 1 + 1 + 0
= 3
In this first line , I translated from the syntatic sugar for lists
to the " real " representation using ' : ' and ' [ ] ' . I then
systematically applied the rules of the ' length ' function to get to
some arithmetic to be evaluated , which evaluates to the length of
the list .
is '0'.
The second case states that the length of a list with a head and a
tail is '1' plus the length of the tail.
We can see how this works by writing out the steps involved in computing the length of a short list:
length [1,2,3]
= length (1:2:3:[])
= 1 + length (2:3:[])
= 1 + 1 + length (3:[])
= 1 + 1 + 1 + length []
= 1 + 1 + 1 + 0
= 3
In this first line, I translated from the syntatic sugar for lists
to the "real" representation using ':' and '[]'. I then
systematically applied the rules of the 'length' function to get to
some arithmetic to be evaluated, which evaluates to the length of
the list. -}
sumList :: [Integer] -> Integer
sumList [] = 0
sumList (x:xs) = x + sumList xs
Writing out the steps involved has a similar structure , but with
different values :
sumList [ 1,2,3 ]
= sumList ( 1:2:3 : [ ] )
= 1 + sumList ( 2:3 : [ ] )
= 1 + 2 + sumList ( 3 : [ ] )
= 1 + 2 + 3 + sumList [ ]
= 1 + 2 + 3 + 0
= 6
different values:
sumList [1,2,3]
= sumList (1:2:3:[])
= 1 + sumList (2:3:[])
= 1 + 2 + sumList (3:[])
= 1 + 2 + 3 + sumList []
= 1 + 2 + 3 + 0
= 6
-}
! Part 1.5 : APPENDING AND REVERSING LISTS
Two useful functions on lists are ' append ' and ' reverse ' . These will
also give us an opporuntity to see how to use multiple functions to
accomplish a task .
' append ' is intended to put two lists one after the other . So we
should have :
append [ 1,2 ] [ 3,4 ]
evaluates to
[ 1,2,3,4 ]
To define this function , we think in terms of what we ought to do
for all possible cases of input list .
When the first list is empty , we have :
append [ ] ys
Appending the empty list with ' ys ' ought to give us ' ys ' .
When the first list has a head and a tail , we have :
append ( x : xs ) ys
If we assume that we know how to append ' xs ' and ' ys ' , then we are
left with the problem of what to do with the ' x ' . Since it was at
the head of the first list , and the first list is going on the front
of the second list , a reasonable thing to do is to put it on the
head of the final list :
x : append xs ys
Putting this together , we get the following recursive definition :
Two useful functions on lists are 'append' and 'reverse'. These will
also give us an opporuntity to see how to use multiple functions to
accomplish a task.
'append' is intended to put two lists one after the other. So we
should have:
append [1,2] [3,4]
evaluates to
[1,2,3,4]
To define this function, we think in terms of what we ought to do
for all possible cases of input list.
When the first list is empty, we have:
append [] ys
Appending the empty list with 'ys' ought to give us 'ys'.
When the first list has a head and a tail, we have:
append (x:xs) ys
If we assume that we know how to append 'xs' and 'ys', then we are
left with the problem of what to do with the 'x'. Since it was at
the head of the first list, and the first list is going on the front
of the second list, a reasonable thing to do is to put it on the
head of the final list:
x : append xs ys
Putting this together, we get the following recursive definition: -}
append :: [a] -> [a] -> [a]
append [] ys = ys
append (x:xs) ys = x : append xs ys
We can check this does the right thing by stepping through the
function for an example input :
append [ 1,2 ] [ 3,4 ]
= append ( 1:2 : [ ] ) [ 3,4 ]
= 1 : append [ 2 ] [ 3,4 ]
= 1 : 2 : append [ ] [ 3,4 ]
= 1 : 2 : [ 3,4 ]
= [ 1,2,3,4 ]
Of course , we can also just run the function :
* Week01 > append [ 1,2 ] [ 3,4 ]
[ 1,2,3,4 ]
function for an example input:
append [1,2] [3,4]
= append (1:2:[]) [3,4]
= 1 : append [2] [3,4]
= 1 : 2 : append [] [3,4]
= 1 : 2 : [3,4]
= [1,2,3,4]
Of course, we can also just run the function:
*Week01> append [1,2] [3,4]
[1,2,3,4]
-}
reverse :: [a] -> [a]
We look at the empty list case first . Reversing the empty list ought
to just be the empty list :
to just be the empty list: -}
reverse [] = []
Reversing a list with something in it is a bit more complex . Let 's
look at two examples :
reverse [ 1,2,3 ] = [ 3,2,1 ]
reverse [ 4,5,6,7 ] = [ 7,6,5,4 ]
Bearing in mind the reasoning we used in the append definition ,
let 's look carefully at what happens to the value at the head of
the input lists . In both cases , it moved to the end . Similarly , the
next element is moved to the position just before the end , and so
on . We can decompose both examples into the following structure ,
using a very informal ( non Haskell ) notation :
reverse ( x : xs ) = " reversed xs " + x at the end
Translating this definition into poses a problem : how do we
put a value at the end of a list ? The answer is to use the ' append '
function to append it on the end :
look at two examples:
reverse [1,2,3] = [3,2,1]
reverse [4,5,6,7] = [7,6,5,4]
Bearing in mind the reasoning we used in the append definition,
let's look carefully at what happens to the value at the head of
the input lists. In both cases, it moved to the end. Similarly, the
next element is moved to the position just before the end, and so
on. We can decompose both examples into the following structure,
using a very informal (non Haskell) notation:
reverse (x : xs) = "reversed xs" + x at the end
Translating this definition into Haskell poses a problem: how do we
put a value at the end of a list? The answer is to use the 'append'
function to append it on the end: -}
reverse (x:xs) = append (reverse xs) [x]
We can check our working by stepping through the definition of
reverse on a small input list :
reverse [ 1,2,3 ]
= reverse ( 1:2:3 : [ ] )
= append ( reverse ( 2:3 : [ ] ) [ 1 ]
= append ( append ( reverse ( 3 : [ ] ) [ 2 ] ) [ 1 ]
= append ( append ( append ( reverse [ ] ) [ 3 ] ) [ 2 ] ) [ 1 ]
= append ( append ( append [ ] [ 3 ] ) [ 2 ] ) [ 1 ]
= [ 3,2,1 ]
And again , we can test it by running it :
* Week01 > reverse [ 1,2,3 ]
[ 3,2,1 ]
reverse on a small input list:
reverse [1,2,3]
= reverse (1:2:3:[])
= append (reverse (2:3:[]) [1]
= append (append (reverse (3:[]) [2]) [1]
= append (append (append (reverse []) [3]) [2]) [1]
= append (append (append [] [3]) [2]) [1]
= [3,2,1]
And again, we can test it by running it:
*Week01> reverse [1,2,3]
[3,2,1]
-}
Looking at the trace of ' reverse ' , we can see that it has a flaw . It
builds up a tower of ' append 's . Evaluating an ' append ' takes time
proportional to the length of the first list . So if we do ' append 's
for every element in the input list we take time :
1 + 2 + 3 + 4 + ... + n = n*(n-1)/2
So the time taken is proportional to the square of the length of
the input list . But we should be able to reverse a list in time
proportional to just the length of the list ! How can we do this ?
The answer is to rewrite ' reverse ' by using an accumulator
parameter that stores the reversed list are building as we
go . Let 's see how this works .
We first define a function called ' fastReverseHelper ' . This takes
two arguments : the list to reverse , and an accumulator that
represents the list that has already been reversed :
builds up a tower of 'append's. Evaluating an 'append' takes time
proportional to the length of the first list. So if we do 'append's
for every element in the input list we take time:
1 + 2 + 3 + 4 + ... + n = n*(n-1)/2
So the time taken is proportional to the square of the length of
the input list. But we should be able to reverse a list in time
proportional to just the length of the list! How can we do this?
The answer is to rewrite 'reverse' by using an accumulator
parameter that stores the reversed list are building as we
go. Let's see how this works.
We first define a function called 'fastReverseHelper'. This takes
two arguments: the list to reverse, and an accumulator that
represents the list that has already been reversed: -}
fastReverseHelper :: [a] -> [a] -> [a]
fastReverseHelper [] accum = accum
fastReverseHelper (x:xs) accum = fastReverseHelper xs (x:accum)
This definition may be a little obscure at first , but it helps to
look at the a trace of how it works on a short list . We start with
the list [ 1,2 ] to reverse , and the empty ' accum'ulator parameter :
fastReverseHelper [ 1,2 ] [ ]
= fastReverseHelper [ 2 ] ( 1 : [ ] )
= fastReverseHelper [ ] ( 2:1 : [ ] )
= [ 2,1 ]
To reverse a list , we write ' ' that calls
' fastReverseHelper ' an empty initial accumulator :
look at the a trace of how it works on a short list. We start with
the list [1,2] to reverse, and the empty 'accum'ulator parameter:
fastReverseHelper [1,2] []
= fastReverseHelper [2] (1:[])
= fastReverseHelper [] (2:1:[])
= [2,1]
To reverse a list, we write 'fastReverse' that calls
'fastReverseHelper' an empty initial accumulator: -}
fastReverse :: [a] -> [a]
fastReverse xs = fastReverseHelper xs []
And we can test it :
* Week01 > fastReverse [ 1,2,3 ]
[ 3,2,1 ]
* Week01 > fastReverse [ 5,4,3,2,1 ]
[ 1,2,3,4,5 ]
*Week01> fastReverse [1,2,3]
[3,2,1]
*Week01> fastReverse [5,4,3,2,1]
[1,2,3,4,5]
-}
! Part 1.6 : TAKE , DROP AND CHUNK
Finally for this week , we 'll look at two more useful list functions ,
and how to put them together . This will also naturally lead to the
idea of nested lists of lists .
The first function is ' take ' , which takes a number of elements from
the front of a list . It is defined by pattern matching on the number
of elements remaining to be taken :
Finally for this week, we'll look at two more useful list functions,
and how to put them together. This will also naturally lead to the
idea of nested lists of lists.
The first function is 'take', which takes a number of elements from
the front of a list. It is defined by pattern matching on the number
of elements remaining to be taken: -}
take :: Integer -> [a] -> [a]
take 0 xs = []
take n [] = []
take n (x:xs) = x : take (n-1) xs
drop :: Integer -> [a] -> [a]
drop 0 xs = xs
drop n [] = []
drop n (x:xs) = drop (n-1) xs
chunk :: Integer -> [a] -> [[a]]
The function ' chunk ' takes an ' Integer ' , which is the chunk size , and
a list of ' a 's . It returns a list of lists of ' a 's ( note the * two *
pairs of square brackets , meaning a list of lists ) .
The idea is that ' chunk n xs ' will split ' xs ' into chunks of size
' n ' . For example :
chunk 2 [ 1,2,3,4,5 ]
should return
[ [ 1,2],[3,4],[5 ] ]
( notice how there was n't enough to fill the last chunk , so we
return a partial chunk . )
We now think about how we will write this function . First , we think
about the empty list case . Turning the empty list into a list of
chunks yields ... the empty list of chunks :
a list of 'a's. It returns a list of lists of 'a's (note the *two*
pairs of square brackets, meaning a list of lists).
The idea is that 'chunk n xs' will split 'xs' into chunks of size
'n'. For example:
chunk 2 [1,2,3,4,5]
should return
[[1,2],[3,4],[5]]
(notice how there wasn't enough to fill the last chunk, so we
return a partial chunk.)
We now think about how we will write this function. First, we think
about the empty list case. Turning the empty list into a list of
chunks yields ... the empty list of chunks: -}
chunk n [] = []
If the list is n't empty , then we create a new list element ( using
' :') . In the head position , we place the new chunk made by ' take n '
to get the first ' n ' elements of the list . The tail of the output
list is constructed by calling chunk recursively on the result of
dropping the first ' n ' elements :
':'). In the head position, we place the new chunk made by 'take n'
to get the first 'n' elements of the list. The tail of the output
list is constructed by calling chunk recursively on the result of
dropping the first 'n' elements: -}
chunk n xs = take n xs : chunk n (drop n xs)
To understand this function , try writing out what it does step by
step on some small examples . I 'll start you off by showing an
example where it does n't work so well . If the chunk size is ' 0 ' ,
then it generates the empty chunk over and over again , forever :
chunk 0 [ 1,2,3,4,5 ]
= take 0 [ 1,2,3,4,5 ] : chunk 0 ( drop 0 [ 1,2,3,4,5 ] )
= [ ] : chunk 0 [ 1,2,3,4,5 ]
= [ ] : [ ] : [ ] : [ ] : ...
step on some small examples. I'll start you off by showing an
example where it doesn't work so well. If the chunk size is '0',
then it generates the empty chunk over and over again, forever:
chunk 0 [1,2,3,4,5]
= take 0 [1,2,3,4,5] : chunk 0 (drop 0 [1,2,3,4,5])
= [] : chunk 0 [1,2,3,4,5]
= [] : [] : [] : [] : ...
-}
|
f64923ba982b359fa88e4d6e124dadf69dc9c2f99b4be32dbd385a6c83c8937e | phillord/tawny-owl | read_test.clj | The contents of this file are subject to the LGPL License , Version 3.0 .
Copyright ( C ) 2013 , 2017 , Newcastle University
;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation , either version 3 of the License , or
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public License
along with this program . If not , see /.
(ns tawny.read-test
(:refer-clojure :exclude [read])
(:use [clojure.test])
(:require
[clojure.set]
[tawny.read :as r]
[tawny.owl :as o]
[tawny.lookup :as l]
[tawny.fixture :as f])
(:import (org.semanticweb.owlapi.model IRI OWLNamedObject OWLOntologyID)
(org.semanticweb.owlapi.util SimpleIRIMapper)))
(def to nil)
(use-fixtures :each
(f/test-ontology-fixture-generator #'to)
f/error-on-default-ontology-fixture)
(def read-test-namespace (find-ns 'tawny.read-test))
(defn get-go-ontology []
(tawny.owl/remove-ontology-maybe
(OWLOntologyID. (IRI/create "")))
(.loadOntologyFromOntologyDocument
(tawny.owl/owl-ontology-manager)
(IRI/create (clojure.java.io/resource "go-snippet.owl"))))
(defn unmap-all-owl [ns]
(let [var-to-iri
(clojure.set/map-invert
(l/iri-to-var ns))]
(doseq
[[var sym] (clojure.set/map-invert (ns-publics ns))
:when (get var-to-iri var)]
(ns-unmap ns sym))))
(deftest read
(is
(do
(try
;; at some point this needs support in tawny.
(.addIRIMapper
(tawny.owl/owl-ontology-manager)
(SimpleIRIMapper.
(IRI/create "-owl-guide-20031209/food")
(IRI/create (clojure.java.io/resource "food.rdf"))))
(r/read :location
(IRI/create (clojure.java.io/resource "wine.rdf"))
:iri "-owl-guide-20030818/wine"
:namespace read-test-namespace
:prefix "wine:")
;; we shouldn't be using this again, but clean up anyway.
(finally
(doseq
[o
(.getOntologies (tawny.owl/owl-ontology-manager))]
(tawny.owl/remove-ontology-maybe (.getOntologyID o)))
(.clearIRIMappers (tawny.owl/owl-ontology-manager))
(unmap-all-owl read-test-namespace))))))
(deftest read-with-mapper
(is
(try
(r/read :location
(IRI/create (clojure.java.io/resource "wine.rdf"))
:iri "-owl-guide-20030818/wine"
:prefix "wine:"
:namespace read-test-namespace
:mapper
(r/resource-iri-mapper
{"-owl-guide-20031209/food",
"food.rdf"}))
(finally
(doseq
[o
(.getOntologies (tawny.owl/owl-ontology-manager))]
(tawny.owl/remove-ontology-maybe (.getOntologyID o))
(unmap-all-owl read-test-namespace))))))
(deftest go-snippet-as-resource
(is (clojure.java.io/resource "go-snippet.owl")))
(deftest go-snippet-filter
(is
(every?
(comp not nil?)
(filter (partial #'r/default-filter (get-go-ontology))
(.getSignature (get-go-ontology)))))
(is
(every?
(comp not nil?)
(filter (partial r/iri-starts-with-filter
""
nil)
(.getSignature (get-go-ontology))))))
;; need to test out label-transform
;; need to test out stop-characters-transform
(deftest go-snippet-transform
(is
(every?
(comp not nil?)
(let [fil
(doall
(map (partial #'r/default-transform nil)
;; this transform works on the anntotations which start with
;; "obo/go" rather than "obo/GO"
(filter (partial
r/iri-starts-with-filter
""
nil)
(.getSignature (get-go-ontology)))))]
;; let form allows me to add println -- not totally stupid
( println " first fil : " fil )
fil)))
(is
(do
(let [fil
(doall
(map (partial r/label-transform (get-go-ontology))
;; the label transform should work on "GO" terms should return
one annotation and one nil which it is superclass . We have
;; chopped the annotation out of the snippet.
(filter (partial r/iri-starts-with-filter
""
nil)
(.getSignature (get-go-ontology)))))]
( println " This Fil : " fil )
fil
))
)
(is
(thrown?
IllegalArgumentException
(let [fil
(doall
(map (partial r/exception-nil-label-transform (get-go-ontology))
this should throw an exception because we have one class without
;; annotation
(filter (partial r/iri-starts-with-filter
""
nil)
(.getSignature (get-go-ontology)))))]
;;(println "Fil 1:" fil)
fil
)
))
)
(deftest go-snippet-read
(is
(try (r/read :location
(IRI/create (clojure.java.io/resource "go-snippet.owl"))
:iri ""
:prefix "go:"
:namespace read-test-namespace)
(finally
(l/clean-var-cache)
(doall
(map ns-unmap
(repeat read-test-namespace)
(vals (l/iri-to-var read-test-namespace))))))))
(deftest stop-characters-transform
(is (= "bob" (r/stop-characters-transform "bob")))
(is (= "bob_" (r/stop-characters-transform "bob(")))
(is (= "bob_bob" (r/stop-characters-transform "bob bob")))
(is (= "_9bob" (r/stop-characters-transform "9bob")))
(is (= "_9_bob" (r/stop-characters-transform "9 bob")))
(is (= "_9_bob" (r/stop-characters-transform " 9 bob"))))
(deftest intern-entity-bug57
(is
(let [A (o/owl-class to "A")]
(r/intern-entity
*ns*
(o/owl-class to "B" :super A)))))
| null | https://raw.githubusercontent.com/phillord/tawny-owl/331e14b838a42adebbd325f80f60830fa0915d76/test/tawny/read_test.clj | clojure | This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
at some point this needs support in tawny.
we shouldn't be using this again, but clean up anyway.
need to test out label-transform
need to test out stop-characters-transform
this transform works on the anntotations which start with
"obo/go" rather than "obo/GO"
let form allows me to add println -- not totally stupid
the label transform should work on "GO" terms should return
chopped the annotation out of the snippet.
annotation
(println "Fil 1:" fil) | The contents of this file are subject to the LGPL License , Version 3.0 .
Copyright ( C ) 2013 , 2017 , Newcastle University
the Free Software Foundation , either version 3 of the License , or
GNU Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public License
along with this program . If not , see /.
(ns tawny.read-test
(:refer-clojure :exclude [read])
(:use [clojure.test])
(:require
[clojure.set]
[tawny.read :as r]
[tawny.owl :as o]
[tawny.lookup :as l]
[tawny.fixture :as f])
(:import (org.semanticweb.owlapi.model IRI OWLNamedObject OWLOntologyID)
(org.semanticweb.owlapi.util SimpleIRIMapper)))
(def to nil)
(use-fixtures :each
(f/test-ontology-fixture-generator #'to)
f/error-on-default-ontology-fixture)
(def read-test-namespace (find-ns 'tawny.read-test))
(defn get-go-ontology []
(tawny.owl/remove-ontology-maybe
(OWLOntologyID. (IRI/create "")))
(.loadOntologyFromOntologyDocument
(tawny.owl/owl-ontology-manager)
(IRI/create (clojure.java.io/resource "go-snippet.owl"))))
(defn unmap-all-owl [ns]
(let [var-to-iri
(clojure.set/map-invert
(l/iri-to-var ns))]
(doseq
[[var sym] (clojure.set/map-invert (ns-publics ns))
:when (get var-to-iri var)]
(ns-unmap ns sym))))
(deftest read
(is
(do
(try
(.addIRIMapper
(tawny.owl/owl-ontology-manager)
(SimpleIRIMapper.
(IRI/create "-owl-guide-20031209/food")
(IRI/create (clojure.java.io/resource "food.rdf"))))
(r/read :location
(IRI/create (clojure.java.io/resource "wine.rdf"))
:iri "-owl-guide-20030818/wine"
:namespace read-test-namespace
:prefix "wine:")
(finally
(doseq
[o
(.getOntologies (tawny.owl/owl-ontology-manager))]
(tawny.owl/remove-ontology-maybe (.getOntologyID o)))
(.clearIRIMappers (tawny.owl/owl-ontology-manager))
(unmap-all-owl read-test-namespace))))))
(deftest read-with-mapper
(is
(try
(r/read :location
(IRI/create (clojure.java.io/resource "wine.rdf"))
:iri "-owl-guide-20030818/wine"
:prefix "wine:"
:namespace read-test-namespace
:mapper
(r/resource-iri-mapper
{"-owl-guide-20031209/food",
"food.rdf"}))
(finally
(doseq
[o
(.getOntologies (tawny.owl/owl-ontology-manager))]
(tawny.owl/remove-ontology-maybe (.getOntologyID o))
(unmap-all-owl read-test-namespace))))))
(deftest go-snippet-as-resource
(is (clojure.java.io/resource "go-snippet.owl")))
(deftest go-snippet-filter
(is
(every?
(comp not nil?)
(filter (partial #'r/default-filter (get-go-ontology))
(.getSignature (get-go-ontology)))))
(is
(every?
(comp not nil?)
(filter (partial r/iri-starts-with-filter
""
nil)
(.getSignature (get-go-ontology))))))
(deftest go-snippet-transform
(is
(every?
(comp not nil?)
(let [fil
(doall
(map (partial #'r/default-transform nil)
(filter (partial
r/iri-starts-with-filter
""
nil)
(.getSignature (get-go-ontology)))))]
( println " first fil : " fil )
fil)))
(is
(do
(let [fil
(doall
(map (partial r/label-transform (get-go-ontology))
one annotation and one nil which it is superclass . We have
(filter (partial r/iri-starts-with-filter
""
nil)
(.getSignature (get-go-ontology)))))]
( println " This Fil : " fil )
fil
))
)
(is
(thrown?
IllegalArgumentException
(let [fil
(doall
(map (partial r/exception-nil-label-transform (get-go-ontology))
this should throw an exception because we have one class without
(filter (partial r/iri-starts-with-filter
""
nil)
(.getSignature (get-go-ontology)))))]
fil
)
))
)
(deftest go-snippet-read
(is
(try (r/read :location
(IRI/create (clojure.java.io/resource "go-snippet.owl"))
:iri ""
:prefix "go:"
:namespace read-test-namespace)
(finally
(l/clean-var-cache)
(doall
(map ns-unmap
(repeat read-test-namespace)
(vals (l/iri-to-var read-test-namespace))))))))
(deftest stop-characters-transform
(is (= "bob" (r/stop-characters-transform "bob")))
(is (= "bob_" (r/stop-characters-transform "bob(")))
(is (= "bob_bob" (r/stop-characters-transform "bob bob")))
(is (= "_9bob" (r/stop-characters-transform "9bob")))
(is (= "_9_bob" (r/stop-characters-transform "9 bob")))
(is (= "_9_bob" (r/stop-characters-transform " 9 bob"))))
(deftest intern-entity-bug57
(is
(let [A (o/owl-class to "A")]
(r/intern-entity
*ns*
(o/owl-class to "B" :super A)))))
|
3fe15e3b99252ed94f4562f091002bd9e57721307bf128e489d3d42fd5af2b05 | samply/blaze | date_time_operators_test.clj | (ns blaze.elm.compiler.date-time-operators-test
"18. Date and Time Operators
Section numbers are according to
-logicalspecification.html."
(:require
[blaze.anomaly :as ba]
[blaze.elm.compiler :as c]
[blaze.elm.compiler.core :as core]
[blaze.elm.compiler.test-util :as tu]
[blaze.elm.date-time :as date-time]
[blaze.elm.literal :as elm]
[blaze.elm.literal-spec]
[blaze.fhir.spec.type.system :as system]
[blaze.test-util :refer [satisfies-prop]]
[clojure.spec.alpha :as s]
[clojure.spec.test.alpha :as st]
[clojure.test :as test :refer [are deftest is testing]]
[clojure.test.check.properties :as prop]
[cognitect.anomalies :as anom]
[java-time.api :as time]
[juxt.iota :refer [given]])
(:import
[java.time Year YearMonth]
[java.time.temporal Temporal]))
(st/instrument)
(tu/instrument-compile)
(defn- fixture [f]
(st/instrument)
(tu/instrument-compile)
(f)
(st/unstrument))
(test/use-fixtures :each fixture)
18.1 Add
;;
See 16.2 . Add
18.2 After
;;
See 19.2 . After
18.3 Before
;;
See 19.3 . Before
18.4 . Equal
;;
See 12.1 . Equal
18.5 . Equivalent
;;
See 12.2 . Equivalent
18.6 . Date
;;
;; The Date operator constructs a date value from the given components.
;;
At least one component must be specified , and no component may be specified
;; at a precision below an unspecified precision. For example, month may be
;; null, but if it is, day must be null as well.
(deftest compile-date-test
(testing "Static Null year"
(is (nil? (c/compile {} #elm/date [{:type "null"}]))))
(testing "Static year"
(is (= (system/date 2019) (c/compile {} #elm/date "2019"))))
(testing "Static year over 10.000"
(given (ba/try-anomaly (c/compile {} #elm/date "10001"))
::anom/category := ::anom/incorrect
::anom/message := "Year `10001` out of range."))
(testing "Dynamic year has type :system/date"
(let [compile-ctx {:library {:parameters {:def [{:name "year"}]}}}
elm #elm/date [#elm/parameter-ref "year"]]
(is (= :system/date (system/type (c/compile compile-ctx elm))))))
(testing "Dynamic Null year"
(let [compile-ctx {:library {:parameters {:def [{:name "year"}]}}}
elm #elm/date [#elm/parameter-ref "year"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"year" nil}}]
(is (nil? (core/-eval expr eval-ctx nil nil)))))
(testing "Dynamic year"
(let [compile-ctx {:library {:parameters {:def [{:name "year"}]}}}
elm #elm/date [#elm/parameter-ref "year"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"year" 2019}}]
(is (= (system/date 2019) (core/-eval expr eval-ctx nil nil)))))
(testing "Dynamic Null month"
(let [compile-ctx {:library {:parameters {:def [{:name "month"}]}}}
elm #elm/date [#elm/integer "2018" #elm/parameter-ref "month"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"month" nil}}]
(is (= (system/date 2018) (core/-eval expr eval-ctx nil nil)))))
(testing "Static year-month"
(are [elm res] (= res (c/compile {} elm))
#elm/date "2019-03"
(system/date 2019 3)))
(testing "Dynamic year-month has type :system/date"
(let [compile-ctx {:library {:parameters {:def [{:name "month"}]}}}
elm #elm/date [#elm/integer "2019" #elm/parameter-ref "month"]]
(is (= :system/date (system/type (c/compile compile-ctx elm))))))
(testing "Dynamic year-month"
(let [compile-ctx {:library {:parameters {:def [{:name "month"}]}}}
elm #elm/date [#elm/integer "2019" #elm/parameter-ref "month"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"month" 3}}]
(is (= (system/date 2019 3) (core/-eval expr eval-ctx nil nil)))))
(testing "Dynamic Null month and day"
(let [compile-ctx {:library
{:parameters {:def [{:name "month"} {:name "day"}]}}}
elm #elm/date [#elm/integer "2020"
#elm/parameter-ref "month"
#elm/parameter-ref "day"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"month" nil "day" nil}}]
(is (= (system/date 2020) (core/-eval expr eval-ctx nil nil)))))
(testing "Dynamic date has type :system/date"
(let [compile-ctx {:library {:parameters {:def [{:name "day"}]}}}
elm #elm/date [#elm/integer "2018"
#elm/integer "5"
#elm/parameter-ref "day"]]
(is (= :system/date (system/type (c/compile compile-ctx elm))))))
(testing "Dynamic Null day"
(let [compile-ctx {:library {:parameters {:def [{:name "day"}]}}}
elm #elm/date [#elm/integer "2018"
#elm/integer "5"
#elm/parameter-ref "day"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"day" nil}}]
(is (= (system/date 2018 5) (core/-eval expr eval-ctx nil nil)))))
(testing "Static date"
(are [elm res] (= res (c/compile {} elm))
#elm/date "2019-03-23"
(system/date 2019 3 23)))
(testing "Dynamic date"
(let [compile-ctx {:library {:parameters {:def [{:name "day"}]}}}
elm #elm/date [#elm/integer "2019"
#elm/integer "3"
#elm/parameter-ref "day"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"day" 23}}]
(is (= (system/date 2019 3 23) (core/-eval expr eval-ctx nil nil)))))
(testing "an ELM year (only literals) always compiles to a Year"
(satisfies-prop 100
(prop/for-all [year (s/gen :elm/literal-year)]
(instance? Year (c/compile {} year)))))
(testing "an ELM year-month (only literals) always compiles to a YearMonth"
(satisfies-prop 100
(prop/for-all [year-month (s/gen :elm/literal-year-month)]
(instance? YearMonth (c/compile {} year-month)))))
(testing "an ELM date (only literals) always compiles to something implementing Temporal"
(satisfies-prop 100
(prop/for-all [date (s/gen :elm/literal-date)]
(instance? Temporal (c/compile {} date))))))
18.7 . DateFrom
;;
The DateFrom operator returns the date ( with no time components specified ) of
;; the argument.
;;
;; If the argument is null, the result is null.
(deftest compile-date-from-test
(are [x res] (= res (c/compile {} (elm/date-from x)))
#elm/date "2019-04-17" (system/date 2019 4 17)
#elm/date-time "2019-04-17T12:48" (system/date 2019 4 17))
(tu/testing-unary-null elm/date-from)
(tu/testing-unary-form elm/date-from))
18.8 . DateTime
;;
;; The DateTime operator constructs a DateTime value from the given components.
;;
At least one component other than timezoneOffset must be specified , and no
;; component may be specified at a precision below an unspecified precision. For
example , hour may be null , but if it is , minute , second , and millisecond must
;; all be null as well.
;;
If timezoneOffset is not specified , it is defaulted to the timezone offset of
;; the evaluation request.
(deftest compile-date-time-test
(testing "Static Null year"
(is (nil? (c/compile {} #elm/date-time[{:type "null"}]))))
(testing "Static year"
(is (= (system/date-time 2019) (c/compile {} #elm/date-time "2019"))))
(testing "Dynamic Null year"
(let [compile-ctx {:library {:parameters {:def [{:name "year"}]}}}
elm #elm/date-time[#elm/parameter-ref "year"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"year" nil}}]
(is (nil? (core/-eval expr eval-ctx nil nil)))))
(testing "Dynamic year"
(let [compile-ctx {:library {:parameters {:def [{:name "year"}]}}}
elm #elm/date-time[#elm/parameter-ref "year"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"year" 2019}}]
(is (= (system/date-time 2019) (core/-eval expr eval-ctx nil nil)))))
(testing "Dynamic Null month"
(let [compile-ctx {:library {:parameters {:def [{:name "month"}]}}}
elm #elm/date-time[#elm/integer "2018" #elm/parameter-ref "month"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"month" nil}}]
(is (= (system/date-time 2018) (core/-eval expr eval-ctx nil nil)))))
(testing "Static year-month"
(are [elm res] (= res (c/compile {} elm))
#elm/date-time "2019-03"
(system/date-time 2019 3)))
(testing "Dynamic year-month"
(let [compile-ctx {:library {:parameters {:def [{:name "month"}]}}}
elm #elm/date-time[#elm/integer "2019" #elm/parameter-ref "month"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"month" 3}}]
(is (= (system/date-time 2019 3) (core/-eval expr eval-ctx nil nil)))))
(testing "Dynamic Null month and day"
(let [compile-ctx {:library
{:parameters {:def [{:name "month"} {:name "day"}]}}}
elm #elm/date-time[#elm/integer "2020"
#elm/parameter-ref "month"
#elm/parameter-ref "day"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"month" nil "day" nil}}]
(is (= (system/date-time 2020) (core/-eval expr eval-ctx nil nil)))))
(testing "Dynamic Null day"
(let [compile-ctx {:library {:parameters {:def [{:name "day"}]}}}
elm #elm/date-time[#elm/integer "2018"
#elm/integer "5"
#elm/parameter-ref "day"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"day" nil}}]
(is (= (system/date-time 2018 5) (core/-eval expr eval-ctx nil nil)))))
(testing "Static date"
(are [elm res] (= res (c/compile {} elm))
#elm/date-time "2019-03-23"
(system/date-time 2019 3 23)))
(testing "Dynamic date"
(let [compile-ctx {:library {:parameters {:def [{:name "day"}]}}}
elm #elm/date-time[#elm/integer "2019"
#elm/integer "3"
#elm/parameter-ref "day"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"day" 23}}]
(is (= (system/date-time 2019 3 23) (core/-eval expr eval-ctx nil nil)))))
(testing "Static hour"
(are [elm res] (= res (c/compile {} elm))
#elm/date-time "2019-03-23T12"
(system/date-time 2019 3 23 12 0 0)))
(testing "Dynamic hour"
(let [compile-ctx {:library {:parameters {:def [{:name "hour"}]}}}
elm #elm/date-time[#elm/integer "2019"
#elm/integer "3"
#elm/integer "23"
#elm/parameter-ref "hour"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"hour" 12}}]
(is (= (system/date-time 2019 3 23 12 0 0)
(core/-eval expr eval-ctx nil nil)))))
(testing "minute"
(are [elm res] (= res (c/compile {} elm))
#elm/date-time "2019-03-23T12:13"
(system/date-time 2019 3 23 12 13 0)))
(testing "second"
(are [elm res] (= res (c/compile {} elm))
#elm/date-time "2019-03-23T12:13:14"
(system/date-time 2019 3 23 12 13 14)))
(testing "millisecond"
(are [elm res] (= res (c/compile {} elm))
#elm/date-time "2019-03-23T12:13:14.1"
(system/date-time 2019 3 23 12 13 14 1)))
(testing "Invalid DateTime above max value"
(are [elm] (thrown? Exception (c/compile {} elm))
#elm/date-time "10000-12-31T23:59:59.999"))
(testing "with offset"
(are [elm res] (= res (core/-eval (c/compile {} elm) {:now tu/now} nil nil))
#elm/date-time[#elm/integer "2019" #elm/integer "3" #elm/integer "23"
#elm/integer "12" #elm/integer "13" #elm/integer "14" #elm/integer "0"
#elm/decimal "-2"]
(system/date-time 2019 3 23 14 13 14)
#elm/date-time[#elm/integer "2019" #elm/integer "3" #elm/integer "23"
#elm/integer "12" #elm/integer "13" #elm/integer "14" #elm/integer "0"
#elm/decimal "-1"]
(system/date-time 2019 3 23 13 13 14)
#elm/date-time[#elm/integer "2019" #elm/integer "3" #elm/integer "23"
#elm/integer "12" #elm/integer "13" #elm/integer "14" #elm/integer "0"
#elm/decimal "0"]
(system/date-time 2019 3 23 12 13 14)
#elm/date-time[#elm/integer "2019" #elm/integer "3" #elm/integer "23"
#elm/integer "12" #elm/integer "13" #elm/integer "14" #elm/integer "0"
#elm/decimal "1"]
(system/date-time 2019 3 23 11 13 14)
#elm/date-time[#elm/integer "2019" #elm/integer "3" #elm/integer "23"
#elm/integer "12" #elm/integer "13" #elm/integer "14" #elm/integer "0"
#elm/decimal "2"]
(system/date-time 2019 3 23 10 13 14)
#elm/date-time[#elm/integer "2012" #elm/integer "3" #elm/integer "10"
#elm/integer "10" #elm/integer "20" #elm/integer "0" #elm/integer "999"
#elm/decimal "7"]
(system/date-time 2012 3 10 3 20 0 999)))
(testing "with decimal offset"
(are [elm res] (= res (core/-eval (c/compile {} elm) {:now tu/now} nil nil))
#elm/date-time[#elm/integer "2019" #elm/integer "3" #elm/integer "23"
#elm/integer "12" #elm/integer "13" #elm/integer "14" #elm/integer "0"
#elm/decimal "1.5"]
(system/date-time 2019 3 23 10 43 14)))
(testing "an ELM date-time (only literals) always evaluates to something implementing Temporal"
(satisfies-prop 100
(prop/for-all [date-time (s/gen :elm/literal-date-time)]
(instance? Temporal (core/-eval (c/compile {} date-time) {:now tu/now} nil nil))))))
18.9 .
;;
The DateTimeComponentFrom operator returns the specified component of the
;; argument.
;;
;; If the argument is null, the result is null.
;
The precision must be one of Year , Month , Day , Hour , Minute , Second , or
Millisecond . Note specifically that since there is variability how weeks are
counted , Week precision is not supported , and will result in an error .
(deftest compile-date-time-component-from-test
(let [compile (partial tu/compile-unop-precision elm/date-time-component-from)
eval #(core/-eval % {:now tu/now} nil nil)]
(doseq [op-ctor [elm/date elm/date-time]]
(are [x precision res] (= res (eval (compile op-ctor x precision)))
"2019" "Year" 2019
"2019-04" "Year" 2019
"2019-04-17" "Year" 2019
"2019" "Month" nil
"2019-04" "Month" 4
"2019-04-17" "Month" 4
"2019" "Day" nil
"2019-04" "Day" nil
"2019-04-17" "Day" 17))
(are [x precision res] (= res (eval (compile elm/date-time x precision)))
"2019-04-17T12:48" "Hour" 12))
(tu/testing-unary-precision-form elm/date-time-component-from "Year" "Month"
"Day" "Hour" "Minute" "Second" "Millisecond"))
18.10 . DifferenceBetween
;;
The DifferenceBetween operator returns the number of boundaries crossed for
the specified precision between the first and second arguments . If the first
argument is after the second argument , the result is negative . Because this
;; operation is only counting boundaries crossed, the result is always an
;; integer.
;;
For Date values , precision must be one of Year , Month , Week , or Day .
;;
For Time values , precision must be one of Hour , Minute , Second , or
Millisecond .
;;
For calculations involving weeks , Sunday is considered to be the first day of
the week for the purposes of determining boundaries .
;;
;; When calculating the difference between DateTime values with different
;; timezone offsets, implementations should normalize to the timezone offset of
;; the evaluation request timestamp, but only when the comparison precision is
;; hours, minutes, seconds, or milliseconds.
;;
;; If either argument is null, the result is null.
;;
;; Note that this operator can be implemented using Uncertainty as described in
the CQL specification , Chapter 5 , Precision - Based Timing .
(deftest compile-difference-between-test
(let [compile (partial tu/compile-binop-precision elm/difference-between)]
(testing "Year precision"
(doseq [op-xtor [elm/date elm/date-time]]
(are [x y res] (= res (compile op-xtor x y "Year"))
"2018" "2019" 1
"2018" "2017" -1
"2018" "2018" 0)))
(testing "Month precision"
(doseq [op-ctor [elm/date elm/date-time]]
(are [x y res] (= res (compile op-ctor x y "Month"))
"2018-01" "2018-02" 1
"2018-01" "2017-12" -1
"2018-01" "2018-01" 0)))
(testing "Day precision"
(doseq [op-ctor [elm/date elm/date-time]]
(are [x y res] (= res (compile op-ctor x y "Day"))
"2018-01-01" "2018-01-02" 1
"2018-01-01" "2017-12-31" -1
"2018-01-01" "2018-01-01" 0)))
(testing "Hour precision"
(are [x y res] (= res (compile elm/date-time x y "Hour"))
"2018-01-01T00" "2018-01-01T01" 2
"2018-01-01T00" "2017-12-31T23" -2
"2018-01-01T00" "2018-01-01T00" 0))
(testing "Calculating the difference between temporals with insufficient precision results in null."
(doseq [op-ctor [elm/date elm/date-time]]
(are [x y p] (nil? (compile op-ctor x y p))
"2018" "2018" "Month"
"2018-01" "2018-01" "Day"
"2018-01-01" "2018-01-01" "Hour"
"2018" "2018" "Month"
"2018-01" "2018-01" "Day"
"2018-01-01" "2018-01-01" "Hour"))))
(tu/testing-binary-precision-form elm/difference-between "Year" "Month" "Day"))
18.11 . DurationBetween
;;
The DurationBetween operator returns the number of whole calendar periods for
the specified precision between the first and second arguments . If the first
argument is after the second argument , the result is negative . The result of
;; this operation is always an integer; any fractional periods are dropped.
;;
For Date values , precision must be one of Year , Month , Week , or Day .
;;
For Time values , precision must be one of Hour , Minute , Second , or
Millisecond .
;;
For calculations involving weeks , the duration of a week is equivalent to
7 days .
;;
;; When calculating duration between DateTime values with different timezone
;; offsets, implementations should normalize to the timezone offset of the
;; evaluation request timestamp, but only when the comparison precision is
;; hours, minutes, seconds, or milliseconds.
;;
;; If either argument is null, the result is null.
;;
;; Note that this operator can be implemented using Uncertainty as described in
the CQL specification , Chapter 5 , Precision - Based Timing .
(deftest compile-duration-between-test
(let [compile (partial tu/compile-binop-precision elm/duration-between)]
(testing "Year precision"
(doseq [op-xtor [elm/date elm/date-time]]
(are [x y res] (= res (compile op-xtor x y "Year"))
"2018" "2019" 1
"2018" "2017" -1
"2018" "2018" 0)))
(testing "Month precision"
(doseq [op-ctor [elm/date elm/date-time]]
(are [x y res] (= res (compile op-ctor x y "Month"))
"2018-01" "2018-02" 1
"2018-01" "2017-12" -1
"2018-01" "2018-01" 0)))
(testing "Day precision"
(doseq [op-ctor [elm/date elm/date-time]]
(are [x y res] (= res (compile op-ctor x y "Day"))
"2018-01-01" "2018-01-02" 1
"2018-01-01" "2017-12-31" -1
"2018-01-01" "2018-01-01" 0)))
(testing "Hour precision"
(are [x y res] (= res (compile elm/date-time x y "Hour"))
"2018-01-01T00" "2018-01-01T01" 1
"2018-01-01T00" "2017-12-31T23" -1
"2018-01-01T00" "2018-01-01T00" 0))
(testing "Calculating the duration between temporals with insufficient precision results in null."
(doseq [op-ctor [elm/date elm/date-time]]
(are [x y p] (nil? (compile op-ctor x y p))
"2018" "2018" "Month"
"2018-01" "2018-01" "Day"
"2018-01-01" "2018-01-01" "Hour"
"2018" "2018" "Month"
"2018-01" "2018-01" "Day"
"2018-01-01" "2018-01-01" "Hour"))))
(tu/testing-binary-precision-form elm/duration-between "Year" "Month" "Day"))
18.12 . Not Equal
;;
See 12.7 . NotEqual
18.13 . Now
;;
;; The Now operator returns the date and time of the start timestamp associated
with the evaluation request . Now is defined in this way for two reasons :
;;
1 ) The operation will always return the same value within any given
;; evaluation, ensuring that the result of an expression containing Now will
;; always return the same result.
;;
2 ) The operation will return the timestamp associated with the evaluation
;; request, allowing the evaluation to be performed with the same timezone
;; offset information as the data delivered with the evaluation request.
(deftest compile-now-test
(are [elm res] (= res (core/-eval (c/compile {} elm) {:now tu/now} nil nil))
{:type "Now"}
tu/now))
18.14 . SameAs
;;
The SameAs operator is defined for Date , DateTime , and Time values , as well
;; as intervals.
;;
For the Interval overloads , the SameAs operator returns true if the intervals
;; start and end at the same value, using the semantics described in the Start
;; and End operator to determine interval boundaries.
;;
The SameAs operator compares two Date , DateTime , or Time values to the
;; specified precision for equality. Individual component values are compared
starting from the year component down to the specified precision . If all
;; values are specified and have the same value for each component, then the
;; result is true. If a compared component is specified in both dates, but the
;; values are not the same, then the result is false. Otherwise the result is
;; null, as there is not enough information to make a determination.
;;
;; If no precision is specified, the comparison is performed beginning with
years ( or hours for time values ) and proceeding to the finest precision
;; specified in either input.
;;
For Date values , precision must be one of year , month , or day .
;;
For DateTime values , precision must be one of year , month , day , hour , minute ,
;; second, or millisecond.
;;
For Time values , precision must be one of hour , minute , second , or
;; millisecond.
;;
;; Note specifically that due to variability in the way week numbers are
determined , comparisons involving weeks are not supported .
;;
;; As with all date and time calculations, comparisons are performed respecting
;; the timezone offset.
;;
;; If either argument is null, the result is null.
(deftest compile-same-as-test
(testing "Date"
(are [x y res] (= res (tu/compile-binop elm/same-as elm/date x y))
"2019" "2019" true
"2019" "2020" false
"2019-04" "2019-04" true
"2019-04" "2019-05" false
"2019-04-17" "2019-04-17" true
"2019-04-17" "2019-04-18" false)
(tu/testing-binary-null elm/same-as #elm/date "2019")
(tu/testing-binary-null elm/same-as #elm/date "2019-04")
(tu/testing-binary-null elm/same-as #elm/date "2019-04-17")
(testing "with year precision"
(are [x y res] (= res (tu/compile-binop-precision elm/same-as elm/date x y "year"))
"2019" "2019" true
"2019" "2020" false
"2019-04" "2019-04" true
"2019-04" "2019-05" true
"2019-04-17" "2019-04-17" true
"2019-04-17" "2019-04-18" true)))
(testing "DateTime"
(are [x y res] (= res (tu/compile-binop elm/same-as elm/date-time x y))
"2019" "2019" true
"2019" "2020" false
"2019-04" "2019-04" true
"2019-04" "2019-05" false
"2019-04-17" "2019-04-17" true
"2019-04-17" "2019-04-18" false)
(tu/testing-binary-null elm/same-as #elm/date-time "2019")
(tu/testing-binary-null elm/same-as #elm/date-time "2019-04")
(tu/testing-binary-null elm/same-as #elm/date-time "2019-04-17")
(testing "with year precision"
(are [x y res] (= res (tu/compile-binop-precision elm/same-as elm/date-time x y "year"))
"2019" "2019" true
"2019" "2020" false
"2019-04" "2019-04" true
"2019-04" "2019-05" true
"2019-04-17" "2019-04-17" true
"2019-04-17" "2019-04-18" true)))
(tu/testing-binary-precision-form elm/same-as))
18.15 . SameOrBefore
;;
The SameOrBefore operator is defined for Date , DateTime , and Time values , as
;; well as intervals.
;;
;; For the Interval overload, the SameOrBefore operator returns true if the
first interval ends on or before the second one starts . In other words , if
the ending point of the first interval is less than or equal to the starting
point of the second interval , using the semantics described in the Start and
;; End operators to determine interval boundaries.
;;
The SameOrBefore operator compares two Date , DateTime , or Time values to the
specified precision to determine whether the first argument is the same or
before the second argument . The comparison is performed by considering each
precision in order , beginning with years ( or hours for time values ) . If the
values are the same , comparison proceeds to the next precision ; if the first
value is less than the second , the result is true ; if the first value is
greater than the second , the result is false ; if either input has no value
;; for the precision, the comparison stops and the result is null; if the
;; specified precision has been reached, the comparison stops and the result is
;; true.
;;
;; If no precision is specified, the comparison is performed beginning with
years ( or hours for time values ) and proceeding to the finest precision
;; specified in either input.
;;
For Date values , precision must be one of year , month , or day .
;;
For DateTime values , precision must be one of year , month , day , hour , minute ,
;; second, or millisecond.
;;
For Time values , precision must be one of hour , minute , second , or
;; millisecond.
;;
;; Note specifically that due to variability in the way week numbers are
determined , comparisons involving weeks are not supported .
;;
;; When comparing DateTime values with different timezone offsets,
;; implementations should normalize to the timezone offset of the evaluation
request timestamp , but only when the comparison precision is hours , minutes ,
;; seconds, or milliseconds.
;;
;; If either argument is null, the result is null.
(deftest compile-same-or-before-test
(testing "Interval"
(are [x y res] (= res (tu/compile-binop elm/same-or-before elm/interval x y))
[#elm/integer "1" #elm/integer "2"]
[#elm/integer "2" #elm/integer "3"] true))
(testing "Date"
(are [x y res] (= res (tu/compile-binop elm/same-or-before elm/date x y))
"2019" "2020" true
"2019" "2019" true
"2019" "2018" false
"2019-04" "2019-05" true
"2019-04" "2019-04" true
"2019-04" "2019-03" false
"2019-04-17" "2019-04-18" true
"2019-04-17" "2019-04-17" true
"2019-04-17" "2019-04-16" false)
(tu/testing-binary-null elm/same-or-before #elm/date "2019")
(tu/testing-binary-null elm/same-or-before #elm/date "2019-04")
(tu/testing-binary-null elm/same-or-before #elm/date "2019-04-17")
(testing "with year precision"
(are [x y res] (= res (tu/compile-binop-precision elm/same-or-before elm/date x y "year"))
"2019" "2020" true
"2019" "2019" true
"2019" "2018" false
"2019-04" "2019-05" true
"2019-04" "2019-04" true
"2019-04" "2019-03" true)))
(testing "DateTime"
(are [x y res] (= res (tu/compile-binop elm/same-or-before elm/date-time x y))
"2019" "2020" true
"2019" "2019" true
"2019" "2018" false
"2019-04" "2019-05" true
"2019-04" "2019-04" true
"2019-04" "2019-03" false
"2019-04-17" "2019-04-18" true
"2019-04-17" "2019-04-17" true
"2019-04-17" "2019-04-16" false)
(tu/testing-binary-null elm/same-or-before #elm/date-time "2019")
(tu/testing-binary-null elm/same-or-before #elm/date-time "2019-04")
(tu/testing-binary-null elm/same-or-before #elm/date-time "2019-04-17")
(testing "with year precision"
(are [x y res] (= res (tu/compile-binop-precision elm/same-or-before elm/date-time x y "year"))
"2019" "2020" true
"2019" "2019" true
"2019" "2018" false
"2019-04" "2019-05" true
"2019-04" "2019-04" true
"2019-04" "2019-03" true)))
(tu/testing-binary-precision-form elm/same-or-before))
18.15 . SameOrAfter
;;
The SameOrAfter operator is defined for Date , DateTime , and Time values , as
;; well as intervals.
;;
For the Interval overload , the SameOrAfter operator returns true if the first
interval starts on or after the second one ends . In other words , if the
starting point of the first interval is greater than or equal to the ending
point of the second interval , using the semantics described in the Start and
;; End operators to determine interval boundaries.
;;
For the Date , DateTime , and Time overloads , this operator compares two Date ,
DateTime , or Time values to the specified precision to determine whether the
first argument is the same or after the second argument . The comparison is
;; performed by considering each precision in order, beginning with years (or
;; hours for time values). If the values are the same, comparison proceeds to
the next precision ; if the first value is greater than the second , the result
is true ; if the first value is less than the second , the result is false ; if
;; either input has no value for the precision, the comparison stops and the
;; result is null; if the specified precision has been reached, the comparison
;; stops and the result is true.
;;
;; If no precision is specified, the comparison is performed beginning with
years ( or hours for time values ) and proceeding to the finest precision
;; specified in either input.
;;
For Date values , precision must be one of year , month , or day .
;;
For DateTime values , precision must be one of year , month , day , hour , minute ,
;; second, or millisecond.
;;
For Time values , precision must be one of hour , minute , second , or
;; millisecond.
;;
;; Note specifically that due to variability in the way week numbers are
determined , comparisons involving weeks are not supported .
;;
;; When comparing DateTime values with different timezone offsets,
;; implementations should normalize to the timezone offset of the evaluation
request timestamp , but only when the comparison precision is hours , minutes ,
;; seconds, or milliseconds.
;;
;; If either argument is null, the result is null.
(deftest compile-same-or-after-test
(testing "Interval"
(are [x y res] (= res (tu/compile-binop elm/same-or-after elm/interval x y))
[#elm/integer "2" #elm/integer "3"]
[#elm/integer "1" #elm/integer "2"] true))
(testing "Date"
(are [x y res] (= res (tu/compile-binop elm/same-or-after elm/date x y))
"2019" "2018" true
"2019" "2019" true
"2019" "2020" false
"2019-04" "2019-03" true
"2019-04" "2019-04" true
"2019-04" "2019-05" false
"2019-04-17" "2019-04-16" true
"2019-04-17" "2019-04-17" true
"2019-04-17" "2019-04-18" false)
(tu/testing-binary-null elm/same-or-after #elm/date "2019")
(tu/testing-binary-null elm/same-or-after #elm/date "2019-04")
(tu/testing-binary-null elm/same-or-after #elm/date "2019-04-17")
(testing "with year precision"
(are [x y res] (= res (tu/compile-binop-precision elm/same-or-after elm/date x y "year"))
"2019" "2018" true
"2019" "2019" true
"2019" "2020" false
"2019-04" "2019-03" true
"2019-04" "2019-04" true
"2019-04" "2019-05" true)))
(testing "DateTime"
(are [x y res] (= res (tu/compile-binop elm/same-or-after elm/date-time x y))
"2019" "2018" true
"2019" "2019" true
"2019" "2020" false
"2019-04" "2019-03" true
"2019-04" "2019-04" true
"2019-04" "2019-05" false
"2019-04-17" "2019-04-16" true
"2019-04-17" "2019-04-17" true
"2019-04-17" "2019-04-18" false)
(tu/testing-binary-null elm/same-or-after #elm/date-time "2019")
(tu/testing-binary-null elm/same-or-after #elm/date-time "2019-04")
(tu/testing-binary-null elm/same-or-after #elm/date-time "2019-04-17")
(testing "with year precision"
(are [x y res] (= res (tu/compile-binop-precision elm/same-or-after elm/date-time x y "year"))
"2019" "2018" true
"2019" "2019" true
"2019" "2020" false
"2019-04" "2019-03" true
"2019-04" "2019-04" true
"2019-04" "2019-05" true)))
(tu/testing-binary-precision-form elm/same-or-after))
18.18 . Time
;;
The Time operator constructs a time value from the given components .
;;
At least one component other than timezoneOffset must be specified , and no
;; component may be specified at a precision below an unspecified precision.
For example , minute may be null , but if it is , second , and millisecond must
;; all be null as well.
;;
Although the milliseconds are specified with a separate component , seconds
;; and milliseconds are combined and represented as a Decimal for the purposes
;; of comparison.
(deftest compile-time-test
(testing "Static hour"
(are [elm res] (= res (c/compile {} elm))
#elm/time [#elm/integer "12"]
(date-time/local-time 12)))
(testing "Dynamic hour"
(let [compile-ctx {:library {:parameters {:def [{:name "hour"}]}}}
elm #elm/time [#elm/parameter-ref "hour"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"hour" 12}}]
(is (= (date-time/local-time 12) (core/-eval expr eval-ctx nil nil)))))
(testing "Static hour-minute"
(are [elm res] (= res (c/compile {} elm))
#elm/time [#elm/integer "12" #elm/integer "13"]
(date-time/local-time 12 13)))
(testing "Dynamic hour-minute"
(let [compile-ctx {:library {:parameters {:def [{:name "minute"}]}}}
elm #elm/time [#elm/integer "12" #elm/parameter-ref "minute"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"minute" 13}}]
(is (= (date-time/local-time 12 13) (core/-eval expr eval-ctx nil nil)))))
(testing "Static hour-minute-second"
(are [elm res] (= res (c/compile {} elm))
#elm/time [#elm/integer "12" #elm/integer "13" #elm/integer "14"]
(date-time/local-time 12 13 14)))
(testing "Dynamic hour-minute-second"
(let [compile-ctx {:library {:parameters {:def [{:name "second"}]}}}
elm #elm/time [#elm/integer "12"
#elm/integer "13"
#elm/parameter-ref "second"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"second" 14}}]
(is (= (date-time/local-time 12 13 14) (core/-eval expr eval-ctx nil nil)))))
(testing "Static hour-minute-second-millisecond"
(are [elm res] (= res (c/compile {} elm))
#elm/time [#elm/integer "12" #elm/integer "13" #elm/integer "14"
#elm/integer "15"]
(date-time/local-time 12 13 14 15)))
(testing "Dynamic hour-minute-second-millisecond"
(let [compile-ctx {:library {:parameters {:def [{:name "millisecond"}]}}}
elm #elm/time [#elm/integer "12"
#elm/integer "13"
#elm/integer "14"
#elm/parameter-ref "millisecond"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"millisecond" 15}}]
(is (= (date-time/local-time 12 13 14 15) (core/-eval expr eval-ctx nil nil)))))
(testing "an ELM time (only literals) always compiles to a LocalTime"
(satisfies-prop 100
(prop/for-all [time (s/gen :elm/time)]
(date-time/local-time? (c/compile {} time))))))
18.21 .
;;
The TimeOfDay operator returns the time - of - day of the start timestamp
;; associated with the evaluation request. See the Now operator for more
information on the rationale for defining the TimeOfDay operator in this way .
(deftest compile-time-of-day-test
(are [res] (= res (core/-eval (c/compile {} {:type "TimeOfDay"}) {:now tu/now} nil nil))
(time/local-time tu/now)))
18.22 . Today
;;
The Today operator returns the date ( with no time component ) of the start
;; timestamp associated with the evaluation request. See the Now operator for
more information on the rationale for defining the Today operator in this
;; way.
(deftest compile-today-test
(are [res] (= res (core/-eval (c/compile {} {:type "Today"}) {:now tu/now} nil nil))
(time/local-date tu/now)))
| null | https://raw.githubusercontent.com/samply/blaze/315385a281e238adbd48df581d8cc52960a3acda/modules/cql/test/blaze/elm/compiler/date_time_operators_test.clj | clojure |
The Date operator constructs a date value from the given components.
at a precision below an unspecified precision. For example, month may be
null, but if it is, day must be null as well.
the argument.
If the argument is null, the result is null.
The DateTime operator constructs a DateTime value from the given components.
component may be specified at a precision below an unspecified precision. For
all be null as well.
the evaluation request.
argument.
If the argument is null, the result is null.
operation is only counting boundaries crossed, the result is always an
integer.
When calculating the difference between DateTime values with different
timezone offsets, implementations should normalize to the timezone offset of
the evaluation request timestamp, but only when the comparison precision is
hours, minutes, seconds, or milliseconds.
If either argument is null, the result is null.
Note that this operator can be implemented using Uncertainty as described in
this operation is always an integer; any fractional periods are dropped.
When calculating duration between DateTime values with different timezone
offsets, implementations should normalize to the timezone offset of the
evaluation request timestamp, but only when the comparison precision is
hours, minutes, seconds, or milliseconds.
If either argument is null, the result is null.
Note that this operator can be implemented using Uncertainty as described in
The Now operator returns the date and time of the start timestamp associated
evaluation, ensuring that the result of an expression containing Now will
always return the same result.
request, allowing the evaluation to be performed with the same timezone
offset information as the data delivered with the evaluation request.
as intervals.
start and end at the same value, using the semantics described in the Start
and End operator to determine interval boundaries.
specified precision for equality. Individual component values are compared
values are specified and have the same value for each component, then the
result is true. If a compared component is specified in both dates, but the
values are not the same, then the result is false. Otherwise the result is
null, as there is not enough information to make a determination.
If no precision is specified, the comparison is performed beginning with
specified in either input.
second, or millisecond.
millisecond.
Note specifically that due to variability in the way week numbers are
As with all date and time calculations, comparisons are performed respecting
the timezone offset.
If either argument is null, the result is null.
well as intervals.
For the Interval overload, the SameOrBefore operator returns true if the
End operators to determine interval boundaries.
if the first
if the first value is
if either input has no value
for the precision, the comparison stops and the result is null; if the
specified precision has been reached, the comparison stops and the result is
true.
If no precision is specified, the comparison is performed beginning with
specified in either input.
second, or millisecond.
millisecond.
Note specifically that due to variability in the way week numbers are
When comparing DateTime values with different timezone offsets,
implementations should normalize to the timezone offset of the evaluation
seconds, or milliseconds.
If either argument is null, the result is null.
well as intervals.
End operators to determine interval boundaries.
performed by considering each precision in order, beginning with years (or
hours for time values). If the values are the same, comparison proceeds to
if the first value is greater than the second , the result
if the first value is less than the second , the result is false ; if
either input has no value for the precision, the comparison stops and the
result is null; if the specified precision has been reached, the comparison
stops and the result is true.
If no precision is specified, the comparison is performed beginning with
specified in either input.
second, or millisecond.
millisecond.
Note specifically that due to variability in the way week numbers are
When comparing DateTime values with different timezone offsets,
implementations should normalize to the timezone offset of the evaluation
seconds, or milliseconds.
If either argument is null, the result is null.
component may be specified at a precision below an unspecified precision.
all be null as well.
and milliseconds are combined and represented as a Decimal for the purposes
of comparison.
associated with the evaluation request. See the Now operator for more
timestamp associated with the evaluation request. See the Now operator for
way. | (ns blaze.elm.compiler.date-time-operators-test
"18. Date and Time Operators
Section numbers are according to
-logicalspecification.html."
(:require
[blaze.anomaly :as ba]
[blaze.elm.compiler :as c]
[blaze.elm.compiler.core :as core]
[blaze.elm.compiler.test-util :as tu]
[blaze.elm.date-time :as date-time]
[blaze.elm.literal :as elm]
[blaze.elm.literal-spec]
[blaze.fhir.spec.type.system :as system]
[blaze.test-util :refer [satisfies-prop]]
[clojure.spec.alpha :as s]
[clojure.spec.test.alpha :as st]
[clojure.test :as test :refer [are deftest is testing]]
[clojure.test.check.properties :as prop]
[cognitect.anomalies :as anom]
[java-time.api :as time]
[juxt.iota :refer [given]])
(:import
[java.time Year YearMonth]
[java.time.temporal Temporal]))
(st/instrument)
(tu/instrument-compile)
(defn- fixture [f]
(st/instrument)
(tu/instrument-compile)
(f)
(st/unstrument))
(test/use-fixtures :each fixture)
18.1 Add
See 16.2 . Add
18.2 After
See 19.2 . After
18.3 Before
See 19.3 . Before
18.4 . Equal
See 12.1 . Equal
18.5 . Equivalent
See 12.2 . Equivalent
18.6 . Date
At least one component must be specified , and no component may be specified
(deftest compile-date-test
(testing "Static Null year"
(is (nil? (c/compile {} #elm/date [{:type "null"}]))))
(testing "Static year"
(is (= (system/date 2019) (c/compile {} #elm/date "2019"))))
(testing "Static year over 10.000"
(given (ba/try-anomaly (c/compile {} #elm/date "10001"))
::anom/category := ::anom/incorrect
::anom/message := "Year `10001` out of range."))
(testing "Dynamic year has type :system/date"
(let [compile-ctx {:library {:parameters {:def [{:name "year"}]}}}
elm #elm/date [#elm/parameter-ref "year"]]
(is (= :system/date (system/type (c/compile compile-ctx elm))))))
(testing "Dynamic Null year"
(let [compile-ctx {:library {:parameters {:def [{:name "year"}]}}}
elm #elm/date [#elm/parameter-ref "year"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"year" nil}}]
(is (nil? (core/-eval expr eval-ctx nil nil)))))
(testing "Dynamic year"
(let [compile-ctx {:library {:parameters {:def [{:name "year"}]}}}
elm #elm/date [#elm/parameter-ref "year"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"year" 2019}}]
(is (= (system/date 2019) (core/-eval expr eval-ctx nil nil)))))
(testing "Dynamic Null month"
(let [compile-ctx {:library {:parameters {:def [{:name "month"}]}}}
elm #elm/date [#elm/integer "2018" #elm/parameter-ref "month"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"month" nil}}]
(is (= (system/date 2018) (core/-eval expr eval-ctx nil nil)))))
(testing "Static year-month"
(are [elm res] (= res (c/compile {} elm))
#elm/date "2019-03"
(system/date 2019 3)))
(testing "Dynamic year-month has type :system/date"
(let [compile-ctx {:library {:parameters {:def [{:name "month"}]}}}
elm #elm/date [#elm/integer "2019" #elm/parameter-ref "month"]]
(is (= :system/date (system/type (c/compile compile-ctx elm))))))
(testing "Dynamic year-month"
(let [compile-ctx {:library {:parameters {:def [{:name "month"}]}}}
elm #elm/date [#elm/integer "2019" #elm/parameter-ref "month"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"month" 3}}]
(is (= (system/date 2019 3) (core/-eval expr eval-ctx nil nil)))))
(testing "Dynamic Null month and day"
(let [compile-ctx {:library
{:parameters {:def [{:name "month"} {:name "day"}]}}}
elm #elm/date [#elm/integer "2020"
#elm/parameter-ref "month"
#elm/parameter-ref "day"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"month" nil "day" nil}}]
(is (= (system/date 2020) (core/-eval expr eval-ctx nil nil)))))
(testing "Dynamic date has type :system/date"
(let [compile-ctx {:library {:parameters {:def [{:name "day"}]}}}
elm #elm/date [#elm/integer "2018"
#elm/integer "5"
#elm/parameter-ref "day"]]
(is (= :system/date (system/type (c/compile compile-ctx elm))))))
(testing "Dynamic Null day"
(let [compile-ctx {:library {:parameters {:def [{:name "day"}]}}}
elm #elm/date [#elm/integer "2018"
#elm/integer "5"
#elm/parameter-ref "day"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"day" nil}}]
(is (= (system/date 2018 5) (core/-eval expr eval-ctx nil nil)))))
(testing "Static date"
(are [elm res] (= res (c/compile {} elm))
#elm/date "2019-03-23"
(system/date 2019 3 23)))
(testing "Dynamic date"
(let [compile-ctx {:library {:parameters {:def [{:name "day"}]}}}
elm #elm/date [#elm/integer "2019"
#elm/integer "3"
#elm/parameter-ref "day"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"day" 23}}]
(is (= (system/date 2019 3 23) (core/-eval expr eval-ctx nil nil)))))
(testing "an ELM year (only literals) always compiles to a Year"
(satisfies-prop 100
(prop/for-all [year (s/gen :elm/literal-year)]
(instance? Year (c/compile {} year)))))
(testing "an ELM year-month (only literals) always compiles to a YearMonth"
(satisfies-prop 100
(prop/for-all [year-month (s/gen :elm/literal-year-month)]
(instance? YearMonth (c/compile {} year-month)))))
(testing "an ELM date (only literals) always compiles to something implementing Temporal"
(satisfies-prop 100
(prop/for-all [date (s/gen :elm/literal-date)]
(instance? Temporal (c/compile {} date))))))
18.7 . DateFrom
The DateFrom operator returns the date ( with no time components specified ) of
(deftest compile-date-from-test
(are [x res] (= res (c/compile {} (elm/date-from x)))
#elm/date "2019-04-17" (system/date 2019 4 17)
#elm/date-time "2019-04-17T12:48" (system/date 2019 4 17))
(tu/testing-unary-null elm/date-from)
(tu/testing-unary-form elm/date-from))
18.8 . DateTime
At least one component other than timezoneOffset must be specified , and no
example , hour may be null , but if it is , minute , second , and millisecond must
If timezoneOffset is not specified , it is defaulted to the timezone offset of
(deftest compile-date-time-test
(testing "Static Null year"
(is (nil? (c/compile {} #elm/date-time[{:type "null"}]))))
(testing "Static year"
(is (= (system/date-time 2019) (c/compile {} #elm/date-time "2019"))))
(testing "Dynamic Null year"
(let [compile-ctx {:library {:parameters {:def [{:name "year"}]}}}
elm #elm/date-time[#elm/parameter-ref "year"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"year" nil}}]
(is (nil? (core/-eval expr eval-ctx nil nil)))))
(testing "Dynamic year"
(let [compile-ctx {:library {:parameters {:def [{:name "year"}]}}}
elm #elm/date-time[#elm/parameter-ref "year"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"year" 2019}}]
(is (= (system/date-time 2019) (core/-eval expr eval-ctx nil nil)))))
(testing "Dynamic Null month"
(let [compile-ctx {:library {:parameters {:def [{:name "month"}]}}}
elm #elm/date-time[#elm/integer "2018" #elm/parameter-ref "month"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"month" nil}}]
(is (= (system/date-time 2018) (core/-eval expr eval-ctx nil nil)))))
(testing "Static year-month"
(are [elm res] (= res (c/compile {} elm))
#elm/date-time "2019-03"
(system/date-time 2019 3)))
(testing "Dynamic year-month"
(let [compile-ctx {:library {:parameters {:def [{:name "month"}]}}}
elm #elm/date-time[#elm/integer "2019" #elm/parameter-ref "month"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"month" 3}}]
(is (= (system/date-time 2019 3) (core/-eval expr eval-ctx nil nil)))))
(testing "Dynamic Null month and day"
(let [compile-ctx {:library
{:parameters {:def [{:name "month"} {:name "day"}]}}}
elm #elm/date-time[#elm/integer "2020"
#elm/parameter-ref "month"
#elm/parameter-ref "day"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"month" nil "day" nil}}]
(is (= (system/date-time 2020) (core/-eval expr eval-ctx nil nil)))))
(testing "Dynamic Null day"
(let [compile-ctx {:library {:parameters {:def [{:name "day"}]}}}
elm #elm/date-time[#elm/integer "2018"
#elm/integer "5"
#elm/parameter-ref "day"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"day" nil}}]
(is (= (system/date-time 2018 5) (core/-eval expr eval-ctx nil nil)))))
(testing "Static date"
(are [elm res] (= res (c/compile {} elm))
#elm/date-time "2019-03-23"
(system/date-time 2019 3 23)))
(testing "Dynamic date"
(let [compile-ctx {:library {:parameters {:def [{:name "day"}]}}}
elm #elm/date-time[#elm/integer "2019"
#elm/integer "3"
#elm/parameter-ref "day"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"day" 23}}]
(is (= (system/date-time 2019 3 23) (core/-eval expr eval-ctx nil nil)))))
(testing "Static hour"
(are [elm res] (= res (c/compile {} elm))
#elm/date-time "2019-03-23T12"
(system/date-time 2019 3 23 12 0 0)))
(testing "Dynamic hour"
(let [compile-ctx {:library {:parameters {:def [{:name "hour"}]}}}
elm #elm/date-time[#elm/integer "2019"
#elm/integer "3"
#elm/integer "23"
#elm/parameter-ref "hour"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"hour" 12}}]
(is (= (system/date-time 2019 3 23 12 0 0)
(core/-eval expr eval-ctx nil nil)))))
(testing "minute"
(are [elm res] (= res (c/compile {} elm))
#elm/date-time "2019-03-23T12:13"
(system/date-time 2019 3 23 12 13 0)))
(testing "second"
(are [elm res] (= res (c/compile {} elm))
#elm/date-time "2019-03-23T12:13:14"
(system/date-time 2019 3 23 12 13 14)))
(testing "millisecond"
(are [elm res] (= res (c/compile {} elm))
#elm/date-time "2019-03-23T12:13:14.1"
(system/date-time 2019 3 23 12 13 14 1)))
(testing "Invalid DateTime above max value"
(are [elm] (thrown? Exception (c/compile {} elm))
#elm/date-time "10000-12-31T23:59:59.999"))
(testing "with offset"
(are [elm res] (= res (core/-eval (c/compile {} elm) {:now tu/now} nil nil))
#elm/date-time[#elm/integer "2019" #elm/integer "3" #elm/integer "23"
#elm/integer "12" #elm/integer "13" #elm/integer "14" #elm/integer "0"
#elm/decimal "-2"]
(system/date-time 2019 3 23 14 13 14)
#elm/date-time[#elm/integer "2019" #elm/integer "3" #elm/integer "23"
#elm/integer "12" #elm/integer "13" #elm/integer "14" #elm/integer "0"
#elm/decimal "-1"]
(system/date-time 2019 3 23 13 13 14)
#elm/date-time[#elm/integer "2019" #elm/integer "3" #elm/integer "23"
#elm/integer "12" #elm/integer "13" #elm/integer "14" #elm/integer "0"
#elm/decimal "0"]
(system/date-time 2019 3 23 12 13 14)
#elm/date-time[#elm/integer "2019" #elm/integer "3" #elm/integer "23"
#elm/integer "12" #elm/integer "13" #elm/integer "14" #elm/integer "0"
#elm/decimal "1"]
(system/date-time 2019 3 23 11 13 14)
#elm/date-time[#elm/integer "2019" #elm/integer "3" #elm/integer "23"
#elm/integer "12" #elm/integer "13" #elm/integer "14" #elm/integer "0"
#elm/decimal "2"]
(system/date-time 2019 3 23 10 13 14)
#elm/date-time[#elm/integer "2012" #elm/integer "3" #elm/integer "10"
#elm/integer "10" #elm/integer "20" #elm/integer "0" #elm/integer "999"
#elm/decimal "7"]
(system/date-time 2012 3 10 3 20 0 999)))
(testing "with decimal offset"
(are [elm res] (= res (core/-eval (c/compile {} elm) {:now tu/now} nil nil))
#elm/date-time[#elm/integer "2019" #elm/integer "3" #elm/integer "23"
#elm/integer "12" #elm/integer "13" #elm/integer "14" #elm/integer "0"
#elm/decimal "1.5"]
(system/date-time 2019 3 23 10 43 14)))
(testing "an ELM date-time (only literals) always evaluates to something implementing Temporal"
(satisfies-prop 100
(prop/for-all [date-time (s/gen :elm/literal-date-time)]
(instance? Temporal (core/-eval (c/compile {} date-time) {:now tu/now} nil nil))))))
18.9 .
The DateTimeComponentFrom operator returns the specified component of the
The precision must be one of Year , Month , Day , Hour , Minute , Second , or
Millisecond . Note specifically that since there is variability how weeks are
counted , Week precision is not supported , and will result in an error .
(deftest compile-date-time-component-from-test
(let [compile (partial tu/compile-unop-precision elm/date-time-component-from)
eval #(core/-eval % {:now tu/now} nil nil)]
(doseq [op-ctor [elm/date elm/date-time]]
(are [x precision res] (= res (eval (compile op-ctor x precision)))
"2019" "Year" 2019
"2019-04" "Year" 2019
"2019-04-17" "Year" 2019
"2019" "Month" nil
"2019-04" "Month" 4
"2019-04-17" "Month" 4
"2019" "Day" nil
"2019-04" "Day" nil
"2019-04-17" "Day" 17))
(are [x precision res] (= res (eval (compile elm/date-time x precision)))
"2019-04-17T12:48" "Hour" 12))
(tu/testing-unary-precision-form elm/date-time-component-from "Year" "Month"
"Day" "Hour" "Minute" "Second" "Millisecond"))
18.10 . DifferenceBetween
The DifferenceBetween operator returns the number of boundaries crossed for
the specified precision between the first and second arguments . If the first
argument is after the second argument , the result is negative . Because this
For Date values , precision must be one of Year , Month , Week , or Day .
For Time values , precision must be one of Hour , Minute , Second , or
Millisecond .
For calculations involving weeks , Sunday is considered to be the first day of
the week for the purposes of determining boundaries .
the CQL specification , Chapter 5 , Precision - Based Timing .
(deftest compile-difference-between-test
(let [compile (partial tu/compile-binop-precision elm/difference-between)]
(testing "Year precision"
(doseq [op-xtor [elm/date elm/date-time]]
(are [x y res] (= res (compile op-xtor x y "Year"))
"2018" "2019" 1
"2018" "2017" -1
"2018" "2018" 0)))
(testing "Month precision"
(doseq [op-ctor [elm/date elm/date-time]]
(are [x y res] (= res (compile op-ctor x y "Month"))
"2018-01" "2018-02" 1
"2018-01" "2017-12" -1
"2018-01" "2018-01" 0)))
(testing "Day precision"
(doseq [op-ctor [elm/date elm/date-time]]
(are [x y res] (= res (compile op-ctor x y "Day"))
"2018-01-01" "2018-01-02" 1
"2018-01-01" "2017-12-31" -1
"2018-01-01" "2018-01-01" 0)))
(testing "Hour precision"
(are [x y res] (= res (compile elm/date-time x y "Hour"))
"2018-01-01T00" "2018-01-01T01" 2
"2018-01-01T00" "2017-12-31T23" -2
"2018-01-01T00" "2018-01-01T00" 0))
(testing "Calculating the difference between temporals with insufficient precision results in null."
(doseq [op-ctor [elm/date elm/date-time]]
(are [x y p] (nil? (compile op-ctor x y p))
"2018" "2018" "Month"
"2018-01" "2018-01" "Day"
"2018-01-01" "2018-01-01" "Hour"
"2018" "2018" "Month"
"2018-01" "2018-01" "Day"
"2018-01-01" "2018-01-01" "Hour"))))
(tu/testing-binary-precision-form elm/difference-between "Year" "Month" "Day"))
18.11 . DurationBetween
The DurationBetween operator returns the number of whole calendar periods for
the specified precision between the first and second arguments . If the first
argument is after the second argument , the result is negative . The result of
For Date values , precision must be one of Year , Month , Week , or Day .
For Time values , precision must be one of Hour , Minute , Second , or
Millisecond .
For calculations involving weeks , the duration of a week is equivalent to
7 days .
the CQL specification , Chapter 5 , Precision - Based Timing .
(deftest compile-duration-between-test
(let [compile (partial tu/compile-binop-precision elm/duration-between)]
(testing "Year precision"
(doseq [op-xtor [elm/date elm/date-time]]
(are [x y res] (= res (compile op-xtor x y "Year"))
"2018" "2019" 1
"2018" "2017" -1
"2018" "2018" 0)))
(testing "Month precision"
(doseq [op-ctor [elm/date elm/date-time]]
(are [x y res] (= res (compile op-ctor x y "Month"))
"2018-01" "2018-02" 1
"2018-01" "2017-12" -1
"2018-01" "2018-01" 0)))
(testing "Day precision"
(doseq [op-ctor [elm/date elm/date-time]]
(are [x y res] (= res (compile op-ctor x y "Day"))
"2018-01-01" "2018-01-02" 1
"2018-01-01" "2017-12-31" -1
"2018-01-01" "2018-01-01" 0)))
(testing "Hour precision"
(are [x y res] (= res (compile elm/date-time x y "Hour"))
"2018-01-01T00" "2018-01-01T01" 1
"2018-01-01T00" "2017-12-31T23" -1
"2018-01-01T00" "2018-01-01T00" 0))
(testing "Calculating the duration between temporals with insufficient precision results in null."
(doseq [op-ctor [elm/date elm/date-time]]
(are [x y p] (nil? (compile op-ctor x y p))
"2018" "2018" "Month"
"2018-01" "2018-01" "Day"
"2018-01-01" "2018-01-01" "Hour"
"2018" "2018" "Month"
"2018-01" "2018-01" "Day"
"2018-01-01" "2018-01-01" "Hour"))))
(tu/testing-binary-precision-form elm/duration-between "Year" "Month" "Day"))
18.12 . Not Equal
See 12.7 . NotEqual
18.13 . Now
with the evaluation request . Now is defined in this way for two reasons :
1 ) The operation will always return the same value within any given
2 ) The operation will return the timestamp associated with the evaluation
(deftest compile-now-test
(are [elm res] (= res (core/-eval (c/compile {} elm) {:now tu/now} nil nil))
{:type "Now"}
tu/now))
18.14 . SameAs
The SameAs operator is defined for Date , DateTime , and Time values , as well
For the Interval overloads , the SameAs operator returns true if the intervals
The SameAs operator compares two Date , DateTime , or Time values to the
starting from the year component down to the specified precision . If all
years ( or hours for time values ) and proceeding to the finest precision
For Date values , precision must be one of year , month , or day .
For DateTime values , precision must be one of year , month , day , hour , minute ,
For Time values , precision must be one of hour , minute , second , or
determined , comparisons involving weeks are not supported .
(deftest compile-same-as-test
(testing "Date"
(are [x y res] (= res (tu/compile-binop elm/same-as elm/date x y))
"2019" "2019" true
"2019" "2020" false
"2019-04" "2019-04" true
"2019-04" "2019-05" false
"2019-04-17" "2019-04-17" true
"2019-04-17" "2019-04-18" false)
(tu/testing-binary-null elm/same-as #elm/date "2019")
(tu/testing-binary-null elm/same-as #elm/date "2019-04")
(tu/testing-binary-null elm/same-as #elm/date "2019-04-17")
(testing "with year precision"
(are [x y res] (= res (tu/compile-binop-precision elm/same-as elm/date x y "year"))
"2019" "2019" true
"2019" "2020" false
"2019-04" "2019-04" true
"2019-04" "2019-05" true
"2019-04-17" "2019-04-17" true
"2019-04-17" "2019-04-18" true)))
(testing "DateTime"
(are [x y res] (= res (tu/compile-binop elm/same-as elm/date-time x y))
"2019" "2019" true
"2019" "2020" false
"2019-04" "2019-04" true
"2019-04" "2019-05" false
"2019-04-17" "2019-04-17" true
"2019-04-17" "2019-04-18" false)
(tu/testing-binary-null elm/same-as #elm/date-time "2019")
(tu/testing-binary-null elm/same-as #elm/date-time "2019-04")
(tu/testing-binary-null elm/same-as #elm/date-time "2019-04-17")
(testing "with year precision"
(are [x y res] (= res (tu/compile-binop-precision elm/same-as elm/date-time x y "year"))
"2019" "2019" true
"2019" "2020" false
"2019-04" "2019-04" true
"2019-04" "2019-05" true
"2019-04-17" "2019-04-17" true
"2019-04-17" "2019-04-18" true)))
(tu/testing-binary-precision-form elm/same-as))
18.15 . SameOrBefore
The SameOrBefore operator is defined for Date , DateTime , and Time values , as
first interval ends on or before the second one starts . In other words , if
the ending point of the first interval is less than or equal to the starting
point of the second interval , using the semantics described in the Start and
The SameOrBefore operator compares two Date , DateTime , or Time values to the
specified precision to determine whether the first argument is the same or
before the second argument . The comparison is performed by considering each
precision in order , beginning with years ( or hours for time values ) . If the
years ( or hours for time values ) and proceeding to the finest precision
For Date values , precision must be one of year , month , or day .
For DateTime values , precision must be one of year , month , day , hour , minute ,
For Time values , precision must be one of hour , minute , second , or
determined , comparisons involving weeks are not supported .
request timestamp , but only when the comparison precision is hours , minutes ,
(deftest compile-same-or-before-test
(testing "Interval"
(are [x y res] (= res (tu/compile-binop elm/same-or-before elm/interval x y))
[#elm/integer "1" #elm/integer "2"]
[#elm/integer "2" #elm/integer "3"] true))
(testing "Date"
(are [x y res] (= res (tu/compile-binop elm/same-or-before elm/date x y))
"2019" "2020" true
"2019" "2019" true
"2019" "2018" false
"2019-04" "2019-05" true
"2019-04" "2019-04" true
"2019-04" "2019-03" false
"2019-04-17" "2019-04-18" true
"2019-04-17" "2019-04-17" true
"2019-04-17" "2019-04-16" false)
(tu/testing-binary-null elm/same-or-before #elm/date "2019")
(tu/testing-binary-null elm/same-or-before #elm/date "2019-04")
(tu/testing-binary-null elm/same-or-before #elm/date "2019-04-17")
(testing "with year precision"
(are [x y res] (= res (tu/compile-binop-precision elm/same-or-before elm/date x y "year"))
"2019" "2020" true
"2019" "2019" true
"2019" "2018" false
"2019-04" "2019-05" true
"2019-04" "2019-04" true
"2019-04" "2019-03" true)))
(testing "DateTime"
(are [x y res] (= res (tu/compile-binop elm/same-or-before elm/date-time x y))
"2019" "2020" true
"2019" "2019" true
"2019" "2018" false
"2019-04" "2019-05" true
"2019-04" "2019-04" true
"2019-04" "2019-03" false
"2019-04-17" "2019-04-18" true
"2019-04-17" "2019-04-17" true
"2019-04-17" "2019-04-16" false)
(tu/testing-binary-null elm/same-or-before #elm/date-time "2019")
(tu/testing-binary-null elm/same-or-before #elm/date-time "2019-04")
(tu/testing-binary-null elm/same-or-before #elm/date-time "2019-04-17")
(testing "with year precision"
(are [x y res] (= res (tu/compile-binop-precision elm/same-or-before elm/date-time x y "year"))
"2019" "2020" true
"2019" "2019" true
"2019" "2018" false
"2019-04" "2019-05" true
"2019-04" "2019-04" true
"2019-04" "2019-03" true)))
(tu/testing-binary-precision-form elm/same-or-before))
18.15 . SameOrAfter
The SameOrAfter operator is defined for Date , DateTime , and Time values , as
For the Interval overload , the SameOrAfter operator returns true if the first
interval starts on or after the second one ends . In other words , if the
starting point of the first interval is greater than or equal to the ending
point of the second interval , using the semantics described in the Start and
For the Date , DateTime , and Time overloads , this operator compares two Date ,
DateTime , or Time values to the specified precision to determine whether the
first argument is the same or after the second argument . The comparison is
years ( or hours for time values ) and proceeding to the finest precision
For Date values , precision must be one of year , month , or day .
For DateTime values , precision must be one of year , month , day , hour , minute ,
For Time values , precision must be one of hour , minute , second , or
determined , comparisons involving weeks are not supported .
request timestamp , but only when the comparison precision is hours , minutes ,
(deftest compile-same-or-after-test
(testing "Interval"
(are [x y res] (= res (tu/compile-binop elm/same-or-after elm/interval x y))
[#elm/integer "2" #elm/integer "3"]
[#elm/integer "1" #elm/integer "2"] true))
(testing "Date"
(are [x y res] (= res (tu/compile-binop elm/same-or-after elm/date x y))
"2019" "2018" true
"2019" "2019" true
"2019" "2020" false
"2019-04" "2019-03" true
"2019-04" "2019-04" true
"2019-04" "2019-05" false
"2019-04-17" "2019-04-16" true
"2019-04-17" "2019-04-17" true
"2019-04-17" "2019-04-18" false)
(tu/testing-binary-null elm/same-or-after #elm/date "2019")
(tu/testing-binary-null elm/same-or-after #elm/date "2019-04")
(tu/testing-binary-null elm/same-or-after #elm/date "2019-04-17")
(testing "with year precision"
(are [x y res] (= res (tu/compile-binop-precision elm/same-or-after elm/date x y "year"))
"2019" "2018" true
"2019" "2019" true
"2019" "2020" false
"2019-04" "2019-03" true
"2019-04" "2019-04" true
"2019-04" "2019-05" true)))
(testing "DateTime"
(are [x y res] (= res (tu/compile-binop elm/same-or-after elm/date-time x y))
"2019" "2018" true
"2019" "2019" true
"2019" "2020" false
"2019-04" "2019-03" true
"2019-04" "2019-04" true
"2019-04" "2019-05" false
"2019-04-17" "2019-04-16" true
"2019-04-17" "2019-04-17" true
"2019-04-17" "2019-04-18" false)
(tu/testing-binary-null elm/same-or-after #elm/date-time "2019")
(tu/testing-binary-null elm/same-or-after #elm/date-time "2019-04")
(tu/testing-binary-null elm/same-or-after #elm/date-time "2019-04-17")
(testing "with year precision"
(are [x y res] (= res (tu/compile-binop-precision elm/same-or-after elm/date-time x y "year"))
"2019" "2018" true
"2019" "2019" true
"2019" "2020" false
"2019-04" "2019-03" true
"2019-04" "2019-04" true
"2019-04" "2019-05" true)))
(tu/testing-binary-precision-form elm/same-or-after))
18.18 . Time
The Time operator constructs a time value from the given components .
At least one component other than timezoneOffset must be specified , and no
For example , minute may be null , but if it is , second , and millisecond must
Although the milliseconds are specified with a separate component , seconds
(deftest compile-time-test
(testing "Static hour"
(are [elm res] (= res (c/compile {} elm))
#elm/time [#elm/integer "12"]
(date-time/local-time 12)))
(testing "Dynamic hour"
(let [compile-ctx {:library {:parameters {:def [{:name "hour"}]}}}
elm #elm/time [#elm/parameter-ref "hour"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"hour" 12}}]
(is (= (date-time/local-time 12) (core/-eval expr eval-ctx nil nil)))))
(testing "Static hour-minute"
(are [elm res] (= res (c/compile {} elm))
#elm/time [#elm/integer "12" #elm/integer "13"]
(date-time/local-time 12 13)))
(testing "Dynamic hour-minute"
(let [compile-ctx {:library {:parameters {:def [{:name "minute"}]}}}
elm #elm/time [#elm/integer "12" #elm/parameter-ref "minute"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"minute" 13}}]
(is (= (date-time/local-time 12 13) (core/-eval expr eval-ctx nil nil)))))
(testing "Static hour-minute-second"
(are [elm res] (= res (c/compile {} elm))
#elm/time [#elm/integer "12" #elm/integer "13" #elm/integer "14"]
(date-time/local-time 12 13 14)))
(testing "Dynamic hour-minute-second"
(let [compile-ctx {:library {:parameters {:def [{:name "second"}]}}}
elm #elm/time [#elm/integer "12"
#elm/integer "13"
#elm/parameter-ref "second"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"second" 14}}]
(is (= (date-time/local-time 12 13 14) (core/-eval expr eval-ctx nil nil)))))
(testing "Static hour-minute-second-millisecond"
(are [elm res] (= res (c/compile {} elm))
#elm/time [#elm/integer "12" #elm/integer "13" #elm/integer "14"
#elm/integer "15"]
(date-time/local-time 12 13 14 15)))
(testing "Dynamic hour-minute-second-millisecond"
(let [compile-ctx {:library {:parameters {:def [{:name "millisecond"}]}}}
elm #elm/time [#elm/integer "12"
#elm/integer "13"
#elm/integer "14"
#elm/parameter-ref "millisecond"]
expr (c/compile compile-ctx elm)
eval-ctx {:parameters {"millisecond" 15}}]
(is (= (date-time/local-time 12 13 14 15) (core/-eval expr eval-ctx nil nil)))))
(testing "an ELM time (only literals) always compiles to a LocalTime"
(satisfies-prop 100
(prop/for-all [time (s/gen :elm/time)]
(date-time/local-time? (c/compile {} time))))))
18.21 .
The TimeOfDay operator returns the time - of - day of the start timestamp
information on the rationale for defining the TimeOfDay operator in this way .
(deftest compile-time-of-day-test
(are [res] (= res (core/-eval (c/compile {} {:type "TimeOfDay"}) {:now tu/now} nil nil))
(time/local-time tu/now)))
18.22 . Today
The Today operator returns the date ( with no time component ) of the start
more information on the rationale for defining the Today operator in this
(deftest compile-today-test
(are [res] (= res (core/-eval (c/compile {} {:type "Today"}) {:now tu/now} nil nil))
(time/local-date tu/now)))
|
0722b8a307a07c13d8c279f876ff67da82c52fd994860478ed853b399ee3b310 | bomberstudios/mtasc | unzip.ml |
* Unzip - inflate format decompression algorithm
* Copyright ( C ) 2004
* Compliant with RFC 1950 and 1951
*
* This library is free software ; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation ; either
* version 2.1 of the License , or ( at your option ) any later version ,
* with the special exception on linking described in file LICENSE .
*
* This library is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
* Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
* Unzip - inflate format decompression algorithm
* Copyright (C) 2004 Nicolas Cannasse
* Compliant with RFC 1950 and 1951
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version,
* with the special exception on linking described in file LICENSE.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
type huffman =
| Found of int
| NeedBit of huffman * huffman
| NeedBits of int * huffman array
type adler32 = {
mutable a1 : int;
mutable a2 : int;
}
type window = {
mutable wbuffer : string;
mutable wpos : int;
wcrc : adler32;
}
type state =
| Head
| Block
| CData
| Flat
| Crc
| Dist
| DistOne
| Done
type t = {
mutable znbits : int;
mutable zbits : int;
mutable zstate : state;
mutable zfinal : bool;
mutable zhuffman : huffman;
mutable zhuffdist : huffman option;
mutable zlen : int;
mutable zdist : int;
mutable zneeded : int;
mutable zoutput : string;
mutable zoutpos : int;
zinput : IO.input;
zlengths : int array;
zwindow : window;
}
type error_msg =
| Invalid_huffman
| Invalid_data
| Invalid_crc
| Truncated_data
| Unsupported_dictionary
exception Error of error_msg
let error msg = raise (Error msg)
(* ************************************************************************ *)
HUFFMAN TREES
let rec tree_depth = function
| Found _ -> 0
| NeedBits _ -> assert false
| NeedBit (a,b) ->
1 + min (tree_depth a) (tree_depth b)
let rec tree_compress t =
match tree_depth t with
| 0 -> t
| 1 ->
(match t with
| NeedBit (a,b) -> NeedBit (tree_compress a,tree_compress b)
| _ -> assert false)
| d ->
let size = 1 lsl d in
let tbl = Array.make size (Found (-1)) in
tree_walk tbl 0 0 d t;
NeedBits (d,tbl)
and tree_walk tbl p cd d = function
| NeedBit (a,b) when d > 0 ->
tree_walk tbl p (cd + 1) (d-1) a;
tree_walk tbl (p lor (1 lsl cd)) (cd + 1) (d-1) b;
| t ->
Array.set tbl p (tree_compress t)
let make_huffman lengths pos nlengths maxbits =
let counts = Array.make maxbits 0 in
for i = 0 to nlengths - 1 do
let p = Array.unsafe_get lengths (i + pos) in
if p >= maxbits then error Invalid_huffman;
Array.unsafe_set counts p (Array.unsafe_get counts p + 1);
done;
let code = ref 0 in
let tmp = Array.make maxbits 0 in
for i = 1 to maxbits - 2 do
code := (!code + Array.unsafe_get counts i) lsl 1;
Array.unsafe_set tmp i !code;
done;
let bits = Hashtbl.create 0 in
for i = 0 to nlengths - 1 do
let l = Array.unsafe_get lengths (i + pos) in
if l <> 0 then begin
let n = Array.unsafe_get tmp (l - 1) in
Array.unsafe_set tmp (l - 1) (n + 1);
Hashtbl.add bits (n,l) i;
end;
done;
let rec tree_make v l =
if l > maxbits then error Invalid_huffman;
try
Found (Hashtbl.find bits (v,l))
with
Not_found ->
NeedBit (tree_make (v lsl 1) (l + 1) , tree_make (v lsl 1 lor 1) (l + 1))
in
tree_compress (NeedBit (tree_make 0 1 , tree_make 1 1))
(* ************************************************************************ *)
ADLER32 ( CRC )
let adler32_create() = {
a1 = 1;
a2 = 0;
}
let adler32_update a s p l =
let p = ref p in
for i = 0 to l - 1 do
let c = int_of_char (String.unsafe_get s !p) in
a.a1 <- (a.a1 + c) mod 65521;
a.a2 <- (a.a2 + a.a1) mod 65521;
incr p;
done
let adler32_read ch =
let a2a = IO.read_byte ch in
let a2b = IO.read_byte ch in
let a1a = IO.read_byte ch in
let a1b = IO.read_byte ch in
{
a1 = (a1a lsl 8) lor a1b;
a2 = (a2a lsl 8) lor a2b;
}
(* ************************************************************************ *)
(* WINDOW *)
let window_size = 1 lsl 15
let buffer_size = 1 lsl 16
let window_create size = {
wbuffer = String.create buffer_size;
wpos = 0;
wcrc = adler32_create()
}
let window_slide w =
adler32_update w.wcrc w.wbuffer 0 window_size;
let b = String.create buffer_size in
w.wpos <- w.wpos - window_size;
String.unsafe_blit w.wbuffer window_size b 0 w.wpos;
w.wbuffer <- b
let window_add_string w s p len =
if w.wpos + len > buffer_size then window_slide w;
String.unsafe_blit s p w.wbuffer w.wpos len;
w.wpos <- w.wpos + len
let window_add_char w c =
if w.wpos = buffer_size then window_slide w;
String.unsafe_set w.wbuffer w.wpos c;
w.wpos <- w.wpos + 1
let window_get_last_char w =
String.unsafe_get w.wbuffer (w.wpos - 1)
let window_available w =
w.wpos
let window_checksum w =
adler32_update w.wcrc w.wbuffer 0 w.wpos;
w.wcrc
(* ************************************************************************ *)
let len_extra_bits_tbl = [|0;0;0;0;0;0;0;0;1;1;1;1;2;2;2;2;3;3;3;3;4;4;4;4;5;5;5;5;0;-1;-1|]
let len_base_val_tbl = [|3;4;5;6;7;8;9;10;11;13;15;17;19;23;27;31;35;43;51;59;67;83;99;115;131;163;195;227;258|]
let dist_extra_bits_tbl = [|0;0;0;0;1;1;2;2;3;3;4;4;5;5;6;6;7;7;8;8;9;9;10;10;11;11;12;12;13;13;-1;-1|]
let dist_base_val_tbl = [|1;2;3;4;5;7;9;13;17;25;33;49;65;97;129;193;257;385;513;769;1025;1537;2049;3073;4097;6145;8193;12289;16385;24577|]
let code_lengths_pos = [|16;17;18;0;8;7;9;6;10;5;11;4;12;3;13;2;14;1;15|]
let fixed_huffman = make_huffman (Array.init 288 (fun n ->
if n <= 143 then 8
else if n <= 255 then 9
else if n <= 279 then 7
else 8
)) 0 288 10
let get_bits z n =
while z.znbits < n do
z.zbits <- z.zbits lor ((IO.read_byte z.zinput) lsl z.znbits);
z.znbits <- z.znbits + 8;
done;
let b = z.zbits land (1 lsl n - 1) in
z.znbits <- z.znbits - n;
z.zbits <- z.zbits lsr n;
b
let get_bit z =
if z.znbits = 0 then begin
z.znbits <- 8;
z.zbits <- IO.read_byte z.zinput;
end;
let b = z.zbits land 1 = 1 in
z.znbits <- z.znbits - 1;
z.zbits <- z.zbits lsr 1;
b
let rec get_rev_bits z n =
if n = 0 then
0
else if get_bit z then
(1 lsl (n - 1)) lor (get_rev_bits z (n-1))
else
get_rev_bits z (n-1)
let reset_bits z =
z.zbits <- 0;
z.znbits <- 0
let add_string z s p l =
window_add_string z.zwindow s p l;
String.unsafe_blit s p z.zoutput z.zoutpos l;
z.zneeded <- z.zneeded - l;
z.zoutpos <- z.zoutpos + l
let add_char z c =
window_add_char z.zwindow c;
String.unsafe_set z.zoutput z.zoutpos c;
z.zneeded <- z.zneeded - 1;
z.zoutpos <- z.zoutpos + 1
let add_dist_one z n =
let c = window_get_last_char z.zwindow in
let s = String.make n c in
add_string z s 0 n
let add_dist z d l =
add_string z z.zwindow.wbuffer (z.zwindow.wpos - d) l
let rec apply_huffman z = function
| Found n -> n
| NeedBit (a,b) -> apply_huffman z (if get_bit z then b else a)
| NeedBits (n,t) -> apply_huffman z (Array.unsafe_get t (get_bits z n))
let inflate_lengths z a max =
let i = ref 0 in
let prev = ref 0 in
while !i < max do
match apply_huffman z z.zhuffman with
| n when n <= 15 ->
prev := n;
Array.unsafe_set a !i n;
incr i
| 16 ->
let n = 3 + get_bits z 2 in
if !i + n > max then error Invalid_data;
for k = 0 to n - 1 do
Array.unsafe_set a !i !prev;
incr i;
done;
| 17 ->
let n = 3 + get_bits z 3 in
i := !i + n;
if !i > max then error Invalid_data;
| 18 ->
let n = 11 + get_bits z 7 in
i := !i + n;
if !i > max then error Invalid_data;
| _ ->
error Invalid_data
done
let rec inflate_loop z =
match z.zstate with
| Head ->
let cmf = IO.read_byte z.zinput in
let cm = cmf land 15 in
let cinfo = cmf lsr 4 in
if cm <> 8 || cinfo <> 7 then error Invalid_data;
let flg = IO.read_byte z.zinput in
let fcheck = flg land 31 in
let fdict = flg land 32 <> 0 in
(*let flevel = flg lsr 6 in*)
if (cmf lsl 8 + flg) mod 31 <> 0 then error Invalid_data;
if fdict then error Unsupported_dictionary;
z.zstate <- Block;
inflate_loop z
| Crc ->
let calc = window_checksum z.zwindow in
let crc = adler32_read z.zinput in
if calc <> crc then error Invalid_crc;
z.zstate <- Done;
inflate_loop z
| Done ->
()
| Block ->
z.zfinal <- get_bit z;
let btype = get_bits z 2 in
(match btype with
| 0 -> (* no compression *)
z.zlen <- IO.read_ui16 z.zinput;
let nlen = IO.read_ui16 z.zinput in
if nlen <> 0xFFFF - z.zlen then error Invalid_data;
z.zstate <- Flat;
inflate_loop z;
reset_bits z
fixed
z.zhuffman <- fixed_huffman;
z.zhuffdist <- None;
z.zstate <- CData;
inflate_loop z
dynamic
let hlit = get_bits z 5 + 257 in
let hdist = get_bits z 5 + 1 in
let hclen = get_bits z 4 + 4 in
for i = 0 to hclen - 1 do
Array.unsafe_set z.zlengths (Array.unsafe_get code_lengths_pos i) (get_bits z 3);
done;
for i = hclen to 18 do
Array.unsafe_set z.zlengths (Array.unsafe_get code_lengths_pos i) 0;
done;
z.zhuffman <- make_huffman z.zlengths 0 19 8;
let lengths = Array.make (hlit + hdist) 0 in
inflate_lengths z lengths (hlit + hdist);
z.zhuffdist <- Some (make_huffman lengths hlit hdist 16);
z.zhuffman <- make_huffman lengths 0 hlit 16;
z.zstate <- CData;
inflate_loop z
| _ ->
error Invalid_data)
| Flat ->
let rlen = min z.zlen z.zneeded in
let str = IO.nread z.zinput rlen in
let len = String.length str in
z.zlen <- z.zlen - len;
add_string z str 0 len;
if z.zlen = 0 then z.zstate <- (if z.zfinal then Crc else Block);
if z.zneeded > 0 then inflate_loop z
| DistOne ->
let len = min z.zlen z.zneeded in
add_dist_one z len;
z.zlen <- z.zlen - len;
if z.zlen = 0 then z.zstate <- CData;
if z.zneeded > 0 then inflate_loop z
| Dist ->
while z.zlen > 0 && z.zneeded > 0 do
let len = min z.zneeded (min z.zlen z.zdist) in
add_dist z z.zdist len;
z.zlen <- z.zlen - len;
done;
if z.zlen = 0 then z.zstate <- CData;
if z.zneeded > 0 then inflate_loop z
| CData ->
match apply_huffman z z.zhuffman with
| n when n < 256 ->
add_char z (Char.unsafe_chr n);
if z.zneeded > 0 then inflate_loop z
| 256 ->
z.zstate <- if z.zfinal then Crc else Block;
inflate_loop z
| n ->
let n = n - 257 in
let extra_bits = Array.unsafe_get len_extra_bits_tbl n in
if extra_bits = -1 then error Invalid_data;
z.zlen <- (Array.unsafe_get len_base_val_tbl n) + (get_bits z extra_bits);
let dist_code = (match z.zhuffdist with None -> get_rev_bits z 5 | Some h -> apply_huffman z h) in
let extra_bits = Array.unsafe_get dist_extra_bits_tbl dist_code in
if extra_bits = -1 then error Invalid_data;
z.zdist <- (Array.unsafe_get dist_base_val_tbl dist_code) + (get_bits z extra_bits);
if z.zdist > window_available z.zwindow then error Invalid_data;
z.zstate <- (if z.zdist = 1 then DistOne else Dist);
inflate_loop z
let inflate_data z s pos len =
if pos < 0 || len < 0 || pos + len > String.length s then invalid_arg "inflate_data";
z.zneeded <- len;
z.zoutpos <- pos;
z.zoutput <- s;
try
if len > 0 then inflate_loop z;
len - z.zneeded
with
IO.No_more_input -> error Truncated_data
let inflate_init ?(header=true) ch =
{
zfinal = false;
zhuffman = fixed_huffman;
zhuffdist = None;
zlen = 0;
zdist = 0;
zstate = (if header then Head else Block);
zinput = ch;
zbits = 0;
znbits = 0;
zneeded = 0;
zoutput = "";
zoutpos = 0;
zlengths = Array.make 19 (-1);
zwindow = window_create (1 lsl 15)
}
let inflate ?(header=true) ch =
let z = inflate_init ~header ch in
let s = String.create 1 in
IO.create_in
~read:(fun() ->
let l = inflate_data z s 0 1 in
if l = 1 then String.unsafe_get s 0 else raise IO.No_more_input
)
~input:(fun s p l ->
let n = inflate_data z s p l in
if n = 0 then raise IO.No_more_input;
n
)
~close:(fun () ->
IO.close_in ch
)
| null | https://raw.githubusercontent.com/bomberstudios/mtasc/d7c2441310248776aa89d60f9c8f98d539bfe8de/src/extlib-dev/unzip.ml | ocaml | ************************************************************************
************************************************************************
************************************************************************
WINDOW
************************************************************************
let flevel = flg lsr 6 in
no compression |
* Unzip - inflate format decompression algorithm
* Copyright ( C ) 2004
* Compliant with RFC 1950 and 1951
*
* This library is free software ; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation ; either
* version 2.1 of the License , or ( at your option ) any later version ,
* with the special exception on linking described in file LICENSE .
*
* This library is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
* Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
* Unzip - inflate format decompression algorithm
* Copyright (C) 2004 Nicolas Cannasse
* Compliant with RFC 1950 and 1951
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version,
* with the special exception on linking described in file LICENSE.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
type huffman =
| Found of int
| NeedBit of huffman * huffman
| NeedBits of int * huffman array
type adler32 = {
mutable a1 : int;
mutable a2 : int;
}
type window = {
mutable wbuffer : string;
mutable wpos : int;
wcrc : adler32;
}
type state =
| Head
| Block
| CData
| Flat
| Crc
| Dist
| DistOne
| Done
type t = {
mutable znbits : int;
mutable zbits : int;
mutable zstate : state;
mutable zfinal : bool;
mutable zhuffman : huffman;
mutable zhuffdist : huffman option;
mutable zlen : int;
mutable zdist : int;
mutable zneeded : int;
mutable zoutput : string;
mutable zoutpos : int;
zinput : IO.input;
zlengths : int array;
zwindow : window;
}
type error_msg =
| Invalid_huffman
| Invalid_data
| Invalid_crc
| Truncated_data
| Unsupported_dictionary
exception Error of error_msg
let error msg = raise (Error msg)
HUFFMAN TREES
let rec tree_depth = function
| Found _ -> 0
| NeedBits _ -> assert false
| NeedBit (a,b) ->
1 + min (tree_depth a) (tree_depth b)
let rec tree_compress t =
match tree_depth t with
| 0 -> t
| 1 ->
(match t with
| NeedBit (a,b) -> NeedBit (tree_compress a,tree_compress b)
| _ -> assert false)
| d ->
let size = 1 lsl d in
let tbl = Array.make size (Found (-1)) in
tree_walk tbl 0 0 d t;
NeedBits (d,tbl)
and tree_walk tbl p cd d = function
| NeedBit (a,b) when d > 0 ->
tree_walk tbl p (cd + 1) (d-1) a;
tree_walk tbl (p lor (1 lsl cd)) (cd + 1) (d-1) b;
| t ->
Array.set tbl p (tree_compress t)
let make_huffman lengths pos nlengths maxbits =
let counts = Array.make maxbits 0 in
for i = 0 to nlengths - 1 do
let p = Array.unsafe_get lengths (i + pos) in
if p >= maxbits then error Invalid_huffman;
Array.unsafe_set counts p (Array.unsafe_get counts p + 1);
done;
let code = ref 0 in
let tmp = Array.make maxbits 0 in
for i = 1 to maxbits - 2 do
code := (!code + Array.unsafe_get counts i) lsl 1;
Array.unsafe_set tmp i !code;
done;
let bits = Hashtbl.create 0 in
for i = 0 to nlengths - 1 do
let l = Array.unsafe_get lengths (i + pos) in
if l <> 0 then begin
let n = Array.unsafe_get tmp (l - 1) in
Array.unsafe_set tmp (l - 1) (n + 1);
Hashtbl.add bits (n,l) i;
end;
done;
let rec tree_make v l =
if l > maxbits then error Invalid_huffman;
try
Found (Hashtbl.find bits (v,l))
with
Not_found ->
NeedBit (tree_make (v lsl 1) (l + 1) , tree_make (v lsl 1 lor 1) (l + 1))
in
tree_compress (NeedBit (tree_make 0 1 , tree_make 1 1))
ADLER32 ( CRC )
let adler32_create() = {
a1 = 1;
a2 = 0;
}
let adler32_update a s p l =
let p = ref p in
for i = 0 to l - 1 do
let c = int_of_char (String.unsafe_get s !p) in
a.a1 <- (a.a1 + c) mod 65521;
a.a2 <- (a.a2 + a.a1) mod 65521;
incr p;
done
let adler32_read ch =
let a2a = IO.read_byte ch in
let a2b = IO.read_byte ch in
let a1a = IO.read_byte ch in
let a1b = IO.read_byte ch in
{
a1 = (a1a lsl 8) lor a1b;
a2 = (a2a lsl 8) lor a2b;
}
let window_size = 1 lsl 15
let buffer_size = 1 lsl 16
let window_create size = {
wbuffer = String.create buffer_size;
wpos = 0;
wcrc = adler32_create()
}
let window_slide w =
adler32_update w.wcrc w.wbuffer 0 window_size;
let b = String.create buffer_size in
w.wpos <- w.wpos - window_size;
String.unsafe_blit w.wbuffer window_size b 0 w.wpos;
w.wbuffer <- b
let window_add_string w s p len =
if w.wpos + len > buffer_size then window_slide w;
String.unsafe_blit s p w.wbuffer w.wpos len;
w.wpos <- w.wpos + len
let window_add_char w c =
if w.wpos = buffer_size then window_slide w;
String.unsafe_set w.wbuffer w.wpos c;
w.wpos <- w.wpos + 1
let window_get_last_char w =
String.unsafe_get w.wbuffer (w.wpos - 1)
let window_available w =
w.wpos
let window_checksum w =
adler32_update w.wcrc w.wbuffer 0 w.wpos;
w.wcrc
let len_extra_bits_tbl = [|0;0;0;0;0;0;0;0;1;1;1;1;2;2;2;2;3;3;3;3;4;4;4;4;5;5;5;5;0;-1;-1|]
let len_base_val_tbl = [|3;4;5;6;7;8;9;10;11;13;15;17;19;23;27;31;35;43;51;59;67;83;99;115;131;163;195;227;258|]
let dist_extra_bits_tbl = [|0;0;0;0;1;1;2;2;3;3;4;4;5;5;6;6;7;7;8;8;9;9;10;10;11;11;12;12;13;13;-1;-1|]
let dist_base_val_tbl = [|1;2;3;4;5;7;9;13;17;25;33;49;65;97;129;193;257;385;513;769;1025;1537;2049;3073;4097;6145;8193;12289;16385;24577|]
let code_lengths_pos = [|16;17;18;0;8;7;9;6;10;5;11;4;12;3;13;2;14;1;15|]
let fixed_huffman = make_huffman (Array.init 288 (fun n ->
if n <= 143 then 8
else if n <= 255 then 9
else if n <= 279 then 7
else 8
)) 0 288 10
let get_bits z n =
while z.znbits < n do
z.zbits <- z.zbits lor ((IO.read_byte z.zinput) lsl z.znbits);
z.znbits <- z.znbits + 8;
done;
let b = z.zbits land (1 lsl n - 1) in
z.znbits <- z.znbits - n;
z.zbits <- z.zbits lsr n;
b
let get_bit z =
if z.znbits = 0 then begin
z.znbits <- 8;
z.zbits <- IO.read_byte z.zinput;
end;
let b = z.zbits land 1 = 1 in
z.znbits <- z.znbits - 1;
z.zbits <- z.zbits lsr 1;
b
let rec get_rev_bits z n =
if n = 0 then
0
else if get_bit z then
(1 lsl (n - 1)) lor (get_rev_bits z (n-1))
else
get_rev_bits z (n-1)
let reset_bits z =
z.zbits <- 0;
z.znbits <- 0
let add_string z s p l =
window_add_string z.zwindow s p l;
String.unsafe_blit s p z.zoutput z.zoutpos l;
z.zneeded <- z.zneeded - l;
z.zoutpos <- z.zoutpos + l
let add_char z c =
window_add_char z.zwindow c;
String.unsafe_set z.zoutput z.zoutpos c;
z.zneeded <- z.zneeded - 1;
z.zoutpos <- z.zoutpos + 1
let add_dist_one z n =
let c = window_get_last_char z.zwindow in
let s = String.make n c in
add_string z s 0 n
let add_dist z d l =
add_string z z.zwindow.wbuffer (z.zwindow.wpos - d) l
let rec apply_huffman z = function
| Found n -> n
| NeedBit (a,b) -> apply_huffman z (if get_bit z then b else a)
| NeedBits (n,t) -> apply_huffman z (Array.unsafe_get t (get_bits z n))
let inflate_lengths z a max =
let i = ref 0 in
let prev = ref 0 in
while !i < max do
match apply_huffman z z.zhuffman with
| n when n <= 15 ->
prev := n;
Array.unsafe_set a !i n;
incr i
| 16 ->
let n = 3 + get_bits z 2 in
if !i + n > max then error Invalid_data;
for k = 0 to n - 1 do
Array.unsafe_set a !i !prev;
incr i;
done;
| 17 ->
let n = 3 + get_bits z 3 in
i := !i + n;
if !i > max then error Invalid_data;
| 18 ->
let n = 11 + get_bits z 7 in
i := !i + n;
if !i > max then error Invalid_data;
| _ ->
error Invalid_data
done
let rec inflate_loop z =
match z.zstate with
| Head ->
let cmf = IO.read_byte z.zinput in
let cm = cmf land 15 in
let cinfo = cmf lsr 4 in
if cm <> 8 || cinfo <> 7 then error Invalid_data;
let flg = IO.read_byte z.zinput in
let fcheck = flg land 31 in
let fdict = flg land 32 <> 0 in
if (cmf lsl 8 + flg) mod 31 <> 0 then error Invalid_data;
if fdict then error Unsupported_dictionary;
z.zstate <- Block;
inflate_loop z
| Crc ->
let calc = window_checksum z.zwindow in
let crc = adler32_read z.zinput in
if calc <> crc then error Invalid_crc;
z.zstate <- Done;
inflate_loop z
| Done ->
()
| Block ->
z.zfinal <- get_bit z;
let btype = get_bits z 2 in
(match btype with
z.zlen <- IO.read_ui16 z.zinput;
let nlen = IO.read_ui16 z.zinput in
if nlen <> 0xFFFF - z.zlen then error Invalid_data;
z.zstate <- Flat;
inflate_loop z;
reset_bits z
fixed
z.zhuffman <- fixed_huffman;
z.zhuffdist <- None;
z.zstate <- CData;
inflate_loop z
dynamic
let hlit = get_bits z 5 + 257 in
let hdist = get_bits z 5 + 1 in
let hclen = get_bits z 4 + 4 in
for i = 0 to hclen - 1 do
Array.unsafe_set z.zlengths (Array.unsafe_get code_lengths_pos i) (get_bits z 3);
done;
for i = hclen to 18 do
Array.unsafe_set z.zlengths (Array.unsafe_get code_lengths_pos i) 0;
done;
z.zhuffman <- make_huffman z.zlengths 0 19 8;
let lengths = Array.make (hlit + hdist) 0 in
inflate_lengths z lengths (hlit + hdist);
z.zhuffdist <- Some (make_huffman lengths hlit hdist 16);
z.zhuffman <- make_huffman lengths 0 hlit 16;
z.zstate <- CData;
inflate_loop z
| _ ->
error Invalid_data)
| Flat ->
let rlen = min z.zlen z.zneeded in
let str = IO.nread z.zinput rlen in
let len = String.length str in
z.zlen <- z.zlen - len;
add_string z str 0 len;
if z.zlen = 0 then z.zstate <- (if z.zfinal then Crc else Block);
if z.zneeded > 0 then inflate_loop z
| DistOne ->
let len = min z.zlen z.zneeded in
add_dist_one z len;
z.zlen <- z.zlen - len;
if z.zlen = 0 then z.zstate <- CData;
if z.zneeded > 0 then inflate_loop z
| Dist ->
while z.zlen > 0 && z.zneeded > 0 do
let len = min z.zneeded (min z.zlen z.zdist) in
add_dist z z.zdist len;
z.zlen <- z.zlen - len;
done;
if z.zlen = 0 then z.zstate <- CData;
if z.zneeded > 0 then inflate_loop z
| CData ->
match apply_huffman z z.zhuffman with
| n when n < 256 ->
add_char z (Char.unsafe_chr n);
if z.zneeded > 0 then inflate_loop z
| 256 ->
z.zstate <- if z.zfinal then Crc else Block;
inflate_loop z
| n ->
let n = n - 257 in
let extra_bits = Array.unsafe_get len_extra_bits_tbl n in
if extra_bits = -1 then error Invalid_data;
z.zlen <- (Array.unsafe_get len_base_val_tbl n) + (get_bits z extra_bits);
let dist_code = (match z.zhuffdist with None -> get_rev_bits z 5 | Some h -> apply_huffman z h) in
let extra_bits = Array.unsafe_get dist_extra_bits_tbl dist_code in
if extra_bits = -1 then error Invalid_data;
z.zdist <- (Array.unsafe_get dist_base_val_tbl dist_code) + (get_bits z extra_bits);
if z.zdist > window_available z.zwindow then error Invalid_data;
z.zstate <- (if z.zdist = 1 then DistOne else Dist);
inflate_loop z
let inflate_data z s pos len =
if pos < 0 || len < 0 || pos + len > String.length s then invalid_arg "inflate_data";
z.zneeded <- len;
z.zoutpos <- pos;
z.zoutput <- s;
try
if len > 0 then inflate_loop z;
len - z.zneeded
with
IO.No_more_input -> error Truncated_data
let inflate_init ?(header=true) ch =
{
zfinal = false;
zhuffman = fixed_huffman;
zhuffdist = None;
zlen = 0;
zdist = 0;
zstate = (if header then Head else Block);
zinput = ch;
zbits = 0;
znbits = 0;
zneeded = 0;
zoutput = "";
zoutpos = 0;
zlengths = Array.make 19 (-1);
zwindow = window_create (1 lsl 15)
}
let inflate ?(header=true) ch =
let z = inflate_init ~header ch in
let s = String.create 1 in
IO.create_in
~read:(fun() ->
let l = inflate_data z s 0 1 in
if l = 1 then String.unsafe_get s 0 else raise IO.No_more_input
)
~input:(fun s p l ->
let n = inflate_data z s p l in
if n = 0 then raise IO.No_more_input;
n
)
~close:(fun () ->
IO.close_in ch
)
|
4ab3fc2432c4798afa7218be2ef655532d60b358acd486ccd7349003c54ff5a6 | apache/couchdb-chttpd | chttpd_cors.erl | 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
%
% -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(chttpd_cors).
-export([
maybe_handle_preflight_request/1,
maybe_handle_preflight_request/2,
headers/2,
headers/4
]).
-export([
is_cors_enabled/1,
get_cors_config/1
]).
-include_lib("couch/include/couch_db.hrl").
-include_lib("chttpd/include/chttpd_cors.hrl").
%% /#resource-preflight-requests
maybe_handle_preflight_request(#httpd{method=Method}) when Method /= 'OPTIONS' ->
not_preflight;
maybe_handle_preflight_request(Req) ->
case maybe_handle_preflight_request(Req, get_cors_config(Req)) of
not_preflight ->
not_preflight;
{ok, PreflightHeaders} ->
chttpd:send_response_no_cors(Req, 204, PreflightHeaders, <<>>)
end.
maybe_handle_preflight_request(#httpd{}=Req, Config) ->
case is_cors_enabled(Config) of
true ->
case preflight_request(Req, Config) of
{ok, PreflightHeaders} ->
{ok, PreflightHeaders};
not_preflight ->
not_preflight;
UnknownError ->
couch_log:error(
"Unknown response of chttpd_cors:preflight_request(~p): ~p",
[Req, UnknownError]
),
not_preflight
end;
false ->
not_preflight
end.
preflight_request(Req, Config) ->
case get_origin(Req) of
undefined ->
%% If the Origin header is not present terminate this set of
%% steps. The request is outside the scope of this specification.
%% /#resource-preflight-requests
not_preflight;
Origin ->
AcceptedOrigins = get_accepted_origins(Req, Config),
AcceptAll = lists:member(<<"*">>, AcceptedOrigins),
HandlerFun = fun() ->
handle_preflight_request(Req, Config, Origin)
end,
%% We either need to accept all origins or have it listed
%% in our origins. Origin can only contain a single origin
as the user agent will not follow redirects [ 1 ] . If the
%% value of the Origin header is not a case-sensitive
%% match for any of the values in list of origins do not
%% set any additional headers and terminate this set
of steps [ 1 ] .
%%
[ 1 ] : /#resource-preflight-requests
%%
TODO : Square against multi origin Security Considerations and the
%% Vary header
%%
case AcceptAll orelse lists:member(Origin, AcceptedOrigins) of
true -> HandlerFun();
false -> not_preflight
end
end.
handle_preflight_request(Req, Config, Origin) ->
case chttpd:header_value(Req, "Access-Control-Request-Method") of
undefined ->
If there is no Access - Control - Request - Method header
%% or if parsing failed, do not set any additional headers
%% and terminate this set of steps. The request is outside
%% the scope of this specification.
%% /#resource-preflight-requests
not_preflight;
Method ->
SupportedMethods = get_origin_config(Config, Origin,
<<"allow_methods">>, ?SUPPORTED_METHODS),
SupportedHeaders = get_origin_config(Config, Origin,
<<"allow_headers">>, ?SUPPORTED_HEADERS),
get age
MaxAge = couch_util:get_value(<<"max_age">>, Config,
?CORS_DEFAULT_MAX_AGE),
PreflightHeaders0 = maybe_add_credentials(Config, Origin, [
{"Access-Control-Allow-Origin", binary_to_list(Origin)},
{"Access-Control-Max-Age", MaxAge},
{"Access-Control-Allow-Methods",
string:join(SupportedMethods, ", ")}]),
case lists:member(Method, SupportedMethods) of
true ->
%% method ok , check headers
AccessHeaders = chttpd:header_value(Req,
"Access-Control-Request-Headers"),
{FinalReqHeaders, ReqHeaders} = case AccessHeaders of
undefined -> {"", []};
"" -> {"", []};
Headers ->
%% transform header list in something we
%% could check. make sure everything is a
%% list
RH = [to_lower(H)
|| H <- split_headers(Headers)],
{Headers, RH}
end,
%% check if headers are supported
case ReqHeaders -- SupportedHeaders of
[] ->
PreflightHeaders = PreflightHeaders0 ++
[{"Access-Control-Allow-Headers",
FinalReqHeaders}],
{ok, PreflightHeaders};
_ ->
not_preflight
end;
false ->
%% If method is not a case-sensitive match for any of
%% the values in list of methods do not set any additional
%% headers and terminate this set of steps.
%% /#resource-preflight-requests
not_preflight
end
end.
headers(Req, RequestHeaders) ->
case get_origin(Req) of
undefined ->
%% If the Origin header is not present terminate
%% this set of steps. The request is outside the scope
%% of this specification.
%% /#resource-processing-model
RequestHeaders;
Origin ->
headers(Req, RequestHeaders, Origin, get_cors_config(Req))
end.
headers(_Req, RequestHeaders, undefined, _Config) ->
RequestHeaders;
headers(Req, RequestHeaders, Origin, Config) when is_list(Origin) ->
headers(Req, RequestHeaders, ?l2b(string:to_lower(Origin)), Config);
headers(Req, RequestHeaders, Origin, Config) ->
case is_cors_enabled(Config) of
true ->
AcceptedOrigins = get_accepted_origins(Req, Config),
CorsHeaders = handle_headers(Config, Origin, AcceptedOrigins),
ExposedCouchHeaders = couch_util:get_value(
<<"exposed_headers">>, Config, ?COUCH_HEADERS),
maybe_apply_headers(CorsHeaders, RequestHeaders, ExposedCouchHeaders);
false ->
RequestHeaders
end.
maybe_apply_headers([], RequestHeaders, _ExposedCouchHeaders) ->
RequestHeaders;
maybe_apply_headers(CorsHeaders, RequestHeaders, ExposedCouchHeaders) ->
%% Find all non ?SIMPLE_HEADERS and and non ?SIMPLE_CONTENT_TYPE_VALUES,
expose those through Access - Control - Expose - Headers , allowing
%% the client to access them in the browser. Also append in
%% ?COUCH_HEADERS, as further headers may be added later that
%% need to be exposed.
%% return: RequestHeaders ++ CorsHeaders ++ ACEH
ExposedHeaders0 = simple_headers([K || {K,_V} <- RequestHeaders]),
If Content - Type is not in ExposedHeaders , and the Content - Type
%% is not a member of ?SIMPLE_CONTENT_TYPE_VALUES, then add it
into the list of ExposedHeaders
ContentType = proplists:get_value("content-type", ExposedHeaders0),
IncludeContentType = case ContentType of
undefined ->
false;
_ ->
lists:member(string:to_lower(ContentType), ?SIMPLE_CONTENT_TYPE_VALUES)
end,
ExposedHeaders = case IncludeContentType of
false ->
["content-type" | lists:delete("content-type", ExposedHeaders0)];
true ->
ExposedHeaders0
end,
ExposedCouchHeaders may get added later , so expose them by default
ACEH = [{"Access-Control-Expose-Headers",
string:join(ExposedHeaders ++ ExposedCouchHeaders, ", ")}],
CorsHeaders ++ RequestHeaders ++ ACEH.
simple_headers(Headers) ->
LCHeaders = [to_lower(H) || H <- Headers],
lists:filter(fun(H) -> lists:member(H, ?SIMPLE_HEADERS) end, LCHeaders).
to_lower(String) when is_binary(String) ->
to_lower(?b2l(String));
to_lower(String) ->
string:to_lower(String).
handle_headers(_Config, _Origin, []) ->
[];
handle_headers(Config, Origin, AcceptedOrigins) ->
AcceptAll = lists:member(<<"*">>, AcceptedOrigins),
case AcceptAll orelse lists:member(Origin, AcceptedOrigins) of
true ->
make_cors_header(Config, Origin);
false ->
%% If the value of the Origin header is not a
%% case-sensitive match for any of the values
%% in list of origins, do not set any additional
%% headers and terminate this set of steps.
%% /#resource-requests
[]
end.
make_cors_header(Config, Origin) ->
Headers = [{"Access-Control-Allow-Origin", binary_to_list(Origin)}],
maybe_add_credentials(Config, Origin, Headers).
%% util
maybe_add_credentials(Config, Origin, Headers) ->
case allow_credentials(Config, Origin) of
false ->
Headers;
true ->
Headers ++ [{"Access-Control-Allow-Credentials", "true"}]
end.
allow_credentials(_Config, <<"*">>) ->
false;
allow_credentials(Config, Origin) ->
get_origin_config(Config, Origin, <<"allow_credentials">>,
?CORS_DEFAULT_ALLOW_CREDENTIALS).
get_cors_config(#httpd{cors_config = undefined, mochi_req = MochiReq}) ->
Host = couch_httpd_vhost:host(MochiReq),
EnableCors = config:get("httpd", "enable_cors", "false") =:= "true",
AllowCredentials = cors_config(Host, "credentials", "false") =:= "true",
AllowHeaders = case cors_config(Host, "headers", undefined) of
undefined ->
?SUPPORTED_HEADERS;
AllowHeaders0 ->
[to_lower(H) || H <- split_list(AllowHeaders0)]
end,
AllowMethods = case cors_config(Host, "methods", undefined) of
undefined ->
?SUPPORTED_METHODS;
AllowMethods0 ->
split_list(AllowMethods0)
end,
ExposedHeaders = case cors_config(Host, "exposed_headers", undefined) of
undefined ->
?COUCH_HEADERS;
ExposedHeaders0 ->
[to_lower(H) || H <- split_list(ExposedHeaders0)]
end,
MaxAge = cors_config(Host, "max_age", ?CORS_DEFAULT_MAX_AGE),
Origins0 = binary_split_list(cors_config(Host, "origins", [])),
Origins = [{O, {[]}} || O <- Origins0],
[
{<<"enable_cors">>, EnableCors},
{<<"allow_credentials">>, AllowCredentials},
{<<"allow_methods">>, AllowMethods},
{<<"allow_headers">>, AllowHeaders},
{<<"exposed_headers">>, ExposedHeaders},
{<<"max_age">>, MaxAge},
{<<"origins">>, {Origins}}
];
get_cors_config(#httpd{cors_config = Config}) ->
Config.
cors_config(Host, Key, Default) ->
config:get(cors_section(Host), Key,
config:get("cors", Key, Default)).
cors_section(HostValue) ->
HostPort = maybe_strip_scheme(HostValue),
Host = hd(string:tokens(HostPort, ":")),
"cors:" ++ Host.
maybe_strip_scheme(Host) ->
case string:str(Host, "://") of
0 -> Host;
N -> string:substr(Host, N + 3)
end.
is_cors_enabled(Config) ->
case get(disable_couch_httpd_cors) of
undefined ->
put(disable_couch_httpd_cors, true);
_ ->
ok
end,
couch_util:get_value(<<"enable_cors">>, Config, false).
%% Get a list of {Origin, OriginConfig} tuples
%% ie: get_origin_configs(Config) ->
%% [
%% {<<"">>,
%% {
%% [
%% {<<"allow_credentials">>, true},
%% {<<"allow_methods">>, [<<"POST">>]}
%% ]
%% }
%% },
%% {<<"">>, {[]}}
%% ]
get_origin_configs(Config) ->
{Origins} = couch_util:get_value(<<"origins">>, Config, {[]}),
Origins.
%% Get config for an individual Origin
%% ie: get_origin_config(Config, <<"">>) ->
%% [
%% {<<"allow_credentials">>, true},
%% {<<"allow_methods">>, [<<"POST">>]}
%% ]
get_origin_config(Config, Origin) ->
OriginConfigs = get_origin_configs(Config),
{OriginConfig} = couch_util:get_value(Origin, OriginConfigs, {[]}),
OriginConfig.
%% Get config of a single key for an individual Origin
%% ie: get_origin_config(Config, <<"">>, <<"allow_methods">>, [])
%% [<<"POST">>]
get_origin_config(Config, Origin, Key, Default) ->
OriginConfig = get_origin_config(Config, Origin),
couch_util:get_value(Key, OriginConfig,
couch_util:get_value(Key, Config, Default)).
get_origin(Req) ->
case chttpd:header_value(Req, "Origin") of
undefined ->
undefined;
Origin ->
?l2b(Origin)
end.
get_accepted_origins(_Req, Config) ->
lists:map(fun({K,_V}) -> K end, get_origin_configs(Config)).
split_list(S) ->
re:split(S, "\\s*,\\s*", [trim, {return, list}]).
binary_split_list(S) ->
[list_to_binary(E) || E <- split_list(S)].
split_headers(H) ->
re:split(H, ",\\s*", [{return,list}, trim]).
| null | https://raw.githubusercontent.com/apache/couchdb-chttpd/74002101513c03df74a4c25f3c892f5d003fa5da/src/chttpd_cors.erl | erlang | use this file except in compliance with the License. You may obtain a copy of
the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License.
/#resource-preflight-requests
If the Origin header is not present terminate this set of
steps. The request is outside the scope of this specification.
/#resource-preflight-requests
We either need to accept all origins or have it listed
in our origins. Origin can only contain a single origin
value of the Origin header is not a case-sensitive
match for any of the values in list of origins do not
set any additional headers and terminate this set
Vary header
or if parsing failed, do not set any additional headers
and terminate this set of steps. The request is outside
the scope of this specification.
/#resource-preflight-requests
method ok , check headers
transform header list in something we
could check. make sure everything is a
list
check if headers are supported
If method is not a case-sensitive match for any of
the values in list of methods do not set any additional
headers and terminate this set of steps.
/#resource-preflight-requests
If the Origin header is not present terminate
this set of steps. The request is outside the scope
of this specification.
/#resource-processing-model
Find all non ?SIMPLE_HEADERS and and non ?SIMPLE_CONTENT_TYPE_VALUES,
the client to access them in the browser. Also append in
?COUCH_HEADERS, as further headers may be added later that
need to be exposed.
return: RequestHeaders ++ CorsHeaders ++ ACEH
is not a member of ?SIMPLE_CONTENT_TYPE_VALUES, then add it
If the value of the Origin header is not a
case-sensitive match for any of the values
in list of origins, do not set any additional
headers and terminate this set of steps.
/#resource-requests
util
Get a list of {Origin, OriginConfig} tuples
ie: get_origin_configs(Config) ->
[
{<<"">>,
{
[
{<<"allow_credentials">>, true},
{<<"allow_methods">>, [<<"POST">>]}
]
}
},
{<<"">>, {[]}}
]
Get config for an individual Origin
ie: get_origin_config(Config, <<"">>) ->
[
{<<"allow_credentials">>, true},
{<<"allow_methods">>, [<<"POST">>]}
]
Get config of a single key for an individual Origin
ie: get_origin_config(Config, <<"">>, <<"allow_methods">>, [])
[<<"POST">>] | Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not
distributed under the License is distributed on an " AS IS " BASIS , WITHOUT
-module(chttpd_cors).
-export([
maybe_handle_preflight_request/1,
maybe_handle_preflight_request/2,
headers/2,
headers/4
]).
-export([
is_cors_enabled/1,
get_cors_config/1
]).
-include_lib("couch/include/couch_db.hrl").
-include_lib("chttpd/include/chttpd_cors.hrl").
maybe_handle_preflight_request(#httpd{method=Method}) when Method /= 'OPTIONS' ->
not_preflight;
maybe_handle_preflight_request(Req) ->
case maybe_handle_preflight_request(Req, get_cors_config(Req)) of
not_preflight ->
not_preflight;
{ok, PreflightHeaders} ->
chttpd:send_response_no_cors(Req, 204, PreflightHeaders, <<>>)
end.
maybe_handle_preflight_request(#httpd{}=Req, Config) ->
case is_cors_enabled(Config) of
true ->
case preflight_request(Req, Config) of
{ok, PreflightHeaders} ->
{ok, PreflightHeaders};
not_preflight ->
not_preflight;
UnknownError ->
couch_log:error(
"Unknown response of chttpd_cors:preflight_request(~p): ~p",
[Req, UnknownError]
),
not_preflight
end;
false ->
not_preflight
end.
preflight_request(Req, Config) ->
case get_origin(Req) of
undefined ->
not_preflight;
Origin ->
AcceptedOrigins = get_accepted_origins(Req, Config),
AcceptAll = lists:member(<<"*">>, AcceptedOrigins),
HandlerFun = fun() ->
handle_preflight_request(Req, Config, Origin)
end,
as the user agent will not follow redirects [ 1 ] . If the
of steps [ 1 ] .
[ 1 ] : /#resource-preflight-requests
TODO : Square against multi origin Security Considerations and the
case AcceptAll orelse lists:member(Origin, AcceptedOrigins) of
true -> HandlerFun();
false -> not_preflight
end
end.
handle_preflight_request(Req, Config, Origin) ->
case chttpd:header_value(Req, "Access-Control-Request-Method") of
undefined ->
If there is no Access - Control - Request - Method header
not_preflight;
Method ->
SupportedMethods = get_origin_config(Config, Origin,
<<"allow_methods">>, ?SUPPORTED_METHODS),
SupportedHeaders = get_origin_config(Config, Origin,
<<"allow_headers">>, ?SUPPORTED_HEADERS),
get age
MaxAge = couch_util:get_value(<<"max_age">>, Config,
?CORS_DEFAULT_MAX_AGE),
PreflightHeaders0 = maybe_add_credentials(Config, Origin, [
{"Access-Control-Allow-Origin", binary_to_list(Origin)},
{"Access-Control-Max-Age", MaxAge},
{"Access-Control-Allow-Methods",
string:join(SupportedMethods, ", ")}]),
case lists:member(Method, SupportedMethods) of
true ->
AccessHeaders = chttpd:header_value(Req,
"Access-Control-Request-Headers"),
{FinalReqHeaders, ReqHeaders} = case AccessHeaders of
undefined -> {"", []};
"" -> {"", []};
Headers ->
RH = [to_lower(H)
|| H <- split_headers(Headers)],
{Headers, RH}
end,
case ReqHeaders -- SupportedHeaders of
[] ->
PreflightHeaders = PreflightHeaders0 ++
[{"Access-Control-Allow-Headers",
FinalReqHeaders}],
{ok, PreflightHeaders};
_ ->
not_preflight
end;
false ->
not_preflight
end
end.
headers(Req, RequestHeaders) ->
case get_origin(Req) of
undefined ->
RequestHeaders;
Origin ->
headers(Req, RequestHeaders, Origin, get_cors_config(Req))
end.
headers(_Req, RequestHeaders, undefined, _Config) ->
RequestHeaders;
headers(Req, RequestHeaders, Origin, Config) when is_list(Origin) ->
headers(Req, RequestHeaders, ?l2b(string:to_lower(Origin)), Config);
headers(Req, RequestHeaders, Origin, Config) ->
case is_cors_enabled(Config) of
true ->
AcceptedOrigins = get_accepted_origins(Req, Config),
CorsHeaders = handle_headers(Config, Origin, AcceptedOrigins),
ExposedCouchHeaders = couch_util:get_value(
<<"exposed_headers">>, Config, ?COUCH_HEADERS),
maybe_apply_headers(CorsHeaders, RequestHeaders, ExposedCouchHeaders);
false ->
RequestHeaders
end.
maybe_apply_headers([], RequestHeaders, _ExposedCouchHeaders) ->
RequestHeaders;
maybe_apply_headers(CorsHeaders, RequestHeaders, ExposedCouchHeaders) ->
expose those through Access - Control - Expose - Headers , allowing
ExposedHeaders0 = simple_headers([K || {K,_V} <- RequestHeaders]),
If Content - Type is not in ExposedHeaders , and the Content - Type
into the list of ExposedHeaders
ContentType = proplists:get_value("content-type", ExposedHeaders0),
IncludeContentType = case ContentType of
undefined ->
false;
_ ->
lists:member(string:to_lower(ContentType), ?SIMPLE_CONTENT_TYPE_VALUES)
end,
ExposedHeaders = case IncludeContentType of
false ->
["content-type" | lists:delete("content-type", ExposedHeaders0)];
true ->
ExposedHeaders0
end,
ExposedCouchHeaders may get added later , so expose them by default
ACEH = [{"Access-Control-Expose-Headers",
string:join(ExposedHeaders ++ ExposedCouchHeaders, ", ")}],
CorsHeaders ++ RequestHeaders ++ ACEH.
simple_headers(Headers) ->
LCHeaders = [to_lower(H) || H <- Headers],
lists:filter(fun(H) -> lists:member(H, ?SIMPLE_HEADERS) end, LCHeaders).
to_lower(String) when is_binary(String) ->
to_lower(?b2l(String));
to_lower(String) ->
string:to_lower(String).
handle_headers(_Config, _Origin, []) ->
[];
handle_headers(Config, Origin, AcceptedOrigins) ->
AcceptAll = lists:member(<<"*">>, AcceptedOrigins),
case AcceptAll orelse lists:member(Origin, AcceptedOrigins) of
true ->
make_cors_header(Config, Origin);
false ->
[]
end.
make_cors_header(Config, Origin) ->
Headers = [{"Access-Control-Allow-Origin", binary_to_list(Origin)}],
maybe_add_credentials(Config, Origin, Headers).
maybe_add_credentials(Config, Origin, Headers) ->
case allow_credentials(Config, Origin) of
false ->
Headers;
true ->
Headers ++ [{"Access-Control-Allow-Credentials", "true"}]
end.
allow_credentials(_Config, <<"*">>) ->
false;
allow_credentials(Config, Origin) ->
get_origin_config(Config, Origin, <<"allow_credentials">>,
?CORS_DEFAULT_ALLOW_CREDENTIALS).
get_cors_config(#httpd{cors_config = undefined, mochi_req = MochiReq}) ->
Host = couch_httpd_vhost:host(MochiReq),
EnableCors = config:get("httpd", "enable_cors", "false") =:= "true",
AllowCredentials = cors_config(Host, "credentials", "false") =:= "true",
AllowHeaders = case cors_config(Host, "headers", undefined) of
undefined ->
?SUPPORTED_HEADERS;
AllowHeaders0 ->
[to_lower(H) || H <- split_list(AllowHeaders0)]
end,
AllowMethods = case cors_config(Host, "methods", undefined) of
undefined ->
?SUPPORTED_METHODS;
AllowMethods0 ->
split_list(AllowMethods0)
end,
ExposedHeaders = case cors_config(Host, "exposed_headers", undefined) of
undefined ->
?COUCH_HEADERS;
ExposedHeaders0 ->
[to_lower(H) || H <- split_list(ExposedHeaders0)]
end,
MaxAge = cors_config(Host, "max_age", ?CORS_DEFAULT_MAX_AGE),
Origins0 = binary_split_list(cors_config(Host, "origins", [])),
Origins = [{O, {[]}} || O <- Origins0],
[
{<<"enable_cors">>, EnableCors},
{<<"allow_credentials">>, AllowCredentials},
{<<"allow_methods">>, AllowMethods},
{<<"allow_headers">>, AllowHeaders},
{<<"exposed_headers">>, ExposedHeaders},
{<<"max_age">>, MaxAge},
{<<"origins">>, {Origins}}
];
get_cors_config(#httpd{cors_config = Config}) ->
Config.
cors_config(Host, Key, Default) ->
config:get(cors_section(Host), Key,
config:get("cors", Key, Default)).
cors_section(HostValue) ->
HostPort = maybe_strip_scheme(HostValue),
Host = hd(string:tokens(HostPort, ":")),
"cors:" ++ Host.
maybe_strip_scheme(Host) ->
case string:str(Host, "://") of
0 -> Host;
N -> string:substr(Host, N + 3)
end.
is_cors_enabled(Config) ->
case get(disable_couch_httpd_cors) of
undefined ->
put(disable_couch_httpd_cors, true);
_ ->
ok
end,
couch_util:get_value(<<"enable_cors">>, Config, false).
get_origin_configs(Config) ->
{Origins} = couch_util:get_value(<<"origins">>, Config, {[]}),
Origins.
get_origin_config(Config, Origin) ->
OriginConfigs = get_origin_configs(Config),
{OriginConfig} = couch_util:get_value(Origin, OriginConfigs, {[]}),
OriginConfig.
get_origin_config(Config, Origin, Key, Default) ->
OriginConfig = get_origin_config(Config, Origin),
couch_util:get_value(Key, OriginConfig,
couch_util:get_value(Key, Config, Default)).
get_origin(Req) ->
case chttpd:header_value(Req, "Origin") of
undefined ->
undefined;
Origin ->
?l2b(Origin)
end.
get_accepted_origins(_Req, Config) ->
lists:map(fun({K,_V}) -> K end, get_origin_configs(Config)).
split_list(S) ->
re:split(S, "\\s*,\\s*", [trim, {return, list}]).
binary_split_list(S) ->
[list_to_binary(E) || E <- split_list(S)].
split_headers(H) ->
re:split(H, ",\\s*", [{return,list}, trim]).
|
cf8323082c6d945c89aa3449d0409e8e1fadcd71bb62f72c0dfe377e1d8bf8f2 | wboag/Scheme-NLP | test-ngrams.rkt | #lang racket
(require "../ngrams.rkt")
; Instantiate model
(define model-a (new ngram-model (n 2)))
(define model-b (new ngram-model (n 1)))
; Train model on input data
(send model-a train 'file "../data/greet.txt")
; Predict probabiity of a sentence
(newline)
(display "<probability>")
(newline)
(display (send model-a probability "John read Moby Dick"))
(newline)
(display (send model-a probability "Cher read a book"))
(newline)
(display (send model-a probability "Cher read a book" 'smooth 'additive 1))
(newline)
; Generate a random sequence of text
(newline)
(display "<generate>")
(newline)
(display (send model-a generate 10 '("<s>")))
(newline)
; Get frequencies
(newline)
(display "<get-frequencies>")
(newline)
(display (send model-a get-frequency '("John" "read") 'smooth 'additive 1))
(newline)
(display (send model-a get-frequency '("Cher" "read") 'smooth 'additive .03))
(newline)
(display (send model-a get-frequency '("a" "book")))
(newline)
(display (send model-a get-frequency '("John") 'smooth 'additive 1))
(newline) | null | https://raw.githubusercontent.com/wboag/Scheme-NLP/8899d49c689f2b147a0f0485110c5a7e2c97abca/testing/test-ngrams.rkt | racket | Instantiate model
Train model on input data
Predict probabiity of a sentence
Generate a random sequence of text
Get frequencies | #lang racket
(require "../ngrams.rkt")
(define model-a (new ngram-model (n 2)))
(define model-b (new ngram-model (n 1)))
(send model-a train 'file "../data/greet.txt")
(newline)
(display "<probability>")
(newline)
(display (send model-a probability "John read Moby Dick"))
(newline)
(display (send model-a probability "Cher read a book"))
(newline)
(display (send model-a probability "Cher read a book" 'smooth 'additive 1))
(newline)
(newline)
(display "<generate>")
(newline)
(display (send model-a generate 10 '("<s>")))
(newline)
(newline)
(display "<get-frequencies>")
(newline)
(display (send model-a get-frequency '("John" "read") 'smooth 'additive 1))
(newline)
(display (send model-a get-frequency '("Cher" "read") 'smooth 'additive .03))
(newline)
(display (send model-a get-frequency '("a" "book")))
(newline)
(display (send model-a get-frequency '("John") 'smooth 'additive 1))
(newline) |
1ac70fa83b8515a23c75d6bb900ba686554f5f5c02a6bd826b754ca41669750a | aitorres/firelink | FlowGraphGenerator.hs | module FireLink.BackEnd.FlowGraphGenerator(
generateFlowGraph, BasicBlock, NumberedBlock, FlowGraph,
entryVertex, exitVertex, getAllVariables, getProgramVariables
) where
import Data.Char (isDigit)
import Data.Graph
import Data.List (nub)
import Data.Maybe
import qualified Data.Set as Set
import FireLink.BackEnd.CodeGenerator (OperandType (..), TAC (..),
TACSymEntry (..),
catTACSymEntries,
isConditionalJump, isJump,
isProgramEnd,
isUnconditionalJump)
import FireLink.BackEnd.Utils
import TACType
-- | A numbered instruction (the number being a unique identifier within some context)
type NumberedTAC = (Int, TAC)
-- | Semantic shortcut for a list of numbered instructions
type NumberedTACs = [NumberedTAC]
| A group of TAC within a basic context
type BasicBlock = [TAC]
-- | Semantic shortcut for a list of basic blocks
type BasicBlocks = [BasicBlock]
| A numbered TAC block ( the number being a unique identifier within some context )
type NumberedBlock = (Int, BasicBlock)
-- | Semantic shortcut for a list of numbered blocks
type NumberedBlocks = [NumberedBlock]
-- | Semantic shortcut for a list of edges
type Edges = [Edge]
| FlowGraph representation . First tuple contains the basic blocks , with their respective number
-- | Second tuple position contains the graph with the basic block numbers as edges.
-- | Graph nodes includes -1 as entry node and `length numberedBlocks` as exit node
type FlowGraph = (NumberedBlocks, Graph)
-- | Generates and returns the flow graph
| that correspond to a given list of TAC instructions .
generateFlowGraph :: [TAC] -> FlowGraph
generateFlowGraph code =
let numberedInstructions = numberTACs code
basicBlocks = findBasicBlocks numberedInstructions
numberedBlocks = numberBlocks basicBlocks
fallEdges = getFallEdges numberedBlocks
entryEdge = (-1, 0) -- ENTRY
EXIT
jumpEdges = getJumpEdges numberedBlocks exitNode
edges = entryEdge : jumpEdges ++ fallEdges
graph = buildG (-1, length numberedBlocks) edges
in (numberedBlocks, graph)
-- | Helper to centralize what value is associated with flow graph entryVertex
entryVertex :: FlowGraph -> Vertex
entryVertex = const (-1)
-- | Same for exitVertex
exitVertex :: FlowGraph -> Vertex
exitVertex = length . fst
| Given an integer that represents an EXIT vertex , and a
-- | list of numbered blocks, returns a list of edges
-- | from blocks that end up in jumps to their jumped blocks,
| including jumps from exit blocks to the EXIT vertex
getJumpEdges :: NumberedBlocks -> Vertex -> Edges
getJumpEdges code vExit = foldr findAllJumpEdges [] code
where
findAllJumpEdges :: NumberedBlock -> Edges -> Edges
findAllJumpEdges (i, cb) es =
let lastInstr = last cb
ThreeAddressCode op _ dC dJ = lastInstr
in if isConditionalJump op || op == GoTo
then let (j, _) = findDestinyBlock dJ code
in (i, j) : es
else if isProgramEnd op then (i, vExit) : es
else es
findDestinyBlock :: Maybe OperandType -> NumberedBlocks -> NumberedBlock
findDestinyBlock d = head . filter (\(_, b) -> head b == ThreeAddressCode NewLabel Nothing d Nothing)
findFunctionDefBlock :: Vertex -> NumberedBlocks -> NumberedBlock
findFunctionDefBlock i = last . filter (\(i', cb) -> i' <= i && (isFuncLabel . head) cb)
isFuncLabel :: TAC -> Bool
isFuncLabel (ThreeAddressCode NewLabel _ (Just (Label s)) _) = let sc = head s in (not . isDigit) sc
isFuncLabel _ = False
getCallsToLabel :: Maybe OperandType -> NumberedBlocks -> [Vertex]
getCallsToLabel Nothing _ = []
getCallsToLabel (Just l) code =
let blocksEndingWithCall = filter (endsWithCallToLabel l) code
We add 1 because we should return to the block immediately following this one
in map ((+1) . fst) blocksEndingWithCall
endsWithCallToLabel :: OperandType -> NumberedBlock -> Bool
endsWithCallToLabel l (_, tacs) = let lastInstr = last tacs in isCallToLabel lastInstr l
isCallToLabel :: TAC -> OperandType -> Bool
isCallToLabel (ThreeAddressCode Call _ (Just l) _) l' = l == l'
isCallToLabel _ _ = False
-- | Given a list of numbered blocks, finds all fall edges, that is,
-- | edges from a block to its following block (fall-through edges)
-- | where applicable (i.e. if there are no unconditional jumps
| at the end of the first block )
getFallEdges :: NumberedBlocks -> Edges
getFallEdges [] = []
getFallEdges [x] = []
getFallEdges (x:ys@(y:_)) = case hasFallEdge x y of
Nothing -> getFallEdges ys
Just e -> e : getFallEdges ys
where
hasFallEdge :: NumberedBlock -> NumberedBlock -> Maybe Edge
hasFallEdge (i1, t1) (i2, _) =
let ThreeAddressCode op _ _ _ = last t1
in if isUnconditionalJump op || isProgramEnd op then Nothing else Just (i1, i2)
| Given a list of numbered TAC instructions , returns a list with
-- | their basic blocks
findBasicBlocks :: NumberedTACs -> BasicBlocks
findBasicBlocks t = let leaders = findBlockLeaders t in removeLineTags $ findBasicBlocks' t leaders
where
findBasicBlocks' :: NumberedTACs -> NumberedTACs -> [NumberedTACs]
findBasicBlocks' code leaders = groupBasicBlocks code (tail leaders) []
groupBasicBlocks :: NumberedTACs -> NumberedTACs -> NumberedTACs -> [NumberedTACs]
-- If I already recognized the last leader, then all remaining code is just one basic block
groupBasicBlocks code [] [] = [code]
groupBasicBlocks code@(c:cs) leaders@(l:ls) prevCode
| c == l = prevCode : groupBasicBlocks code ls []
| otherwise = groupBasicBlocks cs leaders (prevCode ++ [c])
removeLineTags :: [NumberedTACs] -> BasicBlocks
removeLineTags = map (map snd)
| Given a list of numbered TAC instructions , finds and returns
-- | a list of block leaders:
| 1 . The first instruction ( appended to the result of the aux function )
| 2 . The destiny of each jump ( workaround : since we only leave reachable labels , those are added )
| 3 . The next instruction after each jump / goto
| Conditions ( 2 ) and ( 3 ) are handled in the recursive , aux function
findBlockLeaders :: NumberedTACs -> NumberedTACs
findBlockLeaders ts = nub $ head ts : findBlockLeaders' ts
where
findBlockLeaders' :: NumberedTACs -> NumberedTACs
findBlockLeaders' [] = []
findBlockLeaders' [x] = []
findBlockLeaders' (x:ys@(y:_)) = [y | isJumpTac x] ++ [x | isJumpDestiny x] ++ findBlockLeaders' ys
isJumpTac :: NumberedTAC -> Bool
isJumpTac (_, ThreeAddressCode op _ _ _) = isJump op
isJumpDestiny :: NumberedTAC -> Bool
isJumpDestiny (_, ThreeAddressCode NewLabel _ (Just _) _) = True
isJumpDestiny _ = False
-- | Type-binding application of numberList for a code block
numberTACs :: [TAC] -> NumberedTACs
numberTACs = numberList
-- | Type-binding application of numberList for a list of code blocks
numberBlocks :: BasicBlocks -> NumberedBlocks
numberBlocks = numberList
-- | Given a basic block, builds and returns a list of the string-representation
-- | of all the variables used in the program (including temporals)
getAllVariables :: BasicBlock -> [TACSymEntry]
getAllVariables = foldr getVariables []
where
getVariables :: TAC -> [TACSymEntry] -> [TACSymEntry]
getVariables (ThreeAddressCode _ a b c) xs = xs ++ catTACSymEntries (catMaybes [a, b, c])
| Get all variables used in a list of " NumberedBlock "
getProgramVariables :: NumberedBlocks -> Set.Set TACSymEntry
getProgramVariables = Set.unions . map (Set.fromList . getAllVariables . snd)
| null | https://raw.githubusercontent.com/aitorres/firelink/075d7aad1c053a54e39a27d8db7c3c719d243225/src/FireLink/BackEnd/FlowGraphGenerator.hs | haskell | | A numbered instruction (the number being a unique identifier within some context)
| Semantic shortcut for a list of numbered instructions
| Semantic shortcut for a list of basic blocks
| Semantic shortcut for a list of numbered blocks
| Semantic shortcut for a list of edges
| Second tuple position contains the graph with the basic block numbers as edges.
| Graph nodes includes -1 as entry node and `length numberedBlocks` as exit node
| Generates and returns the flow graph
ENTRY
| Helper to centralize what value is associated with flow graph entryVertex
| Same for exitVertex
| list of numbered blocks, returns a list of edges
| from blocks that end up in jumps to their jumped blocks,
| Given a list of numbered blocks, finds all fall edges, that is,
| edges from a block to its following block (fall-through edges)
| where applicable (i.e. if there are no unconditional jumps
| their basic blocks
If I already recognized the last leader, then all remaining code is just one basic block
| a list of block leaders:
| Type-binding application of numberList for a code block
| Type-binding application of numberList for a list of code blocks
| Given a basic block, builds and returns a list of the string-representation
| of all the variables used in the program (including temporals) | module FireLink.BackEnd.FlowGraphGenerator(
generateFlowGraph, BasicBlock, NumberedBlock, FlowGraph,
entryVertex, exitVertex, getAllVariables, getProgramVariables
) where
import Data.Char (isDigit)
import Data.Graph
import Data.List (nub)
import Data.Maybe
import qualified Data.Set as Set
import FireLink.BackEnd.CodeGenerator (OperandType (..), TAC (..),
TACSymEntry (..),
catTACSymEntries,
isConditionalJump, isJump,
isProgramEnd,
isUnconditionalJump)
import FireLink.BackEnd.Utils
import TACType
type NumberedTAC = (Int, TAC)
type NumberedTACs = [NumberedTAC]
| A group of TAC within a basic context
type BasicBlock = [TAC]
type BasicBlocks = [BasicBlock]
| A numbered TAC block ( the number being a unique identifier within some context )
type NumberedBlock = (Int, BasicBlock)
type NumberedBlocks = [NumberedBlock]
type Edges = [Edge]
| FlowGraph representation . First tuple contains the basic blocks , with their respective number
type FlowGraph = (NumberedBlocks, Graph)
| that correspond to a given list of TAC instructions .
generateFlowGraph :: [TAC] -> FlowGraph
generateFlowGraph code =
let numberedInstructions = numberTACs code
basicBlocks = findBasicBlocks numberedInstructions
numberedBlocks = numberBlocks basicBlocks
fallEdges = getFallEdges numberedBlocks
EXIT
jumpEdges = getJumpEdges numberedBlocks exitNode
edges = entryEdge : jumpEdges ++ fallEdges
graph = buildG (-1, length numberedBlocks) edges
in (numberedBlocks, graph)
entryVertex :: FlowGraph -> Vertex
entryVertex = const (-1)
exitVertex :: FlowGraph -> Vertex
exitVertex = length . fst
| Given an integer that represents an EXIT vertex , and a
| including jumps from exit blocks to the EXIT vertex
getJumpEdges :: NumberedBlocks -> Vertex -> Edges
getJumpEdges code vExit = foldr findAllJumpEdges [] code
where
findAllJumpEdges :: NumberedBlock -> Edges -> Edges
findAllJumpEdges (i, cb) es =
let lastInstr = last cb
ThreeAddressCode op _ dC dJ = lastInstr
in if isConditionalJump op || op == GoTo
then let (j, _) = findDestinyBlock dJ code
in (i, j) : es
else if isProgramEnd op then (i, vExit) : es
else es
findDestinyBlock :: Maybe OperandType -> NumberedBlocks -> NumberedBlock
findDestinyBlock d = head . filter (\(_, b) -> head b == ThreeAddressCode NewLabel Nothing d Nothing)
findFunctionDefBlock :: Vertex -> NumberedBlocks -> NumberedBlock
findFunctionDefBlock i = last . filter (\(i', cb) -> i' <= i && (isFuncLabel . head) cb)
isFuncLabel :: TAC -> Bool
isFuncLabel (ThreeAddressCode NewLabel _ (Just (Label s)) _) = let sc = head s in (not . isDigit) sc
isFuncLabel _ = False
getCallsToLabel :: Maybe OperandType -> NumberedBlocks -> [Vertex]
getCallsToLabel Nothing _ = []
getCallsToLabel (Just l) code =
let blocksEndingWithCall = filter (endsWithCallToLabel l) code
We add 1 because we should return to the block immediately following this one
in map ((+1) . fst) blocksEndingWithCall
endsWithCallToLabel :: OperandType -> NumberedBlock -> Bool
endsWithCallToLabel l (_, tacs) = let lastInstr = last tacs in isCallToLabel lastInstr l
isCallToLabel :: TAC -> OperandType -> Bool
isCallToLabel (ThreeAddressCode Call _ (Just l) _) l' = l == l'
isCallToLabel _ _ = False
| at the end of the first block )
getFallEdges :: NumberedBlocks -> Edges
getFallEdges [] = []
getFallEdges [x] = []
getFallEdges (x:ys@(y:_)) = case hasFallEdge x y of
Nothing -> getFallEdges ys
Just e -> e : getFallEdges ys
where
hasFallEdge :: NumberedBlock -> NumberedBlock -> Maybe Edge
hasFallEdge (i1, t1) (i2, _) =
let ThreeAddressCode op _ _ _ = last t1
in if isUnconditionalJump op || isProgramEnd op then Nothing else Just (i1, i2)
| Given a list of numbered TAC instructions , returns a list with
findBasicBlocks :: NumberedTACs -> BasicBlocks
findBasicBlocks t = let leaders = findBlockLeaders t in removeLineTags $ findBasicBlocks' t leaders
where
findBasicBlocks' :: NumberedTACs -> NumberedTACs -> [NumberedTACs]
findBasicBlocks' code leaders = groupBasicBlocks code (tail leaders) []
groupBasicBlocks :: NumberedTACs -> NumberedTACs -> NumberedTACs -> [NumberedTACs]
groupBasicBlocks code [] [] = [code]
groupBasicBlocks code@(c:cs) leaders@(l:ls) prevCode
| c == l = prevCode : groupBasicBlocks code ls []
| otherwise = groupBasicBlocks cs leaders (prevCode ++ [c])
removeLineTags :: [NumberedTACs] -> BasicBlocks
removeLineTags = map (map snd)
| Given a list of numbered TAC instructions , finds and returns
| 1 . The first instruction ( appended to the result of the aux function )
| 2 . The destiny of each jump ( workaround : since we only leave reachable labels , those are added )
| 3 . The next instruction after each jump / goto
| Conditions ( 2 ) and ( 3 ) are handled in the recursive , aux function
findBlockLeaders :: NumberedTACs -> NumberedTACs
findBlockLeaders ts = nub $ head ts : findBlockLeaders' ts
where
findBlockLeaders' :: NumberedTACs -> NumberedTACs
findBlockLeaders' [] = []
findBlockLeaders' [x] = []
findBlockLeaders' (x:ys@(y:_)) = [y | isJumpTac x] ++ [x | isJumpDestiny x] ++ findBlockLeaders' ys
isJumpTac :: NumberedTAC -> Bool
isJumpTac (_, ThreeAddressCode op _ _ _) = isJump op
isJumpDestiny :: NumberedTAC -> Bool
isJumpDestiny (_, ThreeAddressCode NewLabel _ (Just _) _) = True
isJumpDestiny _ = False
numberTACs :: [TAC] -> NumberedTACs
numberTACs = numberList
numberBlocks :: BasicBlocks -> NumberedBlocks
numberBlocks = numberList
getAllVariables :: BasicBlock -> [TACSymEntry]
getAllVariables = foldr getVariables []
where
getVariables :: TAC -> [TACSymEntry] -> [TACSymEntry]
getVariables (ThreeAddressCode _ a b c) xs = xs ++ catTACSymEntries (catMaybes [a, b, c])
| Get all variables used in a list of " NumberedBlock "
getProgramVariables :: NumberedBlocks -> Set.Set TACSymEntry
getProgramVariables = Set.unions . map (Set.fromList . getAllVariables . snd)
|
722fd41dbb738afb8cf3a41cb1af14cbc95324e1857b098d23286be7493255a5 | scicloj/metamorph.ml | persistence_tools.clj | (ns scicloj.metamorph.persistence-tools
(:require [clojure.test :as t]
[clojure.tools.reader :as tr]
[clojure.tools.reader.reader-types :as rts]
[clojure.java.classpath]
[scicloj.metamorph.ml.evaluation-handler :as eval]
[clojure.repl]))
(defn keys-in
"Returns a sequence of all key paths in a given map using DFS walk."
[m]
(letfn [(children [node]
(let [v (get-in m node)]
(if (map? v)
(map (fn [x] (conj node x)) (keys v))
[])))
(branch? [node] (-> (children node) seq boolean))]
(->> (keys m)
(map vector)
(mapcat #(tree-seq branch? children %)))))
(defn find-model-data [m]
(->>
(keys-in m)
(filter #(= :model-data (last %)))))
| null | https://raw.githubusercontent.com/scicloj/metamorph.ml/7070dfbdd0561f9534be117a02d6b152e5d3baad/test/scicloj/metamorph/persistence_tools.clj | clojure | (ns scicloj.metamorph.persistence-tools
(:require [clojure.test :as t]
[clojure.tools.reader :as tr]
[clojure.tools.reader.reader-types :as rts]
[clojure.java.classpath]
[scicloj.metamorph.ml.evaluation-handler :as eval]
[clojure.repl]))
(defn keys-in
"Returns a sequence of all key paths in a given map using DFS walk."
[m]
(letfn [(children [node]
(let [v (get-in m node)]
(if (map? v)
(map (fn [x] (conj node x)) (keys v))
[])))
(branch? [node] (-> (children node) seq boolean))]
(->> (keys m)
(map vector)
(mapcat #(tree-seq branch? children %)))))
(defn find-model-data [m]
(->>
(keys-in m)
(filter #(= :model-data (last %)))))
|
|
ab368244bb847ab391990f747105af31212e4ec50706207a919b04cd3d25d5ef | dcastro/twenty48 | main.hs | # LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Concurrent.Async
import Control.Monad.Random (MonadRandom)
import Data.Function ((&))
import qualified Data.List as L
import Data.List.NonEmpty (NonEmpty)
import qualified Data.List.NonEmpty as NE
import Data.Monoid (Sum (..))
import qualified Data.Strict.Maybe as M
import Game.AlphaBeta
import Game.Optimized.Board
import Game.Optimized.Moves
import Game.Types hiding (Score)
import Import
-- | Play the game n number of times and print the average number of wins/score.
-- | This is used for tuning the heuristic function.
main :: IO ()
main = do
boardScores <- map NE.fromList $ replicateConcurrently runs (randomInitialBoard >>= playGame depth)
putStrLn $ "Depth: " <> tshow depth
putStrLn $ "Runs: " <> tshow runs
putStrLn $ "Average score: " <> tshow (averageScore (map snd boardScores))
putStrLn $ "Win rate: " <> tshow (winRate (map fst boardScores)) <> "%"
where
runs = 1000
depth = 3
type Score = Int
type Depth = Int
averageScore :: NonEmpty Score -> Double
averageScore xs = fromIntegral (sum xs) / fromIntegral (NE.length xs)
winRate :: NonEmpty Board -> Double
winRate boards =
fromIntegral (length wins) / fromIntegral (NE.length boards) * 100
where
won b = any (>= twenty48) $ join $ boardToLists b
wins = NE.filter won boards
twenty48 = truncate $ logBase 2 2048
randomInitialBoard :: (MonadIO m, MonadRandom m) => m Board
randomInitialBoard =
emptyBoard & placeCell >>= placeCell
where
emptyBoard = boardFromLists $ replicate 4 $ replicate 4 0
placeCell board = do
cell <- randomCell
coordMb <- randomCoord board
case coordMb of
Nothing -> error "nope"
Just coord -> pure $ playComputer (Computer coord cell) board
playGame :: (MonadIO m, MonadRandom m) => Depth -> Board -> m (Board, Score)
playGame depth b = playGame' 0 b
where
playGame' :: (MonadIO m, MonadRandom m) => Depth -> Board -> m (Board, Score)
playGame' score board = do
case alphaBeta board depth of
M.Nothing -> pure (board, score)
M.Just player ->
let newBoard = playPlayer player board
newScore = score + scoreUp player board
in randomComputerMove newBoard >>= \case
Nothing -> pure (newBoard, newScore)
Just computer -> playGame' newScore (playComputer computer newBoard)
scoreUp :: Player -> Board -> Score
scoreUp (Player d) b =
scoreUp' d (boardToLists b)
where
scoreUp' :: Direction -> [[Cell]] -> Score
scoreUp' dir rows =
case dir of
L -> getSum $ foldMap (Sum . scoreUpRow . filter isOccupied) rows
R -> scoreUp' L rows
U -> scoreUp' L (L.transpose rows)
D -> scoreUp' U rows
| looks at a row ( stripped of zeroes ) , and returns how many points the user would gain from moving
-- | the pieces to the right
-- | (or to the left, it doesn't matter).
scoreUpRow :: [Cell] -> Score
scoreUpRow (Cell x : Cell y : xs)
| x == y = 2 * powerOfTwo x + scoreUpRow xs
| otherwise = scoreUpRow (Cell y : xs)
where powerOfTwo n = 2 ^ (fromIntegral n :: Int)
scoreUpRow _ = 0
| null | https://raw.githubusercontent.com/dcastro/twenty48/d4a58bfa389bb247525fd18f80ef428d84ef5fe9/eval/main.hs | haskell | # LANGUAGE OverloadedStrings #
| Play the game n number of times and print the average number of wins/score.
| This is used for tuning the heuristic function.
| the pieces to the right
| (or to the left, it doesn't matter). | # LANGUAGE LambdaCase #
module Main where
import Control.Concurrent.Async
import Control.Monad.Random (MonadRandom)
import Data.Function ((&))
import qualified Data.List as L
import Data.List.NonEmpty (NonEmpty)
import qualified Data.List.NonEmpty as NE
import Data.Monoid (Sum (..))
import qualified Data.Strict.Maybe as M
import Game.AlphaBeta
import Game.Optimized.Board
import Game.Optimized.Moves
import Game.Types hiding (Score)
import Import
main :: IO ()
main = do
boardScores <- map NE.fromList $ replicateConcurrently runs (randomInitialBoard >>= playGame depth)
putStrLn $ "Depth: " <> tshow depth
putStrLn $ "Runs: " <> tshow runs
putStrLn $ "Average score: " <> tshow (averageScore (map snd boardScores))
putStrLn $ "Win rate: " <> tshow (winRate (map fst boardScores)) <> "%"
where
runs = 1000
depth = 3
type Score = Int
type Depth = Int
averageScore :: NonEmpty Score -> Double
averageScore xs = fromIntegral (sum xs) / fromIntegral (NE.length xs)
winRate :: NonEmpty Board -> Double
winRate boards =
fromIntegral (length wins) / fromIntegral (NE.length boards) * 100
where
won b = any (>= twenty48) $ join $ boardToLists b
wins = NE.filter won boards
twenty48 = truncate $ logBase 2 2048
randomInitialBoard :: (MonadIO m, MonadRandom m) => m Board
randomInitialBoard =
emptyBoard & placeCell >>= placeCell
where
emptyBoard = boardFromLists $ replicate 4 $ replicate 4 0
placeCell board = do
cell <- randomCell
coordMb <- randomCoord board
case coordMb of
Nothing -> error "nope"
Just coord -> pure $ playComputer (Computer coord cell) board
playGame :: (MonadIO m, MonadRandom m) => Depth -> Board -> m (Board, Score)
playGame depth b = playGame' 0 b
where
playGame' :: (MonadIO m, MonadRandom m) => Depth -> Board -> m (Board, Score)
playGame' score board = do
case alphaBeta board depth of
M.Nothing -> pure (board, score)
M.Just player ->
let newBoard = playPlayer player board
newScore = score + scoreUp player board
in randomComputerMove newBoard >>= \case
Nothing -> pure (newBoard, newScore)
Just computer -> playGame' newScore (playComputer computer newBoard)
scoreUp :: Player -> Board -> Score
scoreUp (Player d) b =
scoreUp' d (boardToLists b)
where
scoreUp' :: Direction -> [[Cell]] -> Score
scoreUp' dir rows =
case dir of
L -> getSum $ foldMap (Sum . scoreUpRow . filter isOccupied) rows
R -> scoreUp' L rows
U -> scoreUp' L (L.transpose rows)
D -> scoreUp' U rows
| looks at a row ( stripped of zeroes ) , and returns how many points the user would gain from moving
scoreUpRow :: [Cell] -> Score
scoreUpRow (Cell x : Cell y : xs)
| x == y = 2 * powerOfTwo x + scoreUpRow xs
| otherwise = scoreUpRow (Cell y : xs)
where powerOfTwo n = 2 ^ (fromIntegral n :: Int)
scoreUpRow _ = 0
|
5026db7015ae8eceaafaa586526a8c43f4aed35ab1d1c096e3ea0a75aff6f562 | tonymorris/fp-course | AsWin.hs | # LANGUAGE NoImplicitPrelude #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE FlexibleInstances #
{-# LANGUAGE GADTs #-}
module TicTacToe.AsWin(
AsWin(_Win)
) where
import Control.Applicative(Applicative)
import Control.Lens(Optic, Choice, _1, _Left)
import Data.Either(Either)
import Data.Functor(Functor)
class AsWin p f o where
_Win ::
Optic p f (o w a) (o x a) w x
instance (Choice p, Applicative f) => AsWin p f Either where
_Win =
_Left
instance (p ~ (->), Functor f) => AsWin p f (,) where
_Win =
_1
| null | https://raw.githubusercontent.com/tonymorris/fp-course/73a64c3d4d0df58654a1a9a0ee9d9b11c3818911/projects/TicTacToe/haskell/src/TicTacToe/AsWin.hs | haskell | # LANGUAGE GADTs # | # LANGUAGE NoImplicitPrelude #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE FlexibleInstances #
module TicTacToe.AsWin(
AsWin(_Win)
) where
import Control.Applicative(Applicative)
import Control.Lens(Optic, Choice, _1, _Left)
import Data.Either(Either)
import Data.Functor(Functor)
class AsWin p f o where
_Win ::
Optic p f (o w a) (o x a) w x
instance (Choice p, Applicative f) => AsWin p f Either where
_Win =
_Left
instance (p ~ (->), Functor f) => AsWin p f (,) where
_Win =
_1
|
02136a99b1aff6ac25b0c31d3f4909fa57ce7180fa89ae23ba1c640ee54385e7 | xapi-project/xenopsd | squeeze_test.ml |
* Copyright ( C ) 2006 - 2009 Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
* Copyright (C) 2006-2009 Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*)
(** Simulation environment and set of unit tests for the domain memory balancer. *)
module D = Debug.Make (struct let name = "squeeze_test" end)
open D
open! Squeeze
* Computes the memory_actual delta for a VM assuming the balloon driver
responds at a given speed . Warning : make sure the balloon_rate * time_passed
is > 0 when rounded to an integer .
responds at a given speed. Warning: make sure the balloon_rate * time_passed
is > 0 when rounded to an integer. *)
let compute_memory_actual_delta domain rate time =
let max_change = Int64.of_float (time *. Int64.to_float rate) in
(* compute the direction of travel of the balloon *)
let vector =
if domain.memory_actual_kib > domain.target_kib then -1L else 1L
in
let distance = (domain.target_kib -* domain.memory_actual_kib) ** vector in
(* We stop when we get to 'inaccuracy_kib' *)
let distance' = max 0L (distance -* domain.inaccuracy_kib) in
(* don't exceed the target *)
let distance'' = min distance' max_change in
distance'' ** vector
class virtual vm initial_domain =
object (self)
val mutable domain = initial_domain
val mutable time_of_last_update = 0.
(** Return the current domain state *)
method get_domain = domain
(** Helper function to change the domain's balloon target *)
method set_target new_target_kib =
if new_target_kib <> domain.target_kib then
debug "domid %d: target change was %Ld now %Ld (max %Ld)" domain.domid
domain.target_kib new_target_kib domain.memory_max_kib ;
if new_target_kib > domain.memory_max_kib then
failwith
(Printf.sprintf
"Target set above max_mem domid %d; max_mem = %Ld; target = %Ld"
domain.domid domain.memory_max_kib new_target_kib
) ;
domain <- {domain with target_kib= new_target_kib}
(** Helper function to set the domain's maxmem *)
method set_maxmem new_max_kib =
if domain.target_kib > new_max_kib then
failwith
(Printf.sprintf
"mem_max set below target domid %d; max_mem = %Ld; target = %Ld"
domain.domid new_max_kib domain.target_kib
) ;
domain <- {domain with memory_max_kib= new_max_kib}
(** Given a number of time units since the last call to 'update', compute
the expected change in memory_actual. Note that this might be
unfulfilled if the host is low on memory. *)
method virtual compute_memory_actual_delta : float -> int64
(** Called by the simulator to update memory_actual. It also returns
memory_actual so the host free memory total can be updated. *)
method update host_free_mem time =
let time_passed = time -. time_of_last_update in
(* We can release as much memory as we like but *)
(* we can't allocate more than is available *)
let delta = self#compute_memory_actual_delta time_passed in
(* By construction it should never be possible for a domain to wish to
allocate more memory than exists. *)
if delta > host_free_mem then
failwith
(Printf.sprintf
"Attempted to allocate more than host_free_mem domid = %d; delta \
= %Ld; free = %Ld"
domain.domid delta host_free_mem
) ;
domain <-
{domain with memory_actual_kib= domain.memory_actual_kib +* delta} ;
time_of_last_update <- time ;
delta
(* if -ve this means host memory increased *)
end
(** Represents a VM whose balloon driver responds at a certain speed *)
class idealised_vm initial_domain balloon_rate_kib_per_unit_time =
object
inherit vm initial_domain
method compute_memory_actual_delta time_passed =
compute_memory_actual_delta domain balloon_rate_kib_per_unit_time
time_passed
end
(** Represents a VM whose balloon driver responds at a certain speed but which
has a minimum limit *)
class idealised_vm_with_limit initial_domain balloon_rate_kib_per_unit_time
minimum_memory =
object
inherit vm initial_domain
method compute_memory_actual_delta time_passed =
let delta =
compute_memory_actual_delta domain balloon_rate_kib_per_unit_time
time_passed
in
let proposed_new_memory_actual = domain.memory_actual_kib +* delta in
(* If the proposed_new_memory_actual is bigger than our memory actual *)
(* then this is always ok. *)
(* If the proposed value is smaller but greater than the minumum then *)
(* this is always ok too. *)
(* If the proposed value is smaller and less than the minimum then *)
(* this is clipped. *)
if
proposed_new_memory_actual > domain.memory_actual_kib
|| proposed_new_memory_actual > minimum_memory
then
delta
else
minimum_memory -* domain.memory_actual_kib
(* this takes us to the minimum *)
end
(** Represents a VM which fails to allocate above a certain threshold *)
class idealised_vm_with_upper_limit initial_domain rate limit =
object
inherit vm initial_domain
method compute_memory_actual_delta time_passed =
let delta = compute_memory_actual_delta domain rate time_passed in
let proposed_new_memory_actual = domain.memory_actual_kib +* delta in
if proposed_new_memory_actual < limit then
delta
else
limit -* domain.memory_actual_kib
end
(** Represents a VM whose balloon driver has completely failed *)
class stuck_vm initial_domain =
object
inherit vm initial_domain
method compute_memory_actual_delta _ = 0L
end
* Represents a VM whose balloon driver moves at a constant rate but gets stuck
for ' interval ' seconds every ' interval ' seconds
for 'interval' seconds every 'interval' seconds *)
class intermittently_stuck_vm initial_domain balloon_rate_kib_per_unit_time
interval =
object
inherit vm initial_domain
method compute_memory_actual_delta time_passed =
(* Every interval we switch from stuck to non-stuck. Assume for *)
(* simplicity that time_passed < 1 and that our timesteps are *)
(* suitably small that we disregard transients. *)
let notstuck t = int_of_float (t /. interval) mod 2 = 0 in
let useful_time =
if
notstuck time_of_last_update
&& notstuck (time_of_last_update +. time_passed)
then
time_passed
else
0.
in
debug "useful_time = %.2f (current actual = %Ld; target = %Ld)"
useful_time domain.memory_actual_kib domain.target_kib ;
compute_memory_actual_delta domain balloon_rate_kib_per_unit_time
useful_time
end
type scenario = {
name: string
; description: string
; should_succeed: bool
; scenario_domains: vm list
; host_free_mem_kib: int64
; required_mem_kib: int64
; fistpoints: Squeeze.fistpoint list
}
let scenario_a =
{
name= "a"
; description=
"a small domain with a hidden limit and a large domain which exhibits \
'sticky' behaviour"
; should_succeed= true
; scenario_domains=
[
new idealised_vm_with_limit
(domain_make 0 true 1000L 1500L 2000L 1500L 1500L 4L)
100L 1250L
; new intermittently_stuck_vm
(domain_make 1 true 2500L 3500L 4500L 3500L 3500L 4L)
500L 0.25
]
; host_free_mem_kib= 0L
; required_mem_kib= 1000L
; fistpoints= []
}
let scenario_b =
{
name= "b"
; description=
"two domains exhibiting 'sticky' behaviour with different periods: one > \
than the assumed stuck interval and the other <"
; should_succeed= true
; scenario_domains=
[
new intermittently_stuck_vm
(domain_make 1 true 500L 3500L 4500L 3500L 3500L 4L)
100L 3.
; new intermittently_stuck_vm
(domain_make 0 true 500L 1500L 2500L 1500L 1500L 4L)
100L 1.5
]
; host_free_mem_kib= 0L
; required_mem_kib= 1000L
; fistpoints= []
}
let scenario_c =
{
name= "c"
; description= "dynamic_mins are too high to allow enough memory to be freed"
; should_succeed= false
; scenario_domains=
[
new idealised_vm
(domain_make 0 true 1000L 1500L 2000L 1500L 1500L 0L)
100L
; new idealised_vm
(domain_make 1 true 2000L 2500L 3000L 2500L 2500L 0L)
100L
]
; host_free_mem_kib= 0L
; required_mem_kib= 1500L
; fistpoints= []
}
let scenario_d =
{
name= "d"
; description=
"looks ok but one VM is permanently stuck above its dynamic_min"
; should_succeed= false
; scenario_domains=
[
new idealised_vm
(domain_make 0 true 1000L 1500L 2000L 1500L 1500L 0L)
100L
; new idealised_vm_with_limit
(domain_make 1 true 2000L 2500L 3000L 2500L 2500L 0L)
100L 2250L
]
; host_free_mem_kib= 0L
; required_mem_kib= 1000L
; fistpoints= []
}
let scenario_e =
{
name= "e"
; description=
"one domain needs to free but is stuck, other domain needs to allocate \
but can't because there is not enough free memory. We need to give up \
on the stuck domain first and then tell the other domain to free rather \
than allocate. We must not conclude the second domain is stuck because \
it can't allocate."
; should_succeed= true
; scenario_domains=
[
(* The stuck domain is using more than it should be if the memory was
freed and everything balanced *)
new stuck_vm
(*actual*) 7000L 7000L 0L
)
; (* The working domain is using less than it should be if the memory was
freed and everything balanced *)
new idealised_vm
(*actual*) 6000L 6000L 0L
)
100L
]
; host_free_mem_kib= 0L
; required_mem_kib= 1000L
The system has 3000L units of surplus memory . Ideally we 'd give 1000L to
the system and then split the remaining 2000L units proportionally
amongst the domains : 500L to 0 and 1500L to 1 . If both domains were ideal
then we could set 0 's target to 5500L ( down ) and 1 's target to ( up )
However since the stuck domain is stuck this strategy will fail . In this
case we want the idealised VM to release the 1000L units of memory .
However the likely failure mode is that it will have been asked to
increase its allocation and been unable to do so because all host memory
is exhausted . It will then also have been marked as stuck and the
operation will fail .
the system and then split the remaining 2000L units proportionally
amongst the domains: 500L to 0 and 1500L to 1. If both domains were ideal
then we could set 0's target to 5500L (down) and 1's target to 6500L (up)
However since the stuck domain is stuck this strategy will fail. In this
case we want the idealised VM to release the 1000L units of memory.
However the likely failure mode is that it will have been asked to
increase its allocation and been unable to do so because all host memory
is exhausted. It will then also have been marked as stuck and the
operation will fail. *)
fistpoints= []
}
let scenario_f =
{
scenario_e with
name= "f"
; should_succeed= false
; fistpoints=
[Squeeze.DisableTwoPhaseTargetSets]
Since one domain is trying to allocate and the other free ( but is
stuck ) , the allocating domain will try to allocate more memory than is
free on the host IF we disable our two - phase setting of the domain
targets . In real life , xen allocates memory from the top down , keeping
memory < 4GiB until the end . This is important because some small
structures can only be placed in memory < 4GiB. If we give this memory
to a guest then the balloon driver may well only release memory > 4GiB
resulting in a system with memory free but memory allocation failures
on domain create .
stuck), the allocating domain will try to allocate more memory than is
free on the host IF we disable our two-phase setting of the domain
targets. In real life, xen allocates memory from the top down, keeping
memory < 4GiB until the end. This is important because some small
structures can only be placed in memory < 4GiB. If we give this memory
to a guest then the balloon driver may well only release memory > 4GiB
resulting in a system with memory free but memory allocation failures
on domain create. *)
}
let scenario_g =
{
scenario_a with
name= "g"
; should_succeed= false
; fistpoints=
[Squeeze.DisableInaccuracyCompensation]
The two domains are programmed to have an inaccuracy of 4KiB. We will
conclude that the domains are both stuck if we do n't take this into
account .
conclude that the domains are both stuck if we don't take this into
account. *)
}
let scenario_h =
{
name= "h"
; description=
"a small domain with a hidden upper limit and a perfectly working domain"
; should_succeed= true
; scenario_domains=
[
new idealised_vm_with_upper_limit
(domain_make 0 true 1000L 1500L 2000L 1500L 1500L 4L)
100L 1500L
; new idealised_vm
(domain_make 1 true 1000L 1500L 2000L 1500L 1500L 4L)
100L
(* this one can take up the slack *)
]
; host_free_mem_kib= 1000L
; required_mem_kib= 0L
; fistpoints= []
}
scenario_a with < 24L after the balancing will fail
let all_scenarios =
[
scenario_a
; scenario_b
; scenario_c
; scenario_d
; scenario_e
; scenario_f
; scenario_g
; scenario_h
]
let verify_memory_is_guaranteed_free host kib =
(* Each domain could set its memory_actual to this much and still be
considered ok *)
let extreme domain = domain.target_kib +* domain.inaccuracy_kib in
let increase domain = extreme domain -* domain.memory_actual_kib in
let total = List.fold_left ( +* ) 0L (List.map increase host.domains) in
if host.free_mem_kib -* total < kib then
failwith
(Printf.sprintf
"Memory not guaranteed free: free_mem = %Ld; total guests could take \
= %Ld; required free = %Ld"
host.free_mem_kib total kib
)
let files_created_by_scenario scenario =
[
Printf.sprintf "%s.dat" scenario.name
; Printf.sprintf "%s.out" scenario.name
; Printf.sprintf "%s.gp" scenario.name
]
(** Run a full simulation of the given scenario *)
let simulate scenario =
let host_free_mem_kib = ref scenario.host_free_mem_kib in
let all_domains = ref scenario.scenario_domains in
let domid_to_domain =
List.map (fun x -> (x#get_domain.domid, x)) !all_domains
in
(* Update all the recorded balloon targets *)
let execute_action (action : action) =
let domain = List.assoc action.action_domid domid_to_domain in
if action.new_target_kib > domain#get_domain.memory_max_kib then (
domain#set_maxmem action.new_target_kib ;
domain#set_target action.new_target_kib
) else (
domain#set_target action.new_target_kib ;
domain#set_maxmem action.new_target_kib
)
in
let setmaxmem domid kib =
debug "setmaxmem domid = %d; kib = %Ld" domid kib ;
execute_action {Squeeze.action_domid= domid; new_target_kib= kib}
in
(* Allow the simulated balloon drivers to change memory_actual_kib *)
(* and update host_free_memory accordingly. *)
let update_balloons time =
List.iter
(fun d ->
let delta = d#update !host_free_mem_kib time in
host_free_mem_kib := !host_free_mem_kib -* delta
)
!all_domains
in
let dat_filename = Printf.sprintf "%s.dat" scenario.name in
let out_filename = Printf.sprintf "%s.out" scenario.name in
let dat_oc = open_out dat_filename in
let out_oc = open_out out_filename in
let cols = [Gnuplot.Memory_actual; Gnuplot.Target] in
Gnuplot.write_header dat_oc cols ;
let i = ref 0 in
let gettimeofday () = float_of_int !i /. 10. in
let make_host () =
Squeeze.make_host ~free_mem_kib:!host_free_mem_kib
~domains:(List.map (fun d -> d#get_domain) !all_domains)
in
let wait _ =
incr i ;
let t = gettimeofday () in
update_balloons t ;
Gnuplot.write_row dat_oc (make_host ()) cols t
in
let io =
{
verbose= true
; Squeeze.gettimeofday
; make_host=
(fun () -> (Printf.sprintf "F%Ld" !host_free_mem_kib, make_host ()))
; domain_setmaxmem= setmaxmem
; wait
; execute_action
; target_host_free_mem_kib= scenario.required_mem_kib
; free_memory_tolerance_kib= 0L
}
in
Xapi_stdext_pervasives.Pervasiveext.finally
(fun () ->
(* Phase 1: attempt to free memory *)
debug "%s: attempting to free %Ld KiB" scenario.name
scenario.required_mem_kib ;
Squeeze.change_host_free_memory ~fistpoints:scenario.fistpoints io
scenario.required_mem_kib (fun x -> x >= scenario.required_mem_kib
) ;
debug "%s: %Ld KiB of memory has been freed" scenario.name
scenario.required_mem_kib ;
(* Check that even if all domains ballooned up to target + accuracy, this
much memory would still be free *)
verify_memory_is_guaranteed_free (make_host ()) scenario.required_mem_kib ;
Phase 2 : use some of this memory and return the rest to remaining VMs
host_free_mem_kib := !host_free_mem_kib -* 500L ;
Phase 3 : give free memory back to VMs
Squeeze.change_host_free_memory ~fistpoints:scenario.fistpoints io 0L
(fun x -> x <= 32L
) ;
debug "%s: After rebalancing only %Ld KiB of memory is used" scenario.name
!host_free_mem_kib ;
verify_memory_is_guaranteed_free (make_host ()) 0L
)
(fun () ->
close_out dat_oc ;
close_out out_oc ;
Gnuplot.write_gp scenario.name (make_host ()) cols
)
let failed_scenarios = ref []
let scenario_error_table = ref []
let run_test scenario =
try
simulate scenario ;
List.iter Xapi_stdext_unix.Unixext.unlink_safe
(files_created_by_scenario scenario) ;
if not scenario.should_succeed then (
failed_scenarios := scenario :: !failed_scenarios ;
scenario_error_table :=
(scenario, "simulation was expected tp fail but succeeded")
:: !scenario_error_table
)
with e ->
if scenario.should_succeed then (
failed_scenarios := scenario :: !failed_scenarios ;
scenario_error_table :=
( scenario
, Printf.sprintf "simulation was expected to succeed but failed: %s"
(Printexc.to_string e)
)
:: !scenario_error_table
) else
List.iter Xapi_stdext_unix.Unixext.unlink_safe
(files_created_by_scenario scenario)
let prepare_tests scenarios =
let prepare_test scenario =
(scenario.description, `Quick, fun () -> run_test scenario)
in
List.map prepare_test scenarios
let go () =
let suite = [("squeeze test", prepare_tests all_scenarios)] in
Debug.log_to_stdout () ;
Alcotest.run "squeeze suite" suite
| null | https://raw.githubusercontent.com/xapi-project/xenopsd/2a66192f4e23fd7ebd839980dc6e6078d02b7d81/squeezed/test/squeeze_test.ml | ocaml | * Simulation environment and set of unit tests for the domain memory balancer.
compute the direction of travel of the balloon
We stop when we get to 'inaccuracy_kib'
don't exceed the target
* Return the current domain state
* Helper function to change the domain's balloon target
* Helper function to set the domain's maxmem
* Given a number of time units since the last call to 'update', compute
the expected change in memory_actual. Note that this might be
unfulfilled if the host is low on memory.
* Called by the simulator to update memory_actual. It also returns
memory_actual so the host free memory total can be updated.
We can release as much memory as we like but
we can't allocate more than is available
By construction it should never be possible for a domain to wish to
allocate more memory than exists.
if -ve this means host memory increased
* Represents a VM whose balloon driver responds at a certain speed
* Represents a VM whose balloon driver responds at a certain speed but which
has a minimum limit
If the proposed_new_memory_actual is bigger than our memory actual
then this is always ok.
If the proposed value is smaller but greater than the minumum then
this is always ok too.
If the proposed value is smaller and less than the minimum then
this is clipped.
this takes us to the minimum
* Represents a VM which fails to allocate above a certain threshold
* Represents a VM whose balloon driver has completely failed
Every interval we switch from stuck to non-stuck. Assume for
simplicity that time_passed < 1 and that our timesteps are
suitably small that we disregard transients.
The stuck domain is using more than it should be if the memory was
freed and everything balanced
actual
The working domain is using less than it should be if the memory was
freed and everything balanced
actual
this one can take up the slack
Each domain could set its memory_actual to this much and still be
considered ok
* Run a full simulation of the given scenario
Update all the recorded balloon targets
Allow the simulated balloon drivers to change memory_actual_kib
and update host_free_memory accordingly.
Phase 1: attempt to free memory
Check that even if all domains ballooned up to target + accuracy, this
much memory would still be free |
* Copyright ( C ) 2006 - 2009 Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
* Copyright (C) 2006-2009 Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*)
module D = Debug.Make (struct let name = "squeeze_test" end)
open D
open! Squeeze
* Computes the memory_actual delta for a VM assuming the balloon driver
responds at a given speed . Warning : make sure the balloon_rate * time_passed
is > 0 when rounded to an integer .
responds at a given speed. Warning: make sure the balloon_rate * time_passed
is > 0 when rounded to an integer. *)
let compute_memory_actual_delta domain rate time =
let max_change = Int64.of_float (time *. Int64.to_float rate) in
let vector =
if domain.memory_actual_kib > domain.target_kib then -1L else 1L
in
let distance = (domain.target_kib -* domain.memory_actual_kib) ** vector in
let distance' = max 0L (distance -* domain.inaccuracy_kib) in
let distance'' = min distance' max_change in
distance'' ** vector
class virtual vm initial_domain =
object (self)
val mutable domain = initial_domain
val mutable time_of_last_update = 0.
method get_domain = domain
method set_target new_target_kib =
if new_target_kib <> domain.target_kib then
debug "domid %d: target change was %Ld now %Ld (max %Ld)" domain.domid
domain.target_kib new_target_kib domain.memory_max_kib ;
if new_target_kib > domain.memory_max_kib then
failwith
(Printf.sprintf
"Target set above max_mem domid %d; max_mem = %Ld; target = %Ld"
domain.domid domain.memory_max_kib new_target_kib
) ;
domain <- {domain with target_kib= new_target_kib}
method set_maxmem new_max_kib =
if domain.target_kib > new_max_kib then
failwith
(Printf.sprintf
"mem_max set below target domid %d; max_mem = %Ld; target = %Ld"
domain.domid new_max_kib domain.target_kib
) ;
domain <- {domain with memory_max_kib= new_max_kib}
method virtual compute_memory_actual_delta : float -> int64
method update host_free_mem time =
let time_passed = time -. time_of_last_update in
let delta = self#compute_memory_actual_delta time_passed in
if delta > host_free_mem then
failwith
(Printf.sprintf
"Attempted to allocate more than host_free_mem domid = %d; delta \
= %Ld; free = %Ld"
domain.domid delta host_free_mem
) ;
domain <-
{domain with memory_actual_kib= domain.memory_actual_kib +* delta} ;
time_of_last_update <- time ;
delta
end
class idealised_vm initial_domain balloon_rate_kib_per_unit_time =
object
inherit vm initial_domain
method compute_memory_actual_delta time_passed =
compute_memory_actual_delta domain balloon_rate_kib_per_unit_time
time_passed
end
class idealised_vm_with_limit initial_domain balloon_rate_kib_per_unit_time
minimum_memory =
object
inherit vm initial_domain
method compute_memory_actual_delta time_passed =
let delta =
compute_memory_actual_delta domain balloon_rate_kib_per_unit_time
time_passed
in
let proposed_new_memory_actual = domain.memory_actual_kib +* delta in
if
proposed_new_memory_actual > domain.memory_actual_kib
|| proposed_new_memory_actual > minimum_memory
then
delta
else
minimum_memory -* domain.memory_actual_kib
end
class idealised_vm_with_upper_limit initial_domain rate limit =
object
inherit vm initial_domain
method compute_memory_actual_delta time_passed =
let delta = compute_memory_actual_delta domain rate time_passed in
let proposed_new_memory_actual = domain.memory_actual_kib +* delta in
if proposed_new_memory_actual < limit then
delta
else
limit -* domain.memory_actual_kib
end
class stuck_vm initial_domain =
object
inherit vm initial_domain
method compute_memory_actual_delta _ = 0L
end
* Represents a VM whose balloon driver moves at a constant rate but gets stuck
for ' interval ' seconds every ' interval ' seconds
for 'interval' seconds every 'interval' seconds *)
class intermittently_stuck_vm initial_domain balloon_rate_kib_per_unit_time
interval =
object
inherit vm initial_domain
method compute_memory_actual_delta time_passed =
let notstuck t = int_of_float (t /. interval) mod 2 = 0 in
let useful_time =
if
notstuck time_of_last_update
&& notstuck (time_of_last_update +. time_passed)
then
time_passed
else
0.
in
debug "useful_time = %.2f (current actual = %Ld; target = %Ld)"
useful_time domain.memory_actual_kib domain.target_kib ;
compute_memory_actual_delta domain balloon_rate_kib_per_unit_time
useful_time
end
type scenario = {
name: string
; description: string
; should_succeed: bool
; scenario_domains: vm list
; host_free_mem_kib: int64
; required_mem_kib: int64
; fistpoints: Squeeze.fistpoint list
}
let scenario_a =
{
name= "a"
; description=
"a small domain with a hidden limit and a large domain which exhibits \
'sticky' behaviour"
; should_succeed= true
; scenario_domains=
[
new idealised_vm_with_limit
(domain_make 0 true 1000L 1500L 2000L 1500L 1500L 4L)
100L 1250L
; new intermittently_stuck_vm
(domain_make 1 true 2500L 3500L 4500L 3500L 3500L 4L)
500L 0.25
]
; host_free_mem_kib= 0L
; required_mem_kib= 1000L
; fistpoints= []
}
let scenario_b =
{
name= "b"
; description=
"two domains exhibiting 'sticky' behaviour with different periods: one > \
than the assumed stuck interval and the other <"
; should_succeed= true
; scenario_domains=
[
new intermittently_stuck_vm
(domain_make 1 true 500L 3500L 4500L 3500L 3500L 4L)
100L 3.
; new intermittently_stuck_vm
(domain_make 0 true 500L 1500L 2500L 1500L 1500L 4L)
100L 1.5
]
; host_free_mem_kib= 0L
; required_mem_kib= 1000L
; fistpoints= []
}
let scenario_c =
{
name= "c"
; description= "dynamic_mins are too high to allow enough memory to be freed"
; should_succeed= false
; scenario_domains=
[
new idealised_vm
(domain_make 0 true 1000L 1500L 2000L 1500L 1500L 0L)
100L
; new idealised_vm
(domain_make 1 true 2000L 2500L 3000L 2500L 2500L 0L)
100L
]
; host_free_mem_kib= 0L
; required_mem_kib= 1500L
; fistpoints= []
}
let scenario_d =
{
name= "d"
; description=
"looks ok but one VM is permanently stuck above its dynamic_min"
; should_succeed= false
; scenario_domains=
[
new idealised_vm
(domain_make 0 true 1000L 1500L 2000L 1500L 1500L 0L)
100L
; new idealised_vm_with_limit
(domain_make 1 true 2000L 2500L 3000L 2500L 2500L 0L)
100L 2250L
]
; host_free_mem_kib= 0L
; required_mem_kib= 1000L
; fistpoints= []
}
let scenario_e =
{
name= "e"
; description=
"one domain needs to free but is stuck, other domain needs to allocate \
but can't because there is not enough free memory. We need to give up \
on the stuck domain first and then tell the other domain to free rather \
than allocate. We must not conclude the second domain is stuck because \
it can't allocate."
; should_succeed= true
; scenario_domains=
[
new stuck_vm
)
new idealised_vm
)
100L
]
; host_free_mem_kib= 0L
; required_mem_kib= 1000L
The system has 3000L units of surplus memory . Ideally we 'd give 1000L to
the system and then split the remaining 2000L units proportionally
amongst the domains : 500L to 0 and 1500L to 1 . If both domains were ideal
then we could set 0 's target to 5500L ( down ) and 1 's target to ( up )
However since the stuck domain is stuck this strategy will fail . In this
case we want the idealised VM to release the 1000L units of memory .
However the likely failure mode is that it will have been asked to
increase its allocation and been unable to do so because all host memory
is exhausted . It will then also have been marked as stuck and the
operation will fail .
the system and then split the remaining 2000L units proportionally
amongst the domains: 500L to 0 and 1500L to 1. If both domains were ideal
then we could set 0's target to 5500L (down) and 1's target to 6500L (up)
However since the stuck domain is stuck this strategy will fail. In this
case we want the idealised VM to release the 1000L units of memory.
However the likely failure mode is that it will have been asked to
increase its allocation and been unable to do so because all host memory
is exhausted. It will then also have been marked as stuck and the
operation will fail. *)
fistpoints= []
}
let scenario_f =
{
scenario_e with
name= "f"
; should_succeed= false
; fistpoints=
[Squeeze.DisableTwoPhaseTargetSets]
Since one domain is trying to allocate and the other free ( but is
stuck ) , the allocating domain will try to allocate more memory than is
free on the host IF we disable our two - phase setting of the domain
targets . In real life , xen allocates memory from the top down , keeping
memory < 4GiB until the end . This is important because some small
structures can only be placed in memory < 4GiB. If we give this memory
to a guest then the balloon driver may well only release memory > 4GiB
resulting in a system with memory free but memory allocation failures
on domain create .
stuck), the allocating domain will try to allocate more memory than is
free on the host IF we disable our two-phase setting of the domain
targets. In real life, xen allocates memory from the top down, keeping
memory < 4GiB until the end. This is important because some small
structures can only be placed in memory < 4GiB. If we give this memory
to a guest then the balloon driver may well only release memory > 4GiB
resulting in a system with memory free but memory allocation failures
on domain create. *)
}
let scenario_g =
{
scenario_a with
name= "g"
; should_succeed= false
; fistpoints=
[Squeeze.DisableInaccuracyCompensation]
The two domains are programmed to have an inaccuracy of 4KiB. We will
conclude that the domains are both stuck if we do n't take this into
account .
conclude that the domains are both stuck if we don't take this into
account. *)
}
let scenario_h =
{
name= "h"
; description=
"a small domain with a hidden upper limit and a perfectly working domain"
; should_succeed= true
; scenario_domains=
[
new idealised_vm_with_upper_limit
(domain_make 0 true 1000L 1500L 2000L 1500L 1500L 4L)
100L 1500L
; new idealised_vm
(domain_make 1 true 1000L 1500L 2000L 1500L 1500L 4L)
100L
]
; host_free_mem_kib= 1000L
; required_mem_kib= 0L
; fistpoints= []
}
scenario_a with < 24L after the balancing will fail
let all_scenarios =
[
scenario_a
; scenario_b
; scenario_c
; scenario_d
; scenario_e
; scenario_f
; scenario_g
; scenario_h
]
let verify_memory_is_guaranteed_free host kib =
let extreme domain = domain.target_kib +* domain.inaccuracy_kib in
let increase domain = extreme domain -* domain.memory_actual_kib in
let total = List.fold_left ( +* ) 0L (List.map increase host.domains) in
if host.free_mem_kib -* total < kib then
failwith
(Printf.sprintf
"Memory not guaranteed free: free_mem = %Ld; total guests could take \
= %Ld; required free = %Ld"
host.free_mem_kib total kib
)
let files_created_by_scenario scenario =
[
Printf.sprintf "%s.dat" scenario.name
; Printf.sprintf "%s.out" scenario.name
; Printf.sprintf "%s.gp" scenario.name
]
let simulate scenario =
let host_free_mem_kib = ref scenario.host_free_mem_kib in
let all_domains = ref scenario.scenario_domains in
let domid_to_domain =
List.map (fun x -> (x#get_domain.domid, x)) !all_domains
in
let execute_action (action : action) =
let domain = List.assoc action.action_domid domid_to_domain in
if action.new_target_kib > domain#get_domain.memory_max_kib then (
domain#set_maxmem action.new_target_kib ;
domain#set_target action.new_target_kib
) else (
domain#set_target action.new_target_kib ;
domain#set_maxmem action.new_target_kib
)
in
let setmaxmem domid kib =
debug "setmaxmem domid = %d; kib = %Ld" domid kib ;
execute_action {Squeeze.action_domid= domid; new_target_kib= kib}
in
let update_balloons time =
List.iter
(fun d ->
let delta = d#update !host_free_mem_kib time in
host_free_mem_kib := !host_free_mem_kib -* delta
)
!all_domains
in
let dat_filename = Printf.sprintf "%s.dat" scenario.name in
let out_filename = Printf.sprintf "%s.out" scenario.name in
let dat_oc = open_out dat_filename in
let out_oc = open_out out_filename in
let cols = [Gnuplot.Memory_actual; Gnuplot.Target] in
Gnuplot.write_header dat_oc cols ;
let i = ref 0 in
let gettimeofday () = float_of_int !i /. 10. in
let make_host () =
Squeeze.make_host ~free_mem_kib:!host_free_mem_kib
~domains:(List.map (fun d -> d#get_domain) !all_domains)
in
let wait _ =
incr i ;
let t = gettimeofday () in
update_balloons t ;
Gnuplot.write_row dat_oc (make_host ()) cols t
in
let io =
{
verbose= true
; Squeeze.gettimeofday
; make_host=
(fun () -> (Printf.sprintf "F%Ld" !host_free_mem_kib, make_host ()))
; domain_setmaxmem= setmaxmem
; wait
; execute_action
; target_host_free_mem_kib= scenario.required_mem_kib
; free_memory_tolerance_kib= 0L
}
in
Xapi_stdext_pervasives.Pervasiveext.finally
(fun () ->
debug "%s: attempting to free %Ld KiB" scenario.name
scenario.required_mem_kib ;
Squeeze.change_host_free_memory ~fistpoints:scenario.fistpoints io
scenario.required_mem_kib (fun x -> x >= scenario.required_mem_kib
) ;
debug "%s: %Ld KiB of memory has been freed" scenario.name
scenario.required_mem_kib ;
verify_memory_is_guaranteed_free (make_host ()) scenario.required_mem_kib ;
Phase 2 : use some of this memory and return the rest to remaining VMs
host_free_mem_kib := !host_free_mem_kib -* 500L ;
Phase 3 : give free memory back to VMs
Squeeze.change_host_free_memory ~fistpoints:scenario.fistpoints io 0L
(fun x -> x <= 32L
) ;
debug "%s: After rebalancing only %Ld KiB of memory is used" scenario.name
!host_free_mem_kib ;
verify_memory_is_guaranteed_free (make_host ()) 0L
)
(fun () ->
close_out dat_oc ;
close_out out_oc ;
Gnuplot.write_gp scenario.name (make_host ()) cols
)
let failed_scenarios = ref []
let scenario_error_table = ref []
let run_test scenario =
try
simulate scenario ;
List.iter Xapi_stdext_unix.Unixext.unlink_safe
(files_created_by_scenario scenario) ;
if not scenario.should_succeed then (
failed_scenarios := scenario :: !failed_scenarios ;
scenario_error_table :=
(scenario, "simulation was expected tp fail but succeeded")
:: !scenario_error_table
)
with e ->
if scenario.should_succeed then (
failed_scenarios := scenario :: !failed_scenarios ;
scenario_error_table :=
( scenario
, Printf.sprintf "simulation was expected to succeed but failed: %s"
(Printexc.to_string e)
)
:: !scenario_error_table
) else
List.iter Xapi_stdext_unix.Unixext.unlink_safe
(files_created_by_scenario scenario)
let prepare_tests scenarios =
let prepare_test scenario =
(scenario.description, `Quick, fun () -> run_test scenario)
in
List.map prepare_test scenarios
let go () =
let suite = [("squeeze test", prepare_tests all_scenarios)] in
Debug.log_to_stdout () ;
Alcotest.run "squeeze suite" suite
|
4cd98e2a60cabab50fe3dc53b68726fb5b8a234ecb13d0530f3c4770efee091a | heraldry/heraldicon | variant.cljs | (ns spec.heraldry.charge.variant
(:require
[cljs.spec.alpha :as s]))
(s/def :heraldry.charge.variant/id string?)
(s/def :heraldry.charge.variant/version (s/nilable number?))
(s/def :heraldry.charge/variant (s/keys :opt-un [:heraldry.charge.variant/version]
:req-un [:heraldry.charge.variant/id]))
| null | https://raw.githubusercontent.com/heraldry/heraldicon/5b1ee92bdbeb8e4ad16fbdad3d7e83db3cda2ed7/src/spec/heraldry/charge/variant.cljs | clojure | (ns spec.heraldry.charge.variant
(:require
[cljs.spec.alpha :as s]))
(s/def :heraldry.charge.variant/id string?)
(s/def :heraldry.charge.variant/version (s/nilable number?))
(s/def :heraldry.charge/variant (s/keys :opt-un [:heraldry.charge.variant/version]
:req-un [:heraldry.charge.variant/id]))
|
|
b5124d050469e0626897a785cab5b6f7814a450eb2f7dbae7b32d068985073a6 | launchdarkly/erlang-server-sdk | ldclient_rollout.erl | %%-------------------------------------------------------------------
%% @doc Rollout data type
@private
%% @end
%%-------------------------------------------------------------------
-module(ldclient_rollout).
%% API
-export([new/1]).
-export([bucket_context/6]).
-export([rollout_context/3]).
%% Types
-type seed() :: non_neg_integer() | null.
-type rollout() :: #{
variations => [weighted_variation()],
bucketBy => ldclient_attribute_reference:attribute_reference(),
contextKind => ldclient_context:kind_value(),
kind => rollout_kind(),
seed => seed()
}.
%% Describes how contexts will be bucketed into variations during a percentage rollout
-type rollout_kind() :: rollout | experiment.
%% the type of rollout to use,
%% - rollout uses old hashing ignoring rollout:seed
%% - experiment uses new hashing
-type weighted_variation() :: #{
variation => ldclient_flag:variation(),
0 to 100000
untracked => boolean()
}.
%% Describes a fraction of contexts who will receive a specific variation
-type rollout_result() :: {
Variation :: ldclient_flag:variation(),
InExperiment :: boolean()
} | malformed_flag.
-export_type([rollout/0]).
-export_type([rollout_result/0]).
%%===================================================================
%% API
%%===================================================================
-spec new(map()) -> rollout().
new(#{<<"variations">> := Variations} = Map) ->
#{
variations => parse_variations(Variations),
bucketBy => get_bucket_by(Map),
kind => parse_rollout_kind(maps:get(<<"kind">>, Map, <<"rollout">>)),
seed => maps:get(<<"seed">>, Map, null),
contextKind => maps:get(<<"contextKind">>, Map, <<"user">>)
}.
-spec parse_rollout_kind(Kind :: binary()) -> rollout_kind().
parse_rollout_kind(<<"experiment">>) -> experiment;
parse_rollout_kind(<<"rollout">>) -> rollout;
parse_rollout_kind(Kind) ->
%% If we are not familiar with this kind, then log it and default to rollout.
error_logger:warning_msg("Unrecognized rollout type: ~p", [Kind]),
rollout.
-spec rollout_context(
Rollout :: rollout(),
Flag :: ldclient_flag:flag(),
Context :: ldclient_context:context()) -> rollout_result().
rollout_context(#{bucketBy := #{valid := false}} = _Rollout, _Flag, _Context) ->
malformed_flag;
rollout_context(#{
kind := experiment,
seed := Seed,
variations := WeightedVariations,
bucketBy := BucketBy,
contextKind := ContextKind
} = _Rollout,
#{key := FlagKey, salt := FlagSalt} = _Flag, Context) ->
HasContext = lists:member(ContextKind, ldclient_context:get_kinds(Context)),
Bucket = bucket_context(Seed, FlagKey, FlagSalt, Context, BucketBy, ContextKind),
#{variation := Variation, untracked := Untracked} = match_weighted_variations(Bucket, WeightedVariations),
%% If the context did not contain the kind, then we are not in an experiment.
{Variation, (not Untracked) and HasContext};
rollout_context(#{
variations := WeightedVariations,
bucketBy := BucketBy,
seed := Seed,
contextKind := ContextKind
} = _Rollout, #{key := FlagKey, salt := FlagSalt} = _Flag, Context) ->
Bucket = bucket_context(Seed, FlagKey, FlagSalt, Context, BucketBy,ContextKind),
VariationBucket = match_weighted_variations(Bucket, WeightedVariations),
extract_variation(VariationBucket, false).
extract_variation(null, false) -> {null, false};
extract_variation(#{variation := Variation}, InExperiment) ->
{Variation, InExperiment}.
-spec bucket_context(
Seed :: seed(),
Key :: ldclient_flag:key(),
Salt :: binary(),
Context :: ldclient_context:context(),
BucketBy :: ldclient_attribute_reference:attribute_reference(),
ContextKind :: ldclient_context:kind_value()) -> float().
bucket_context(Seed, Key, Salt, Context, BucketBy, ContextKind) ->
ContextValue = ldclient_context:get(ContextKind, BucketBy, Context),
bucket_context_value(Seed, Key, Salt, bucketable_value(ContextValue)).
%%===================================================================
Internal functions
%%===================================================================
-spec parse_variations([map()]) -> [weighted_variation()].
parse_variations(Variations) ->
F = fun(#{<<"variation">> := Variation} = Map, Acc) ->
Data = #{
variation => Variation,
weight => maps:get(<<"weight">>, Map, 0),
untracked => maps:get(<<"untracked">>, Map, false)
},
[Data|Acc];
(_, Acc) ->
Acc
end,
lists:foldr(F, [], Variations).
-spec match_weighted_variations(float(), [weighted_variation()]) -> weighted_variation() | null.
match_weighted_variations(_, []) -> null;
match_weighted_variations(Bucket, WeightedVariations) ->
match_weighted_variations(Bucket, WeightedVariations, 0.0).
-spec match_weighted_variations(float(), [weighted_variation()], float()) -> weighted_variation() | null.
match_weighted_variations(_Bucket, [], _Sum) -> null;
match_weighted_variations(_Bucket, [WeightedVariation|[]], _Sum) -> WeightedVariation;
match_weighted_variations(Bucket, [#{weight := Weight} = WeightedVariation|_], Sum)
when Bucket < Sum + Weight / 100000 ->
WeightedVariation;
match_weighted_variations(Bucket, [#{weight := Weight}|Rest], Sum) ->
match_weighted_variations(Bucket, Rest, Sum + Weight / 100000).
-spec bucket_context_value(
Seed :: seed(),
FlagKey :: ldclient_flag:key(),
Salt :: binary(),
ContextValue :: binary() | null) -> float().
bucket_context_value(null, _FlagKey, _Salt, null) -> 0.0;
%% when no seed is present hash with `key.salt.attribute`
bucket_context_value(null, FlagKey, Salt, ContextValue) ->
bucket_hash(<<FlagKey/binary, $., Salt/binary, $., ContextValue/binary>>);
%% when a seed is present hash with `seed.attribute`
bucket_context_value(Seed, _FlagKey, _Salt, ContextValue) ->
Prefix = integer_to_binary(Seed),
bucket_hash(<<Prefix/binary, $., ContextValue/binary>>).
-spec bucket_hash(binary()) -> float().
bucket_hash(Hash) ->
Sha1 = crypto:hash(sha, Hash),
Sha1Hex = lists:flatten([[io_lib:format("~2.16.0B",[X]) || <<X:8>> <= Sha1 ]]),
Sha1_15 = string:substr(Sha1Hex, 1, 15),
Int = list_to_integer(Sha1_15, 16),
Int / 1152921504606846975.
-spec bucketable_value(any()) -> binary() | null.
bucketable_value(V) when is_binary(V) -> V;
bucketable_value(V) when is_integer(V) -> list_to_binary(integer_to_list(V));
bucketable_value(V) when is_float(V) -> if V == trunc(V) -> list_to_binary(integer_to_list(trunc(V))); true -> null end;
bucketable_value(_) -> null.
%% @doc Get the attribute reference to bucket by.
%%
For experiments we always bucket by key , for other rollout kinds we bucket by the field . This is done when
%% parsing the flag, instead of when evaluating the flag, for performance and simplicity of evaluation.
%%
%% For backward compatibility we escape the attribute using our logic for legacy attributes when there is not
%% a context kind. New data should always have a contextKind.
%% @end
-spec get_bucket_by(RawRollout :: map()) -> ldclient_attribute_reference:attribute_reference().
get_bucket_by(#{<<"kind">> := <<"experiment">>} = _Rollout) -> ldclient_attribute_reference:new(<<"key">>);
get_bucket_by(RawRollout) ->
case maps:is_key(<<"contextKind">>, RawRollout) of
%% Had context kind, so it is new data and we do not need to escape.
true -> ldclient_attribute_reference:new(maps:get(<<"bucketBy">>, RawRollout, <<"key">>));
%% Did not have context kind, so we assume the data to be old, and we need to escape the attribute.
false -> ldclient_attribute_reference:new_from_legacy(maps:get(<<"bucketBy">>, RawRollout, <<"key">>))
end.
| null | https://raw.githubusercontent.com/launchdarkly/erlang-server-sdk/d9a4442a8a214bf950dec8182b26cd042436f4c8/src/ldclient_rollout.erl | erlang | -------------------------------------------------------------------
@doc Rollout data type
@end
-------------------------------------------------------------------
API
Types
Describes how contexts will be bucketed into variations during a percentage rollout
the type of rollout to use,
- rollout uses old hashing ignoring rollout:seed
- experiment uses new hashing
Describes a fraction of contexts who will receive a specific variation
===================================================================
API
===================================================================
If we are not familiar with this kind, then log it and default to rollout.
If the context did not contain the kind, then we are not in an experiment.
===================================================================
===================================================================
when no seed is present hash with `key.salt.attribute`
when a seed is present hash with `seed.attribute`
@doc Get the attribute reference to bucket by.
parsing the flag, instead of when evaluating the flag, for performance and simplicity of evaluation.
For backward compatibility we escape the attribute using our logic for legacy attributes when there is not
a context kind. New data should always have a contextKind.
@end
Had context kind, so it is new data and we do not need to escape.
Did not have context kind, so we assume the data to be old, and we need to escape the attribute. | @private
-module(ldclient_rollout).
-export([new/1]).
-export([bucket_context/6]).
-export([rollout_context/3]).
-type seed() :: non_neg_integer() | null.
-type rollout() :: #{
variations => [weighted_variation()],
bucketBy => ldclient_attribute_reference:attribute_reference(),
contextKind => ldclient_context:kind_value(),
kind => rollout_kind(),
seed => seed()
}.
-type rollout_kind() :: rollout | experiment.
-type weighted_variation() :: #{
variation => ldclient_flag:variation(),
0 to 100000
untracked => boolean()
}.
-type rollout_result() :: {
Variation :: ldclient_flag:variation(),
InExperiment :: boolean()
} | malformed_flag.
-export_type([rollout/0]).
-export_type([rollout_result/0]).
-spec new(map()) -> rollout().
new(#{<<"variations">> := Variations} = Map) ->
#{
variations => parse_variations(Variations),
bucketBy => get_bucket_by(Map),
kind => parse_rollout_kind(maps:get(<<"kind">>, Map, <<"rollout">>)),
seed => maps:get(<<"seed">>, Map, null),
contextKind => maps:get(<<"contextKind">>, Map, <<"user">>)
}.
-spec parse_rollout_kind(Kind :: binary()) -> rollout_kind().
parse_rollout_kind(<<"experiment">>) -> experiment;
parse_rollout_kind(<<"rollout">>) -> rollout;
parse_rollout_kind(Kind) ->
error_logger:warning_msg("Unrecognized rollout type: ~p", [Kind]),
rollout.
-spec rollout_context(
Rollout :: rollout(),
Flag :: ldclient_flag:flag(),
Context :: ldclient_context:context()) -> rollout_result().
rollout_context(#{bucketBy := #{valid := false}} = _Rollout, _Flag, _Context) ->
malformed_flag;
rollout_context(#{
kind := experiment,
seed := Seed,
variations := WeightedVariations,
bucketBy := BucketBy,
contextKind := ContextKind
} = _Rollout,
#{key := FlagKey, salt := FlagSalt} = _Flag, Context) ->
HasContext = lists:member(ContextKind, ldclient_context:get_kinds(Context)),
Bucket = bucket_context(Seed, FlagKey, FlagSalt, Context, BucketBy, ContextKind),
#{variation := Variation, untracked := Untracked} = match_weighted_variations(Bucket, WeightedVariations),
{Variation, (not Untracked) and HasContext};
rollout_context(#{
variations := WeightedVariations,
bucketBy := BucketBy,
seed := Seed,
contextKind := ContextKind
} = _Rollout, #{key := FlagKey, salt := FlagSalt} = _Flag, Context) ->
Bucket = bucket_context(Seed, FlagKey, FlagSalt, Context, BucketBy,ContextKind),
VariationBucket = match_weighted_variations(Bucket, WeightedVariations),
extract_variation(VariationBucket, false).
extract_variation(null, false) -> {null, false};
extract_variation(#{variation := Variation}, InExperiment) ->
{Variation, InExperiment}.
-spec bucket_context(
Seed :: seed(),
Key :: ldclient_flag:key(),
Salt :: binary(),
Context :: ldclient_context:context(),
BucketBy :: ldclient_attribute_reference:attribute_reference(),
ContextKind :: ldclient_context:kind_value()) -> float().
bucket_context(Seed, Key, Salt, Context, BucketBy, ContextKind) ->
ContextValue = ldclient_context:get(ContextKind, BucketBy, Context),
bucket_context_value(Seed, Key, Salt, bucketable_value(ContextValue)).
Internal functions
-spec parse_variations([map()]) -> [weighted_variation()].
parse_variations(Variations) ->
F = fun(#{<<"variation">> := Variation} = Map, Acc) ->
Data = #{
variation => Variation,
weight => maps:get(<<"weight">>, Map, 0),
untracked => maps:get(<<"untracked">>, Map, false)
},
[Data|Acc];
(_, Acc) ->
Acc
end,
lists:foldr(F, [], Variations).
-spec match_weighted_variations(float(), [weighted_variation()]) -> weighted_variation() | null.
match_weighted_variations(_, []) -> null;
match_weighted_variations(Bucket, WeightedVariations) ->
match_weighted_variations(Bucket, WeightedVariations, 0.0).
-spec match_weighted_variations(float(), [weighted_variation()], float()) -> weighted_variation() | null.
match_weighted_variations(_Bucket, [], _Sum) -> null;
match_weighted_variations(_Bucket, [WeightedVariation|[]], _Sum) -> WeightedVariation;
match_weighted_variations(Bucket, [#{weight := Weight} = WeightedVariation|_], Sum)
when Bucket < Sum + Weight / 100000 ->
WeightedVariation;
match_weighted_variations(Bucket, [#{weight := Weight}|Rest], Sum) ->
match_weighted_variations(Bucket, Rest, Sum + Weight / 100000).
-spec bucket_context_value(
Seed :: seed(),
FlagKey :: ldclient_flag:key(),
Salt :: binary(),
ContextValue :: binary() | null) -> float().
bucket_context_value(null, _FlagKey, _Salt, null) -> 0.0;
bucket_context_value(null, FlagKey, Salt, ContextValue) ->
bucket_hash(<<FlagKey/binary, $., Salt/binary, $., ContextValue/binary>>);
bucket_context_value(Seed, _FlagKey, _Salt, ContextValue) ->
Prefix = integer_to_binary(Seed),
bucket_hash(<<Prefix/binary, $., ContextValue/binary>>).
-spec bucket_hash(binary()) -> float().
bucket_hash(Hash) ->
Sha1 = crypto:hash(sha, Hash),
Sha1Hex = lists:flatten([[io_lib:format("~2.16.0B",[X]) || <<X:8>> <= Sha1 ]]),
Sha1_15 = string:substr(Sha1Hex, 1, 15),
Int = list_to_integer(Sha1_15, 16),
Int / 1152921504606846975.
-spec bucketable_value(any()) -> binary() | null.
bucketable_value(V) when is_binary(V) -> V;
bucketable_value(V) when is_integer(V) -> list_to_binary(integer_to_list(V));
bucketable_value(V) when is_float(V) -> if V == trunc(V) -> list_to_binary(integer_to_list(trunc(V))); true -> null end;
bucketable_value(_) -> null.
For experiments we always bucket by key , for other rollout kinds we bucket by the field . This is done when
-spec get_bucket_by(RawRollout :: map()) -> ldclient_attribute_reference:attribute_reference().
get_bucket_by(#{<<"kind">> := <<"experiment">>} = _Rollout) -> ldclient_attribute_reference:new(<<"key">>);
get_bucket_by(RawRollout) ->
case maps:is_key(<<"contextKind">>, RawRollout) of
true -> ldclient_attribute_reference:new(maps:get(<<"bucketBy">>, RawRollout, <<"key">>));
false -> ldclient_attribute_reference:new_from_legacy(maps:get(<<"bucketBy">>, RawRollout, <<"key">>))
end.
|
c6ed9f34ab31f84241aac8c4e41cec5d8b7bac85e54845cc9ba949d81aa2747d | discus-lang/ddc | BuilderX8664Darwin.hs | {-# OPTIONS_HADDOCK hide #-}
module DDC.Build.Builder.BuilderX8664Darwin where
import DDC.Build.Builder.Base
import qualified DDC.Core.Salt.Platform as Llvm
import qualified System.Directory as System
builder_X8664_Darwin config host mVersion
= Builder
{ builderName = "x86_64-darwin"
, buildHost = Platform ArchX86_64 (OsDarwin mVersion)
, buildTarget = Platform ArchX86_64 (OsDarwin mVersion)
, buildSpec = Llvm.platform64
, buildBaseSrcDir = builderConfigBaseSrcDir config
, buildBaseLibDir = builderConfigBaseLibDir config
, buildLlvmVersion = builderHostLlvmVersion host
, buildLlc
= \llFile sFile
-> doCmd "LLVM compiler" [(2, BuilderCanceled)]
[ builderHostLlvmBinPath host </> "opt"
, llFile
, "|"
, builderHostLlvmBinPath host </> "llc"
, "-O1 -march=x86-64 -relocation-model=pic"
, "-o", sFile ]
, buildCC
= \cFile oFile
-> doCmd "C compiler" [(2, BuilderCanceled)]
[ "cc -Werror -std=c99 -O3 -m64"
, "-c", cFile
, "-o", oFile
, "-I" ++ builderConfigBaseSrcDir config </> "ddc-runtime/sea" ]
, buildAs
= \sFile oFile
-> doCmd "assembler" [(2, BuilderCanceled)]
[ builderHostLlvmBinPath host </> "llvm-mc"
, "-filetype=obj"
From LLVM 3.8 we need to set the -triple explicitly which includes
the OS specifier . llc inserts a pragma into the output
.s files saying they 're for a specific version of . If we
do n't set the same version in the triple passed to llvm - mc then
it throws a warning . Note that is OSX v10.10.5 etc .
, case mVersion of
Nothing -> ""
Just (major, _minor, _patch)
-> "-triple=x86_64-apple-macosx10." ++ show (major - 4)
, "-o", oFile
, sFile ]
, buildLdExe
= \oFiles binFile -> do
let pathBuild = builderConfigBaseLibDir config
</> "ddc-runtime" </> "build"
let pathRuntime = pathBuild </> "libddc-runtime"
<.> (if builderConfigLinkStatic config
then "a" else "dylib")
doCmd "linker" [(2, BuilderCanceled)]
[ "cc -m64"
, "-Wl,-dead_strip"
, "-o", binFile
, intercalate " " oFiles
, pathRuntime ]
, buildLdLibStatic
= \oFiles libFile
-> doCmd "linker" [(2, BuilderCanceled)]
$ ["ar r", libFile] ++ oFiles
, buildLdLibShared
= \oFiles libFile -> do
-- The install_name is the intended install path of the dylib.
-- When executables are linked against a library with an install_name
-- set that path is added to the linker meta-data of the executable.
-- When the system then loads the executable it tries to find the dylib
-- at that previously set path.
--
-- Setting headerpad_max_install_names adds space to the header so
-- that the install_name can be rewritten to a longer one using
-- the command line install_name_tool.
--
libFile' <- System.makeAbsolute libFile
doCmd "linker" [(2, BuilderCanceled)]
$ [ "cc -m64"
, "-dynamiclib -undefined dynamic_lookup"
, "-install_name " ++ libFile'
, "-headerpad_max_install_names"
, "-o", libFile ] ++ oFiles
}
| null | https://raw.githubusercontent.com/discus-lang/ddc/2baa1b4e2d43b6b02135257677671a83cb7384ac/src/s1/ddc-build/DDC/Build/Builder/BuilderX8664Darwin.hs | haskell | # OPTIONS_HADDOCK hide #
The install_name is the intended install path of the dylib.
When executables are linked against a library with an install_name
set that path is added to the linker meta-data of the executable.
When the system then loads the executable it tries to find the dylib
at that previously set path.
Setting headerpad_max_install_names adds space to the header so
that the install_name can be rewritten to a longer one using
the command line install_name_tool.
|
module DDC.Build.Builder.BuilderX8664Darwin where
import DDC.Build.Builder.Base
import qualified DDC.Core.Salt.Platform as Llvm
import qualified System.Directory as System
builder_X8664_Darwin config host mVersion
= Builder
{ builderName = "x86_64-darwin"
, buildHost = Platform ArchX86_64 (OsDarwin mVersion)
, buildTarget = Platform ArchX86_64 (OsDarwin mVersion)
, buildSpec = Llvm.platform64
, buildBaseSrcDir = builderConfigBaseSrcDir config
, buildBaseLibDir = builderConfigBaseLibDir config
, buildLlvmVersion = builderHostLlvmVersion host
, buildLlc
= \llFile sFile
-> doCmd "LLVM compiler" [(2, BuilderCanceled)]
[ builderHostLlvmBinPath host </> "opt"
, llFile
, "|"
, builderHostLlvmBinPath host </> "llc"
, "-O1 -march=x86-64 -relocation-model=pic"
, "-o", sFile ]
, buildCC
= \cFile oFile
-> doCmd "C compiler" [(2, BuilderCanceled)]
[ "cc -Werror -std=c99 -O3 -m64"
, "-c", cFile
, "-o", oFile
, "-I" ++ builderConfigBaseSrcDir config </> "ddc-runtime/sea" ]
, buildAs
= \sFile oFile
-> doCmd "assembler" [(2, BuilderCanceled)]
[ builderHostLlvmBinPath host </> "llvm-mc"
, "-filetype=obj"
From LLVM 3.8 we need to set the -triple explicitly which includes
the OS specifier . llc inserts a pragma into the output
.s files saying they 're for a specific version of . If we
do n't set the same version in the triple passed to llvm - mc then
it throws a warning . Note that is OSX v10.10.5 etc .
, case mVersion of
Nothing -> ""
Just (major, _minor, _patch)
-> "-triple=x86_64-apple-macosx10." ++ show (major - 4)
, "-o", oFile
, sFile ]
, buildLdExe
= \oFiles binFile -> do
let pathBuild = builderConfigBaseLibDir config
</> "ddc-runtime" </> "build"
let pathRuntime = pathBuild </> "libddc-runtime"
<.> (if builderConfigLinkStatic config
then "a" else "dylib")
doCmd "linker" [(2, BuilderCanceled)]
[ "cc -m64"
, "-Wl,-dead_strip"
, "-o", binFile
, intercalate " " oFiles
, pathRuntime ]
, buildLdLibStatic
= \oFiles libFile
-> doCmd "linker" [(2, BuilderCanceled)]
$ ["ar r", libFile] ++ oFiles
, buildLdLibShared
= \oFiles libFile -> do
libFile' <- System.makeAbsolute libFile
doCmd "linker" [(2, BuilderCanceled)]
$ [ "cc -m64"
, "-dynamiclib -undefined dynamic_lookup"
, "-install_name " ++ libFile'
, "-headerpad_max_install_names"
, "-o", libFile ] ++ oFiles
}
|
045999a73532e227fb0b3ef2719ef47611506c005b98e591e360fa61357f3df4 | brown/city-hash | package.lisp |
(in-package #:common-lisp-user)
(defpackage #:city-hash
(:documentation "An implementation of the CityHash family of hash functions.")
(:use #:common-lisp #:com.google.base)
(:import-from #:nibbles
nibbles:ub32ref/le
nibbles:ub64ref/le)
(:import-from #:swap-bytes
swap-bytes:swap-bytes-32
swap-bytes:swap-bytes-64)
(:export #:city-hash-32
#:city-hash-64
#:city-hash-64-with-seed
#:city-hash-64-with-seeds
#:city-hash-128
#:city-hash-128-with-seed))
| null | https://raw.githubusercontent.com/brown/city-hash/47c236670a63330e86e7ba327e5526ed9843767b/package.lisp | lisp |
(in-package #:common-lisp-user)
(defpackage #:city-hash
(:documentation "An implementation of the CityHash family of hash functions.")
(:use #:common-lisp #:com.google.base)
(:import-from #:nibbles
nibbles:ub32ref/le
nibbles:ub64ref/le)
(:import-from #:swap-bytes
swap-bytes:swap-bytes-32
swap-bytes:swap-bytes-64)
(:export #:city-hash-32
#:city-hash-64
#:city-hash-64-with-seed
#:city-hash-64-with-seeds
#:city-hash-128
#:city-hash-128-with-seed))
|
|
9700180a4c844b140ccb62cf86389addd297300c1703535a2a798a38de2832a7 | yallop/ocaml-reex | test_match.ml |
* Copyright ( c ) 2022 .
*
* This file is distributed under the terms of the MIT License .
* See the file LICENSE for details .
* Copyright (c) 2022 Jeremy Yallop.
*
* This file is distributed under the terms of the MIT License.
* See the file LICENSE for details.
*)
open OUnit2
open Reex
let matches_ r = .< fun s -> .~(Reex_match.match_ .<0>. .<s>. [r,fun _ ~index ~len _ -> .<.~index = .~len>.] ~otherwise: .<false>.) >.
let matchn rs = .< fun s -> .~(Reex_match.match_ .<0>. .<s>.
(List.mapi (fun i r -> (r, fun _ ~index ~len:_ s -> .<(i, String.sub .~s 0 .~index)>.)) rs)
~otherwise: .<(-1, "")>.) >.
let rec repeat n x = if n = 0 then epsilon else x >>> repeat (pred n) x
let test_basics _ =
let (=~) = Runnative.run
and (/=~) r = Runnative.run .< fun s -> Stdlib.not (.~r s) >. in begin
let r1 = matches_ (chr 'a' >>> star (chr 'b') >>> chr 'a') in
assert (r1 /=~ "");
assert (r1 /=~ "a");
assert (r1 =~ "aa");
assert (r1 =~ "aba");
assert (r1 =~ "abbba");
assert (r1 /=~ "abbb");
assert (r1 /=~ "caba");
let r2 = matches_ (plus (range '0' '9')) in
assert (r2 /=~ "");
assert (r2 /=~ "a");
assert (r2 =~ "0");
assert (r2 =~ "0123");
assert (r2 =~ "4444");
let r3 = matches_ epsilon in
assert (r3 =~ "");
assert (r3 /=~ "a");
let r4 = matches_ empty in
assert (r4 /=~ "");
assert (r4 /=~ "a");
let r5 = matches_ (repeat 10 (opt (chr 'a')) >>> repeat 10 (chr 'a')) in
assert (r5 =~ "aaaaaaaaaa");
end
let test_longest_match _ =
let case = Runnative.run @@ matchn [regex "aa"; regex "a*b"] in
begin
assert_equal (0,"aa") (case "aa");
assert_equal (0,"aa") (case "aac");
assert_equal (0,"aa") (case "aaaaac");
assert_equal (1,"aab") (case "aab");
assert_equal (1,"ab") (case "abc");
assert_equal (1,"b") (case "baa");
end
let test_with_regenerate _ =
( 1 ) generate random regular expressions
( 2 ) generate random test cases for the regular expressions
(2) generate random test cases for the regular expressions *)
let check (re, pos, neg) =
1 . Compile the regular expression .
let cre = Runnative.run (matches_ re) in
2 . Test !
List.for_all (fun s -> cre s) pos &&
List.for_all (fun s -> Stdlib.not @@ cre s) neg
in
assert_equal 0 (QCheck_runner.run_tests ~verbose:true
[QCheck.Test.make Regex_generator.regex_testcase_gen check])
let suite = "Match tests" >::: [
"basics" >:: test_basics;
"longest " >:: test_longest_match;
(* "regenerate" >:: test_with_regenerate; *)
]
let _ =
run_test_tt_main suite
| null | https://raw.githubusercontent.com/yallop/ocaml-reex/94eea88bb06be5e295627f437d7a585bd9d9b0a6/tests/test_match.ml | ocaml | "regenerate" >:: test_with_regenerate; |
* Copyright ( c ) 2022 .
*
* This file is distributed under the terms of the MIT License .
* See the file LICENSE for details .
* Copyright (c) 2022 Jeremy Yallop.
*
* This file is distributed under the terms of the MIT License.
* See the file LICENSE for details.
*)
open OUnit2
open Reex
let matches_ r = .< fun s -> .~(Reex_match.match_ .<0>. .<s>. [r,fun _ ~index ~len _ -> .<.~index = .~len>.] ~otherwise: .<false>.) >.
let matchn rs = .< fun s -> .~(Reex_match.match_ .<0>. .<s>.
(List.mapi (fun i r -> (r, fun _ ~index ~len:_ s -> .<(i, String.sub .~s 0 .~index)>.)) rs)
~otherwise: .<(-1, "")>.) >.
let rec repeat n x = if n = 0 then epsilon else x >>> repeat (pred n) x
let test_basics _ =
let (=~) = Runnative.run
and (/=~) r = Runnative.run .< fun s -> Stdlib.not (.~r s) >. in begin
let r1 = matches_ (chr 'a' >>> star (chr 'b') >>> chr 'a') in
assert (r1 /=~ "");
assert (r1 /=~ "a");
assert (r1 =~ "aa");
assert (r1 =~ "aba");
assert (r1 =~ "abbba");
assert (r1 /=~ "abbb");
assert (r1 /=~ "caba");
let r2 = matches_ (plus (range '0' '9')) in
assert (r2 /=~ "");
assert (r2 /=~ "a");
assert (r2 =~ "0");
assert (r2 =~ "0123");
assert (r2 =~ "4444");
let r3 = matches_ epsilon in
assert (r3 =~ "");
assert (r3 /=~ "a");
let r4 = matches_ empty in
assert (r4 /=~ "");
assert (r4 /=~ "a");
let r5 = matches_ (repeat 10 (opt (chr 'a')) >>> repeat 10 (chr 'a')) in
assert (r5 =~ "aaaaaaaaaa");
end
let test_longest_match _ =
let case = Runnative.run @@ matchn [regex "aa"; regex "a*b"] in
begin
assert_equal (0,"aa") (case "aa");
assert_equal (0,"aa") (case "aac");
assert_equal (0,"aa") (case "aaaaac");
assert_equal (1,"aab") (case "aab");
assert_equal (1,"ab") (case "abc");
assert_equal (1,"b") (case "baa");
end
let test_with_regenerate _ =
( 1 ) generate random regular expressions
( 2 ) generate random test cases for the regular expressions
(2) generate random test cases for the regular expressions *)
let check (re, pos, neg) =
1 . Compile the regular expression .
let cre = Runnative.run (matches_ re) in
2 . Test !
List.for_all (fun s -> cre s) pos &&
List.for_all (fun s -> Stdlib.not @@ cre s) neg
in
assert_equal 0 (QCheck_runner.run_tests ~verbose:true
[QCheck.Test.make Regex_generator.regex_testcase_gen check])
let suite = "Match tests" >::: [
"basics" >:: test_basics;
"longest " >:: test_longest_match;
]
let _ =
run_test_tt_main suite
|
c762fd4a78a58d2c2e6b354fa8f560464f2c76fd3503ea5e40705c6cc4d49dbd | vikram/lisplibraries | errors.lisp | (in-package :trivial-sockets)
;; you're using a part of the interface that the implementation doesn't do
(define-condition unsupported (error)
((feature :initarg :feature :reader unsupported-feature))
(:report (lambda (c s)
(format s "~S does not support trivial-socket feature ~S."
(lisp-implementation-type) (unsupported-feature c)))))
;; all-purpose error: host not found, host not responding,
;; no service on that port, etc
(define-condition socket-error (error)
((nested-error :initarg :nested-error :reader socket-nested-error)))
| null | https://raw.githubusercontent.com/vikram/lisplibraries/105e3ef2d165275eb78f36f5090c9e2cdd0754dd/site/ucw-boxset/dependencies/trivial-sockets_until-i-can-merge-with-the-mainline/errors.lisp | lisp | you're using a part of the interface that the implementation doesn't do
all-purpose error: host not found, host not responding,
no service on that port, etc | (in-package :trivial-sockets)
(define-condition unsupported (error)
((feature :initarg :feature :reader unsupported-feature))
(:report (lambda (c s)
(format s "~S does not support trivial-socket feature ~S."
(lisp-implementation-type) (unsupported-feature c)))))
(define-condition socket-error (error)
((nested-error :initarg :nested-error :reader socket-nested-error)))
|
9a55c22c947c3abf91ac27ba397140548495c8c6bbc4fb5ec6db9787529606d8 | VisionsGlobalEmpowerment/webchange | add_text.clj | (ns webchange.templates.library.flipbook.add-text
(:require
[clojure.tools.logging :as log]
[webchange.templates.library.flipbook.display-names :refer [update-display-names]]
[webchange.templates.library.flipbook.add-page :refer [get-action-data]]
[webchange.utils.flipbook :as f]
[webchange.utils.scene-action-data :refer [create-text-animation-action]]
[webchange.utils.scene-data :as s]
[webchange.utils.text :refer [text->chunks]]))
(defn- get-text-name
[activity-data page-object-name]
(let [{:keys [children]} (->> (keyword page-object-name)
(s/get-scene-object activity-data))]
(str page-object-name "-text-" (count children))))
(defn get-text-data
[text {:keys [width padding]}]
(let [content {:text text
:chunks (text->chunks text)
:word-wrap true}
dimensions {:x padding
:y padding
:width (->> (* 2 padding) (- width))}
align {:align "left"
:vertical-align "top"}
font {:fill 0
:font-family "Lexend Deca"
:font-size 38}]
(merge {:type "text"
:editable? {:select true
:drag true}
:metadata {:removable? true}}
content dimensions align font)))
(defn- add-text-animation-action
[activity-data page-position {:keys [action object text-name text]}]
(if action
(let [text-action (create-text-animation-action {:inner-action {:target text-name
:phrase-text text}})]
(update-in activity-data [:actions (keyword action) :data] concat [text-action]))
(let [{:keys [name data]} (let [action-name (str object "-action")]
{:name action-name
:data (get-action-data {:action-name action-name
:text-name text-name
:text-value text})})
book-object-name (-> activity-data f/get-book-object-name keyword) ]
(-> activity-data
(assoc-in [:objects book-object-name :pages page-position :action] name)
(assoc-in [:actions (keyword name)] data)))))
(defn add-text
[activity-data page-idx {:keys [page-params]}]
(let [page-idx (or page-idx 0)
{:keys [action object]} (f/get-page-data activity-data page-idx)
text "Text"
text-name (get-text-name activity-data object)
text-data (get-text-data text page-params)]
(-> activity-data
(update :objects assoc (keyword text-name) text-data)
(update-in [:objects (keyword object) :children] concat [text-name])
(add-text-animation-action page-idx {:action action
:object object
:text-name text-name
:text text})
(update-display-names))))
| null | https://raw.githubusercontent.com/VisionsGlobalEmpowerment/webchange/d16f88e2e1dc8aa6acea26f7c45629b4242a32b4/src/clj/webchange/templates/library/flipbook/add_text.clj | clojure | (ns webchange.templates.library.flipbook.add-text
(:require
[clojure.tools.logging :as log]
[webchange.templates.library.flipbook.display-names :refer [update-display-names]]
[webchange.templates.library.flipbook.add-page :refer [get-action-data]]
[webchange.utils.flipbook :as f]
[webchange.utils.scene-action-data :refer [create-text-animation-action]]
[webchange.utils.scene-data :as s]
[webchange.utils.text :refer [text->chunks]]))
(defn- get-text-name
[activity-data page-object-name]
(let [{:keys [children]} (->> (keyword page-object-name)
(s/get-scene-object activity-data))]
(str page-object-name "-text-" (count children))))
(defn get-text-data
[text {:keys [width padding]}]
(let [content {:text text
:chunks (text->chunks text)
:word-wrap true}
dimensions {:x padding
:y padding
:width (->> (* 2 padding) (- width))}
align {:align "left"
:vertical-align "top"}
font {:fill 0
:font-family "Lexend Deca"
:font-size 38}]
(merge {:type "text"
:editable? {:select true
:drag true}
:metadata {:removable? true}}
content dimensions align font)))
(defn- add-text-animation-action
[activity-data page-position {:keys [action object text-name text]}]
(if action
(let [text-action (create-text-animation-action {:inner-action {:target text-name
:phrase-text text}})]
(update-in activity-data [:actions (keyword action) :data] concat [text-action]))
(let [{:keys [name data]} (let [action-name (str object "-action")]
{:name action-name
:data (get-action-data {:action-name action-name
:text-name text-name
:text-value text})})
book-object-name (-> activity-data f/get-book-object-name keyword) ]
(-> activity-data
(assoc-in [:objects book-object-name :pages page-position :action] name)
(assoc-in [:actions (keyword name)] data)))))
(defn add-text
[activity-data page-idx {:keys [page-params]}]
(let [page-idx (or page-idx 0)
{:keys [action object]} (f/get-page-data activity-data page-idx)
text "Text"
text-name (get-text-name activity-data object)
text-data (get-text-data text page-params)]
(-> activity-data
(update :objects assoc (keyword text-name) text-data)
(update-in [:objects (keyword object) :children] concat [text-name])
(add-text-animation-action page-idx {:action action
:object object
:text-name text-name
:text text})
(update-display-names))))
|
|
4cc0c127a21d68cf2950b440d495deec215b82edc92e908e4353d70d61e622e4 | bmeurer/ocamljit2 | oo.mli | (***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
(* the special exception on linking described in file ../LICENSE. *)
(* *)
(***********************************************************************)
$ Id$
(** Operations on objects *)
val copy : (< .. > as 'a) -> 'a
* [ o ] returns a copy of object [ o ] , that is a fresh
object with the same methods and instance variables as [ o ]
object with the same methods and instance variables as [o] *)
external id : < .. > -> int = "%field1"
(** Return an integer identifying this object, unique for
the current execution of the program. *)
(**/**)
(** For internal use (CamlIDL) *)
val new_method : string -> CamlinternalOO.tag
val public_method_label : string -> CamlinternalOO.tag
| null | https://raw.githubusercontent.com/bmeurer/ocamljit2/ef06db5c688c1160acc1de1f63c29473bcd0055c/stdlib/oo.mli | ocaml | *********************************************************************
Objective Caml
the special exception on linking described in file ../LICENSE.
*********************************************************************
* Operations on objects
* Return an integer identifying this object, unique for
the current execution of the program.
*/*
* For internal use (CamlIDL) | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
$ Id$
val copy : (< .. > as 'a) -> 'a
* [ o ] returns a copy of object [ o ] , that is a fresh
object with the same methods and instance variables as [ o ]
object with the same methods and instance variables as [o] *)
external id : < .. > -> int = "%field1"
val new_method : string -> CamlinternalOO.tag
val public_method_label : string -> CamlinternalOO.tag
|
68c5e04da8e38943880abce4cc7a4249e0ba31151b266e3d0b609b9f1d2593f2 | ecraven/r7rs-swank | gerbil.scm | (define ($scheme-name)
"gerbil-scheme")
(define (remove-underscores-and-trailing-numbers str)
(define last (- (string-length str) 1))
(cond ((char-numeric? (string-ref str last))
(remove-underscores-and-trailing-numbers (substring str 0 last)))
((char=? (string-ref str last) #\_)
(remove-underscores-and-trailing-numbers (substring str 0 last)))
((char=? (string-ref str 0) #\_)
(remove-underscores-and-trailing-numbers (substring str 1 (+ last 1))))
(else
(string->symbol str))))
(define (xmap fun lst)
(if (null? lst)
'()
(if (not (pair? lst))
(fun lst)
(cons (fun (car lst)) (xmap fun (cdr lst))))))
(define (unsyntax-bindings lst)
(xmap (lambda (sym)
(let ((s (symbol->string sym)))
(remove-underscores-and-trailing-numbers s)))
lst))
(define ($function-parameters-and-documentation name)
(let* ((binding (call/cc (lambda (k) (with-exception-handler (lambda (c) (k #f)) (lambda () (eval (string->symbol name) (param:environment)))))))
(source (if binding (##decompile binding) #f)))
(if (and source
(pair? source)
(not (null? source)))
(let ((s (car source)))
(case s
((lambda ##lambda)
(cons (cons (string->symbol name) (unsyntax-bindings (cadr source)))
(if (string? (caddr source)) (caddr source) #f)))
(else
(cons #f #f))))
(cons #f #f))))
(define ($set-package name)
(list name name))
(define ($open-tcp-server port-number port-file handler)
(let ((n (or port-number (+ 10000 (random-integer 40000)))))
(let* ((p (open-tcp-server n)))
(handler n p))))
(define ($tcp-server-accept p handler)
(let ((c (read p)))
(handler c c)))
(define hash-table-set! hash-put!)
(define hash-table-ref/default hash-ref)
(define hash-table-size hash-length)
;;(define hash-table? hash-table?)
(%#extern (hash-table? table?))
(define (hash-table-walk table fun) (hash-for-each fun table))
(define hash-table-delete! hash-remove!)
TODO remove when let - values works correctly
(define-syntax let-values
(syntax-rules ()
((let-values ((vals form)) body0 body ...)
(call-with-values (lambda () form) (lambda vals body0 body ...)))))
(define ($all-package-names)
(cons "(user)" (map expander-context-id (filter module-context? (map cdr (hash->list (current-expander-module-registry)))))))
(define ($error-description error)
(let ((o (open-output-string)))
(display-exception error o)
(get-output-string o)))
(define ($output-to-repl thunk)
;; basic implementation, print all output at the end, this should
;; be replaced with a custom output port
(let ((o (open-output-string)))
(parameterize ((current-output-port o)
(current-error-port o))
(let-values ((x (thunk)))
(swank/write-string (get-output-string o) #f)
(apply values x)))))
(define (env-name->environment env-name)
(cond ((or (and (string? env-name) (string=? env-name "(user)"))
(and (symbol? env-name) (eq? env-name 'nil)))
(gx#current-expander-context))
(else
(let ((name (string->symbol env-name)))
(find (lambda (e) (eq? (expander-context-id e) name))
(filter module-context? (map cdr (hash->list (current-expander-module-registry)))))))))
(define $environment env-name->environment)
(define (environment-bindings env-name)
(let ((env (env-name->environment env-name)))
(if env
(map car (hash->list (expander-context-table env)))
'())))
(define (string-match-forward a b)
(let* ((a-len (string-length a))
(b-len (string-length b))
(min-len (min a-len b-len)))
(let loop ((i 0))
(if (> i min-len)
(- i 1)
(if (string=? (substring a 0 i) (substring b 0 i))
(loop (+ i 1))
(- i 1))))))
(define (longest-common-prefix strings)
(if (null? strings)
""
(fold (lambda (s1 s2) (substring s2 0 (string-match-forward s1 s2))) (car strings) (cdr strings))))
(define ($completions prefix env-name)
(let ((matches (filter (lambda (el) (string-prefix? prefix el))
(map symbol->string (environment-bindings env-name)))))
(cons matches
(longest-common-prefix matches))))
(define ($condition-trace condition)
'())
(define ($frame-locals-and-catch-tags nr)
'())
(define ($frame-var-value frame index)
#f)
(define ($condition-msg condition)
"UNKNOWN")
(define ($condition-links condition)
'())
(define ($handle-condition exception)
#f)
(define ($pretty-print object)
(pp object (current-output-port)))
(define ($inspect-fallback object)
#f)
(define-record-type <istate>
(make-istate object parts actions next previous content)
istate?
(object istate-object)
(parts istate-parts)
(actions istate-actions)
(next istate-next set-istate-next!)
(previous istate-previous)
(content istate-content))
(define %repl-result-history-ref ##repl-result-history-ref)
(define (repl-result-history-ref id)
;; If we are swanky
(if (param:environment)
(call-with-values
(lambda () (swank:lookup-presented-object
(- last-presentation-id id)))
(lambda (value exists?)
(unless (eq? 'nil exists?)
value)))
;;otherwise, back to normal
(%repl-result-history-ref id)))
(define ($binding-documentation name)
#f)
(define ($apropos name)
'())
(define ($condition-location condition)
#f)
(define ($macroexpand-1 form)
form)
(define ($macroexpand-all form)
form)
| null | https://raw.githubusercontent.com/ecraven/r7rs-swank/c483de0397502e35f47f216bd73c84e714d7670c/specific/gerbil.scm | scheme | (define hash-table? hash-table?)
basic implementation, print all output at the end, this should
be replaced with a custom output port
If we are swanky
otherwise, back to normal | (define ($scheme-name)
"gerbil-scheme")
(define (remove-underscores-and-trailing-numbers str)
(define last (- (string-length str) 1))
(cond ((char-numeric? (string-ref str last))
(remove-underscores-and-trailing-numbers (substring str 0 last)))
((char=? (string-ref str last) #\_)
(remove-underscores-and-trailing-numbers (substring str 0 last)))
((char=? (string-ref str 0) #\_)
(remove-underscores-and-trailing-numbers (substring str 1 (+ last 1))))
(else
(string->symbol str))))
(define (xmap fun lst)
(if (null? lst)
'()
(if (not (pair? lst))
(fun lst)
(cons (fun (car lst)) (xmap fun (cdr lst))))))
(define (unsyntax-bindings lst)
(xmap (lambda (sym)
(let ((s (symbol->string sym)))
(remove-underscores-and-trailing-numbers s)))
lst))
(define ($function-parameters-and-documentation name)
(let* ((binding (call/cc (lambda (k) (with-exception-handler (lambda (c) (k #f)) (lambda () (eval (string->symbol name) (param:environment)))))))
(source (if binding (##decompile binding) #f)))
(if (and source
(pair? source)
(not (null? source)))
(let ((s (car source)))
(case s
((lambda ##lambda)
(cons (cons (string->symbol name) (unsyntax-bindings (cadr source)))
(if (string? (caddr source)) (caddr source) #f)))
(else
(cons #f #f))))
(cons #f #f))))
(define ($set-package name)
(list name name))
(define ($open-tcp-server port-number port-file handler)
(let ((n (or port-number (+ 10000 (random-integer 40000)))))
(let* ((p (open-tcp-server n)))
(handler n p))))
(define ($tcp-server-accept p handler)
(let ((c (read p)))
(handler c c)))
(define hash-table-set! hash-put!)
(define hash-table-ref/default hash-ref)
(define hash-table-size hash-length)
(%#extern (hash-table? table?))
(define (hash-table-walk table fun) (hash-for-each fun table))
(define hash-table-delete! hash-remove!)
TODO remove when let - values works correctly
(define-syntax let-values
(syntax-rules ()
((let-values ((vals form)) body0 body ...)
(call-with-values (lambda () form) (lambda vals body0 body ...)))))
(define ($all-package-names)
(cons "(user)" (map expander-context-id (filter module-context? (map cdr (hash->list (current-expander-module-registry)))))))
(define ($error-description error)
(let ((o (open-output-string)))
(display-exception error o)
(get-output-string o)))
(define ($output-to-repl thunk)
(let ((o (open-output-string)))
(parameterize ((current-output-port o)
(current-error-port o))
(let-values ((x (thunk)))
(swank/write-string (get-output-string o) #f)
(apply values x)))))
(define (env-name->environment env-name)
(cond ((or (and (string? env-name) (string=? env-name "(user)"))
(and (symbol? env-name) (eq? env-name 'nil)))
(gx#current-expander-context))
(else
(let ((name (string->symbol env-name)))
(find (lambda (e) (eq? (expander-context-id e) name))
(filter module-context? (map cdr (hash->list (current-expander-module-registry)))))))))
(define $environment env-name->environment)
(define (environment-bindings env-name)
(let ((env (env-name->environment env-name)))
(if env
(map car (hash->list (expander-context-table env)))
'())))
(define (string-match-forward a b)
(let* ((a-len (string-length a))
(b-len (string-length b))
(min-len (min a-len b-len)))
(let loop ((i 0))
(if (> i min-len)
(- i 1)
(if (string=? (substring a 0 i) (substring b 0 i))
(loop (+ i 1))
(- i 1))))))
(define (longest-common-prefix strings)
(if (null? strings)
""
(fold (lambda (s1 s2) (substring s2 0 (string-match-forward s1 s2))) (car strings) (cdr strings))))
(define ($completions prefix env-name)
(let ((matches (filter (lambda (el) (string-prefix? prefix el))
(map symbol->string (environment-bindings env-name)))))
(cons matches
(longest-common-prefix matches))))
(define ($condition-trace condition)
'())
(define ($frame-locals-and-catch-tags nr)
'())
(define ($frame-var-value frame index)
#f)
(define ($condition-msg condition)
"UNKNOWN")
(define ($condition-links condition)
'())
(define ($handle-condition exception)
#f)
(define ($pretty-print object)
(pp object (current-output-port)))
(define ($inspect-fallback object)
#f)
(define-record-type <istate>
(make-istate object parts actions next previous content)
istate?
(object istate-object)
(parts istate-parts)
(actions istate-actions)
(next istate-next set-istate-next!)
(previous istate-previous)
(content istate-content))
(define %repl-result-history-ref ##repl-result-history-ref)
(define (repl-result-history-ref id)
(if (param:environment)
(call-with-values
(lambda () (swank:lookup-presented-object
(- last-presentation-id id)))
(lambda (value exists?)
(unless (eq? 'nil exists?)
value)))
(%repl-result-history-ref id)))
(define ($binding-documentation name)
#f)
(define ($apropos name)
'())
(define ($condition-location condition)
#f)
(define ($macroexpand-1 form)
form)
(define ($macroexpand-all form)
form)
|
cc8a08005c9f667e2a4a2fede96809f18352cff5c124a19ebbe041a0d6f9c9ec | jgm/texmath | texmath.hs | # LANGUAGE CPP #
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Text.TeXMath
import Data.Char (isSpace)
import Text.XML.Light
import System.IO
import System.Environment
import System.Console.GetOpt
import System.Exit
import Data.Maybe
import Text.Pandoc.Definition
import Network.URI (unEscapeString)
import Data.Aeson (encode, (.=), object)
import qualified Data.ByteString.Lazy as B
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Data.Version ( showVersion )
import Text.Show.Pretty (ppShow)
import Paths_texmath (version)
tshow :: Show a => a -> T.Text
tshow = T.pack . ppShow
inHtml :: Element -> Element
inHtml e =
add_attr (Attr (unqual "xmlns") "") $
unode "html"
[ unode "head" $
add_attr (Attr (unqual "content") "application/xhtml+xml; charset=UTF-8") $
add_attr (Attr (unqual "http-equiv") "Content-Type") $
unode "meta" ()
, unode "body" e ]
type Reader = T.Text -> Either T.Text [Exp]
data Writer = XMLWriter (DisplayType -> [Exp] -> Element)
| StringWriter (DisplayType -> [Exp] -> T.Text)
| PandocWriter (DisplayType -> [Exp] -> Maybe [Inline])
readers :: [(T.Text, Reader)]
readers = [
("tex", readTeX)
, ("mathml", readMathML)
, ("omml", readOMML)
, ("native", readNative)]
readNative :: T.Text -> Either T.Text [Exp]
readNative s =
case reads (T.unpack s) of
((exps, ws):_) | all isSpace ws -> Right exps
((_, (_:_)):_) -> Left "Could not read whole input as native Exp"
_ -> Left "Could not read input as native Exp"
writers :: [(T.Text, Writer)]
writers = [
("native", StringWriter (\_ es -> tshow es) )
, ("tex", StringWriter (\_ -> writeTeX))
, ("eqn", StringWriter writeEqn)
, ("omml", XMLWriter writeOMML)
, ("xhtml", XMLWriter (\dt e -> inHtml (writeMathML dt e)))
, ("mathml", XMLWriter writeMathML)
, ("pandoc", PandocWriter writePandoc)]
data Options = Options {
optDisplay :: DisplayType
, optIn :: T.Text
, optOut :: T.Text }
def :: Options
def = Options DisplayBlock "tex" "mathml"
options :: [OptDescr (Options -> IO Options)]
options =
[ Option [] ["inline"]
(NoArg (\opts -> return opts {optDisplay = DisplayInline}))
"Use the inline display style"
, Option "f" ["from"]
(ReqArg (\s opts -> return opts {optIn = T.pack s}) "FORMAT")
("Input format: " <> T.unpack (T.intercalate ", " (map fst readers)))
, Option "t" ["to"]
(ReqArg (\s opts -> return opts {optOut = T.pack s}) "FORMAT")
("Output format: " <> T.unpack (T.intercalate ", " (map fst writers)))
, Option "v" ["version"]
(NoArg (\_ -> do
hPutStrLn stderr $ "Version " <> showVersion version
exitWith ExitSuccess))
"Print version"
, Option "h" ["help"]
(NoArg (\_ -> do
prg <- getProgName
hPutStrLn stderr (usageInfo (prg <> " [OPTIONS] [FILE*]") options)
exitWith ExitSuccess))
"Show help"
]
output :: DisplayType -> Writer -> [Exp] -> T.Text
output dt (XMLWriter w) es = output dt (StringWriter (\dt' -> T.pack . ppElement . w dt' )) es
output dt (StringWriter w) es = w dt es
output dt (PandocWriter w) es = tshow (fromMaybe fallback (w dt es))
where fallback = [Math mt $ writeTeX es]
mt = case dt of
DisplayBlock -> DisplayMath
DisplayInline -> InlineMath
err :: Bool -> Int -> T.Text -> IO a
err cgi code msg = do
if cgi
then B.putStr $ encode $ object ["error" .= msg]
else T.hPutStrLn stderr msg
exitWith $ ExitFailure code
ensureFinalNewline :: T.Text -> T.Text
ensureFinalNewline xs = case T.unsnoc xs of
Nothing -> xs
Just (_, '\n') -> xs
_ -> xs <> "\n"
urlUnencode :: T.Text -> T.Text
urlUnencode = T.pack . unEscapeString . plusToSpace . T.unpack
where plusToSpace ('+':xs) = "%20" <> plusToSpace xs
plusToSpace (x:xs) = x : plusToSpace xs
plusToSpace [] = []
main :: IO ()
main = do
progname <- getProgName
let cgi = progname == "texmath-cgi"
if cgi
then runCGI
else runCommandLine
runCommandLine :: IO ()
runCommandLine = do
args <- getArgs
let (actions, files, _) = getOpt RequireOrder options args
opts <- foldl (>>=) (return def) actions
inp <- case files of
[] -> T.getContents
_ -> T.concat <$> mapM T.readFile files
reader <- case lookup (optIn opts) readers of
Just r -> return r
Nothing -> err False 3 "Unrecognised reader"
writer <- case lookup (optOut opts) writers of
Just w -> return w
Nothing -> err False 5 "Unrecognised writer"
case reader inp of
Left msg -> err False 1 msg
Right v -> T.putStr $ ensureFinalNewline
$ output (optDisplay opts) writer v
exitWith ExitSuccess
runCGI :: IO ()
runCGI = do
query <- T.getContents
let topairs xs = case T.break (=='=') xs of
(ys, zs) -> case T.uncons zs of
Just ('=', zs') -> (urlUnencode ys, urlUnencode zs')
_ -> (urlUnencode ys, "")
let pairs = map topairs $ T.split (== '&') query
inp <- case lookup "input" pairs of
Just x -> return x
Nothing -> err True 3 "Query missing 'input'"
reader <- case lookup "from" pairs of
Just x -> case lookup x readers of
Just y -> return y
Nothing -> err True 5 "Unsupported value of 'from'"
Nothing -> err True 3 "Query missing 'from'"
writer <- case lookup "to" pairs of
Just x -> case lookup x writers of
Just y -> return y
Nothing -> err True 7 "Unsupported value of 'to'"
Nothing -> err True 3 "Query missing 'to'"
let inline = isJust $ lookup "inline" pairs
putStr "Content-type: text/json; charset=UTF-8\n\n"
case reader inp of
Left msg -> err True 1 msg
Right v -> B.putStr $ encode $ object
[ "success" .=
ensureFinalNewline (output
(if inline
then DisplayInline
else DisplayBlock) writer v) ]
exitWith ExitSuccess
| null | https://raw.githubusercontent.com/jgm/texmath/cac1b789a4d40730402c15111d5214a9a8577f81/extra/texmath.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE CPP #
module Main where
import Text.TeXMath
import Data.Char (isSpace)
import Text.XML.Light
import System.IO
import System.Environment
import System.Console.GetOpt
import System.Exit
import Data.Maybe
import Text.Pandoc.Definition
import Network.URI (unEscapeString)
import Data.Aeson (encode, (.=), object)
import qualified Data.ByteString.Lazy as B
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Data.Version ( showVersion )
import Text.Show.Pretty (ppShow)
import Paths_texmath (version)
tshow :: Show a => a -> T.Text
tshow = T.pack . ppShow
inHtml :: Element -> Element
inHtml e =
add_attr (Attr (unqual "xmlns") "") $
unode "html"
[ unode "head" $
add_attr (Attr (unqual "content") "application/xhtml+xml; charset=UTF-8") $
add_attr (Attr (unqual "http-equiv") "Content-Type") $
unode "meta" ()
, unode "body" e ]
type Reader = T.Text -> Either T.Text [Exp]
data Writer = XMLWriter (DisplayType -> [Exp] -> Element)
| StringWriter (DisplayType -> [Exp] -> T.Text)
| PandocWriter (DisplayType -> [Exp] -> Maybe [Inline])
readers :: [(T.Text, Reader)]
readers = [
("tex", readTeX)
, ("mathml", readMathML)
, ("omml", readOMML)
, ("native", readNative)]
readNative :: T.Text -> Either T.Text [Exp]
readNative s =
case reads (T.unpack s) of
((exps, ws):_) | all isSpace ws -> Right exps
((_, (_:_)):_) -> Left "Could not read whole input as native Exp"
_ -> Left "Could not read input as native Exp"
writers :: [(T.Text, Writer)]
writers = [
("native", StringWriter (\_ es -> tshow es) )
, ("tex", StringWriter (\_ -> writeTeX))
, ("eqn", StringWriter writeEqn)
, ("omml", XMLWriter writeOMML)
, ("xhtml", XMLWriter (\dt e -> inHtml (writeMathML dt e)))
, ("mathml", XMLWriter writeMathML)
, ("pandoc", PandocWriter writePandoc)]
data Options = Options {
optDisplay :: DisplayType
, optIn :: T.Text
, optOut :: T.Text }
def :: Options
def = Options DisplayBlock "tex" "mathml"
options :: [OptDescr (Options -> IO Options)]
options =
[ Option [] ["inline"]
(NoArg (\opts -> return opts {optDisplay = DisplayInline}))
"Use the inline display style"
, Option "f" ["from"]
(ReqArg (\s opts -> return opts {optIn = T.pack s}) "FORMAT")
("Input format: " <> T.unpack (T.intercalate ", " (map fst readers)))
, Option "t" ["to"]
(ReqArg (\s opts -> return opts {optOut = T.pack s}) "FORMAT")
("Output format: " <> T.unpack (T.intercalate ", " (map fst writers)))
, Option "v" ["version"]
(NoArg (\_ -> do
hPutStrLn stderr $ "Version " <> showVersion version
exitWith ExitSuccess))
"Print version"
, Option "h" ["help"]
(NoArg (\_ -> do
prg <- getProgName
hPutStrLn stderr (usageInfo (prg <> " [OPTIONS] [FILE*]") options)
exitWith ExitSuccess))
"Show help"
]
output :: DisplayType -> Writer -> [Exp] -> T.Text
output dt (XMLWriter w) es = output dt (StringWriter (\dt' -> T.pack . ppElement . w dt' )) es
output dt (StringWriter w) es = w dt es
output dt (PandocWriter w) es = tshow (fromMaybe fallback (w dt es))
where fallback = [Math mt $ writeTeX es]
mt = case dt of
DisplayBlock -> DisplayMath
DisplayInline -> InlineMath
err :: Bool -> Int -> T.Text -> IO a
err cgi code msg = do
if cgi
then B.putStr $ encode $ object ["error" .= msg]
else T.hPutStrLn stderr msg
exitWith $ ExitFailure code
ensureFinalNewline :: T.Text -> T.Text
ensureFinalNewline xs = case T.unsnoc xs of
Nothing -> xs
Just (_, '\n') -> xs
_ -> xs <> "\n"
urlUnencode :: T.Text -> T.Text
urlUnencode = T.pack . unEscapeString . plusToSpace . T.unpack
where plusToSpace ('+':xs) = "%20" <> plusToSpace xs
plusToSpace (x:xs) = x : plusToSpace xs
plusToSpace [] = []
main :: IO ()
main = do
progname <- getProgName
let cgi = progname == "texmath-cgi"
if cgi
then runCGI
else runCommandLine
runCommandLine :: IO ()
runCommandLine = do
args <- getArgs
let (actions, files, _) = getOpt RequireOrder options args
opts <- foldl (>>=) (return def) actions
inp <- case files of
[] -> T.getContents
_ -> T.concat <$> mapM T.readFile files
reader <- case lookup (optIn opts) readers of
Just r -> return r
Nothing -> err False 3 "Unrecognised reader"
writer <- case lookup (optOut opts) writers of
Just w -> return w
Nothing -> err False 5 "Unrecognised writer"
case reader inp of
Left msg -> err False 1 msg
Right v -> T.putStr $ ensureFinalNewline
$ output (optDisplay opts) writer v
exitWith ExitSuccess
runCGI :: IO ()
runCGI = do
query <- T.getContents
let topairs xs = case T.break (=='=') xs of
(ys, zs) -> case T.uncons zs of
Just ('=', zs') -> (urlUnencode ys, urlUnencode zs')
_ -> (urlUnencode ys, "")
let pairs = map topairs $ T.split (== '&') query
inp <- case lookup "input" pairs of
Just x -> return x
Nothing -> err True 3 "Query missing 'input'"
reader <- case lookup "from" pairs of
Just x -> case lookup x readers of
Just y -> return y
Nothing -> err True 5 "Unsupported value of 'from'"
Nothing -> err True 3 "Query missing 'from'"
writer <- case lookup "to" pairs of
Just x -> case lookup x writers of
Just y -> return y
Nothing -> err True 7 "Unsupported value of 'to'"
Nothing -> err True 3 "Query missing 'to'"
let inline = isJust $ lookup "inline" pairs
putStr "Content-type: text/json; charset=UTF-8\n\n"
case reader inp of
Left msg -> err True 1 msg
Right v -> B.putStr $ encode $ object
[ "success" .=
ensureFinalNewline (output
(if inline
then DisplayInline
else DisplayBlock) writer v) ]
exitWith ExitSuccess
|
cba528016c8bcea014ecf51280db7d594f07d9e88aacae834a3048bf9a99e564 | achirkin/vulkan | 02-GLFWWindow.hs | |
In this example , I follow first parts of vulkan-tutorial.com to create a window
and pick a device using GLFW .
Parts of the code are moved to Lib
In this example, I follow first parts of vulkan-tutorial.com to create a window
and pick a device using GLFW.
Parts of the code are moved to Lib
-}
module Main (main) where
import Control.Exception
import Control.Monad
import Foreign.Marshal.Alloc
import Foreign.Marshal.Array
import Foreign.Storable
import Graphics.UI.GLFW (ClientAPI (..), WindowHint (..))
import qualified Graphics.UI.GLFW as GLFW
import Graphics.Vulkan
import Graphics.Vulkan.Core_1_0
import Lib.Utils
import Lib.Vulkan (withVulkanInstance)
main :: IO ()
main = withGLFWWindow $ \window ->
withVulkanInstanceExt $ \vulkanInstance -> do
dev <- pickPhysicalDevice vulkanInstance
putStrLn $ "Selected device: " ++ show dev
glfwMainLoop window (return ())
withGLFWWindow :: (GLFW.Window -> IO ()) -> IO ()
withGLFWWindow action = do
GLFW.init >>= flip unless
(throwVKMsg "Failed to initialize GLFW.")
even if something bad happens , we need to terminate GLFW
flip finally (GLFW.terminate >> putStrLn "Terminated GLFW.") $ do
GLFW.getVersionString >>= mapM_ (putStrLn . ("GLFW version: " ++))
GLFW.vulkanSupported >>= flip unless
(throwVKMsg "GLFW reports that vulkan is not supported!")
GLFW.windowHint $ WindowHint'ClientAPI ClientAPI'NoAPI
GLFW.windowHint $ WindowHint'Resizable False
mw <- GLFW.createWindow 800 600 "Vulkan window" Nothing Nothing
case mw of
Nothing -> throwVKMsg "Failed to initialize GLFW window."
Just w -> do
putStrLn "Initialized GLFW window."
finally (action w)
(GLFW.destroyWindow w >> putStrLn "Closed GLFW window.")
glfwMainLoop :: GLFW.Window -> IO () -> IO ()
glfwMainLoop w action = go
where
go = do
should <- GLFW.windowShouldClose w
unless should $ GLFW.pollEvents >> action >> go
withVulkanInstanceExt :: (VkInstance -> IO ()) -> IO ()
withVulkanInstanceExt action = do
get required extension names from GLFW
glfwReqExts <- GLFW.getRequiredInstanceExtensions
withVulkanInstance
"02-GLFWWindow"
glfwReqExts
["VK_LAYER_LUNARG_standard_validation"]
action
pickPhysicalDevice :: VkInstance -> IO VkPhysicalDevice
pickPhysicalDevice vkInstance = do
devs <- alloca $ \deviceCountPtr -> do
throwingVK "pickPhysicalDevice: Failed to enumerate physical devices."
$ vkEnumeratePhysicalDevices vkInstance deviceCountPtr VK_NULL_HANDLE
devCount <- fromIntegral <$> peek deviceCountPtr
when (devCount <= 0) $ throwVKMsg "Zero device count!"
putStrLn $ "Found " ++ show devCount ++ " devices."
allocaArray devCount $ \devicesPtr -> do
throwingVK "pickPhysicalDevice: Failed to enumerate physical devices."
$ vkEnumeratePhysicalDevices vkInstance deviceCountPtr devicesPtr
peekArray devCount devicesPtr
selectFirstSuitable devs
where
selectFirstSuitable [] = throwVKMsg "No suitable devices!"
selectFirstSuitable (x:xs) = isDeviceSuitable x >>= \yes ->
if yes then pure x
else selectFirstSuitable xs
isDeviceSuitable :: VkPhysicalDevice -> IO Bool
isDeviceSuitable _ = pure True
| null | https://raw.githubusercontent.com/achirkin/vulkan/b2e0568c71b5135010f4bba939cd8dcf7a05c361/vulkan-examples/02-GLFWWindow.hs | haskell | |
In this example , I follow first parts of vulkan-tutorial.com to create a window
and pick a device using GLFW .
Parts of the code are moved to Lib
In this example, I follow first parts of vulkan-tutorial.com to create a window
and pick a device using GLFW.
Parts of the code are moved to Lib
-}
module Main (main) where
import Control.Exception
import Control.Monad
import Foreign.Marshal.Alloc
import Foreign.Marshal.Array
import Foreign.Storable
import Graphics.UI.GLFW (ClientAPI (..), WindowHint (..))
import qualified Graphics.UI.GLFW as GLFW
import Graphics.Vulkan
import Graphics.Vulkan.Core_1_0
import Lib.Utils
import Lib.Vulkan (withVulkanInstance)
main :: IO ()
main = withGLFWWindow $ \window ->
withVulkanInstanceExt $ \vulkanInstance -> do
dev <- pickPhysicalDevice vulkanInstance
putStrLn $ "Selected device: " ++ show dev
glfwMainLoop window (return ())
withGLFWWindow :: (GLFW.Window -> IO ()) -> IO ()
withGLFWWindow action = do
GLFW.init >>= flip unless
(throwVKMsg "Failed to initialize GLFW.")
even if something bad happens , we need to terminate GLFW
flip finally (GLFW.terminate >> putStrLn "Terminated GLFW.") $ do
GLFW.getVersionString >>= mapM_ (putStrLn . ("GLFW version: " ++))
GLFW.vulkanSupported >>= flip unless
(throwVKMsg "GLFW reports that vulkan is not supported!")
GLFW.windowHint $ WindowHint'ClientAPI ClientAPI'NoAPI
GLFW.windowHint $ WindowHint'Resizable False
mw <- GLFW.createWindow 800 600 "Vulkan window" Nothing Nothing
case mw of
Nothing -> throwVKMsg "Failed to initialize GLFW window."
Just w -> do
putStrLn "Initialized GLFW window."
finally (action w)
(GLFW.destroyWindow w >> putStrLn "Closed GLFW window.")
glfwMainLoop :: GLFW.Window -> IO () -> IO ()
glfwMainLoop w action = go
where
go = do
should <- GLFW.windowShouldClose w
unless should $ GLFW.pollEvents >> action >> go
withVulkanInstanceExt :: (VkInstance -> IO ()) -> IO ()
withVulkanInstanceExt action = do
get required extension names from GLFW
glfwReqExts <- GLFW.getRequiredInstanceExtensions
withVulkanInstance
"02-GLFWWindow"
glfwReqExts
["VK_LAYER_LUNARG_standard_validation"]
action
pickPhysicalDevice :: VkInstance -> IO VkPhysicalDevice
pickPhysicalDevice vkInstance = do
devs <- alloca $ \deviceCountPtr -> do
throwingVK "pickPhysicalDevice: Failed to enumerate physical devices."
$ vkEnumeratePhysicalDevices vkInstance deviceCountPtr VK_NULL_HANDLE
devCount <- fromIntegral <$> peek deviceCountPtr
when (devCount <= 0) $ throwVKMsg "Zero device count!"
putStrLn $ "Found " ++ show devCount ++ " devices."
allocaArray devCount $ \devicesPtr -> do
throwingVK "pickPhysicalDevice: Failed to enumerate physical devices."
$ vkEnumeratePhysicalDevices vkInstance deviceCountPtr devicesPtr
peekArray devCount devicesPtr
selectFirstSuitable devs
where
selectFirstSuitable [] = throwVKMsg "No suitable devices!"
selectFirstSuitable (x:xs) = isDeviceSuitable x >>= \yes ->
if yes then pure x
else selectFirstSuitable xs
isDeviceSuitable :: VkPhysicalDevice -> IO Bool
isDeviceSuitable _ = pure True
|
|
5aa0930e18caf1c488b55eadad1b59059bda60ccc3893c029e1365e5e08c4140 | KavehYousefi/Esoteric-programming-languages | main.lisp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
This program implements an interpreter for the joke language " OHE " ,
invented by the Esolang user " ResU " .
;;
;; Concept
;; =======
Any program authored in the OHE programming language partakes of a
treatment concerning its code by the same 's neglect ,
;; instead merely printing the text "Hello, world!".
;;
;;
;; Architecture
;; ============
OHE neither prescribes nor requires any architectural warklooms .
;;
;;
;; Data Types
;; ==========
;; The insignificance apportioned to its source code perforce excludes
;; the participation of data types. Solely the ASCII character set, as a
;; supplying substrate for the requisite text "Hello, world!" may be
;; adduced in this agency. Ensuing from this premise, characters, and
;; their compositions in the form of strings, account for the recognized
;; data types.
;;
;;
;; Syntax
;; ======
;; The insignificance and ineffectuality of its source code ascertains
;; any character's admission into a program.
;;
;; == GRAMMAR ==
;; The following Extended Backus-Naur Form (EBNF) avails in the
;; language's syntactical explication:
;;
;; program := { character } ;
;; character := "a" | ... | "z" | "A" | ... | "Z"
| " 0 " | " 1 " | " 2 " | " 3 " | " 4 "
| " 5 " | " 6 " | " 7 " | " 8 " | " 9 "
;; | ...
;; ;
;;
;;
;; Instructions
;; ============
;; The language does not administer any construe to the notion of
;; instructions; its perfect tolerance regarding input in all forms
;; compatible to one's apprehension is meted against an equipollence in
;; the matter of its neglect.
;;
;; --------------------------------------------------------------------
;;
Author :
Date : 2022 - 06 - 13
;;
;; Sources:
;; -> ""
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; -- Implementation of interpreter. -- ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun interpret-OHE (code)
"Interprets the piece of OHE CODE and returns no value."
(declare (type string code))
(declare (ignore code))
(format T "~&Hello, world!")
(values))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; -- Test cases. -- ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(interpret-OHE "")
;;; -------------------------------------------------------
(interpret-OHE "input")
| null | https://raw.githubusercontent.com/KavehYousefi/Esoteric-programming-languages/8e0143ebd0978798f0137d10479066c3ac56acec/OHE/OHE_001/main.lisp | lisp |
Concept
=======
instead merely printing the text "Hello, world!".
Architecture
============
Data Types
==========
The insignificance apportioned to its source code perforce excludes
the participation of data types. Solely the ASCII character set, as a
supplying substrate for the requisite text "Hello, world!" may be
adduced in this agency. Ensuing from this premise, characters, and
their compositions in the form of strings, account for the recognized
data types.
Syntax
======
The insignificance and ineffectuality of its source code ascertains
any character's admission into a program.
== GRAMMAR ==
The following Extended Backus-Naur Form (EBNF) avails in the
language's syntactical explication:
program := { character } ;
character := "a" | ... | "z" | "A" | ... | "Z"
| ...
;
Instructions
============
The language does not administer any construe to the notion of
instructions; its perfect tolerance regarding input in all forms
compatible to one's apprehension is meted against an equipollence in
the matter of its neglect.
--------------------------------------------------------------------
Sources:
-> ""
-- Implementation of interpreter. -- ;;
-- Test cases. -- ;;
------------------------------------------------------- | This program implements an interpreter for the joke language " OHE " ,
invented by the Esolang user " ResU " .
Any program authored in the OHE programming language partakes of a
treatment concerning its code by the same 's neglect ,
OHE neither prescribes nor requires any architectural warklooms .
| " 0 " | " 1 " | " 2 " | " 3 " | " 4 "
| " 5 " | " 6 " | " 7 " | " 8 " | " 9 "
Author :
Date : 2022 - 06 - 13
(defun interpret-OHE (code)
"Interprets the piece of OHE CODE and returns no value."
(declare (type string code))
(declare (ignore code))
(format T "~&Hello, world!")
(values))
(interpret-OHE "")
(interpret-OHE "input")
|
06a8d3dba5e036b236f0341c0245d37b3991a72e0fcdf413f08a1156a06cae60 | cedlemo/OCaml-GI-ctypes-bindings-generator | Icon_source.ml | open Ctypes
open Foreign
type t
let t_typ : t structure typ = structure "Icon_source"
let create =
foreign "gtk_icon_source_new" (void @-> returning (ptr t_typ))
let copy =
foreign "gtk_icon_source_copy" (ptr t_typ @-> returning (ptr t_typ))
let free =
foreign "gtk_icon_source_free" (ptr t_typ @-> returning (void))
let get_direction =
foreign "gtk_icon_source_get_direction" (ptr t_typ @-> returning (Text_direction.t_view))
let get_direction_wildcarded =
foreign "gtk_icon_source_get_direction_wildcarded" (ptr t_typ @-> returning (bool))
let get_filename =
foreign "gtk_icon_source_get_filename" (ptr t_typ @-> returning (string_opt))
let get_icon_name =
foreign "gtk_icon_source_get_icon_name" (ptr t_typ @-> returning (string_opt))
let get_pixbuf =
foreign "gtk_icon_source_get_pixbuf" (ptr t_typ @-> returning (ptr Pixbuf.t_typ))
let get_size =
foreign "gtk_icon_source_get_size" (ptr t_typ @-> returning (int32_t))
let get_size_wildcarded =
foreign "gtk_icon_source_get_size_wildcarded" (ptr t_typ @-> returning (bool))
let get_state =
foreign "gtk_icon_source_get_state" (ptr t_typ @-> returning (State_type.t_view))
let get_state_wildcarded =
foreign "gtk_icon_source_get_state_wildcarded" (ptr t_typ @-> returning (bool))
let set_direction =
foreign "gtk_icon_source_set_direction" (ptr t_typ @-> Text_direction.t_view @-> returning (void))
let set_direction_wildcarded =
foreign "gtk_icon_source_set_direction_wildcarded" (ptr t_typ @-> bool @-> returning (void))
let set_filename =
foreign "gtk_icon_source_set_filename" (ptr t_typ @-> string @-> returning (void))
let set_icon_name =
foreign "gtk_icon_source_set_icon_name" (ptr t_typ @-> string_opt @-> returning (void))
let set_pixbuf =
foreign "gtk_icon_source_set_pixbuf" (ptr t_typ @-> ptr Pixbuf.t_typ @-> returning (void))
let set_size =
foreign "gtk_icon_source_set_size" (ptr t_typ @-> int32_t @-> returning (void))
let set_size_wildcarded =
foreign "gtk_icon_source_set_size_wildcarded" (ptr t_typ @-> bool @-> returning (void))
let set_state =
foreign "gtk_icon_source_set_state" (ptr t_typ @-> State_type.t_view @-> returning (void))
let set_state_wildcarded =
foreign "gtk_icon_source_set_state_wildcarded" (ptr t_typ @-> bool @-> returning (void))
| null | https://raw.githubusercontent.com/cedlemo/OCaml-GI-ctypes-bindings-generator/21a4d449f9dbd6785131979b91aa76877bad2615/tools/Gtk3/Icon_source.ml | ocaml | open Ctypes
open Foreign
type t
let t_typ : t structure typ = structure "Icon_source"
let create =
foreign "gtk_icon_source_new" (void @-> returning (ptr t_typ))
let copy =
foreign "gtk_icon_source_copy" (ptr t_typ @-> returning (ptr t_typ))
let free =
foreign "gtk_icon_source_free" (ptr t_typ @-> returning (void))
let get_direction =
foreign "gtk_icon_source_get_direction" (ptr t_typ @-> returning (Text_direction.t_view))
let get_direction_wildcarded =
foreign "gtk_icon_source_get_direction_wildcarded" (ptr t_typ @-> returning (bool))
let get_filename =
foreign "gtk_icon_source_get_filename" (ptr t_typ @-> returning (string_opt))
let get_icon_name =
foreign "gtk_icon_source_get_icon_name" (ptr t_typ @-> returning (string_opt))
let get_pixbuf =
foreign "gtk_icon_source_get_pixbuf" (ptr t_typ @-> returning (ptr Pixbuf.t_typ))
let get_size =
foreign "gtk_icon_source_get_size" (ptr t_typ @-> returning (int32_t))
let get_size_wildcarded =
foreign "gtk_icon_source_get_size_wildcarded" (ptr t_typ @-> returning (bool))
let get_state =
foreign "gtk_icon_source_get_state" (ptr t_typ @-> returning (State_type.t_view))
let get_state_wildcarded =
foreign "gtk_icon_source_get_state_wildcarded" (ptr t_typ @-> returning (bool))
let set_direction =
foreign "gtk_icon_source_set_direction" (ptr t_typ @-> Text_direction.t_view @-> returning (void))
let set_direction_wildcarded =
foreign "gtk_icon_source_set_direction_wildcarded" (ptr t_typ @-> bool @-> returning (void))
let set_filename =
foreign "gtk_icon_source_set_filename" (ptr t_typ @-> string @-> returning (void))
let set_icon_name =
foreign "gtk_icon_source_set_icon_name" (ptr t_typ @-> string_opt @-> returning (void))
let set_pixbuf =
foreign "gtk_icon_source_set_pixbuf" (ptr t_typ @-> ptr Pixbuf.t_typ @-> returning (void))
let set_size =
foreign "gtk_icon_source_set_size" (ptr t_typ @-> int32_t @-> returning (void))
let set_size_wildcarded =
foreign "gtk_icon_source_set_size_wildcarded" (ptr t_typ @-> bool @-> returning (void))
let set_state =
foreign "gtk_icon_source_set_state" (ptr t_typ @-> State_type.t_view @-> returning (void))
let set_state_wildcarded =
foreign "gtk_icon_source_set_state_wildcarded" (ptr t_typ @-> bool @-> returning (void))
|
|
927c75e06708c0de571ed865daf2af01bb63915cc6f9cd369783a15e90879e2e | lexi-lambda/freer-simple | Reader.hs | -- |
Module : Control . . Freer . Reader
-- Description: Reader effects, for encapsulating an environment.
Copyright : ( c ) 2016 Allele Dev ; 2017 Ixperta Solutions s.r.o . ; 2017
-- License: BSD3
Maintainer : < >
-- Stability: experimental
Portability : GHC specific language extensions .
--
-- Composable handler for 'Reader' effects. Handy for encapsulating an
-- environment with immutable state for interpreters.
--
-- Using <> as a starting point.
module Control.Monad.Freer.Reader
( -- * Reader Effect
Reader(..)
-- * Reader Operations
, ask
, asks
, local
-- * Reader Handlers
, runReader
* Example 1 : Simple Reader Usage
-- $simpleReaderExample
* Example 2 : Modifying Reader Content With @local@
-- $localExample
) where
import Control.Monad.Freer (Eff, Member, interpose, interpret, send)
-- | Represents shared immutable environment of type @(e :: *)@ which is made
-- available to effectful computation.
data Reader r a where
Ask :: Reader r r
-- | Request a value of the environment.
ask :: forall r effs. Member (Reader r) effs => Eff effs r
ask = send Ask
-- | Request a value of the environment, and apply as selector\/projection
-- function to it.
asks
:: forall r effs a
. Member (Reader r) effs
=> (r -> a)
-- ^ The selector\/projection function to be applied to the environment.
-> Eff effs a
asks f = f <$> ask
-- | Handler for 'Reader' effects.
runReader :: forall r effs a. r -> Eff (Reader r ': effs) a -> Eff effs a
runReader r = interpret (\Ask -> pure r)
-- | Locally rebind the value in the dynamic environment.
--
-- This function is like a relay; it is both an admin for 'Reader' requests,
-- and a requestor of them.
local
:: forall r effs a. Member (Reader r) effs
=> (r -> r)
-> Eff effs a
-> Eff effs a
local f m = do
r <- asks f
interpose @(Reader r) (\Ask -> pure r) m
-- $simpleReaderExample
--
-- In this example the 'Reader' effect provides access to variable bindings.
-- Bindings are a @Map@ of integer variables. The variable @count@ contains
-- number of variables in the bindings. You can see how to run a Reader effect
-- and retrieve data from it with 'runReader', how to access the Reader data
-- with 'ask' and 'asks'.
--
> import Control . Monad . Freer
> import Control . . Freer . Reader
-- > import Data.Map as Map
-- > import Data.Maybe
-- >
-- > type Bindings = Map String Int
-- >
-- > -- Returns True if the "count" variable contains correct bindings size.
-- > isCountCorrect :: Bindings -> Bool
> isCountCorrect bindings = run $ runReader bindings calc_isCountCorrect
-- >
-- > -- The Reader effect, which implements this complicated check.
-- > calc_isCountCorrect :: Eff '[Reader Bindings] Bool
-- > calc_isCountCorrect = do
-- > count <- asks (lookupVar "count")
-- > bindings <- (ask :: Eff '[Reader Bindings] Bindings)
-- > return (count == (Map.size bindings))
-- >
-- > -- The selector function to use with 'asks'.
-- > -- Returns value of the variable with specified name.
-- > lookupVar :: String -> Bindings -> Int
-- > lookupVar name bindings = fromJust (Map.lookup name bindings)
-- >
-- > sampleBindings :: Map.Map String Int
> sampleBindings = Map.fromList [ ( " ) , ( " 1",1 ) , ( " b",2 ) ]
-- >
-- > main :: IO ()
-- > main = putStrLn
-- > $ "Count is correct for bindings " ++ show sampleBindings ++ ": "
-- > ++ show (isCountCorrect sampleBindings)
-- $localExample
--
-- Shows how to modify 'Reader' content with 'local'.
--
> import Control . Monad . Freer
> import Control . . Freer . Reader
-- >
-- > import Data.Map as Map
-- > import Data.Maybe
-- >
-- > type Bindings = Map String Int
-- >
-- > calculateContentLen :: Eff '[Reader String] Int
-- > calculateContentLen = do
-- > content <- (ask :: Eff '[Reader String] String)
-- > return (length content)
-- >
-- > -- Calls calculateContentLen after adding a prefix to the Reader content.
-- > calculateModifiedContentLen :: Eff '[Reader String] Int
-- > calculateModifiedContentLen = local ("Prefix " ++) calculateContentLen
-- >
-- > main :: IO ()
-- > main = do
> let s = " 12345 "
> let modifiedLen = run $ runReader s calculateModifiedContentLen
> let len = run $ runReader s calculateContentLen
> " Modified 's ' length : " + + ( show modifiedLen )
> " Original 's ' length : " + + ( show len )
| null | https://raw.githubusercontent.com/lexi-lambda/freer-simple/e5ef0fec4a79585f99c0df8bc9e2e67cc0c0fb4a/src/Control/Monad/Freer/Reader.hs | haskell | |
Description: Reader effects, for encapsulating an environment.
License: BSD3
Stability: experimental
Composable handler for 'Reader' effects. Handy for encapsulating an
environment with immutable state for interpreters.
Using <> as a starting point.
* Reader Effect
* Reader Operations
* Reader Handlers
$simpleReaderExample
$localExample
| Represents shared immutable environment of type @(e :: *)@ which is made
available to effectful computation.
| Request a value of the environment.
| Request a value of the environment, and apply as selector\/projection
function to it.
^ The selector\/projection function to be applied to the environment.
| Handler for 'Reader' effects.
| Locally rebind the value in the dynamic environment.
This function is like a relay; it is both an admin for 'Reader' requests,
and a requestor of them.
$simpleReaderExample
In this example the 'Reader' effect provides access to variable bindings.
Bindings are a @Map@ of integer variables. The variable @count@ contains
number of variables in the bindings. You can see how to run a Reader effect
and retrieve data from it with 'runReader', how to access the Reader data
with 'ask' and 'asks'.
> import Data.Map as Map
> import Data.Maybe
>
> type Bindings = Map String Int
>
> -- Returns True if the "count" variable contains correct bindings size.
> isCountCorrect :: Bindings -> Bool
>
> -- The Reader effect, which implements this complicated check.
> calc_isCountCorrect :: Eff '[Reader Bindings] Bool
> calc_isCountCorrect = do
> count <- asks (lookupVar "count")
> bindings <- (ask :: Eff '[Reader Bindings] Bindings)
> return (count == (Map.size bindings))
>
> -- The selector function to use with 'asks'.
> -- Returns value of the variable with specified name.
> lookupVar :: String -> Bindings -> Int
> lookupVar name bindings = fromJust (Map.lookup name bindings)
>
> sampleBindings :: Map.Map String Int
>
> main :: IO ()
> main = putStrLn
> $ "Count is correct for bindings " ++ show sampleBindings ++ ": "
> ++ show (isCountCorrect sampleBindings)
$localExample
Shows how to modify 'Reader' content with 'local'.
>
> import Data.Map as Map
> import Data.Maybe
>
> type Bindings = Map String Int
>
> calculateContentLen :: Eff '[Reader String] Int
> calculateContentLen = do
> content <- (ask :: Eff '[Reader String] String)
> return (length content)
>
> -- Calls calculateContentLen after adding a prefix to the Reader content.
> calculateModifiedContentLen :: Eff '[Reader String] Int
> calculateModifiedContentLen = local ("Prefix " ++) calculateContentLen
>
> main :: IO ()
> main = do | Module : Control . . Freer . Reader
Copyright : ( c ) 2016 Allele Dev ; 2017 Ixperta Solutions s.r.o . ; 2017
Maintainer : < >
Portability : GHC specific language extensions .
module Control.Monad.Freer.Reader
Reader(..)
, ask
, asks
, local
, runReader
* Example 1 : Simple Reader Usage
* Example 2 : Modifying Reader Content With @local@
) where
import Control.Monad.Freer (Eff, Member, interpose, interpret, send)
data Reader r a where
Ask :: Reader r r
ask :: forall r effs. Member (Reader r) effs => Eff effs r
ask = send Ask
asks
:: forall r effs a
. Member (Reader r) effs
=> (r -> a)
-> Eff effs a
asks f = f <$> ask
runReader :: forall r effs a. r -> Eff (Reader r ': effs) a -> Eff effs a
runReader r = interpret (\Ask -> pure r)
local
:: forall r effs a. Member (Reader r) effs
=> (r -> r)
-> Eff effs a
-> Eff effs a
local f m = do
r <- asks f
interpose @(Reader r) (\Ask -> pure r) m
> import Control . Monad . Freer
> import Control . . Freer . Reader
> isCountCorrect bindings = run $ runReader bindings calc_isCountCorrect
> sampleBindings = Map.fromList [ ( " ) , ( " 1",1 ) , ( " b",2 ) ]
> import Control . Monad . Freer
> import Control . . Freer . Reader
> let s = " 12345 "
> let modifiedLen = run $ runReader s calculateModifiedContentLen
> let len = run $ runReader s calculateContentLen
> " Modified 's ' length : " + + ( show modifiedLen )
> " Original 's ' length : " + + ( show len )
|
b84f93bbabe6e3fe0e7912412dab4378537717c9aef3edeb9f7e177db98a4518 | bluemont/kria | user.clj | (ns user
(:require
[clojure.pprint :refer (pprint)]
[clojure.repl :refer :all]
[clojure.string :as str]
[clojure.test :refer [run-tests run-all-tests]]
[clojure.tools.namespace.repl :refer (refresh)]
[kria.bucket :as bucket]
[kria.client :as client]
[kria.conversions :as conv]
[kria.core :as core]
[kria.index :as index]
[kria.polling :as p]
[kria.object :as object]
[kria.schema :as schema]
[kria.search :as search]
[kria.server :as server]))
(set! *warn-on-reflection* true)
(def result (atom nil))
(defn result-cb
[asc e a]
(if-not e
(reset! result a)
(if (instance? Throwable e)
(.printStackTrace ^Throwable e)
(println e))))
(def streaming (atom []))
(def stream-result (promise))
(defn stream-cb
[coll]
(if coll
(swap! streaming concat coll)
(deliver stream-result @streaming)))
| null | https://raw.githubusercontent.com/bluemont/kria/8ed7fb1ebda8bfa1a2a6d7a3acf05e2255fcf0f0/dev/user.clj | clojure | (ns user
(:require
[clojure.pprint :refer (pprint)]
[clojure.repl :refer :all]
[clojure.string :as str]
[clojure.test :refer [run-tests run-all-tests]]
[clojure.tools.namespace.repl :refer (refresh)]
[kria.bucket :as bucket]
[kria.client :as client]
[kria.conversions :as conv]
[kria.core :as core]
[kria.index :as index]
[kria.polling :as p]
[kria.object :as object]
[kria.schema :as schema]
[kria.search :as search]
[kria.server :as server]))
(set! *warn-on-reflection* true)
(def result (atom nil))
(defn result-cb
[asc e a]
(if-not e
(reset! result a)
(if (instance? Throwable e)
(.printStackTrace ^Throwable e)
(println e))))
(def streaming (atom []))
(def stream-result (promise))
(defn stream-cb
[coll]
(if coll
(swap! streaming concat coll)
(deliver stream-result @streaming)))
|
|
45820b04f80975ffd2ca516b5119c44e16f320497459c5f394fde104342704b6 | pariyatti/kosa | time_fixtures.clj | (ns kuti.fixtures.time-fixtures
(:require [kuti.support.time :as time]))
(defn freeze-clock
([t]
(time/freeze-clock!)
(t)
(time/unfreeze-clock!))
([date-time test-fn]
(time/freeze-clock! date-time)
(test-fn)
(time/unfreeze-clock!)))
(def win95 (time/instant "1995-08-24T00:00:00.000Z"))
(defn freeze-clock-1995 [t]
(time/freeze-clock! win95)
(t)
(time/unfreeze-clock!))
| null | https://raw.githubusercontent.com/pariyatti/kosa/692fc236c596baa11fd562f4998d2e683cfb4466/test/kuti/fixtures/time_fixtures.clj | clojure | (ns kuti.fixtures.time-fixtures
(:require [kuti.support.time :as time]))
(defn freeze-clock
([t]
(time/freeze-clock!)
(t)
(time/unfreeze-clock!))
([date-time test-fn]
(time/freeze-clock! date-time)
(test-fn)
(time/unfreeze-clock!)))
(def win95 (time/instant "1995-08-24T00:00:00.000Z"))
(defn freeze-clock-1995 [t]
(time/freeze-clock! win95)
(t)
(time/unfreeze-clock!))
|
|
b2adda2c7ce5a994a7c92fe9525e4dc8f53fd035cd8e2a35a00a15c77bd4405a | mpdairy/posh | datomic.clj | (ns posh.clj.datomic
(:require [posh.plugin-base :as base]
[posh.lib.ratom :as rx]
[datomic.api :as d]))
(defn- TODO [& [msg]] (throw (ex-info (str "TODO: " msg) nil)))
(defn- conn? [x] (instance? datomic.Connection x))
; TODO maybe we don't want blocking here?)
(defn- transact!* [& args] @(apply d/transact args))
(defn- listen!
([conn callback] (listen! conn (rand) callback))
([conn key callback]
{:pre [(conn? conn)]}
(TODO "Need to figure out how to listen to Datomic connection in the same way as DataScript")
key))
(def dcfg
(let [dcfg {:db d/db
:pull* d/pull
:pull-many d/pull-many
:q d/q
:filter d/filter
:with d/with
:entid d/entid
:transact! transact!*
:listen! listen!
:conn? conn?
:ratom rx/atom
:make-reaction rx/make-reaction}]
(assoc dcfg :pull (partial base/safe-pull dcfg))))
(base/add-plugin dcfg)
| null | https://raw.githubusercontent.com/mpdairy/posh/2347c8505f795ab252dbab2fcdf27eca65a75b58/src/posh/clj/datomic.clj | clojure | TODO maybe we don't want blocking here?) | (ns posh.clj.datomic
(:require [posh.plugin-base :as base]
[posh.lib.ratom :as rx]
[datomic.api :as d]))
(defn- TODO [& [msg]] (throw (ex-info (str "TODO: " msg) nil)))
(defn- conn? [x] (instance? datomic.Connection x))
(defn- transact!* [& args] @(apply d/transact args))
(defn- listen!
([conn callback] (listen! conn (rand) callback))
([conn key callback]
{:pre [(conn? conn)]}
(TODO "Need to figure out how to listen to Datomic connection in the same way as DataScript")
key))
(def dcfg
(let [dcfg {:db d/db
:pull* d/pull
:pull-many d/pull-many
:q d/q
:filter d/filter
:with d/with
:entid d/entid
:transact! transact!*
:listen! listen!
:conn? conn?
:ratom rx/atom
:make-reaction rx/make-reaction}]
(assoc dcfg :pull (partial base/safe-pull dcfg))))
(base/add-plugin dcfg)
|
99d486eabd5b0fa4e61d04b49a430e402d18972e2bfdf292ec1b057c4edb88be | acl2/acl2 | (RP::CREATE-EVAL-FNC
(13 13 (:REWRITE DEFAULT-CAR))
(7 7 (:REWRITE DEFAULT-CDR))
(3 3 (:REWRITE SYMBOL-LISTP-IMPLIES-SYMBOLP))
(3 3 (:REWRITE INTEGER-LISTP-IMPLIES-INTEGERP))
(3 3 (:REWRITE DEFAULT-<-2))
(3 3 (:REWRITE DEFAULT-<-1))
)
(APPLY-FOR-DEFEVALUATOR)
(RP::RP-EVL)
(EVAL-LIST-KWOTE-LST)
(TRUE-LIST-FIX-EV-LST)
(EV-COMMUTES-CAR)
(EV-LST-COMMUTES-CDR)
(RP::RP-EVL-OF-FNCALL-ARGS)
(RP::RP-EVL-OF-VARIABLE)
(RP::RP-EVL-OF-QUOTE)
(RP::RP-EVL-OF-LAMBDA)
(RP::RP-EVL-LST-OF-ATOM)
(RP::RP-EVL-LST-OF-CONS)
(RP::RP-EVL-OF-NONSYMBOL-ATOM)
(RP::RP-EVL-OF-BAD-FNCALL)
(RP::RP-EVL-OF-EQUAL-CALL)
(RP::RP-EVL-OF-FALIST-CALL)
(RP::RP-EVL-OF-NOT-CALL)
(RP::RP-EVL-OF-IF-CALL)
(RP::RP-EVL-OF-HIDE-CALL)
(RP::RP-EVL-OF-IMPLIES-CALL)
(RP::RP-EVL-OF-CASESPLIT-FROM-CONTEXT-TRIG-CALL)
(RP::RP-EVL-OF-DONT-RW-CONTEXT-CALL)
(RP::RP-EVL-OF-CONS-CALL)
(RP::RP-EVL-OF-SYNP-CALL)
(RP::RP-EVL-OF-RETURN-LAST-CALL)
(RP::RP-EVL-OF-RP-CALL)
(RP::RP-EVL-OF-CDR-CALL)
(RP::RP-EVL-OF-CAR-CALL)
(RP::RP-EVL-OF-IFF-CALL)
(RP::RP-EVL-OF-TYPESPEC-CHECK-CALL)
(RP::RP-EVL-OF-ACL2-NUMBERP-CALL)
(RP::RP-EVL-OF-UNARY---CALL)
(RP::RP-EVL-OF-UNARY-/-CALL)
(RP::RP-EVL-OF-<-CALL)
(RP::RP-EVL-OF-CHAR-CODE-CALL)
(RP::RP-EVL-OF-CHARACTERP-CALL)
(RP::RP-EVL-OF-CODE-CHAR-CALL)
(RP::RP-EVL-OF-INTEGERP-CALL)
(RP::RP-EVL-OF-NATP-CALL)
(RP::RP-EVL-OF-ZP-CALL)
(RP::RP-EVL-OF-BITP-CALL)
(RP::RP-EVL-OF-RATIONALP-CALL)
(RP::RP-EVL-OF-SYMBOLP-CALL)
(RP::RP-EVL-OF-COMPLEX-RATIONALP-CALL)
(RP::RP-EVL-OF-DENOMINATOR-CALL)
(RP::RP-EVL-OF-STRINGP-CALL)
(RP::RP-EVL-OF-NUMERATOR-CALL)
(RP::RP-EVL-OF-REALPART-CALL)
(RP::RP-EVL-OF-IMAGPART-CALL)
(RP::RP-EVL-OF-COERCE-CALL)
(RP::RP-EVL-OF-SYMBOL-PACKAGE-NAME-CALL)
(RP::RP-EVL-OF-INTERN-IN-PACKAGE-OF-SYMBOL-CALL)
(RP::RP-EVL-OF-SYMBOL-NAME-CALL)
(RP::RP-EVL-OF-BAD-ATOM<=-CALL)
(RP::RP-EVL-OF-BINARY-+-CALL)
(RP::RP-EVL-OF-BINARY-*-CALL)
(RP::RP-EVL-OF-CONSP-CALL)
(RP::RP-EVL-OF-FORCE-CALL)
(RP::RP-EVL-OF-FORCE$-CALL)
(RP::RP-EVL-OF-RP-EQUAL-CALL)
(RP::RP-EVL-OF-RP-EQUAL-SUBTERMS-CALL)
(RP::RP-EVL-OF-RP-EQUAL-CNT-CALL)
(RP::RP-EVL-OF-RP-EQUAL-CNT-SUBTERMS-CALL)
(RP::RP-EVL-OF-APPLY$-CALL)
(RP::RP-EVL-OF-APPLY$-USERFN-CALL)
(RP::RP-EVL-OF-BADGE-USERFN-CALL)
(RP::RP-EVL-DISJOIN-CONS)
(RP::RP-EVL-DISJOIN-WHEN-CONSP)
(RP::RP-EVL-DISJOIN-ATOM
(1 1 (:REWRITE RP::RP-EVL-OF-IF-CALL))
)
(RP::RP-EVL-DISJOIN-APPEND
(23 23 (:REWRITE RP::RP-EVL-OF-QUOTE))
(23 23 (:REWRITE RP::RP-EVL-OF-IF-CALL))
)
(RP::RP-EVL-CONJOIN-CONS)
(RP::RP-EVL-CONJOIN-WHEN-CONSP)
(RP::RP-EVL-CONJOIN-ATOM
(1 1 (:REWRITE RP::RP-EVL-OF-IF-CALL))
)
(RP::RP-EVL-CONJOIN-APPEND
(23 23 (:REWRITE RP::RP-EVL-OF-QUOTE))
(23 23 (:REWRITE RP::RP-EVL-OF-IF-CALL))
)
(RP::RP-EVL-CONJOIN-CLAUSES-CONS
(100 50 (:DEFINITION DISJOIN))
(50 50 (:DEFINITION DISJOIN2))
(7 7 (:REWRITE RP::RP-EVL-DISJOIN-ATOM))
(5 5 (:REWRITE RP::RP-EVL-CONJOIN-ATOM))
)
(RP::RP-EVL-CONJOIN-CLAUSES-WHEN-CONSP
(24 24 (:REWRITE RP::RP-EVL-OF-QUOTE))
(24 24 (:REWRITE RP::RP-EVL-OF-IF-CALL))
(18 9 (:DEFINITION DISJOIN))
(9 9 (:REWRITE RP::RP-EVL-DISJOIN-ATOM))
(9 9 (:DEFINITION DISJOIN2))
)
(RP::RP-EVL-CONJOIN-CLAUSES-ATOM
(1 1 (:REWRITE RP::RP-EVL-OF-IF-CALL))
)
(RP::RP-EVL-CONJOIN-CLAUSES-APPEND
(65 65 (:REWRITE RP::RP-EVL-OF-QUOTE))
(65 65 (:REWRITE RP::RP-EVL-OF-IF-CALL))
(24 12 (:DEFINITION DISJOIN))
(12 12 (:REWRITE RP::RP-EVL-DISJOIN-ATOM))
(12 12 (:DEFINITION DISJOIN2))
)
(RP::RP-EVL-THEOREMP-CONJOIN-CONS
(53 53 (:REWRITE RP::RP-EVL-CONJOIN-ATOM))
)
(RP::RP-EVL-THEOREMP-CONJOIN-APPEND)
(RP::RP-EVL-THEOREMP-CONJOIN-CLAUSES-CONS
(3 3 (:REWRITE RP::RP-EVL-DISJOIN-ATOM))
(3 3 (:REWRITE RP::RP-EVL-CONJOIN-ATOM))
)
(RP::RP-EVL-THEOREMP-CONJOIN-CLAUSES-APPEND
(15 15 (:REWRITE RP::RP-EVL-DISJOIN-ATOM))
)
(RP::RP-EVL-THEOREMP-DISJOIN-CONS-UNLESS-THEOREMP
(4 4 (:REWRITE RP::RP-EVL-DISJOIN-ATOM))
)
(RP::RP-EVL-THEOREMP-DISJOIN-WHEN-CONSP-UNLESS-THEOREMP
(4 4 (:REWRITE RP::RP-EVL-DISJOIN-ATOM))
)
(RP::RP-EVL-FALSIFY-SUFFICIENT)
(RP::RP-EVL-META-EXTRACT-CONTEXTUAL-BADGUY-SUFFICIENT)
(RP::RP-EVL-META-EXTRACT-GLOBAL-BADGUY-SUFFICIENT)
(RP::RP-EVL-META-EXTRACT-GLOBAL-BADGUY-TRUE-LISTP)
(RP::RP-EVL-META-EXTRACT-TYPESET)
(RP::RP-EVL-META-EXTRACT-RW+-EQUAL)
(RP::RP-EVL-META-EXTRACT-RW+-IFF)
(RP::RP-EVL-META-EXTRACT-RW+-EQUIV)
(RP::RP-EVL-META-EXTRACT-RW-EQUAL)
(RP::RP-EVL-META-EXTRACT-RW-IFF)
(RP::RP-EVL-META-EXTRACT-RW-EQUIV)
(RP::RP-EVL-META-EXTRACT-MFC-AP)
(RP::RP-EVL-META-EXTRACT-RELIEVE-HYP)
(RP::RP-EVL-META-EXTRACT-FORMULA
(9 9 (:REWRITE RP::RP-EVL-OF-VARIABLE))
(9 9 (:REWRITE RP::RP-EVL-OF-TYPESPEC-CHECK-CALL))
(9 9 (:REWRITE RP::RP-EVL-OF-QUOTE))
(9 9 (:REWRITE RP::RP-EVL-OF-NOT-CALL))
(9 9 (:REWRITE RP::RP-EVL-OF-LAMBDA))
(9 9 (:REWRITE RP::RP-EVL-OF-IMPLIES-CALL))
(9 9 (:REWRITE RP::RP-EVL-OF-IFF-CALL))
(9 9 (:REWRITE RP::RP-EVL-OF-IF-CALL))
(9 9 (:REWRITE RP::RP-EVL-OF-EQUAL-CALL))
(8 8 (:REWRITE RP::RP-EVL-OF-NONSYMBOL-ATOM))
(8 8 (:REWRITE RP::RP-EVL-OF-BAD-FNCALL))
)
(RP::RP-EVL-META-EXTRACT-LEMMA-TERM)
(RP::RP-EVL-META-EXTRACT-LEMMA)
(RP::RP-EVL-META-EXTRACT-FNCALL-LOGIC)
(RP::RP-EVL-META-EXTRACT-FNCALL)
(RP::RP-EVL-META-EXTRACT-MAGIC-EV)
(RP::RP-EVL-META-EXTRACT-MAGIC-EV-LST)
(RP::RP-EVL-META-EXTRACT-FN-CHECK-DEF)
(RP::RP-EVL-LST-OF-PAIRLIS)
(RP::RP-EVL-LST-OF-PAIRLIS-APPEND-REST)
(RP::RP-EVL-LST-OF-PAIRLIS-APPEND-HEAD-REST)
(RP::EVAL-AND-ALL
(4 1 (:REWRITE RP::RP-TERMP-IMPLIES-CDR-LISTP))
(3 1 (:DEFINITION ALISTP))
(2 2 (:REWRITE DEFAULT-CDR))
(2 2 (:REWRITE DEFAULT-CAR))
)
(RP::VALID-SC
(1023 752 (:REWRITE RP::MEASURE-LEMMA1))
(699 3 (:DEFINITION RP::RP-TRANS))
(542 34 (:DEFINITION RP::EX-FROM-RP))
(434 160 (:REWRITE DEFAULT-CDR))
(432 1 (:DEFINITION RP::EVAL-AND-ALL))
(403 232 (:REWRITE RP::MEASURE-LEMMA1-2))
(267 3 (:DEFINITION RP::TRANS-LIST))
(266 90 (:REWRITE DEFAULT-CAR))
(36 18 (:REWRITE RP::CONS-COUNT-ATOM))
(33 33 (:TYPE-PRESCRIPTION RP::RP-TRANS-LST))
(28 28 (:REWRITE LEN-MEMBER-EQUAL-LOOP$-AS))
(9 3 (:REWRITE RP::RP-EVL-OF-ZP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-UNARY-/-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-UNARY---CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-TYPESPEC-CHECK-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-SYNP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-SYMBOLP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-SYMBOL-PACKAGE-NAME-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-SYMBOL-NAME-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-STRINGP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-SUBTERMS-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-CNT-SUBTERMS-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-CNT-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RETURN-LAST-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-REALPART-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RATIONALP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-QUOTE))
(9 3 (:REWRITE RP::RP-EVL-OF-NUMERATOR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-NOT-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-NATP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-LAMBDA))
(9 3 (:REWRITE RP::RP-EVL-OF-INTERN-IN-PACKAGE-OF-SYMBOL-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-INTEGERP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-IMPLIES-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-IMAGPART-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-IFF-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-IF-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-HIDE-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-FORCE-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-FORCE$-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-FALIST-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-EQUAL-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-DONT-RW-CONTEXT-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-DENOMINATOR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CONSP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CONS-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-COMPLEX-RATIONALP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-COERCE-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CODE-CHAR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CHARACTERP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CHAR-CODE-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CDR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CASESPLIT-FROM-CONTEXT-TRIG-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CAR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BITP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BINARY-+-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BINARY-*-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BADGE-USERFN-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BAD-ATOM<=-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-APPLY$-USERFN-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-APPLY$-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-ACL2-NUMBERP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-<-CALL))
(9 3 (:DEFINITION QUOTEP))
(8 8 (:REWRITE FN-CHECK-DEF-NOT-QUOTE))
(6 3 (:REWRITE RP::RP-EVL-OF-VARIABLE))
(3 3 (:REWRITE SYMBOL-LISTP-IMPLIES-SYMBOLP))
(1 1 (:REWRITE RP::EQUALITY-MEASURE-LEMMA3))
)
(RP::FLAG-VALID-SC
(1023 752 (:REWRITE RP::MEASURE-LEMMA1))
(699 3 (:DEFINITION RP::RP-TRANS))
(542 34 (:DEFINITION RP::EX-FROM-RP))
(434 160 (:REWRITE DEFAULT-CDR))
(432 1 (:DEFINITION RP::EVAL-AND-ALL))
(403 232 (:REWRITE RP::MEASURE-LEMMA1-2))
(267 3 (:DEFINITION RP::TRANS-LIST))
(266 90 (:REWRITE DEFAULT-CAR))
(36 18 (:REWRITE RP::CONS-COUNT-ATOM))
(33 33 (:TYPE-PRESCRIPTION RP::RP-TRANS-LST))
(28 28 (:REWRITE LEN-MEMBER-EQUAL-LOOP$-AS))
(11 11 (:TYPE-PRESCRIPTION RP::CONTEXT-FROM-RP))
(9 3 (:REWRITE RP::RP-EVL-OF-ZP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-UNARY-/-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-UNARY---CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-TYPESPEC-CHECK-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-SYNP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-SYMBOLP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-SYMBOL-PACKAGE-NAME-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-SYMBOL-NAME-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-STRINGP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-SUBTERMS-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-CNT-SUBTERMS-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-CNT-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RETURN-LAST-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-REALPART-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RATIONALP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-QUOTE))
(9 3 (:REWRITE RP::RP-EVL-OF-NUMERATOR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-NOT-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-NATP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-LAMBDA))
(9 3 (:REWRITE RP::RP-EVL-OF-INTERN-IN-PACKAGE-OF-SYMBOL-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-INTEGERP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-IMPLIES-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-IMAGPART-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-IFF-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-IF-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-HIDE-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-FORCE-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-FORCE$-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-FALIST-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-EQUAL-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-DONT-RW-CONTEXT-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-DENOMINATOR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CONSP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CONS-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-COMPLEX-RATIONALP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-COERCE-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CODE-CHAR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CHARACTERP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CHAR-CODE-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CDR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CASESPLIT-FROM-CONTEXT-TRIG-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CAR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BITP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BINARY-+-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BINARY-*-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BADGE-USERFN-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BAD-ATOM<=-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-APPLY$-USERFN-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-APPLY$-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-ACL2-NUMBERP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-<-CALL))
(9 3 (:DEFINITION QUOTEP))
(8 8 (:REWRITE FN-CHECK-DEF-NOT-QUOTE))
(6 3 (:REWRITE RP::RP-EVL-OF-VARIABLE))
(3 3 (:REWRITE SYMBOL-LISTP-IMPLIES-SYMBOLP))
(1 1 (:REWRITE RP::EQUALITY-MEASURE-LEMMA3))
)
(FLAG::FLAG-EQUIV-LEMMA)
(RP::FLAG-VALID-SC-EQUIVALENCES)
(RP::EVALS-EQUAL-SK)
(RP::EVALS-EQUAL-SK-NECC)
(RP::EVAL-AND-ALL-NT
(4 1 (:REWRITE RP::RP-TERMP-IMPLIES-CDR-LISTP))
(3 1 (:DEFINITION ALISTP))
(2 2 (:REWRITE DEFAULT-CDR))
(2 2 (:REWRITE DEFAULT-CAR))
)
(RP::VALID-SC-NT
(555 464 (:REWRITE RP::MEASURE-LEMMA1))
(199 1 (:DEFINITION RP::EVAL-AND-ALL-NT))
(155 10 (:DEFINITION RP::EX-FROM-RP))
(137 61 (:REWRITE DEFAULT-CDR))
(110 39 (:REWRITE DEFAULT-CAR))
(64 64 (:REWRITE RP::MEASURE-LEMMA1-2))
(36 18 (:REWRITE RP::CONS-COUNT-ATOM))
(28 28 (:REWRITE LEN-MEMBER-EQUAL-LOOP$-AS))
(9 3 (:REWRITE RP::RP-EVL-OF-ZP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-UNARY-/-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-UNARY---CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-TYPESPEC-CHECK-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-SYNP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-SYMBOLP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-SYMBOL-PACKAGE-NAME-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-SYMBOL-NAME-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-STRINGP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-SUBTERMS-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-CNT-SUBTERMS-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-CNT-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RETURN-LAST-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-REALPART-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RATIONALP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-QUOTE))
(9 3 (:REWRITE RP::RP-EVL-OF-NUMERATOR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-NOT-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-NATP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-LAMBDA))
(9 3 (:REWRITE RP::RP-EVL-OF-INTERN-IN-PACKAGE-OF-SYMBOL-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-INTEGERP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-IMPLIES-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-IMAGPART-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-IFF-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-IF-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-HIDE-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-FORCE-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-FORCE$-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-FALIST-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-EQUAL-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-DONT-RW-CONTEXT-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-DENOMINATOR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CONSP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CONS-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-COMPLEX-RATIONALP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-COERCE-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CODE-CHAR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CHARACTERP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CHAR-CODE-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CDR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CASESPLIT-FROM-CONTEXT-TRIG-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CAR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BITP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BINARY-+-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BINARY-*-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BADGE-USERFN-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BAD-ATOM<=-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-APPLY$-USERFN-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-APPLY$-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-ACL2-NUMBERP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-<-CALL))
(6 3 (:REWRITE RP::RP-EVL-OF-VARIABLE))
(5 5 (:REWRITE FN-CHECK-DEF-NOT-QUOTE))
(3 3 (:REWRITE SYMBOL-LISTP-IMPLIES-SYMBOLP))
(1 1 (:REWRITE RP::EQUALITY-MEASURE-LEMMA3))
)
(RP::FLAG-VALID-SC-NT
(555 464 (:REWRITE RP::MEASURE-LEMMA1))
(199 1 (:DEFINITION RP::EVAL-AND-ALL-NT))
(155 10 (:DEFINITION RP::EX-FROM-RP))
(137 61 (:REWRITE DEFAULT-CDR))
(110 39 (:REWRITE DEFAULT-CAR))
(64 64 (:REWRITE RP::MEASURE-LEMMA1-2))
(36 18 (:REWRITE RP::CONS-COUNT-ATOM))
(28 28 (:REWRITE LEN-MEMBER-EQUAL-LOOP$-AS))
(11 11 (:TYPE-PRESCRIPTION RP::CONTEXT-FROM-RP))
(9 3 (:REWRITE RP::RP-EVL-OF-ZP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-UNARY-/-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-UNARY---CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-TYPESPEC-CHECK-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-SYNP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-SYMBOLP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-SYMBOL-PACKAGE-NAME-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-SYMBOL-NAME-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-STRINGP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-SUBTERMS-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-CNT-SUBTERMS-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-CNT-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RETURN-LAST-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-REALPART-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RATIONALP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-QUOTE))
(9 3 (:REWRITE RP::RP-EVL-OF-NUMERATOR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-NOT-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-NATP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-LAMBDA))
(9 3 (:REWRITE RP::RP-EVL-OF-INTERN-IN-PACKAGE-OF-SYMBOL-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-INTEGERP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-IMPLIES-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-IMAGPART-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-IFF-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-IF-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-HIDE-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-FORCE-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-FORCE$-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-FALIST-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-EQUAL-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-DONT-RW-CONTEXT-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-DENOMINATOR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CONSP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CONS-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-COMPLEX-RATIONALP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-COERCE-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CODE-CHAR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CHARACTERP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CHAR-CODE-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CDR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CASESPLIT-FROM-CONTEXT-TRIG-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CAR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BITP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BINARY-+-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BINARY-*-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BADGE-USERFN-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BAD-ATOM<=-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-APPLY$-USERFN-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-APPLY$-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-ACL2-NUMBERP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-<-CALL))
(6 3 (:REWRITE RP::RP-EVL-OF-VARIABLE))
(5 5 (:REWRITE FN-CHECK-DEF-NOT-QUOTE))
(3 3 (:REWRITE SYMBOL-LISTP-IMPLIES-SYMBOLP))
(1 1 (:REWRITE RP::EQUALITY-MEASURE-LEMMA3))
)
(FLAG::FLAG-EQUIV-LEMMA)
(RP::FLAG-VALID-SC-NT-EQUIVALENCES)
(RP::VALID-RULEP-SK-BODY)
(RP::VALID-RULEP-SK)
(RP::VALID-RULEP-SK-NECC)
(RP::VALID-RULEP)
(RP::VALID-RULESP)
(RP::VALID-RULES-ALISTP)
(RP::VALID-RULES-LIST-LISTP)
(RP::VALID-RULES-ALISTP-DEF2)
(RP::VALID-RP-STATEP)
(RP::VALID-RP-STATEP-NECC)
(RP::VALID-RULESP-IMPLIES-RULE-LIST-SYNTAXP
(1432 24 (:DEFINITION RP::EVAL-AND-ALL-NT))
(1120 8 (:DEFINITION RP::VALID-SC-NT))
(208 208 (:REWRITE DEFAULT-CDR))
(164 164 (:REWRITE DEFAULT-CAR))
(96 48 (:REWRITE RP::RP-EVL-OF-VARIABLE))
(48 48 (:REWRITE SYMBOL-LISTP-IMPLIES-SYMBOLP))
(48 48 (:REWRITE RP::RP-EVL-OF-ZP-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-UNARY-/-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-UNARY---CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-TYPESPEC-CHECK-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-SYNP-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-SYMBOLP-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-SYMBOL-PACKAGE-NAME-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-SYMBOL-NAME-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-STRINGP-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-SUBTERMS-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-CNT-SUBTERMS-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-CNT-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-RP-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-RETURN-LAST-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-REALPART-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-RATIONALP-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-QUOTE))
(48 48 (:REWRITE RP::RP-EVL-OF-NUMERATOR-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-NOT-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-NATP-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-LAMBDA))
(48 48 (:REWRITE RP::RP-EVL-OF-INTERN-IN-PACKAGE-OF-SYMBOL-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-INTEGERP-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-IMPLIES-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-IMAGPART-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-IFF-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-IF-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-HIDE-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-FORCE-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-FORCE$-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-FALIST-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-EQUAL-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-DONT-RW-CONTEXT-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-DENOMINATOR-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-CONSP-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-CONS-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-COMPLEX-RATIONALP-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-COERCE-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-CODE-CHAR-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-CHARACTERP-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-CHAR-CODE-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-CDR-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-CASESPLIT-FROM-CONTEXT-TRIG-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-CAR-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-BITP-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-BINARY-+-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-BINARY-*-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-BADGE-USERFN-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-BAD-ATOM<=-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-APPLY$-USERFN-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-APPLY$-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-ACL2-NUMBERP-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-<-CALL))
(48 8 (:DEFINITION RP::INCLUDE-FNC))
(32 8 (:DEFINITION RP::EX-FROM-RP))
(24 8 (:DEFINITION QUOTEP))
(16 16 (:TYPE-PRESCRIPTION RP::CONTEXT-FROM-RP))
(16 16 (:REWRITE FN-CHECK-DEF-NOT-QUOTE))
(8 8 (:TYPE-PRESCRIPTION RP::IS-RP$INLINE))
(8 8 (:TYPE-PRESCRIPTION RP::IS-IF$INLINE))
(4 4 (:REWRITE RP::VALID-RULEP-SK-NECC))
)
(RP::VALID-RP-STATEP-AND-RP-STATEP-IMPLIES-VALID-RP-STATE-SYNTAXP
(1652 2 (:DEFINITION RP::VALID-RULESP))
(1628 2 (:DEFINITION RP::VALID-RULEP))
(1622 2 (:DEFINITION RP::VALID-RULEP-SK))
(1620 2 (:DEFINITION RP::VALID-RULEP-SK-BODY))
(716 12 (:DEFINITION RP::EVAL-AND-ALL-NT))
(560 4 (:DEFINITION RP::VALID-SC-NT))
(104 104 (:REWRITE DEFAULT-CDR))
(74 74 (:REWRITE DEFAULT-CAR))
(48 24 (:REWRITE RP::RP-EVL-OF-VARIABLE))
(48 12 (:DEFINITION RP::RP-RHS$INLINE))
(32 8 (:DEFINITION RP::RP-HYP$INLINE))
(26 26 (:REWRITE SYMBOL-LISTP-IMPLIES-SYMBOLP))
(24 24 (:REWRITE RP::RP-EVL-OF-ZP-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-UNARY-/-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-UNARY---CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-TYPESPEC-CHECK-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-SYNP-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-SYMBOLP-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-SYMBOL-PACKAGE-NAME-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-SYMBOL-NAME-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-STRINGP-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-SUBTERMS-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-CNT-SUBTERMS-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-CNT-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-RP-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-RETURN-LAST-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-REALPART-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-RATIONALP-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-QUOTE))
(24 24 (:REWRITE RP::RP-EVL-OF-NUMERATOR-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-NOT-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-NATP-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-LAMBDA))
(24 24 (:REWRITE RP::RP-EVL-OF-INTERN-IN-PACKAGE-OF-SYMBOL-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-INTEGERP-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-IMPLIES-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-IMAGPART-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-IFF-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-IF-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-HIDE-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-FORCE-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-FORCE$-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-FALIST-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-EQUAL-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-DONT-RW-CONTEXT-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-DENOMINATOR-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-CONSP-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-CONS-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-COMPLEX-RATIONALP-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-COERCE-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-CODE-CHAR-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-CHARACTERP-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-CHAR-CODE-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-CDR-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-CASESPLIT-FROM-CONTEXT-TRIG-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-CAR-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-BITP-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-BINARY-+-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-BINARY-*-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-BADGE-USERFN-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-BAD-ATOM<=-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-APPLY$-USERFN-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-APPLY$-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-ACL2-NUMBERP-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-<-CALL))
(24 4 (:DEFINITION RP::INCLUDE-FNC))
(20 20 (:TYPE-PRESCRIPTION RP::EVAL-AND-ALL-NT))
(16 4 (:DEFINITION RP::EX-FROM-RP))
(12 4 (:DEFINITION RP::RP-LHS$INLINE))
(12 4 (:DEFINITION QUOTEP))
(8 8 (:TYPE-PRESCRIPTION RP::VALID-SC-NT))
(8 8 (:TYPE-PRESCRIPTION RP::INCLUDE-FNC))
(8 8 (:TYPE-PRESCRIPTION RP::CONTEXT-FROM-RP))
(8 8 (:REWRITE FN-CHECK-DEF-NOT-QUOTE))
(8 2 (:DEFINITION RP::RP-IFF-FLAG$INLINE))
(4 4 (:TYPE-PRESCRIPTION RP::RULE-SYNTAXP-FN))
(4 4 (:TYPE-PRESCRIPTION RP::IS-RP$INLINE))
(4 4 (:TYPE-PRESCRIPTION RP::IS-IF$INLINE))
(3 3 (:REWRITE RP::VALID-RP-STATEP-NECC))
(2 2 (:REWRITE RP::VALID-RULEP-SK-NECC))
(2 2 (:REWRITE RP::VALID-RP-STATE-SYNTAXP-AUX-NECC))
(2 2 (:DEFINITION IFF))
)
| null | https://raw.githubusercontent.com/acl2/acl2/f64742cc6d41c35f9d3f94e154cd5fd409105d34/books/projects/rp-rewriter/.sys/eval-functions%40useless-runes.lsp | lisp | (RP::CREATE-EVAL-FNC
(13 13 (:REWRITE DEFAULT-CAR))
(7 7 (:REWRITE DEFAULT-CDR))
(3 3 (:REWRITE SYMBOL-LISTP-IMPLIES-SYMBOLP))
(3 3 (:REWRITE INTEGER-LISTP-IMPLIES-INTEGERP))
(3 3 (:REWRITE DEFAULT-<-2))
(3 3 (:REWRITE DEFAULT-<-1))
)
(APPLY-FOR-DEFEVALUATOR)
(RP::RP-EVL)
(EVAL-LIST-KWOTE-LST)
(TRUE-LIST-FIX-EV-LST)
(EV-COMMUTES-CAR)
(EV-LST-COMMUTES-CDR)
(RP::RP-EVL-OF-FNCALL-ARGS)
(RP::RP-EVL-OF-VARIABLE)
(RP::RP-EVL-OF-QUOTE)
(RP::RP-EVL-OF-LAMBDA)
(RP::RP-EVL-LST-OF-ATOM)
(RP::RP-EVL-LST-OF-CONS)
(RP::RP-EVL-OF-NONSYMBOL-ATOM)
(RP::RP-EVL-OF-BAD-FNCALL)
(RP::RP-EVL-OF-EQUAL-CALL)
(RP::RP-EVL-OF-FALIST-CALL)
(RP::RP-EVL-OF-NOT-CALL)
(RP::RP-EVL-OF-IF-CALL)
(RP::RP-EVL-OF-HIDE-CALL)
(RP::RP-EVL-OF-IMPLIES-CALL)
(RP::RP-EVL-OF-CASESPLIT-FROM-CONTEXT-TRIG-CALL)
(RP::RP-EVL-OF-DONT-RW-CONTEXT-CALL)
(RP::RP-EVL-OF-CONS-CALL)
(RP::RP-EVL-OF-SYNP-CALL)
(RP::RP-EVL-OF-RETURN-LAST-CALL)
(RP::RP-EVL-OF-RP-CALL)
(RP::RP-EVL-OF-CDR-CALL)
(RP::RP-EVL-OF-CAR-CALL)
(RP::RP-EVL-OF-IFF-CALL)
(RP::RP-EVL-OF-TYPESPEC-CHECK-CALL)
(RP::RP-EVL-OF-ACL2-NUMBERP-CALL)
(RP::RP-EVL-OF-UNARY---CALL)
(RP::RP-EVL-OF-UNARY-/-CALL)
(RP::RP-EVL-OF-<-CALL)
(RP::RP-EVL-OF-CHAR-CODE-CALL)
(RP::RP-EVL-OF-CHARACTERP-CALL)
(RP::RP-EVL-OF-CODE-CHAR-CALL)
(RP::RP-EVL-OF-INTEGERP-CALL)
(RP::RP-EVL-OF-NATP-CALL)
(RP::RP-EVL-OF-ZP-CALL)
(RP::RP-EVL-OF-BITP-CALL)
(RP::RP-EVL-OF-RATIONALP-CALL)
(RP::RP-EVL-OF-SYMBOLP-CALL)
(RP::RP-EVL-OF-COMPLEX-RATIONALP-CALL)
(RP::RP-EVL-OF-DENOMINATOR-CALL)
(RP::RP-EVL-OF-STRINGP-CALL)
(RP::RP-EVL-OF-NUMERATOR-CALL)
(RP::RP-EVL-OF-REALPART-CALL)
(RP::RP-EVL-OF-IMAGPART-CALL)
(RP::RP-EVL-OF-COERCE-CALL)
(RP::RP-EVL-OF-SYMBOL-PACKAGE-NAME-CALL)
(RP::RP-EVL-OF-INTERN-IN-PACKAGE-OF-SYMBOL-CALL)
(RP::RP-EVL-OF-SYMBOL-NAME-CALL)
(RP::RP-EVL-OF-BAD-ATOM<=-CALL)
(RP::RP-EVL-OF-BINARY-+-CALL)
(RP::RP-EVL-OF-BINARY-*-CALL)
(RP::RP-EVL-OF-CONSP-CALL)
(RP::RP-EVL-OF-FORCE-CALL)
(RP::RP-EVL-OF-FORCE$-CALL)
(RP::RP-EVL-OF-RP-EQUAL-CALL)
(RP::RP-EVL-OF-RP-EQUAL-SUBTERMS-CALL)
(RP::RP-EVL-OF-RP-EQUAL-CNT-CALL)
(RP::RP-EVL-OF-RP-EQUAL-CNT-SUBTERMS-CALL)
(RP::RP-EVL-OF-APPLY$-CALL)
(RP::RP-EVL-OF-APPLY$-USERFN-CALL)
(RP::RP-EVL-OF-BADGE-USERFN-CALL)
(RP::RP-EVL-DISJOIN-CONS)
(RP::RP-EVL-DISJOIN-WHEN-CONSP)
(RP::RP-EVL-DISJOIN-ATOM
(1 1 (:REWRITE RP::RP-EVL-OF-IF-CALL))
)
(RP::RP-EVL-DISJOIN-APPEND
(23 23 (:REWRITE RP::RP-EVL-OF-QUOTE))
(23 23 (:REWRITE RP::RP-EVL-OF-IF-CALL))
)
(RP::RP-EVL-CONJOIN-CONS)
(RP::RP-EVL-CONJOIN-WHEN-CONSP)
(RP::RP-EVL-CONJOIN-ATOM
(1 1 (:REWRITE RP::RP-EVL-OF-IF-CALL))
)
(RP::RP-EVL-CONJOIN-APPEND
(23 23 (:REWRITE RP::RP-EVL-OF-QUOTE))
(23 23 (:REWRITE RP::RP-EVL-OF-IF-CALL))
)
(RP::RP-EVL-CONJOIN-CLAUSES-CONS
(100 50 (:DEFINITION DISJOIN))
(50 50 (:DEFINITION DISJOIN2))
(7 7 (:REWRITE RP::RP-EVL-DISJOIN-ATOM))
(5 5 (:REWRITE RP::RP-EVL-CONJOIN-ATOM))
)
(RP::RP-EVL-CONJOIN-CLAUSES-WHEN-CONSP
(24 24 (:REWRITE RP::RP-EVL-OF-QUOTE))
(24 24 (:REWRITE RP::RP-EVL-OF-IF-CALL))
(18 9 (:DEFINITION DISJOIN))
(9 9 (:REWRITE RP::RP-EVL-DISJOIN-ATOM))
(9 9 (:DEFINITION DISJOIN2))
)
(RP::RP-EVL-CONJOIN-CLAUSES-ATOM
(1 1 (:REWRITE RP::RP-EVL-OF-IF-CALL))
)
(RP::RP-EVL-CONJOIN-CLAUSES-APPEND
(65 65 (:REWRITE RP::RP-EVL-OF-QUOTE))
(65 65 (:REWRITE RP::RP-EVL-OF-IF-CALL))
(24 12 (:DEFINITION DISJOIN))
(12 12 (:REWRITE RP::RP-EVL-DISJOIN-ATOM))
(12 12 (:DEFINITION DISJOIN2))
)
(RP::RP-EVL-THEOREMP-CONJOIN-CONS
(53 53 (:REWRITE RP::RP-EVL-CONJOIN-ATOM))
)
(RP::RP-EVL-THEOREMP-CONJOIN-APPEND)
(RP::RP-EVL-THEOREMP-CONJOIN-CLAUSES-CONS
(3 3 (:REWRITE RP::RP-EVL-DISJOIN-ATOM))
(3 3 (:REWRITE RP::RP-EVL-CONJOIN-ATOM))
)
(RP::RP-EVL-THEOREMP-CONJOIN-CLAUSES-APPEND
(15 15 (:REWRITE RP::RP-EVL-DISJOIN-ATOM))
)
(RP::RP-EVL-THEOREMP-DISJOIN-CONS-UNLESS-THEOREMP
(4 4 (:REWRITE RP::RP-EVL-DISJOIN-ATOM))
)
(RP::RP-EVL-THEOREMP-DISJOIN-WHEN-CONSP-UNLESS-THEOREMP
(4 4 (:REWRITE RP::RP-EVL-DISJOIN-ATOM))
)
(RP::RP-EVL-FALSIFY-SUFFICIENT)
(RP::RP-EVL-META-EXTRACT-CONTEXTUAL-BADGUY-SUFFICIENT)
(RP::RP-EVL-META-EXTRACT-GLOBAL-BADGUY-SUFFICIENT)
(RP::RP-EVL-META-EXTRACT-GLOBAL-BADGUY-TRUE-LISTP)
(RP::RP-EVL-META-EXTRACT-TYPESET)
(RP::RP-EVL-META-EXTRACT-RW+-EQUAL)
(RP::RP-EVL-META-EXTRACT-RW+-IFF)
(RP::RP-EVL-META-EXTRACT-RW+-EQUIV)
(RP::RP-EVL-META-EXTRACT-RW-EQUAL)
(RP::RP-EVL-META-EXTRACT-RW-IFF)
(RP::RP-EVL-META-EXTRACT-RW-EQUIV)
(RP::RP-EVL-META-EXTRACT-MFC-AP)
(RP::RP-EVL-META-EXTRACT-RELIEVE-HYP)
(RP::RP-EVL-META-EXTRACT-FORMULA
(9 9 (:REWRITE RP::RP-EVL-OF-VARIABLE))
(9 9 (:REWRITE RP::RP-EVL-OF-TYPESPEC-CHECK-CALL))
(9 9 (:REWRITE RP::RP-EVL-OF-QUOTE))
(9 9 (:REWRITE RP::RP-EVL-OF-NOT-CALL))
(9 9 (:REWRITE RP::RP-EVL-OF-LAMBDA))
(9 9 (:REWRITE RP::RP-EVL-OF-IMPLIES-CALL))
(9 9 (:REWRITE RP::RP-EVL-OF-IFF-CALL))
(9 9 (:REWRITE RP::RP-EVL-OF-IF-CALL))
(9 9 (:REWRITE RP::RP-EVL-OF-EQUAL-CALL))
(8 8 (:REWRITE RP::RP-EVL-OF-NONSYMBOL-ATOM))
(8 8 (:REWRITE RP::RP-EVL-OF-BAD-FNCALL))
)
(RP::RP-EVL-META-EXTRACT-LEMMA-TERM)
(RP::RP-EVL-META-EXTRACT-LEMMA)
(RP::RP-EVL-META-EXTRACT-FNCALL-LOGIC)
(RP::RP-EVL-META-EXTRACT-FNCALL)
(RP::RP-EVL-META-EXTRACT-MAGIC-EV)
(RP::RP-EVL-META-EXTRACT-MAGIC-EV-LST)
(RP::RP-EVL-META-EXTRACT-FN-CHECK-DEF)
(RP::RP-EVL-LST-OF-PAIRLIS)
(RP::RP-EVL-LST-OF-PAIRLIS-APPEND-REST)
(RP::RP-EVL-LST-OF-PAIRLIS-APPEND-HEAD-REST)
(RP::EVAL-AND-ALL
(4 1 (:REWRITE RP::RP-TERMP-IMPLIES-CDR-LISTP))
(3 1 (:DEFINITION ALISTP))
(2 2 (:REWRITE DEFAULT-CDR))
(2 2 (:REWRITE DEFAULT-CAR))
)
(RP::VALID-SC
(1023 752 (:REWRITE RP::MEASURE-LEMMA1))
(699 3 (:DEFINITION RP::RP-TRANS))
(542 34 (:DEFINITION RP::EX-FROM-RP))
(434 160 (:REWRITE DEFAULT-CDR))
(432 1 (:DEFINITION RP::EVAL-AND-ALL))
(403 232 (:REWRITE RP::MEASURE-LEMMA1-2))
(267 3 (:DEFINITION RP::TRANS-LIST))
(266 90 (:REWRITE DEFAULT-CAR))
(36 18 (:REWRITE RP::CONS-COUNT-ATOM))
(33 33 (:TYPE-PRESCRIPTION RP::RP-TRANS-LST))
(28 28 (:REWRITE LEN-MEMBER-EQUAL-LOOP$-AS))
(9 3 (:REWRITE RP::RP-EVL-OF-ZP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-UNARY-/-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-UNARY---CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-TYPESPEC-CHECK-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-SYNP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-SYMBOLP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-SYMBOL-PACKAGE-NAME-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-SYMBOL-NAME-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-STRINGP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-SUBTERMS-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-CNT-SUBTERMS-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-CNT-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RETURN-LAST-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-REALPART-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RATIONALP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-QUOTE))
(9 3 (:REWRITE RP::RP-EVL-OF-NUMERATOR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-NOT-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-NATP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-LAMBDA))
(9 3 (:REWRITE RP::RP-EVL-OF-INTERN-IN-PACKAGE-OF-SYMBOL-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-INTEGERP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-IMPLIES-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-IMAGPART-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-IFF-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-IF-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-HIDE-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-FORCE-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-FORCE$-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-FALIST-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-EQUAL-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-DONT-RW-CONTEXT-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-DENOMINATOR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CONSP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CONS-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-COMPLEX-RATIONALP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-COERCE-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CODE-CHAR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CHARACTERP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CHAR-CODE-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CDR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CASESPLIT-FROM-CONTEXT-TRIG-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CAR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BITP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BINARY-+-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BINARY-*-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BADGE-USERFN-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BAD-ATOM<=-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-APPLY$-USERFN-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-APPLY$-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-ACL2-NUMBERP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-<-CALL))
(9 3 (:DEFINITION QUOTEP))
(8 8 (:REWRITE FN-CHECK-DEF-NOT-QUOTE))
(6 3 (:REWRITE RP::RP-EVL-OF-VARIABLE))
(3 3 (:REWRITE SYMBOL-LISTP-IMPLIES-SYMBOLP))
(1 1 (:REWRITE RP::EQUALITY-MEASURE-LEMMA3))
)
(RP::FLAG-VALID-SC
(1023 752 (:REWRITE RP::MEASURE-LEMMA1))
(699 3 (:DEFINITION RP::RP-TRANS))
(542 34 (:DEFINITION RP::EX-FROM-RP))
(434 160 (:REWRITE DEFAULT-CDR))
(432 1 (:DEFINITION RP::EVAL-AND-ALL))
(403 232 (:REWRITE RP::MEASURE-LEMMA1-2))
(267 3 (:DEFINITION RP::TRANS-LIST))
(266 90 (:REWRITE DEFAULT-CAR))
(36 18 (:REWRITE RP::CONS-COUNT-ATOM))
(33 33 (:TYPE-PRESCRIPTION RP::RP-TRANS-LST))
(28 28 (:REWRITE LEN-MEMBER-EQUAL-LOOP$-AS))
(11 11 (:TYPE-PRESCRIPTION RP::CONTEXT-FROM-RP))
(9 3 (:REWRITE RP::RP-EVL-OF-ZP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-UNARY-/-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-UNARY---CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-TYPESPEC-CHECK-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-SYNP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-SYMBOLP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-SYMBOL-PACKAGE-NAME-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-SYMBOL-NAME-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-STRINGP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-SUBTERMS-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-CNT-SUBTERMS-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-CNT-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RETURN-LAST-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-REALPART-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RATIONALP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-QUOTE))
(9 3 (:REWRITE RP::RP-EVL-OF-NUMERATOR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-NOT-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-NATP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-LAMBDA))
(9 3 (:REWRITE RP::RP-EVL-OF-INTERN-IN-PACKAGE-OF-SYMBOL-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-INTEGERP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-IMPLIES-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-IMAGPART-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-IFF-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-IF-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-HIDE-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-FORCE-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-FORCE$-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-FALIST-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-EQUAL-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-DONT-RW-CONTEXT-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-DENOMINATOR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CONSP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CONS-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-COMPLEX-RATIONALP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-COERCE-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CODE-CHAR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CHARACTERP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CHAR-CODE-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CDR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CASESPLIT-FROM-CONTEXT-TRIG-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CAR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BITP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BINARY-+-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BINARY-*-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BADGE-USERFN-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BAD-ATOM<=-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-APPLY$-USERFN-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-APPLY$-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-ACL2-NUMBERP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-<-CALL))
(9 3 (:DEFINITION QUOTEP))
(8 8 (:REWRITE FN-CHECK-DEF-NOT-QUOTE))
(6 3 (:REWRITE RP::RP-EVL-OF-VARIABLE))
(3 3 (:REWRITE SYMBOL-LISTP-IMPLIES-SYMBOLP))
(1 1 (:REWRITE RP::EQUALITY-MEASURE-LEMMA3))
)
(FLAG::FLAG-EQUIV-LEMMA)
(RP::FLAG-VALID-SC-EQUIVALENCES)
(RP::EVALS-EQUAL-SK)
(RP::EVALS-EQUAL-SK-NECC)
(RP::EVAL-AND-ALL-NT
(4 1 (:REWRITE RP::RP-TERMP-IMPLIES-CDR-LISTP))
(3 1 (:DEFINITION ALISTP))
(2 2 (:REWRITE DEFAULT-CDR))
(2 2 (:REWRITE DEFAULT-CAR))
)
(RP::VALID-SC-NT
(555 464 (:REWRITE RP::MEASURE-LEMMA1))
(199 1 (:DEFINITION RP::EVAL-AND-ALL-NT))
(155 10 (:DEFINITION RP::EX-FROM-RP))
(137 61 (:REWRITE DEFAULT-CDR))
(110 39 (:REWRITE DEFAULT-CAR))
(64 64 (:REWRITE RP::MEASURE-LEMMA1-2))
(36 18 (:REWRITE RP::CONS-COUNT-ATOM))
(28 28 (:REWRITE LEN-MEMBER-EQUAL-LOOP$-AS))
(9 3 (:REWRITE RP::RP-EVL-OF-ZP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-UNARY-/-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-UNARY---CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-TYPESPEC-CHECK-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-SYNP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-SYMBOLP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-SYMBOL-PACKAGE-NAME-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-SYMBOL-NAME-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-STRINGP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-SUBTERMS-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-CNT-SUBTERMS-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-CNT-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RETURN-LAST-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-REALPART-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RATIONALP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-QUOTE))
(9 3 (:REWRITE RP::RP-EVL-OF-NUMERATOR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-NOT-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-NATP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-LAMBDA))
(9 3 (:REWRITE RP::RP-EVL-OF-INTERN-IN-PACKAGE-OF-SYMBOL-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-INTEGERP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-IMPLIES-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-IMAGPART-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-IFF-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-IF-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-HIDE-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-FORCE-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-FORCE$-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-FALIST-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-EQUAL-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-DONT-RW-CONTEXT-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-DENOMINATOR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CONSP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CONS-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-COMPLEX-RATIONALP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-COERCE-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CODE-CHAR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CHARACTERP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CHAR-CODE-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CDR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CASESPLIT-FROM-CONTEXT-TRIG-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CAR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BITP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BINARY-+-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BINARY-*-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BADGE-USERFN-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BAD-ATOM<=-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-APPLY$-USERFN-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-APPLY$-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-ACL2-NUMBERP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-<-CALL))
(6 3 (:REWRITE RP::RP-EVL-OF-VARIABLE))
(5 5 (:REWRITE FN-CHECK-DEF-NOT-QUOTE))
(3 3 (:REWRITE SYMBOL-LISTP-IMPLIES-SYMBOLP))
(1 1 (:REWRITE RP::EQUALITY-MEASURE-LEMMA3))
)
(RP::FLAG-VALID-SC-NT
(555 464 (:REWRITE RP::MEASURE-LEMMA1))
(199 1 (:DEFINITION RP::EVAL-AND-ALL-NT))
(155 10 (:DEFINITION RP::EX-FROM-RP))
(137 61 (:REWRITE DEFAULT-CDR))
(110 39 (:REWRITE DEFAULT-CAR))
(64 64 (:REWRITE RP::MEASURE-LEMMA1-2))
(36 18 (:REWRITE RP::CONS-COUNT-ATOM))
(28 28 (:REWRITE LEN-MEMBER-EQUAL-LOOP$-AS))
(11 11 (:TYPE-PRESCRIPTION RP::CONTEXT-FROM-RP))
(9 3 (:REWRITE RP::RP-EVL-OF-ZP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-UNARY-/-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-UNARY---CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-TYPESPEC-CHECK-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-SYNP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-SYMBOLP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-SYMBOL-PACKAGE-NAME-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-SYMBOL-NAME-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-STRINGP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-SUBTERMS-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-CNT-SUBTERMS-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-CNT-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RETURN-LAST-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-REALPART-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-RATIONALP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-QUOTE))
(9 3 (:REWRITE RP::RP-EVL-OF-NUMERATOR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-NOT-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-NATP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-LAMBDA))
(9 3 (:REWRITE RP::RP-EVL-OF-INTERN-IN-PACKAGE-OF-SYMBOL-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-INTEGERP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-IMPLIES-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-IMAGPART-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-IFF-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-IF-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-HIDE-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-FORCE-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-FORCE$-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-FALIST-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-EQUAL-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-DONT-RW-CONTEXT-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-DENOMINATOR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CONSP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CONS-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-COMPLEX-RATIONALP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-COERCE-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CODE-CHAR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CHARACTERP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CHAR-CODE-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CDR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CASESPLIT-FROM-CONTEXT-TRIG-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-CAR-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BITP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BINARY-+-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BINARY-*-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BADGE-USERFN-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-BAD-ATOM<=-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-APPLY$-USERFN-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-APPLY$-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-ACL2-NUMBERP-CALL))
(9 3 (:REWRITE RP::RP-EVL-OF-<-CALL))
(6 3 (:REWRITE RP::RP-EVL-OF-VARIABLE))
(5 5 (:REWRITE FN-CHECK-DEF-NOT-QUOTE))
(3 3 (:REWRITE SYMBOL-LISTP-IMPLIES-SYMBOLP))
(1 1 (:REWRITE RP::EQUALITY-MEASURE-LEMMA3))
)
(FLAG::FLAG-EQUIV-LEMMA)
(RP::FLAG-VALID-SC-NT-EQUIVALENCES)
(RP::VALID-RULEP-SK-BODY)
(RP::VALID-RULEP-SK)
(RP::VALID-RULEP-SK-NECC)
(RP::VALID-RULEP)
(RP::VALID-RULESP)
(RP::VALID-RULES-ALISTP)
(RP::VALID-RULES-LIST-LISTP)
(RP::VALID-RULES-ALISTP-DEF2)
(RP::VALID-RP-STATEP)
(RP::VALID-RP-STATEP-NECC)
(RP::VALID-RULESP-IMPLIES-RULE-LIST-SYNTAXP
(1432 24 (:DEFINITION RP::EVAL-AND-ALL-NT))
(1120 8 (:DEFINITION RP::VALID-SC-NT))
(208 208 (:REWRITE DEFAULT-CDR))
(164 164 (:REWRITE DEFAULT-CAR))
(96 48 (:REWRITE RP::RP-EVL-OF-VARIABLE))
(48 48 (:REWRITE SYMBOL-LISTP-IMPLIES-SYMBOLP))
(48 48 (:REWRITE RP::RP-EVL-OF-ZP-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-UNARY-/-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-UNARY---CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-TYPESPEC-CHECK-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-SYNP-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-SYMBOLP-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-SYMBOL-PACKAGE-NAME-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-SYMBOL-NAME-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-STRINGP-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-SUBTERMS-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-CNT-SUBTERMS-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-CNT-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-RP-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-RETURN-LAST-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-REALPART-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-RATIONALP-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-QUOTE))
(48 48 (:REWRITE RP::RP-EVL-OF-NUMERATOR-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-NOT-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-NATP-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-LAMBDA))
(48 48 (:REWRITE RP::RP-EVL-OF-INTERN-IN-PACKAGE-OF-SYMBOL-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-INTEGERP-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-IMPLIES-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-IMAGPART-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-IFF-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-IF-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-HIDE-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-FORCE-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-FORCE$-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-FALIST-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-EQUAL-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-DONT-RW-CONTEXT-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-DENOMINATOR-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-CONSP-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-CONS-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-COMPLEX-RATIONALP-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-COERCE-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-CODE-CHAR-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-CHARACTERP-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-CHAR-CODE-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-CDR-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-CASESPLIT-FROM-CONTEXT-TRIG-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-CAR-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-BITP-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-BINARY-+-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-BINARY-*-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-BADGE-USERFN-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-BAD-ATOM<=-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-APPLY$-USERFN-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-APPLY$-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-ACL2-NUMBERP-CALL))
(48 48 (:REWRITE RP::RP-EVL-OF-<-CALL))
(48 8 (:DEFINITION RP::INCLUDE-FNC))
(32 8 (:DEFINITION RP::EX-FROM-RP))
(24 8 (:DEFINITION QUOTEP))
(16 16 (:TYPE-PRESCRIPTION RP::CONTEXT-FROM-RP))
(16 16 (:REWRITE FN-CHECK-DEF-NOT-QUOTE))
(8 8 (:TYPE-PRESCRIPTION RP::IS-RP$INLINE))
(8 8 (:TYPE-PRESCRIPTION RP::IS-IF$INLINE))
(4 4 (:REWRITE RP::VALID-RULEP-SK-NECC))
)
(RP::VALID-RP-STATEP-AND-RP-STATEP-IMPLIES-VALID-RP-STATE-SYNTAXP
(1652 2 (:DEFINITION RP::VALID-RULESP))
(1628 2 (:DEFINITION RP::VALID-RULEP))
(1622 2 (:DEFINITION RP::VALID-RULEP-SK))
(1620 2 (:DEFINITION RP::VALID-RULEP-SK-BODY))
(716 12 (:DEFINITION RP::EVAL-AND-ALL-NT))
(560 4 (:DEFINITION RP::VALID-SC-NT))
(104 104 (:REWRITE DEFAULT-CDR))
(74 74 (:REWRITE DEFAULT-CAR))
(48 24 (:REWRITE RP::RP-EVL-OF-VARIABLE))
(48 12 (:DEFINITION RP::RP-RHS$INLINE))
(32 8 (:DEFINITION RP::RP-HYP$INLINE))
(26 26 (:REWRITE SYMBOL-LISTP-IMPLIES-SYMBOLP))
(24 24 (:REWRITE RP::RP-EVL-OF-ZP-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-UNARY-/-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-UNARY---CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-TYPESPEC-CHECK-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-SYNP-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-SYMBOLP-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-SYMBOL-PACKAGE-NAME-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-SYMBOL-NAME-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-STRINGP-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-SUBTERMS-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-CNT-SUBTERMS-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-CNT-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-RP-EQUAL-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-RP-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-RETURN-LAST-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-REALPART-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-RATIONALP-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-QUOTE))
(24 24 (:REWRITE RP::RP-EVL-OF-NUMERATOR-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-NOT-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-NATP-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-LAMBDA))
(24 24 (:REWRITE RP::RP-EVL-OF-INTERN-IN-PACKAGE-OF-SYMBOL-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-INTEGERP-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-IMPLIES-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-IMAGPART-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-IFF-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-IF-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-HIDE-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-FORCE-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-FORCE$-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-FALIST-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-EQUAL-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-DONT-RW-CONTEXT-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-DENOMINATOR-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-CONSP-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-CONS-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-COMPLEX-RATIONALP-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-COERCE-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-CODE-CHAR-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-CHARACTERP-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-CHAR-CODE-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-CDR-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-CASESPLIT-FROM-CONTEXT-TRIG-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-CAR-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-BITP-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-BINARY-+-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-BINARY-*-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-BADGE-USERFN-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-BAD-ATOM<=-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-APPLY$-USERFN-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-APPLY$-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-ACL2-NUMBERP-CALL))
(24 24 (:REWRITE RP::RP-EVL-OF-<-CALL))
(24 4 (:DEFINITION RP::INCLUDE-FNC))
(20 20 (:TYPE-PRESCRIPTION RP::EVAL-AND-ALL-NT))
(16 4 (:DEFINITION RP::EX-FROM-RP))
(12 4 (:DEFINITION RP::RP-LHS$INLINE))
(12 4 (:DEFINITION QUOTEP))
(8 8 (:TYPE-PRESCRIPTION RP::VALID-SC-NT))
(8 8 (:TYPE-PRESCRIPTION RP::INCLUDE-FNC))
(8 8 (:TYPE-PRESCRIPTION RP::CONTEXT-FROM-RP))
(8 8 (:REWRITE FN-CHECK-DEF-NOT-QUOTE))
(8 2 (:DEFINITION RP::RP-IFF-FLAG$INLINE))
(4 4 (:TYPE-PRESCRIPTION RP::RULE-SYNTAXP-FN))
(4 4 (:TYPE-PRESCRIPTION RP::IS-RP$INLINE))
(4 4 (:TYPE-PRESCRIPTION RP::IS-IF$INLINE))
(3 3 (:REWRITE RP::VALID-RP-STATEP-NECC))
(2 2 (:REWRITE RP::VALID-RULEP-SK-NECC))
(2 2 (:REWRITE RP::VALID-RP-STATE-SYNTAXP-AUX-NECC))
(2 2 (:DEFINITION IFF))
)
|
||
60a39bc11bf6c3a7fdd42dc8bbadc4467535b1030037fa78ee7f44a0d4dd36e8 | maximedenes/native-coq | topconstr.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
(*i*)
open Pp
open Errors
open Util
open Names
open Nameops
open Libnames
open Glob_term
open Term
open Mod_subst
(*i*)
(**********************************************************************)
This is the subtype of glob_constr allowed in syntactic extensions
For AList : first constr is iterator , second is terminator ;
first i d is where each argument of the list has to be substituted
in iterator and snd i d is alternative name just for printing ;
boolean is associativity
first id is where each argument of the list has to be substituted
in iterator and snd id is alternative name just for printing;
boolean is associativity *)
type aconstr =
(* Part common to glob_constr and cases_pattern *)
| ARef of global_reference
| AVar of identifier
| AApp of aconstr * aconstr list
| AHole of Evd.hole_kind
| AList of identifier * identifier * aconstr * aconstr * bool
(* Part only in glob_constr *)
| ALambda of name * aconstr * aconstr
| AProd of name * aconstr * aconstr
| ABinderList of identifier * identifier * aconstr * aconstr
| ALetIn of name * aconstr * aconstr
| ACases of case_style * aconstr option *
(aconstr * (name * (inductive * name list) option)) list *
(cases_pattern list * aconstr) list
| ALetTuple of name list * (name * aconstr option) * aconstr * aconstr
| AIf of aconstr * (name * aconstr option) * aconstr * aconstr
| ARec of fix_kind * identifier array *
(name * aconstr option * aconstr) list array * aconstr array *
aconstr array
| ASort of glob_sort
| APatVar of patvar
| ACast of aconstr * aconstr cast_type
| ANativeInt of Uint63.t
| ANativeArr of aconstr * aconstr array
type scope_name = string
type tmp_scope_name = scope_name
type subscopes = tmp_scope_name option * scope_name list
type notation_var_instance_type =
| NtnTypeConstr | NtnTypeConstrList | NtnTypeBinderList
type notation_var_internalization_type =
| NtnInternTypeConstr | NtnInternTypeBinder | NtnInternTypeIdent
type interpretation =
(identifier * (subscopes * notation_var_instance_type)) list * aconstr
(**********************************************************************)
(* Re-interpret a notation as a glob_constr, taking care of binders *)
let name_to_ident = function
| Anonymous -> error "This expression should be a simple identifier."
| Name id -> id
let to_id g e id = let e,na = g e (Name id) in e,name_to_ident na
let rec cases_pattern_fold_map loc g e = function
| PatVar (_,na) ->
let e',na' = g e na in e', PatVar (loc,na')
| PatCstr (_,cstr,patl,na) ->
let e',na' = g e na in
let e',patl' = list_fold_map (cases_pattern_fold_map loc g) e patl in
e', PatCstr (loc,cstr,patl',na')
let rec subst_glob_vars l = function
| GVar (_,id) as r -> (try List.assoc id l with Not_found -> r)
| GProd (loc,Name id,bk,t,c) ->
let id =
try match List.assoc id l with GVar(_,id') -> id' | _ -> id
with Not_found -> id in
GProd (loc,Name id,bk,subst_glob_vars l t,subst_glob_vars l c)
| GLambda (loc,Name id,bk,t,c) ->
let id =
try match List.assoc id l with GVar(_,id') -> id' | _ -> id
with Not_found -> id in
GLambda (loc,Name id,bk,subst_glob_vars l t,subst_glob_vars l c)
| r -> map_glob_constr (subst_glob_vars l) r (* assume: id is not binding *)
let ldots_var = id_of_string ".."
let glob_constr_of_aconstr_with_binders loc g f e = function
| AVar id -> GVar (loc,id)
| AApp (a,args) -> GApp (loc,f e a, List.map (f e) args)
| AList (x,y,iter,tail,swap) ->
let t = f e tail in let it = f e iter in
let innerl = (ldots_var,t)::(if swap then [] else [x,GVar(loc,y)]) in
let inner = GApp (loc,GVar (loc,ldots_var),[subst_glob_vars innerl it]) in
let outerl = (ldots_var,inner)::(if swap then [x,GVar(loc,y)] else []) in
subst_glob_vars outerl it
| ABinderList (x,y,iter,tail) ->
let t = f e tail in let it = f e iter in
let innerl = [(ldots_var,t);(x,GVar(loc,y))] in
let inner = GApp (loc,GVar (loc,ldots_var),[subst_glob_vars innerl it]) in
let outerl = [(ldots_var,inner)] in
subst_glob_vars outerl it
| ALambda (na,ty,c) ->
let e',na = g e na in GLambda (loc,na,Explicit,f e ty,f e' c)
| AProd (na,ty,c) ->
let e',na = g e na in GProd (loc,na,Explicit,f e ty,f e' c)
| ALetIn (na,b,c) ->
let e',na = g e na in GLetIn (loc,na,f e b,f e' c)
| ACases (sty,rtntypopt,tml,eqnl) ->
let e',tml' = List.fold_right (fun (tm,(na,t)) (e',tml') ->
let e',t' = match t with
| None -> e',None
| Some (ind,nal) ->
let e',nal' = List.fold_right (fun na (e',nal) ->
let e',na' = g e' na in e',na'::nal) nal (e',[]) in
e',Some (loc,ind,nal') in
let e',na' = g e' na in
(e',(f e tm,(na',t'))::tml')) tml (e,[]) in
let fold (idl,e) na = let (e,na) = g e na in ((name_cons na idl,e),na) in
let eqnl' = List.map (fun (patl,rhs) ->
let ((idl,e),patl) =
list_fold_map (cases_pattern_fold_map loc fold) ([],e) patl in
(loc,idl,patl,f e rhs)) eqnl in
GCases (loc,sty,Option.map (f e') rtntypopt,tml',eqnl')
| ALetTuple (nal,(na,po),b,c) ->
let e',nal = list_fold_map g e nal in
let e'',na = g e na in
GLetTuple (loc,nal,(na,Option.map (f e'') po),f e b,f e' c)
| AIf (c,(na,po),b1,b2) ->
let e',na = g e na in
GIf (loc,f e c,(na,Option.map (f e') po),f e b1,f e b2)
| ARec (fk,idl,dll,tl,bl) ->
let e,dll = array_fold_map (list_fold_map (fun e (na,oc,b) ->
let e,na = g e na in
(e,(na,Explicit,Option.map (f e) oc,f e b)))) e dll in
let e',idl = array_fold_map (to_id g) e idl in
GRec (loc,fk,idl,dll,Array.map (f e) tl,Array.map (f e') bl)
| ACast (c,k) -> GCast (loc,f e c,
match k with
| CastConv (k,t) -> CastConv (k,f e t)
| CastCoerce -> CastCoerce)
| ASort x -> GSort (loc,x)
| AHole x -> GHole (loc,x)
| APatVar n -> GPatVar (loc,(false,n))
| ARef x -> GRef (loc,x)
| ANativeInt i -> GNativeInt(loc, i)
| ANativeArr(t,p) -> GNativeArr(loc, f e t, Array.map (f e) p)
let rec glob_constr_of_aconstr loc x =
let rec aux () x =
glob_constr_of_aconstr_with_binders loc (fun () id -> ((),id)) aux () x
in aux () x
(****************************************************************************)
(* Translating a glob_constr into a notation, interpreting recursive patterns *)
let add_id r id = r := (id :: pi1 !r, pi2 !r, pi3 !r)
let add_name r = function Anonymous -> () | Name id -> add_id r id
let split_at_recursive_part c =
let sub = ref None in
let rec aux = function
| GApp (loc0,GVar(loc,v),c::l) when v = ldots_var ->
if !sub <> None then
Not narrowed enough to find only one recursive part
raise Not_found
else
(sub := Some c;
if l = [] then GVar (loc,ldots_var)
else GApp (loc0,GVar (loc,ldots_var),l))
| c -> map_glob_constr aux c in
let outer_iterator = aux c in
match !sub with
| None -> (* No recursive pattern found *) raise Not_found
| Some c ->
match outer_iterator with
| GVar (_,v) when v = ldots_var -> (* Not enough context *) raise Not_found
| _ -> outer_iterator, c
let on_true_do b f c = if b then (f c; b) else b
let compare_glob_constr f add t1 t2 = match t1,t2 with
| GRef (_,r1), GRef (_,r2) -> eq_gr r1 r2
| GVar (_,v1), GVar (_,v2) -> on_true_do (v1 = v2) add (Name v1)
| GApp (_,f1,l1), GApp (_,f2,l2) -> f f1 f2 & list_for_all2eq f l1 l2
| GLambda (_,na1,bk1,ty1,c1), GLambda (_,na2,bk2,ty2,c2) when na1 = na2 && bk1 = bk2 -> on_true_do (f ty1 ty2 & f c1 c2) add na1
| GProd (_,na1,bk1,ty1,c1), GProd (_,na2,bk2,ty2,c2) when na1 = na2 && bk1 = bk2 ->
on_true_do (f ty1 ty2 & f c1 c2) add na1
| GHole _, GHole _ -> true
| GSort (_,s1), GSort (_,s2) -> s1 = s2
| GLetIn (_,na1,b1,c1), GLetIn (_,na2,b2,c2) when na1 = na2 ->
on_true_do (f b1 b2 & f c1 c2) add na1
| GNativeInt(_,i1), GNativeInt(_,i2) -> Uint63.eq i1 i2
| GNativeArr(_,t1,p1),GNativeArr(_,t2,p2) ->
f t1 t2 & array_for_all2 f p1 p2
| (GCases _ | GRec _
| GPatVar _ | GEvar _ | GLetTuple _ | GIf _ | GCast _),_
| _,(GCases _ | GRec _
| GPatVar _ | GEvar _ | GLetTuple _ | GIf _ | GCast _)
-> error "Unsupported construction in recursive notations."
| (GRef _ | GVar _ | GApp _ | GLambda _ | GProd _
| GHole _ | GSort _ | GLetIn _ | GNativeInt _ | GNativeArr _), _
-> false
let rec eq_glob_constr t1 t2 = compare_glob_constr eq_glob_constr (fun _ -> ()) t1 t2
let subtract_loc loc1 loc2 = make_loc (fst (unloc loc1),fst (unloc loc2)-1)
let check_is_hole id = function GHole _ -> () | t ->
user_err_loc (loc_of_glob_constr t,"",
strbrk "In recursive notation with binders, " ++ pr_id id ++
strbrk " is expected to come without type.")
let compare_recursive_parts found f (iterator,subc) =
let diff = ref None in
let terminator = ref None in
let rec aux c1 c2 = match c1,c2 with
| GVar(_,v), term when v = ldots_var ->
(* We found the pattern *)
assert (!terminator = None); terminator := Some term;
true
| GApp (_,GVar(_,v),l1), GApp (_,term,l2) when v = ldots_var ->
(* We found the pattern, but there are extra arguments *)
(* (this allows e.g. alternative (recursive) notation of application) *)
assert (!terminator = None); terminator := Some term;
list_for_all2eq aux l1 l2
| GVar (_,x), GVar (_,y) when x<>y ->
(* We found the position where it differs *)
let lassoc = (!terminator <> None) in
let x,y = if lassoc then y,x else x,y in
!diff = None && (diff := Some (x,y,Some lassoc); true)
| GLambda (_,Name x,_,t_x,c), GLambda (_,Name y,_,t_y,term)
| GProd (_,Name x,_,t_x,c), GProd (_,Name y,_,t_y,term) ->
(* We found a binding position where it differs *)
check_is_hole x t_x;
check_is_hole y t_y;
!diff = None && (diff := Some (x,y,None); aux c term)
| _ ->
compare_glob_constr aux (add_name found) c1 c2 in
if aux iterator subc then
match !diff with
| None ->
let loc1 = loc_of_glob_constr iterator in
let loc2 = loc_of_glob_constr (Option.get !terminator) in
(* Here, we would need a loc made of several parts ... *)
user_err_loc (subtract_loc loc1 loc2,"",
str "Both ends of the recursive pattern are the same.")
| Some (x,y,Some lassoc) ->
let newfound = (pi1 !found, (x,y) :: pi2 !found, pi3 !found) in
let iterator =
f (if lassoc then subst_glob_vars [y,GVar(dummy_loc,x)] iterator
else iterator) in
(* found have been collected by compare_constr *)
found := newfound;
AList (x,y,iterator,f (Option.get !terminator),lassoc)
| Some (x,y,None) ->
let newfound = (pi1 !found, pi2 !found, (x,y) :: pi3 !found) in
let iterator = f iterator in
(* found have been collected by compare_constr *)
found := newfound;
ABinderList (x,y,iterator,f (Option.get !terminator))
else
raise Not_found
let aconstr_and_vars_of_glob_constr a =
let found = ref ([],[],[]) in
let rec aux c =
let keepfound = !found in
(* n^2 complexity but small and done only once per notation *)
try compare_recursive_parts found aux' (split_at_recursive_part c)
with Not_found ->
found := keepfound;
match c with
| GApp (_,GVar (loc,f),[c]) when f = ldots_var ->
Fall on the second part of the recursive pattern w/o having
found the first part
found the first part *)
user_err_loc (loc,"",
str "Cannot find where the recursive pattern starts.")
| c ->
aux' c
and aux' = function
| GVar (_,id) -> add_id found id; AVar id
| GApp (_,g,args) -> AApp (aux g, List.map aux args)
| GLambda (_,na,bk,ty,c) -> add_name found na; ALambda (na,aux ty,aux c)
| GProd (_,na,bk,ty,c) -> add_name found na; AProd (na,aux ty,aux c)
| GLetIn (_,na,b,c) -> add_name found na; ALetIn (na,aux b,aux c)
| GCases (_,sty,rtntypopt,tml,eqnl) ->
let f (_,idl,pat,rhs) = List.iter (add_id found) idl; (pat,aux rhs) in
ACases (sty,Option.map aux rtntypopt,
List.map (fun (tm,(na,x)) ->
add_name found na;
Option.iter
(fun (_,_,nl) -> List.iter (add_name found) nl) x;
(aux tm,(na,Option.map (fun (_,ind,nal) -> (ind,nal)) x))) tml,
List.map f eqnl)
| GLetTuple (loc,nal,(na,po),b,c) ->
add_name found na;
List.iter (add_name found) nal;
ALetTuple (nal,(na,Option.map aux po),aux b,aux c)
| GIf (loc,c,(na,po),b1,b2) ->
add_name found na;
AIf (aux c,(na,Option.map aux po),aux b1,aux b2)
| GRec (_,fk,idl,dll,tl,bl) ->
Array.iter (add_id found) idl;
let dll = Array.map (List.map (fun (na,bk,oc,b) ->
if bk <> Explicit then
error "Binders marked as implicit not allowed in notations.";
add_name found na; (na,Option.map aux oc,aux b))) dll in
ARec (fk,idl,dll,Array.map aux tl,Array.map aux bl)
| GCast (_,c,k) -> ACast (aux c,
match k with CastConv (k,t) -> CastConv (k,aux t)
| CastCoerce -> CastCoerce)
| GSort (_,s) -> ASort s
| GHole (_,w) -> AHole w
| GRef (_,r) -> ARef r
| GPatVar (_,(_,n)) -> APatVar n
| GNativeInt(_,i) -> ANativeInt i
| GNativeArr(_,t,p) -> ANativeArr(aux t, Array.map aux p)
| GEvar _ ->
error "Existential variables not allowed in notations."
in
let t = aux a in
(* Side effect *)
t, !found
let rec list_rev_mem_assoc x = function
| [] -> false
| (_,x')::l -> x = x' || list_rev_mem_assoc x l
let check_variables vars recvars (found,foundrec,foundrecbinding) =
let useless_vars = List.map snd recvars in
let vars = List.filter (fun (y,_) -> not (List.mem y useless_vars)) vars in
let check_recvar x =
if List.mem x found then
errorlabstrm "" (pr_id x ++
strbrk " should only be used in the recursive part of a pattern.") in
List.iter (fun (x,y) -> check_recvar x; check_recvar y)
(foundrec@foundrecbinding);
let check_bound x =
if not (List.mem x found) then
if List.mem_assoc x foundrec or List.mem_assoc x foundrecbinding
or list_rev_mem_assoc x foundrec or list_rev_mem_assoc x foundrecbinding
then
error ((string_of_id x)^" should not be bound in a recursive pattern of the right-hand side.")
else
error ((string_of_id x)^" is unbound in the right-hand side.") in
let check_pair s x y where =
if not (List.mem (x,y) where) then
errorlabstrm "" (strbrk "in the right-hand side, " ++ pr_id x ++
str " and " ++ pr_id y ++ strbrk " should appear in " ++ str s ++
str " position as part of a recursive pattern.") in
let check_type (x,typ) =
match typ with
| NtnInternTypeConstr ->
begin
try check_pair "term" x (List.assoc x recvars) foundrec
with Not_found -> check_bound x
end
| NtnInternTypeBinder ->
begin
try check_pair "binding" x (List.assoc x recvars) foundrecbinding
with Not_found -> check_bound x
end
| NtnInternTypeIdent -> check_bound x in
List.iter check_type vars
let aconstr_of_glob_constr vars recvars a =
let a,found = aconstr_and_vars_of_glob_constr a in
check_variables vars recvars found;
a
(* Substitution of kernel names, avoiding a list of bound identifiers *)
let aconstr_of_constr avoiding t =
aconstr_of_glob_constr [] [] (Detyping.detype false avoiding [] t)
let rec subst_pat subst pat =
match pat with
| PatVar _ -> pat
| PatCstr (loc,((kn,i),j),cpl,n) ->
let kn' = subst_ind subst kn
and cpl' = list_smartmap (subst_pat subst) cpl in
if kn' == kn && cpl' == cpl then pat else
PatCstr (loc,((kn',i),j),cpl',n)
let rec subst_aconstr subst bound raw =
match raw with
| ARef ref ->
let ref',t = subst_global subst ref in
if ref' == ref then raw else
aconstr_of_constr bound t
| AVar _ -> raw
| AApp (r,rl) ->
let r' = subst_aconstr subst bound r
and rl' = list_smartmap (subst_aconstr subst bound) rl in
if r' == r && rl' == rl then raw else
AApp(r',rl')
| AList (id1,id2,r1,r2,b) ->
let r1' = subst_aconstr subst bound r1
and r2' = subst_aconstr subst bound r2 in
if r1' == r1 && r2' == r2 then raw else
AList (id1,id2,r1',r2',b)
| ALambda (n,r1,r2) ->
let r1' = subst_aconstr subst bound r1
and r2' = subst_aconstr subst bound r2 in
if r1' == r1 && r2' == r2 then raw else
ALambda (n,r1',r2')
| AProd (n,r1,r2) ->
let r1' = subst_aconstr subst bound r1
and r2' = subst_aconstr subst bound r2 in
if r1' == r1 && r2' == r2 then raw else
AProd (n,r1',r2')
| ABinderList (id1,id2,r1,r2) ->
let r1' = subst_aconstr subst bound r1
and r2' = subst_aconstr subst bound r2 in
if r1' == r1 && r2' == r2 then raw else
ABinderList (id1,id2,r1',r2')
| ALetIn (n,r1,r2) ->
let r1' = subst_aconstr subst bound r1
and r2' = subst_aconstr subst bound r2 in
if r1' == r1 && r2' == r2 then raw else
ALetIn (n,r1',r2')
| ACases (sty,rtntypopt,rl,branches) ->
let rtntypopt' = Option.smartmap (subst_aconstr subst bound) rtntypopt
and rl' = list_smartmap
(fun (a,(n,signopt) as x) ->
let a' = subst_aconstr subst bound a in
let signopt' = Option.map (fun ((indkn,i),nal as z) ->
let indkn' = subst_ind subst indkn in
if indkn == indkn' then z else ((indkn',i),nal)) signopt in
if a' == a && signopt' == signopt then x else (a',(n,signopt')))
rl
and branches' = list_smartmap
(fun (cpl,r as branch) ->
let cpl' = list_smartmap (subst_pat subst) cpl
and r' = subst_aconstr subst bound r in
if cpl' == cpl && r' == r then branch else
(cpl',r'))
branches
in
if rtntypopt' == rtntypopt && rtntypopt == rtntypopt' &
rl' == rl && branches' == branches then raw else
ACases (sty,rtntypopt',rl',branches')
| ALetTuple (nal,(na,po),b,c) ->
let po' = Option.smartmap (subst_aconstr subst bound) po
and b' = subst_aconstr subst bound b
and c' = subst_aconstr subst bound c in
if po' == po && b' == b && c' == c then raw else
ALetTuple (nal,(na,po'),b',c')
| AIf (c,(na,po),b1,b2) ->
let po' = Option.smartmap (subst_aconstr subst bound) po
and b1' = subst_aconstr subst bound b1
and b2' = subst_aconstr subst bound b2
and c' = subst_aconstr subst bound c in
if po' == po && b1' == b1 && b2' == b2 && c' == c then raw else
AIf (c',(na,po'),b1',b2')
| ARec (fk,idl,dll,tl,bl) ->
let dll' =
array_smartmap (list_smartmap (fun (na,oc,b as x) ->
let oc' = Option.smartmap (subst_aconstr subst bound) oc in
let b' = subst_aconstr subst bound b in
if oc' == oc && b' == b then x else (na,oc',b'))) dll in
let tl' = array_smartmap (subst_aconstr subst bound) tl in
let bl' = array_smartmap (subst_aconstr subst bound) bl in
if dll' == dll && tl' == tl && bl' == bl then raw else
ARec (fk,idl,dll',tl',bl')
| APatVar _ | ASort _ -> raw
| AHole (Evd.ImplicitArg (ref,i,b)) ->
let ref',t = subst_global subst ref in
if ref' == ref then raw else
AHole (Evd.InternalHole)
| AHole (Evd.BinderType _ | Evd.QuestionMark _ | Evd.CasesType
| Evd.InternalHole | Evd.TomatchTypeParameter _ | Evd.GoalEvar
| Evd.ImpossibleCase | Evd.MatchingVar _) -> raw
| ANativeInt _ -> raw
| ANativeArr(t,p) ->
let t' = subst_aconstr subst bound t
and p' = array_smartmap (subst_aconstr subst bound) p in
if t' == t && p' == p then raw else
ANativeArr(t',p')
| ACast (r1,k) ->
match k with
CastConv (k, r2) ->
let r1' = subst_aconstr subst bound r1
and r2' = subst_aconstr subst bound r2 in
if r1' == r1 && r2' == r2 then raw else
ACast (r1',CastConv (k,r2'))
| CastCoerce ->
let r1' = subst_aconstr subst bound r1 in
if r1' == r1 then raw else
ACast (r1',CastCoerce)
let subst_interpretation subst (metas,pat) =
let bound = List.map fst metas in
(metas,subst_aconstr subst bound pat)
(* Pattern-matching glob_constr and aconstr *)
let abstract_return_type_context pi mklam tml rtno =
Option.map (fun rtn ->
let nal =
List.flatten (List.map (fun (_,(na,t)) ->
match t with Some x -> (pi x)@[na] | None -> [na]) tml) in
List.fold_right mklam nal rtn)
rtno
let abstract_return_type_context_glob_constr =
abstract_return_type_context (fun (_,_,nal) -> nal)
(fun na c -> GLambda(dummy_loc,na,Explicit,GHole(dummy_loc,Evd.InternalHole),c))
let abstract_return_type_context_aconstr =
abstract_return_type_context snd
(fun na c -> ALambda(na,AHole Evd.InternalHole,c))
exception No_match
let rec alpha_var id1 id2 = function
| (i1,i2)::_ when i1=id1 -> i2 = id2
| (i1,i2)::_ when i2=id2 -> i1 = id1
| _::idl -> alpha_var id1 id2 idl
| [] -> id1 = id2
let alpha_eq_val (x,y) = x = y
let bind_env alp (sigma,sigmalist,sigmabinders as fullsigma) var v =
try
let vvar = List.assoc var sigma in
if alpha_eq_val (v,vvar) then fullsigma
else raise No_match
with Not_found ->
(* Check that no capture of binding variables occur *)
if List.exists (fun (id,_) ->occur_glob_constr id v) alp then raise No_match;
(* TODO: handle the case of multiple occs in different scopes *)
((var,v)::sigma,sigmalist,sigmabinders)
let bind_binder (sigma,sigmalist,sigmabinders) x bl =
(sigma,sigmalist,(x,List.rev bl)::sigmabinders)
let match_fix_kind fk1 fk2 =
match (fk1,fk2) with
| GCoFix n1, GCoFix n2 -> n1 = n2
| GFix (nl1,n1), GFix (nl2,n2) ->
n1 = n2 &&
array_for_all2 (fun (n1,_) (n2,_) -> n2 = None || n1 = n2) nl1 nl2
| _ -> false
let match_opt f sigma t1 t2 = match (t1,t2) with
| None, None -> sigma
| Some t1, Some t2 -> f sigma t1 t2
| _ -> raise No_match
let match_names metas (alp,sigma) na1 na2 = match (na1,na2) with
| (_,Name id2) when List.mem id2 (fst metas) ->
let rhs = match na1 with
| Name id1 -> GVar (dummy_loc,id1)
| Anonymous -> GHole (dummy_loc,Evd.InternalHole) in
alp, bind_env alp sigma id2 rhs
| (Name id1,Name id2) -> (id1,id2)::alp,sigma
| (Anonymous,Anonymous) -> alp,sigma
| _ -> raise No_match
let rec match_cases_pattern_binders metas acc pat1 pat2 =
match (pat1,pat2) with
| PatVar (_,na1), PatVar (_,na2) -> match_names metas acc na1 na2
| PatCstr (_,c1,patl1,na1), PatCstr (_,c2,patl2,na2)
when c1 = c2 & List.length patl1 = List.length patl2 ->
List.fold_left2 (match_cases_pattern_binders metas)
(match_names metas acc na1 na2) patl1 patl2
| _ -> raise No_match
let glue_letin_with_decls = true
let rec match_iterated_binders islambda decls = function
| GLambda (_,na,bk,t,b) when islambda ->
match_iterated_binders islambda ((na,bk,None,t)::decls) b
| GProd (_,(Name _ as na),bk,t,b) when not islambda ->
match_iterated_binders islambda ((na,bk,None,t)::decls) b
| GLetIn (loc,na,c,b) when glue_letin_with_decls ->
match_iterated_binders islambda
((na,Explicit (*?*), Some c,GHole(loc,Evd.BinderType na))::decls) b
| b -> (decls,b)
let remove_sigma x (sigmavar,sigmalist,sigmabinders) =
(List.remove_assoc x sigmavar,sigmalist,sigmabinders)
let rec match_abinderlist_with_app match_fun metas sigma rest x iter termin =
let rec aux sigma acc rest =
try
let sigma = match_fun (ldots_var::fst metas,snd metas) sigma rest iter in
let rest = List.assoc ldots_var (pi1 sigma) in
let b = match List.assoc x (pi3 sigma) with [b] -> b | _ ->assert false in
let sigma = remove_sigma x (remove_sigma ldots_var sigma) in
aux sigma (b::acc) rest
with No_match when acc <> [] ->
acc, match_fun metas sigma rest termin in
let bl,sigma = aux sigma [] rest in
bind_binder sigma x bl
let match_alist match_fun metas sigma rest x iter termin lassoc =
let rec aux sigma acc rest =
try
let sigma = match_fun (ldots_var::fst metas,snd metas) sigma rest iter in
let rest = List.assoc ldots_var (pi1 sigma) in
let t = List.assoc x (pi1 sigma) in
let sigma = remove_sigma x (remove_sigma ldots_var sigma) in
aux sigma (t::acc) rest
with No_match when acc <> [] ->
acc, match_fun metas sigma rest termin in
let l,sigma = aux sigma [] rest in
(pi1 sigma, (x,if lassoc then l else List.rev l)::pi2 sigma, pi3 sigma)
let does_not_come_from_already_eta_expanded_var =
(* This is hack to avoid looping on a rule with rhs of the form *)
(* "?f (fun ?x => ?g)" since otherwise, matching "F H" expands in *)
(* "F (fun x => H x)" and "H x" is recursively matched against the same *)
(* rule, giving "H (fun x' => x x')" and so on. *)
(* Ideally, we would need the type of the expression to know which of *)
(* the arguments applied to it can be eta-expanded without looping. *)
(* The following test is then an approximation of what can be done *)
(* optimally (whether other looping situations can occur remains to be *)
(* checked). *)
function GVar _ -> false | _ -> true
let rec match_ inner u alp (tmetas,blmetas as metas) sigma a1 a2 =
match (a1,a2) with
(* Matching notation variable *)
| r1, AVar id2 when List.mem id2 tmetas -> bind_env alp sigma id2 r1
(* Matching recursive notations for terms *)
| r1, AList (x,_,iter,termin,lassoc) ->
match_alist (match_hd u alp) metas sigma r1 x iter termin lassoc
(* Matching recursive notations for binders: ad hoc cases supporting let-in *)
| GLambda (_,na1,bk,t1,b1), ABinderList (x,_,ALambda (Name id2,_,b2),termin)->
let (decls,b) = match_iterated_binders true [(na1,bk,None,t1)] b1 in
(* TODO: address the possibility that termin is a Lambda itself *)
match_in u alp metas (bind_binder sigma x decls) b termin
| GProd (_,na1,bk,t1,b1), ABinderList (x,_,AProd (Name id2,_,b2),termin)
when na1 <> Anonymous ->
let (decls,b) = match_iterated_binders false [(na1,bk,None,t1)] b1 in
(* TODO: address the possibility that termin is a Prod itself *)
match_in u alp metas (bind_binder sigma x decls) b termin
(* Matching recursive notations for binders: general case *)
| r, ABinderList (x,_,iter,termin) ->
match_abinderlist_with_app (match_hd u alp) metas sigma r x iter termin
(* Matching individual binders as part of a recursive pattern *)
| GLambda (_,na,bk,t,b1), ALambda (Name id,_,b2) when List.mem id blmetas ->
match_in u alp metas (bind_binder sigma id [(na,bk,None,t)]) b1 b2
| GProd (_,na,bk,t,b1), AProd (Name id,_,b2)
when List.mem id blmetas & na <> Anonymous ->
match_in u alp metas (bind_binder sigma id [(na,bk,None,t)]) b1 b2
(* Matching compositionally *)
| GVar (_,id1), AVar id2 when alpha_var id1 id2 alp -> sigma
| GRef (_,r1), ARef r2 when (eq_gr r1 r2) -> sigma
| GPatVar (_,(_,n1)), APatVar n2 when n1=n2 -> sigma
| GApp (loc,f1,l1), AApp (f2,l2) ->
let n1 = List.length l1 and n2 = List.length l2 in
let f1,l1,f2,l2 =
if n1 < n2 then
let l21,l22 = list_chop (n2-n1) l2 in f1,l1, AApp (f2,l21), l22
else if n1 > n2 then
let l11,l12 = list_chop (n1-n2) l1 in GApp (loc,f1,l11),l12, f2,l2
else f1,l1, f2, l2 in
let may_use_eta = does_not_come_from_already_eta_expanded_var f1 in
List.fold_left2 (match_ may_use_eta u alp metas)
(match_in u alp metas sigma f1 f2) l1 l2
| GLambda (_,na1,_,t1,b1), ALambda (na2,t2,b2) ->
match_binders u alp metas na1 na2 (match_in u alp metas sigma t1 t2) b1 b2
| GProd (_,na1,_,t1,b1), AProd (na2,t2,b2) ->
match_binders u alp metas na1 na2 (match_in u alp metas sigma t1 t2) b1 b2
| GLetIn (_,na1,t1,b1), ALetIn (na2,t2,b2) ->
match_binders u alp metas na1 na2 (match_in u alp metas sigma t1 t2) b1 b2
| GCases (_,sty1,rtno1,tml1,eqnl1), ACases (sty2,rtno2,tml2,eqnl2)
when sty1 = sty2
& List.length tml1 = List.length tml2
& List.length eqnl1 = List.length eqnl2 ->
let rtno1' = abstract_return_type_context_glob_constr tml1 rtno1 in
let rtno2' = abstract_return_type_context_aconstr tml2 rtno2 in
let sigma =
try Option.fold_left2 (match_in u alp metas) sigma rtno1' rtno2'
with Option.Heterogeneous -> raise No_match
in
let sigma = List.fold_left2
(fun s (tm1,_) (tm2,_) ->
match_in u alp metas s tm1 tm2) sigma tml1 tml2 in
List.fold_left2 (match_equations u alp metas) sigma eqnl1 eqnl2
| GLetTuple (_,nal1,(na1,to1),b1,c1), ALetTuple (nal2,(na2,to2),b2,c2)
when List.length nal1 = List.length nal2 ->
let sigma = match_opt (match_binders u alp metas na1 na2) sigma to1 to2 in
let sigma = match_in u alp metas sigma b1 b2 in
let (alp,sigma) =
List.fold_left2 (match_names metas) (alp,sigma) nal1 nal2 in
match_in u alp metas sigma c1 c2
| GIf (_,a1,(na1,to1),b1,c1), AIf (a2,(na2,to2),b2,c2) ->
let sigma = match_opt (match_binders u alp metas na1 na2) sigma to1 to2 in
List.fold_left2 (match_in u alp metas) sigma [a1;b1;c1] [a2;b2;c2]
| GRec (_,fk1,idl1,dll1,tl1,bl1), ARec (fk2,idl2,dll2,tl2,bl2)
when match_fix_kind fk1 fk2 & Array.length idl1 = Array.length idl2 &
array_for_all2 (fun l1 l2 -> List.length l1 = List.length l2) dll1 dll2
->
let alp,sigma = array_fold_left2
(List.fold_left2 (fun (alp,sigma) (na1,_,oc1,b1) (na2,oc2,b2) ->
let sigma =
match_in u alp metas
(match_opt (match_in u alp metas) sigma oc1 oc2) b1 b2
in match_names metas (alp,sigma) na1 na2)) (alp,sigma) dll1 dll2 in
let sigma = array_fold_left2 (match_in u alp metas) sigma tl1 tl2 in
let alp,sigma = array_fold_right2 (fun id1 id2 alsig ->
match_names metas alsig (Name id1) (Name id2)) idl1 idl2 (alp,sigma) in
array_fold_left2 (match_in u alp metas) sigma bl1 bl2
| GCast(_,c1, CastConv(_,t1)), ACast(c2, CastConv (_,t2)) ->
match_in u alp metas (match_in u alp metas sigma c1 c2) t1 t2
| GCast(_,c1, CastCoerce), ACast(c2, CastCoerce) ->
match_in u alp metas sigma c1 c2
| GSort (_,GType _), ASort (GType None) when not u -> sigma
| GSort (_,s1), ASort s2 when s1 = s2 -> sigma
Do n't hide Metas , they bind in ltac
| a, AHole _ -> sigma
On the fly eta - expansion so as to use notations of the form
" exists x , P x " for " ex P " ; expects type not given because do n't know
otherwise how to ensure it corresponds to a well - typed eta - expansion ;
ensure at least one constructor is consumed to avoid looping
"exists x, P x" for "ex P"; expects type not given because don't know
otherwise how to ensure it corresponds to a well-typed eta-expansion;
ensure at least one constructor is consumed to avoid looping *)
| b1, ALambda (Name id,AHole _,b2) when inner ->
let id' = Namegen.next_ident_away id (free_glob_vars b1) in
match_in u alp metas (bind_binder sigma id
[(Name id',Explicit,None,GHole(dummy_loc,Evd.BinderType (Name id')))])
(mkGApp dummy_loc b1 (GVar (dummy_loc,id'))) b2
| (GRec _ | GEvar _), _
| _,_ -> raise No_match
and match_in u = match_ true u
and match_hd u = match_ false u
and match_binders u alp metas na1 na2 sigma b1 b2 =
let (alp,sigma) = match_names metas (alp,sigma) na1 na2 in
match_in u alp metas sigma b1 b2
and match_equations u alp metas sigma (_,_,patl1,rhs1) (patl2,rhs2) =
patl1 and patl2 have the same length because they respectively
correspond to some tml1 and tml2 that have the same length
correspond to some tml1 and tml2 that have the same length *)
let (alp,sigma) =
List.fold_left2 (match_cases_pattern_binders metas)
(alp,sigma) patl1 patl2 in
match_in u alp metas sigma rhs1 rhs2
let match_aconstr u c (metas,pat) =
let vars = list_split_by (fun (_,(_,x)) -> x <> NtnTypeBinderList) metas in
let vars = (List.map fst (fst vars), List.map fst (snd vars)) in
let terms,termlists,binders = match_ false u [] vars ([],[],[]) c pat in
(* Reorder canonically the substitution *)
let find x =
try List.assoc x terms
with Not_found ->
(* Happens for binders bound to Anonymous *)
(* Find a better way to propagate Anonymous... *)
GVar (dummy_loc,x) in
List.fold_right (fun (x,(scl,typ)) (terms',termlists',binders') ->
match typ with
| NtnTypeConstr ->
((find x, scl)::terms',termlists',binders')
| NtnTypeConstrList ->
(terms',(List.assoc x termlists,scl)::termlists',binders')
| NtnTypeBinderList ->
(terms',termlists',(List.assoc x binders,scl)::binders'))
metas ([],[],[])
(* Matching cases pattern *)
let add_patterns_for_params (ind,k) l =
let mib,_ = Global.lookup_inductive ind in
let nparams = mib.Declarations.mind_nparams in
Util.list_addn nparams (PatVar (dummy_loc,Anonymous)) l
let bind_env_cases_pattern (sigma,sigmalist,x as fullsigma) var v =
try
let vvar = List.assoc var sigma in
if v=vvar then fullsigma else raise No_match
with Not_found ->
(* TODO: handle the case of multiple occs in different scopes *)
(var,v)::sigma,sigmalist,x
let rec match_cases_pattern metas sigma a1 a2 =
let match_cases_pattern_no_more_args metas sigma a1 a2 =
match match_cases_pattern metas sigma a1 a2 with
|out,[] -> out
|_ -> raise No_match in
match (a1,a2) with
| r1, AVar id2 when List.mem id2 metas -> (bind_env_cases_pattern sigma id2 r1),[]
| PatVar (_,Anonymous), AHole _ -> sigma,[]
| PatCstr (loc,(ind,_ as r1),largs,_), ARef (ConstructRef r2) when r1 = r2 ->
sigma,largs
| PatCstr (loc,(ind,_ as r1),args1,_), AApp (ARef (ConstructRef r2),l2)
when r1 = r2 ->
let l1 = add_patterns_for_params r1 args1 in
let le2 = List.length l2 in
if le2 > List.length l1
then
raise No_match
else
let l1',more_args = Util.list_chop le2 l1 in
(List.fold_left2 (match_cases_pattern_no_more_args metas) sigma l1' l2),more_args
| r1, AList (x,_,iter,termin,lassoc) ->
(match_alist (fun (metas,_) -> match_cases_pattern_no_more_args metas)
(metas,[]) (pi1 sigma,pi2 sigma,()) r1 x iter termin lassoc),[]
| _ -> raise No_match
let match_aconstr_cases_pattern c (metas,pat) =
let vars = List.map fst metas in
let (terms,termlists,()),more_args = match_cases_pattern vars ([],[],()) c pat in
(* Reorder canonically the substitution *)
(List.fold_right (fun (x,(scl,typ)) (terms',termlists') ->
match typ with
| NtnTypeConstr -> ((List.assoc x terms, scl)::terms',termlists')
| NtnTypeConstrList -> (terms',(List.assoc x termlists,scl)::termlists')
| NtnTypeBinderList -> assert false)
metas ([],[])),more_args
(**********************************************************************)
(*s Concrete syntax for terms *)
type notation = string
type explicitation = ExplByPos of int * identifier option | ExplByName of identifier
type binder_kind = Default of binding_kind | Generalized of binding_kind * binding_kind * bool
type abstraction_kind = AbsLambda | AbsPi
type proj_flag = int option (* [Some n] = proj of the n-th visible argument *)
type prim_token = Numeral of Bigint.bigint | String of string
type cases_pattern_expr =
| CPatAlias of loc * cases_pattern_expr * identifier
| CPatCstr of loc * reference * cases_pattern_expr list
| CPatCstrExpl of loc * reference * cases_pattern_expr list
| CPatAtom of loc * reference option
| CPatOr of loc * cases_pattern_expr list
| CPatNotation of loc * notation * cases_pattern_notation_substitution
| CPatPrim of loc * prim_token
| CPatRecord of loc * (reference * cases_pattern_expr) list
| CPatDelimiters of loc * string * cases_pattern_expr
and cases_pattern_notation_substitution =
* for
cases_pattern_expr list list (** for recursive notations *)
type constr_expr =
| CRef of reference
| CFix of loc * identifier located * fix_expr list
| CCoFix of loc * identifier located * cofix_expr list
| CProdN of loc * (name located list * binder_kind * constr_expr) list * constr_expr
| CLambdaN of loc * (name located list * binder_kind * constr_expr) list * constr_expr
| CLetIn of loc * name located * constr_expr * constr_expr
| CAppExpl of loc * (proj_flag * reference) * constr_expr list
| CApp of loc * (proj_flag * constr_expr) *
(constr_expr * explicitation located option) list
| CRecord of loc * constr_expr option * (reference * constr_expr) list
| CCases of loc * case_style * constr_expr option *
(constr_expr * (name located option * cases_pattern_expr option)) list *
(loc * cases_pattern_expr list located list * constr_expr) list
| CLetTuple of loc * name located list * (name located option * constr_expr option) *
constr_expr * constr_expr
| CIf of loc * constr_expr * (name located option * constr_expr option)
* constr_expr * constr_expr
| CHole of loc * Evd.hole_kind option
| CPatVar of loc * (bool * patvar)
| CEvar of loc * existential_key * constr_expr list option
| CSort of loc * glob_sort
| CCast of loc * constr_expr * constr_expr cast_type
| CNotation of loc * notation * constr_notation_substitution
| CGeneralization of loc * binding_kind * abstraction_kind option * constr_expr
| CPrim of loc * prim_token
| CDelimiters of loc * string * constr_expr
| CNativeArr of loc * constr_expr * constr_expr array
and fix_expr =
identifier located * (identifier located option * recursion_order_expr) * local_binder list * constr_expr * constr_expr
and cofix_expr =
identifier located * local_binder list * constr_expr * constr_expr
and recursion_order_expr =
| CStructRec
| CWfRec of constr_expr
| CMeasureRec of constr_expr * constr_expr option (* measure, relation *)
and local_binder =
| LocalRawDef of name located * constr_expr
| LocalRawAssum of name located list * binder_kind * constr_expr
and constr_notation_substitution =
for
constr_expr list list * (* for recursive notations *)
local_binder list list (* for binders subexpressions *)
type typeclass_constraint = name located * binding_kind * constr_expr
and typeclass_context = typeclass_constraint list
type constr_pattern_expr = constr_expr
let oldfashion_patterns = ref (true)
let write_oldfashion_patterns = Goptions.declare_bool_option {
Goptions.optsync = true; Goptions.optdepr = false;
Goptions.optname =
"Constructors in patterns require all their arguments but no parameters instead of explicit parameters and arguments";
Goptions.optkey = ["Asymmetric";"Patterns"];
Goptions.optread = (fun () -> !oldfashion_patterns);
Goptions.optwrite = (fun a -> oldfashion_patterns:=a);
}
(***********************)
(* For binders parsing *)
let default_binder_kind = Default Explicit
let names_of_local_assums bl =
List.flatten (List.map (function LocalRawAssum(l,_,_)->l|_->[]) bl)
let names_of_local_binders bl =
List.flatten (List.map (function LocalRawAssum(l,_,_)->l|LocalRawDef(l,_)->[l]) bl)
(**********************************************************************)
(* Miscellaneous *)
let error_invalid_pattern_notation loc =
user_err_loc (loc,"",str "Invalid notation for pattern.")
(**********************************************************************)
(* Functions on constr_expr *)
let constr_loc = function
| CRef (Ident (loc,_)) -> loc
| CRef (Qualid (loc,_)) -> loc
| CFix (loc,_,_) -> loc
| CCoFix (loc,_,_) -> loc
| CProdN (loc,_,_) -> loc
| CLambdaN (loc,_,_) -> loc
| CLetIn (loc,_,_,_) -> loc
| CAppExpl (loc,_,_) -> loc
| CApp (loc,_,_) -> loc
| CRecord (loc,_,_) -> loc
| CCases (loc,_,_,_,_) -> loc
| CLetTuple (loc,_,_,_,_) -> loc
| CIf (loc,_,_,_,_) -> loc
| CHole (loc, _) -> loc
| CPatVar (loc,_) -> loc
| CEvar (loc,_,_) -> loc
| CSort (loc,_) -> loc
| CCast (loc,_,_) -> loc
| CNotation (loc,_,_) -> loc
| CGeneralization (loc,_,_,_) -> loc
| CPrim (loc,_) -> loc
| CDelimiters (loc,_,_) -> loc
| CNativeArr (loc, _, _) -> loc
let cases_pattern_expr_loc = function
| CPatAlias (loc,_,_) -> loc
| CPatCstr (loc,_,_) -> loc
| CPatCstrExpl (loc,_,_) -> loc
| CPatAtom (loc,_) -> loc
| CPatOr (loc,_) -> loc
| CPatNotation (loc,_,_) -> loc
| CPatRecord (loc, _) -> loc
| CPatPrim (loc,_) -> loc
| CPatDelimiters (loc,_,_) -> loc
let local_binder_loc = function
| LocalRawAssum ((loc,_)::_,_,t)
| LocalRawDef ((loc,_),t) -> join_loc loc (constr_loc t)
| LocalRawAssum ([],_,_) -> assert false
let local_binders_loc bll =
if bll = [] then dummy_loc else
join_loc (local_binder_loc (List.hd bll)) (local_binder_loc (list_last bll))
let ids_of_cases_indtype =
let rec vars_of ids = function
(* We deal only with the regular cases *)
| (CPatCstr (_,_,l)|CPatCstrExpl (_, _, l)|CPatNotation (_,_,(l,[]))) -> List.fold_left vars_of [] l
(* assume the ntn is applicative and does not instantiate the head !! *)
| CPatDelimiters(_,_,c) -> vars_of ids c
| CPatAtom (_, Some (Libnames.Ident (_, x))) -> x::ids
| _ -> ids in
vars_of []
let ids_of_cases_tomatch tms =
List.fold_right
(fun (_,(ona,indnal)) l ->
Option.fold_right (fun t -> (@) (ids_of_cases_indtype t))
indnal (Option.fold_right (down_located name_cons) ona l))
tms []
let is_constructor id =
try ignore (Nametab.locate_extended (qualid_of_ident id)); true
with Not_found -> true
let rec cases_pattern_fold_names f a = function
| CPatRecord (_, l) ->
List.fold_left (fun acc (r, cp) -> cases_pattern_fold_names f acc cp) a l
| CPatAlias (_,pat,id) -> f id a
| CPatCstr (_,_,patl) | CPatCstrExpl (_,_,patl) | CPatOr (_,patl) ->
List.fold_left (cases_pattern_fold_names f) a patl
| CPatNotation (_,_,(patl,patll)) ->
List.fold_left (cases_pattern_fold_names f) a ( patll)
| CPatDelimiters (_,_,pat) -> cases_pattern_fold_names f a pat
| CPatAtom (_,Some (Ident (_,id))) when not (is_constructor id) -> f id a
| CPatPrim _ | CPatAtom _ -> a
let ids_of_pattern_list =
List.fold_left
(located_fold_left
(List.fold_left (cases_pattern_fold_names Idset.add)))
Idset.empty
let rec fold_constr_expr_binders g f n acc b = function
| (nal,bk,t)::l ->
let nal = snd (List.split nal) in
let n' = List.fold_right (name_fold g) nal n in
f n (fold_constr_expr_binders g f n' acc b l) t
| [] ->
f n acc b
let rec fold_local_binders g f n acc b = function
| LocalRawAssum (nal,bk,t)::l ->
let nal = snd (List.split nal) in
let n' = List.fold_right (name_fold g) nal n in
f n (fold_local_binders g f n' acc b l) t
| LocalRawDef ((_,na),t)::l ->
f n (fold_local_binders g f (name_fold g na n) acc b l) t
| [] ->
f n acc b
let fold_constr_expr_with_binders g f n acc = function
| CAppExpl (loc,(_,_),l) -> List.fold_left (f n) acc l
| CApp (loc,(_,t),l) -> List.fold_left (f n) (f n acc t) (List.map fst l)
| CProdN (_,l,b) | CLambdaN (_,l,b) -> fold_constr_expr_binders g f n acc b l
| CLetIn (_,na,a,b) -> fold_constr_expr_binders g f n acc b [[na],default_binder_kind,a]
| CCast (loc,a,CastConv(_,b)) -> f n (f n acc a) b
| CCast (loc,a,CastCoerce) -> f n acc a
| CNotation (_,_,(l,ll,bll)) ->
(* The following is an approximation: we don't know exactly if
an ident is binding nor to which subterms bindings apply *)
let acc = List.fold_left (f n) acc ( ll) in
List.fold_left (fun acc bl -> fold_local_binders g f n acc (CHole (dummy_loc,None)) bl) acc bll
| CGeneralization (_,_,_,c) -> f n acc c
| CDelimiters (loc,_,a) -> f n acc a
| CHole _ | CEvar _ | CPatVar _ | CSort _ | CPrim _ | CRef _ ->
acc
| CRecord (loc,_,l) -> List.fold_left (fun acc (id, c) -> f n acc c) acc l
| CCases (loc,sty,rtnpo,al,bl) ->
let ids = ids_of_cases_tomatch al in
let acc = Option.fold_left (f (List.fold_right g ids n)) acc rtnpo in
let acc = List.fold_left (f n) acc (List.map fst al) in
List.fold_right (fun (loc,patl,rhs) acc ->
let ids = ids_of_pattern_list patl in
f (Idset.fold g ids n) acc rhs) bl acc
| CLetTuple (loc,nal,(ona,po),b,c) ->
let n' = List.fold_right (down_located (name_fold g)) nal n in
f (Option.fold_right (down_located (name_fold g)) ona n') (f n acc b) c
| CIf (_,c,(ona,po),b1,b2) ->
let acc = f n (f n (f n acc b1) b2) c in
Option.fold_left
(f (Option.fold_right (down_located (name_fold g)) ona n)) acc po
| CFix (loc,_,l) ->
let n' = List.fold_right (fun ((_,id),_,_,_,_) -> g id) l n in
List.fold_right (fun (_,(_,o),lb,t,c) acc ->
fold_local_binders g f n'
(fold_local_binders g f n acc t lb) c lb) l acc
| CCoFix (loc,_,_) ->
Pp.warning "Capture check in multiple binders not done"; acc
| CNativeArr(loc,t,p) ->
Array.fold_left (f n) (f n acc t) p
let free_vars_of_constr_expr c =
let rec aux bdvars l = function
| CRef (Ident (_,id)) -> if List.mem id bdvars then l else Idset.add id l
| c -> fold_constr_expr_with_binders (fun a l -> a::l) aux bdvars l c
in aux [] Idset.empty c
let occur_var_constr_expr id c = Idset.mem id (free_vars_of_constr_expr c)
let mkIdentC id = CRef (Ident (dummy_loc, id))
let mkRefC r = CRef r
let mkCastC (a,k) = CCast (dummy_loc,a,k)
let mkLambdaC (idl,bk,a,b) = CLambdaN (dummy_loc,[idl,bk,a],b)
let mkLetInC (id,a,b) = CLetIn (dummy_loc,id,a,b)
let mkProdC (idl,bk,a,b) = CProdN (dummy_loc,[idl,bk,a],b)
let mkAppC (f,l) =
let l = List.map (fun x -> (x,None)) l in
match f with
| CApp (_,g,l') -> CApp (dummy_loc, g, l' @ l)
| _ -> CApp (dummy_loc, (None, f), l)
let rec mkCProdN loc bll c =
match bll with
| LocalRawAssum ((loc1,_)::_ as idl,bk,t) :: bll ->
CProdN (loc,[idl,bk,t],mkCProdN (join_loc loc1 loc) bll c)
| LocalRawDef ((loc1,_) as id,b) :: bll ->
CLetIn (loc,id,b,mkCProdN (join_loc loc1 loc) bll c)
| [] -> c
| LocalRawAssum ([],_,_) :: bll -> mkCProdN loc bll c
let rec mkCLambdaN loc bll c =
match bll with
| LocalRawAssum ((loc1,_)::_ as idl,bk,t) :: bll ->
CLambdaN (loc,[idl,bk,t],mkCLambdaN (join_loc loc1 loc) bll c)
| LocalRawDef ((loc1,_) as id,b) :: bll ->
CLetIn (loc,id,b,mkCLambdaN (join_loc loc1 loc) bll c)
| [] -> c
| LocalRawAssum ([],_,_) :: bll -> mkCLambdaN loc bll c
let rec abstract_constr_expr c = function
| [] -> c
| LocalRawDef (x,b)::bl -> mkLetInC(x,b,abstract_constr_expr c bl)
| LocalRawAssum (idl,bk,t)::bl ->
List.fold_right (fun x b -> mkLambdaC([x],bk,t,b)) idl
(abstract_constr_expr c bl)
let rec prod_constr_expr c = function
| [] -> c
| LocalRawDef (x,b)::bl -> mkLetInC(x,b,prod_constr_expr c bl)
| LocalRawAssum (idl,bk,t)::bl ->
List.fold_right (fun x b -> mkProdC([x],bk,t,b)) idl
(prod_constr_expr c bl)
let coerce_reference_to_id = function
| Ident (_,id) -> id
| Qualid (loc,_) ->
user_err_loc (loc, "coerce_reference_to_id",
str "This expression should be a simple identifier.")
let coerce_to_id = function
| CRef (Ident (loc,id)) -> (loc,id)
| a -> user_err_loc
(constr_loc a,"coerce_to_id",
str "This expression should be a simple identifier.")
let coerce_to_name = function
| CRef (Ident (loc,id)) -> (loc,Name id)
| CHole (loc,_) -> (loc,Anonymous)
| a -> user_err_loc
(constr_loc a,"coerce_to_name",
str "This expression should be a name.")
(* Interpret the index of a recursion order annotation *)
let split_at_annot bl na =
let names = List.map snd (names_of_local_assums bl) in
match na with
| None ->
if names = [] then error "A fixpoint needs at least one parameter."
else [], bl
| Some (loc, id) ->
let rec aux acc = function
| LocalRawAssum (bls, k, t) as x :: rest ->
let l, r = list_split_when (fun (loc, na) -> na = Name id) bls in
if r = [] then aux (x :: acc) rest
else
(List.rev (if l = [] then acc else LocalRawAssum (l, k, t) :: acc),
LocalRawAssum (r, k, t) :: rest)
| LocalRawDef _ as x :: rest -> aux (x :: acc) rest
| [] ->
user_err_loc(loc,"",
str "No parameter named " ++ Nameops.pr_id id ++ str".")
in aux [] bl
(* Used in correctness and interface *)
let map_binder g e nal = List.fold_right (down_located (name_fold g)) nal e
let map_binders f g e bl =
(* TODO: avoid variable capture in [t] by some [na] in [List.tl nal] *)
let h (e,bl) (nal,bk,t) = (map_binder g e nal,(nal,bk,f e t)::bl) in
let (e,rbl) = List.fold_left h (e,[]) bl in
(e, List.rev rbl)
let map_local_binders f g e bl =
(* TODO: avoid variable capture in [t] by some [na] in [List.tl nal] *)
let h (e,bl) = function
LocalRawAssum(nal,k,ty) ->
(map_binder g e nal, LocalRawAssum(nal,k,f e ty)::bl)
| LocalRawDef((loc,na),ty) ->
(name_fold g na e, LocalRawDef((loc,na),f e ty)::bl) in
let (e,rbl) = List.fold_left h (e,[]) bl in
(e, List.rev rbl)
let map_constr_expr_with_binders g f e = function
| CAppExpl (loc,r,l) -> CAppExpl (loc,r,List.map (f e) l)
| CApp (loc,(p,a),l) ->
CApp (loc,(p,f e a),List.map (fun (a,i) -> (f e a,i)) l)
| CProdN (loc,bl,b) ->
let (e,bl) = map_binders f g e bl in CProdN (loc,bl,f e b)
| CLambdaN (loc,bl,b) ->
let (e,bl) = map_binders f g e bl in CLambdaN (loc,bl,f e b)
| CLetIn (loc,na,a,b) -> CLetIn (loc,na,f e a,f (name_fold g (snd na) e) b)
| CCast (loc,a,CastConv (k,b)) -> CCast (loc,f e a,CastConv(k, f e b))
| CCast (loc,a,CastCoerce) -> CCast (loc,f e a,CastCoerce)
| CNotation (loc,n,(l,ll,bll)) ->
(* This is an approximation because we don't know what binds what *)
CNotation (loc,n,(List.map (f e) l,List.map (List.map (f e)) ll,
List.map (fun bl -> snd (map_local_binders f g e bl)) bll))
| CGeneralization (loc,b,a,c) -> CGeneralization (loc,b,a,f e c)
| CDelimiters (loc,s,a) -> CDelimiters (loc,s,f e a)
| CHole _ | CEvar _ | CPatVar _ | CSort _
| CPrim _ | CRef _ as x -> x
| CRecord (loc,p,l) -> CRecord (loc,p,List.map (fun (id, c) -> (id, f e c)) l)
| CCases (loc,sty,rtnpo,a,bl) ->
(* TODO: apply g on the binding variables in pat... *)
let bl = List.map (fun (loc,pat,rhs) -> (loc,pat,f e rhs)) bl in
let ids = ids_of_cases_tomatch a in
let po = Option.map (f (List.fold_right g ids e)) rtnpo in
CCases (loc, sty, po, List.map (fun (tm,x) -> (f e tm,x)) a,bl)
| CLetTuple (loc,nal,(ona,po),b,c) ->
let e' = List.fold_right (down_located (name_fold g)) nal e in
let e'' = Option.fold_right (down_located (name_fold g)) ona e in
CLetTuple (loc,nal,(ona,Option.map (f e'') po),f e b,f e' c)
| CIf (loc,c,(ona,po),b1,b2) ->
let e' = Option.fold_right (down_located (name_fold g)) ona e in
CIf (loc,f e c,(ona,Option.map (f e') po),f e b1,f e b2)
| CFix (loc,id,dl) ->
CFix (loc,id,List.map (fun (id,n,bl,t,d) ->
let (e',bl') = map_local_binders f g e bl in
let t' = f e' t in
(* Note: fix names should be inserted before the arguments... *)
let e'' = List.fold_left (fun e ((_,id),_,_,_,_) -> g id e) e' dl in
let d' = f e'' d in
(id,n,bl',t',d')) dl)
| CCoFix (loc,id,dl) ->
CCoFix (loc,id,List.map (fun (id,bl,t,d) ->
let (e',bl') = map_local_binders f g e bl in
let t' = f e' t in
let e'' = List.fold_left (fun e ((_,id),_,_,_) -> g id e) e' dl in
let d' = f e'' d in
(id,bl',t',d')) dl)
| CNativeArr(loc,t,p) -> CNativeArr(loc,f e t,Array.map (f e) p)
Used in
let rec replace_vars_constr_expr l = function
| CRef (Ident (loc,id)) as x ->
(try CRef (Ident (loc,List.assoc id l)) with Not_found -> x)
| c -> map_constr_expr_with_binders List.remove_assoc
replace_vars_constr_expr l c
(**********************************************************************)
(* Concrete syntax for modules and modules types *)
type with_declaration_ast =
| CWith_Module of identifier list located * qualid located
| CWith_Definition of identifier list located * constr_expr
type module_ast =
| CMident of qualid located
| CMapply of loc * module_ast * module_ast
| CMwith of loc * module_ast * with_declaration_ast
(* Returns the ranges of locs of the notation that are not occupied by args *)
(* and which are then occupied by proper symbols of the notation (or spaces) *)
let locs_of_notation loc locs ntn =
let (bl,el) = unloc loc in
let locs = List.map unloc locs in
let rec aux pos = function
| [] -> if pos = el then [] else [(pos,el-1)]
| (ba,ea)::l ->if pos = ba then aux ea l else (pos,ba-1)::aux ea l
in aux bl (Sort.list (fun l1 l2 -> fst l1 < fst l2) locs)
let ntn_loc loc (args,argslist,binderslist) =
locs_of_notation loc
(List.map constr_loc ( argslist)@
List.map local_binders_loc binderslist)
let patntn_loc loc (args,argslist) =
locs_of_notation loc
(List.map cases_pattern_expr_loc ( argslist))
| null | https://raw.githubusercontent.com/maximedenes/native-coq/3623a4d9fe95c165f02f7119c0e6564a83a9f4c9/interp/topconstr.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
i
i
********************************************************************
Part common to glob_constr and cases_pattern
Part only in glob_constr
********************************************************************
Re-interpret a notation as a glob_constr, taking care of binders
assume: id is not binding
**************************************************************************
Translating a glob_constr into a notation, interpreting recursive patterns
No recursive pattern found
Not enough context
We found the pattern
We found the pattern, but there are extra arguments
(this allows e.g. alternative (recursive) notation of application)
We found the position where it differs
We found a binding position where it differs
Here, we would need a loc made of several parts ...
found have been collected by compare_constr
found have been collected by compare_constr
n^2 complexity but small and done only once per notation
Side effect
Substitution of kernel names, avoiding a list of bound identifiers
Pattern-matching glob_constr and aconstr
Check that no capture of binding variables occur
TODO: handle the case of multiple occs in different scopes
?
This is hack to avoid looping on a rule with rhs of the form
"?f (fun ?x => ?g)" since otherwise, matching "F H" expands in
"F (fun x => H x)" and "H x" is recursively matched against the same
rule, giving "H (fun x' => x x')" and so on.
Ideally, we would need the type of the expression to know which of
the arguments applied to it can be eta-expanded without looping.
The following test is then an approximation of what can be done
optimally (whether other looping situations can occur remains to be
checked).
Matching notation variable
Matching recursive notations for terms
Matching recursive notations for binders: ad hoc cases supporting let-in
TODO: address the possibility that termin is a Lambda itself
TODO: address the possibility that termin is a Prod itself
Matching recursive notations for binders: general case
Matching individual binders as part of a recursive pattern
Matching compositionally
Reorder canonically the substitution
Happens for binders bound to Anonymous
Find a better way to propagate Anonymous...
Matching cases pattern
TODO: handle the case of multiple occs in different scopes
Reorder canonically the substitution
********************************************************************
s Concrete syntax for terms
[Some n] = proj of the n-th visible argument
* for recursive notations
measure, relation
for recursive notations
for binders subexpressions
*********************
For binders parsing
********************************************************************
Miscellaneous
********************************************************************
Functions on constr_expr
We deal only with the regular cases
assume the ntn is applicative and does not instantiate the head !!
The following is an approximation: we don't know exactly if
an ident is binding nor to which subterms bindings apply
Interpret the index of a recursion order annotation
Used in correctness and interface
TODO: avoid variable capture in [t] by some [na] in [List.tl nal]
TODO: avoid variable capture in [t] by some [na] in [List.tl nal]
This is an approximation because we don't know what binds what
TODO: apply g on the binding variables in pat...
Note: fix names should be inserted before the arguments...
********************************************************************
Concrete syntax for modules and modules types
Returns the ranges of locs of the notation that are not occupied by args
and which are then occupied by proper symbols of the notation (or spaces) | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Pp
open Errors
open Util
open Names
open Nameops
open Libnames
open Glob_term
open Term
open Mod_subst
This is the subtype of glob_constr allowed in syntactic extensions
For AList : first constr is iterator , second is terminator ;
first i d is where each argument of the list has to be substituted
in iterator and snd i d is alternative name just for printing ;
boolean is associativity
first id is where each argument of the list has to be substituted
in iterator and snd id is alternative name just for printing;
boolean is associativity *)
type aconstr =
| ARef of global_reference
| AVar of identifier
| AApp of aconstr * aconstr list
| AHole of Evd.hole_kind
| AList of identifier * identifier * aconstr * aconstr * bool
| ALambda of name * aconstr * aconstr
| AProd of name * aconstr * aconstr
| ABinderList of identifier * identifier * aconstr * aconstr
| ALetIn of name * aconstr * aconstr
| ACases of case_style * aconstr option *
(aconstr * (name * (inductive * name list) option)) list *
(cases_pattern list * aconstr) list
| ALetTuple of name list * (name * aconstr option) * aconstr * aconstr
| AIf of aconstr * (name * aconstr option) * aconstr * aconstr
| ARec of fix_kind * identifier array *
(name * aconstr option * aconstr) list array * aconstr array *
aconstr array
| ASort of glob_sort
| APatVar of patvar
| ACast of aconstr * aconstr cast_type
| ANativeInt of Uint63.t
| ANativeArr of aconstr * aconstr array
type scope_name = string
type tmp_scope_name = scope_name
type subscopes = tmp_scope_name option * scope_name list
type notation_var_instance_type =
| NtnTypeConstr | NtnTypeConstrList | NtnTypeBinderList
type notation_var_internalization_type =
| NtnInternTypeConstr | NtnInternTypeBinder | NtnInternTypeIdent
type interpretation =
(identifier * (subscopes * notation_var_instance_type)) list * aconstr
let name_to_ident = function
| Anonymous -> error "This expression should be a simple identifier."
| Name id -> id
let to_id g e id = let e,na = g e (Name id) in e,name_to_ident na
let rec cases_pattern_fold_map loc g e = function
| PatVar (_,na) ->
let e',na' = g e na in e', PatVar (loc,na')
| PatCstr (_,cstr,patl,na) ->
let e',na' = g e na in
let e',patl' = list_fold_map (cases_pattern_fold_map loc g) e patl in
e', PatCstr (loc,cstr,patl',na')
let rec subst_glob_vars l = function
| GVar (_,id) as r -> (try List.assoc id l with Not_found -> r)
| GProd (loc,Name id,bk,t,c) ->
let id =
try match List.assoc id l with GVar(_,id') -> id' | _ -> id
with Not_found -> id in
GProd (loc,Name id,bk,subst_glob_vars l t,subst_glob_vars l c)
| GLambda (loc,Name id,bk,t,c) ->
let id =
try match List.assoc id l with GVar(_,id') -> id' | _ -> id
with Not_found -> id in
GLambda (loc,Name id,bk,subst_glob_vars l t,subst_glob_vars l c)
let ldots_var = id_of_string ".."
let glob_constr_of_aconstr_with_binders loc g f e = function
| AVar id -> GVar (loc,id)
| AApp (a,args) -> GApp (loc,f e a, List.map (f e) args)
| AList (x,y,iter,tail,swap) ->
let t = f e tail in let it = f e iter in
let innerl = (ldots_var,t)::(if swap then [] else [x,GVar(loc,y)]) in
let inner = GApp (loc,GVar (loc,ldots_var),[subst_glob_vars innerl it]) in
let outerl = (ldots_var,inner)::(if swap then [x,GVar(loc,y)] else []) in
subst_glob_vars outerl it
| ABinderList (x,y,iter,tail) ->
let t = f e tail in let it = f e iter in
let innerl = [(ldots_var,t);(x,GVar(loc,y))] in
let inner = GApp (loc,GVar (loc,ldots_var),[subst_glob_vars innerl it]) in
let outerl = [(ldots_var,inner)] in
subst_glob_vars outerl it
| ALambda (na,ty,c) ->
let e',na = g e na in GLambda (loc,na,Explicit,f e ty,f e' c)
| AProd (na,ty,c) ->
let e',na = g e na in GProd (loc,na,Explicit,f e ty,f e' c)
| ALetIn (na,b,c) ->
let e',na = g e na in GLetIn (loc,na,f e b,f e' c)
| ACases (sty,rtntypopt,tml,eqnl) ->
let e',tml' = List.fold_right (fun (tm,(na,t)) (e',tml') ->
let e',t' = match t with
| None -> e',None
| Some (ind,nal) ->
let e',nal' = List.fold_right (fun na (e',nal) ->
let e',na' = g e' na in e',na'::nal) nal (e',[]) in
e',Some (loc,ind,nal') in
let e',na' = g e' na in
(e',(f e tm,(na',t'))::tml')) tml (e,[]) in
let fold (idl,e) na = let (e,na) = g e na in ((name_cons na idl,e),na) in
let eqnl' = List.map (fun (patl,rhs) ->
let ((idl,e),patl) =
list_fold_map (cases_pattern_fold_map loc fold) ([],e) patl in
(loc,idl,patl,f e rhs)) eqnl in
GCases (loc,sty,Option.map (f e') rtntypopt,tml',eqnl')
| ALetTuple (nal,(na,po),b,c) ->
let e',nal = list_fold_map g e nal in
let e'',na = g e na in
GLetTuple (loc,nal,(na,Option.map (f e'') po),f e b,f e' c)
| AIf (c,(na,po),b1,b2) ->
let e',na = g e na in
GIf (loc,f e c,(na,Option.map (f e') po),f e b1,f e b2)
| ARec (fk,idl,dll,tl,bl) ->
let e,dll = array_fold_map (list_fold_map (fun e (na,oc,b) ->
let e,na = g e na in
(e,(na,Explicit,Option.map (f e) oc,f e b)))) e dll in
let e',idl = array_fold_map (to_id g) e idl in
GRec (loc,fk,idl,dll,Array.map (f e) tl,Array.map (f e') bl)
| ACast (c,k) -> GCast (loc,f e c,
match k with
| CastConv (k,t) -> CastConv (k,f e t)
| CastCoerce -> CastCoerce)
| ASort x -> GSort (loc,x)
| AHole x -> GHole (loc,x)
| APatVar n -> GPatVar (loc,(false,n))
| ARef x -> GRef (loc,x)
| ANativeInt i -> GNativeInt(loc, i)
| ANativeArr(t,p) -> GNativeArr(loc, f e t, Array.map (f e) p)
let rec glob_constr_of_aconstr loc x =
let rec aux () x =
glob_constr_of_aconstr_with_binders loc (fun () id -> ((),id)) aux () x
in aux () x
let add_id r id = r := (id :: pi1 !r, pi2 !r, pi3 !r)
let add_name r = function Anonymous -> () | Name id -> add_id r id
let split_at_recursive_part c =
let sub = ref None in
let rec aux = function
| GApp (loc0,GVar(loc,v),c::l) when v = ldots_var ->
if !sub <> None then
Not narrowed enough to find only one recursive part
raise Not_found
else
(sub := Some c;
if l = [] then GVar (loc,ldots_var)
else GApp (loc0,GVar (loc,ldots_var),l))
| c -> map_glob_constr aux c in
let outer_iterator = aux c in
match !sub with
| Some c ->
match outer_iterator with
| _ -> outer_iterator, c
let on_true_do b f c = if b then (f c; b) else b
let compare_glob_constr f add t1 t2 = match t1,t2 with
| GRef (_,r1), GRef (_,r2) -> eq_gr r1 r2
| GVar (_,v1), GVar (_,v2) -> on_true_do (v1 = v2) add (Name v1)
| GApp (_,f1,l1), GApp (_,f2,l2) -> f f1 f2 & list_for_all2eq f l1 l2
| GLambda (_,na1,bk1,ty1,c1), GLambda (_,na2,bk2,ty2,c2) when na1 = na2 && bk1 = bk2 -> on_true_do (f ty1 ty2 & f c1 c2) add na1
| GProd (_,na1,bk1,ty1,c1), GProd (_,na2,bk2,ty2,c2) when na1 = na2 && bk1 = bk2 ->
on_true_do (f ty1 ty2 & f c1 c2) add na1
| GHole _, GHole _ -> true
| GSort (_,s1), GSort (_,s2) -> s1 = s2
| GLetIn (_,na1,b1,c1), GLetIn (_,na2,b2,c2) when na1 = na2 ->
on_true_do (f b1 b2 & f c1 c2) add na1
| GNativeInt(_,i1), GNativeInt(_,i2) -> Uint63.eq i1 i2
| GNativeArr(_,t1,p1),GNativeArr(_,t2,p2) ->
f t1 t2 & array_for_all2 f p1 p2
| (GCases _ | GRec _
| GPatVar _ | GEvar _ | GLetTuple _ | GIf _ | GCast _),_
| _,(GCases _ | GRec _
| GPatVar _ | GEvar _ | GLetTuple _ | GIf _ | GCast _)
-> error "Unsupported construction in recursive notations."
| (GRef _ | GVar _ | GApp _ | GLambda _ | GProd _
| GHole _ | GSort _ | GLetIn _ | GNativeInt _ | GNativeArr _), _
-> false
let rec eq_glob_constr t1 t2 = compare_glob_constr eq_glob_constr (fun _ -> ()) t1 t2
let subtract_loc loc1 loc2 = make_loc (fst (unloc loc1),fst (unloc loc2)-1)
let check_is_hole id = function GHole _ -> () | t ->
user_err_loc (loc_of_glob_constr t,"",
strbrk "In recursive notation with binders, " ++ pr_id id ++
strbrk " is expected to come without type.")
let compare_recursive_parts found f (iterator,subc) =
let diff = ref None in
let terminator = ref None in
let rec aux c1 c2 = match c1,c2 with
| GVar(_,v), term when v = ldots_var ->
assert (!terminator = None); terminator := Some term;
true
| GApp (_,GVar(_,v),l1), GApp (_,term,l2) when v = ldots_var ->
assert (!terminator = None); terminator := Some term;
list_for_all2eq aux l1 l2
| GVar (_,x), GVar (_,y) when x<>y ->
let lassoc = (!terminator <> None) in
let x,y = if lassoc then y,x else x,y in
!diff = None && (diff := Some (x,y,Some lassoc); true)
| GLambda (_,Name x,_,t_x,c), GLambda (_,Name y,_,t_y,term)
| GProd (_,Name x,_,t_x,c), GProd (_,Name y,_,t_y,term) ->
check_is_hole x t_x;
check_is_hole y t_y;
!diff = None && (diff := Some (x,y,None); aux c term)
| _ ->
compare_glob_constr aux (add_name found) c1 c2 in
if aux iterator subc then
match !diff with
| None ->
let loc1 = loc_of_glob_constr iterator in
let loc2 = loc_of_glob_constr (Option.get !terminator) in
user_err_loc (subtract_loc loc1 loc2,"",
str "Both ends of the recursive pattern are the same.")
| Some (x,y,Some lassoc) ->
let newfound = (pi1 !found, (x,y) :: pi2 !found, pi3 !found) in
let iterator =
f (if lassoc then subst_glob_vars [y,GVar(dummy_loc,x)] iterator
else iterator) in
found := newfound;
AList (x,y,iterator,f (Option.get !terminator),lassoc)
| Some (x,y,None) ->
let newfound = (pi1 !found, pi2 !found, (x,y) :: pi3 !found) in
let iterator = f iterator in
found := newfound;
ABinderList (x,y,iterator,f (Option.get !terminator))
else
raise Not_found
let aconstr_and_vars_of_glob_constr a =
let found = ref ([],[],[]) in
let rec aux c =
let keepfound = !found in
try compare_recursive_parts found aux' (split_at_recursive_part c)
with Not_found ->
found := keepfound;
match c with
| GApp (_,GVar (loc,f),[c]) when f = ldots_var ->
Fall on the second part of the recursive pattern w/o having
found the first part
found the first part *)
user_err_loc (loc,"",
str "Cannot find where the recursive pattern starts.")
| c ->
aux' c
and aux' = function
| GVar (_,id) -> add_id found id; AVar id
| GApp (_,g,args) -> AApp (aux g, List.map aux args)
| GLambda (_,na,bk,ty,c) -> add_name found na; ALambda (na,aux ty,aux c)
| GProd (_,na,bk,ty,c) -> add_name found na; AProd (na,aux ty,aux c)
| GLetIn (_,na,b,c) -> add_name found na; ALetIn (na,aux b,aux c)
| GCases (_,sty,rtntypopt,tml,eqnl) ->
let f (_,idl,pat,rhs) = List.iter (add_id found) idl; (pat,aux rhs) in
ACases (sty,Option.map aux rtntypopt,
List.map (fun (tm,(na,x)) ->
add_name found na;
Option.iter
(fun (_,_,nl) -> List.iter (add_name found) nl) x;
(aux tm,(na,Option.map (fun (_,ind,nal) -> (ind,nal)) x))) tml,
List.map f eqnl)
| GLetTuple (loc,nal,(na,po),b,c) ->
add_name found na;
List.iter (add_name found) nal;
ALetTuple (nal,(na,Option.map aux po),aux b,aux c)
| GIf (loc,c,(na,po),b1,b2) ->
add_name found na;
AIf (aux c,(na,Option.map aux po),aux b1,aux b2)
| GRec (_,fk,idl,dll,tl,bl) ->
Array.iter (add_id found) idl;
let dll = Array.map (List.map (fun (na,bk,oc,b) ->
if bk <> Explicit then
error "Binders marked as implicit not allowed in notations.";
add_name found na; (na,Option.map aux oc,aux b))) dll in
ARec (fk,idl,dll,Array.map aux tl,Array.map aux bl)
| GCast (_,c,k) -> ACast (aux c,
match k with CastConv (k,t) -> CastConv (k,aux t)
| CastCoerce -> CastCoerce)
| GSort (_,s) -> ASort s
| GHole (_,w) -> AHole w
| GRef (_,r) -> ARef r
| GPatVar (_,(_,n)) -> APatVar n
| GNativeInt(_,i) -> ANativeInt i
| GNativeArr(_,t,p) -> ANativeArr(aux t, Array.map aux p)
| GEvar _ ->
error "Existential variables not allowed in notations."
in
let t = aux a in
t, !found
let rec list_rev_mem_assoc x = function
| [] -> false
| (_,x')::l -> x = x' || list_rev_mem_assoc x l
let check_variables vars recvars (found,foundrec,foundrecbinding) =
let useless_vars = List.map snd recvars in
let vars = List.filter (fun (y,_) -> not (List.mem y useless_vars)) vars in
let check_recvar x =
if List.mem x found then
errorlabstrm "" (pr_id x ++
strbrk " should only be used in the recursive part of a pattern.") in
List.iter (fun (x,y) -> check_recvar x; check_recvar y)
(foundrec@foundrecbinding);
let check_bound x =
if not (List.mem x found) then
if List.mem_assoc x foundrec or List.mem_assoc x foundrecbinding
or list_rev_mem_assoc x foundrec or list_rev_mem_assoc x foundrecbinding
then
error ((string_of_id x)^" should not be bound in a recursive pattern of the right-hand side.")
else
error ((string_of_id x)^" is unbound in the right-hand side.") in
let check_pair s x y where =
if not (List.mem (x,y) where) then
errorlabstrm "" (strbrk "in the right-hand side, " ++ pr_id x ++
str " and " ++ pr_id y ++ strbrk " should appear in " ++ str s ++
str " position as part of a recursive pattern.") in
let check_type (x,typ) =
match typ with
| NtnInternTypeConstr ->
begin
try check_pair "term" x (List.assoc x recvars) foundrec
with Not_found -> check_bound x
end
| NtnInternTypeBinder ->
begin
try check_pair "binding" x (List.assoc x recvars) foundrecbinding
with Not_found -> check_bound x
end
| NtnInternTypeIdent -> check_bound x in
List.iter check_type vars
let aconstr_of_glob_constr vars recvars a =
let a,found = aconstr_and_vars_of_glob_constr a in
check_variables vars recvars found;
a
let aconstr_of_constr avoiding t =
aconstr_of_glob_constr [] [] (Detyping.detype false avoiding [] t)
let rec subst_pat subst pat =
match pat with
| PatVar _ -> pat
| PatCstr (loc,((kn,i),j),cpl,n) ->
let kn' = subst_ind subst kn
and cpl' = list_smartmap (subst_pat subst) cpl in
if kn' == kn && cpl' == cpl then pat else
PatCstr (loc,((kn',i),j),cpl',n)
let rec subst_aconstr subst bound raw =
match raw with
| ARef ref ->
let ref',t = subst_global subst ref in
if ref' == ref then raw else
aconstr_of_constr bound t
| AVar _ -> raw
| AApp (r,rl) ->
let r' = subst_aconstr subst bound r
and rl' = list_smartmap (subst_aconstr subst bound) rl in
if r' == r && rl' == rl then raw else
AApp(r',rl')
| AList (id1,id2,r1,r2,b) ->
let r1' = subst_aconstr subst bound r1
and r2' = subst_aconstr subst bound r2 in
if r1' == r1 && r2' == r2 then raw else
AList (id1,id2,r1',r2',b)
| ALambda (n,r1,r2) ->
let r1' = subst_aconstr subst bound r1
and r2' = subst_aconstr subst bound r2 in
if r1' == r1 && r2' == r2 then raw else
ALambda (n,r1',r2')
| AProd (n,r1,r2) ->
let r1' = subst_aconstr subst bound r1
and r2' = subst_aconstr subst bound r2 in
if r1' == r1 && r2' == r2 then raw else
AProd (n,r1',r2')
| ABinderList (id1,id2,r1,r2) ->
let r1' = subst_aconstr subst bound r1
and r2' = subst_aconstr subst bound r2 in
if r1' == r1 && r2' == r2 then raw else
ABinderList (id1,id2,r1',r2')
| ALetIn (n,r1,r2) ->
let r1' = subst_aconstr subst bound r1
and r2' = subst_aconstr subst bound r2 in
if r1' == r1 && r2' == r2 then raw else
ALetIn (n,r1',r2')
| ACases (sty,rtntypopt,rl,branches) ->
let rtntypopt' = Option.smartmap (subst_aconstr subst bound) rtntypopt
and rl' = list_smartmap
(fun (a,(n,signopt) as x) ->
let a' = subst_aconstr subst bound a in
let signopt' = Option.map (fun ((indkn,i),nal as z) ->
let indkn' = subst_ind subst indkn in
if indkn == indkn' then z else ((indkn',i),nal)) signopt in
if a' == a && signopt' == signopt then x else (a',(n,signopt')))
rl
and branches' = list_smartmap
(fun (cpl,r as branch) ->
let cpl' = list_smartmap (subst_pat subst) cpl
and r' = subst_aconstr subst bound r in
if cpl' == cpl && r' == r then branch else
(cpl',r'))
branches
in
if rtntypopt' == rtntypopt && rtntypopt == rtntypopt' &
rl' == rl && branches' == branches then raw else
ACases (sty,rtntypopt',rl',branches')
| ALetTuple (nal,(na,po),b,c) ->
let po' = Option.smartmap (subst_aconstr subst bound) po
and b' = subst_aconstr subst bound b
and c' = subst_aconstr subst bound c in
if po' == po && b' == b && c' == c then raw else
ALetTuple (nal,(na,po'),b',c')
| AIf (c,(na,po),b1,b2) ->
let po' = Option.smartmap (subst_aconstr subst bound) po
and b1' = subst_aconstr subst bound b1
and b2' = subst_aconstr subst bound b2
and c' = subst_aconstr subst bound c in
if po' == po && b1' == b1 && b2' == b2 && c' == c then raw else
AIf (c',(na,po'),b1',b2')
| ARec (fk,idl,dll,tl,bl) ->
let dll' =
array_smartmap (list_smartmap (fun (na,oc,b as x) ->
let oc' = Option.smartmap (subst_aconstr subst bound) oc in
let b' = subst_aconstr subst bound b in
if oc' == oc && b' == b then x else (na,oc',b'))) dll in
let tl' = array_smartmap (subst_aconstr subst bound) tl in
let bl' = array_smartmap (subst_aconstr subst bound) bl in
if dll' == dll && tl' == tl && bl' == bl then raw else
ARec (fk,idl,dll',tl',bl')
| APatVar _ | ASort _ -> raw
| AHole (Evd.ImplicitArg (ref,i,b)) ->
let ref',t = subst_global subst ref in
if ref' == ref then raw else
AHole (Evd.InternalHole)
| AHole (Evd.BinderType _ | Evd.QuestionMark _ | Evd.CasesType
| Evd.InternalHole | Evd.TomatchTypeParameter _ | Evd.GoalEvar
| Evd.ImpossibleCase | Evd.MatchingVar _) -> raw
| ANativeInt _ -> raw
| ANativeArr(t,p) ->
let t' = subst_aconstr subst bound t
and p' = array_smartmap (subst_aconstr subst bound) p in
if t' == t && p' == p then raw else
ANativeArr(t',p')
| ACast (r1,k) ->
match k with
CastConv (k, r2) ->
let r1' = subst_aconstr subst bound r1
and r2' = subst_aconstr subst bound r2 in
if r1' == r1 && r2' == r2 then raw else
ACast (r1',CastConv (k,r2'))
| CastCoerce ->
let r1' = subst_aconstr subst bound r1 in
if r1' == r1 then raw else
ACast (r1',CastCoerce)
let subst_interpretation subst (metas,pat) =
let bound = List.map fst metas in
(metas,subst_aconstr subst bound pat)
let abstract_return_type_context pi mklam tml rtno =
Option.map (fun rtn ->
let nal =
List.flatten (List.map (fun (_,(na,t)) ->
match t with Some x -> (pi x)@[na] | None -> [na]) tml) in
List.fold_right mklam nal rtn)
rtno
let abstract_return_type_context_glob_constr =
abstract_return_type_context (fun (_,_,nal) -> nal)
(fun na c -> GLambda(dummy_loc,na,Explicit,GHole(dummy_loc,Evd.InternalHole),c))
let abstract_return_type_context_aconstr =
abstract_return_type_context snd
(fun na c -> ALambda(na,AHole Evd.InternalHole,c))
exception No_match
let rec alpha_var id1 id2 = function
| (i1,i2)::_ when i1=id1 -> i2 = id2
| (i1,i2)::_ when i2=id2 -> i1 = id1
| _::idl -> alpha_var id1 id2 idl
| [] -> id1 = id2
let alpha_eq_val (x,y) = x = y
let bind_env alp (sigma,sigmalist,sigmabinders as fullsigma) var v =
try
let vvar = List.assoc var sigma in
if alpha_eq_val (v,vvar) then fullsigma
else raise No_match
with Not_found ->
if List.exists (fun (id,_) ->occur_glob_constr id v) alp then raise No_match;
((var,v)::sigma,sigmalist,sigmabinders)
let bind_binder (sigma,sigmalist,sigmabinders) x bl =
(sigma,sigmalist,(x,List.rev bl)::sigmabinders)
let match_fix_kind fk1 fk2 =
match (fk1,fk2) with
| GCoFix n1, GCoFix n2 -> n1 = n2
| GFix (nl1,n1), GFix (nl2,n2) ->
n1 = n2 &&
array_for_all2 (fun (n1,_) (n2,_) -> n2 = None || n1 = n2) nl1 nl2
| _ -> false
let match_opt f sigma t1 t2 = match (t1,t2) with
| None, None -> sigma
| Some t1, Some t2 -> f sigma t1 t2
| _ -> raise No_match
let match_names metas (alp,sigma) na1 na2 = match (na1,na2) with
| (_,Name id2) when List.mem id2 (fst metas) ->
let rhs = match na1 with
| Name id1 -> GVar (dummy_loc,id1)
| Anonymous -> GHole (dummy_loc,Evd.InternalHole) in
alp, bind_env alp sigma id2 rhs
| (Name id1,Name id2) -> (id1,id2)::alp,sigma
| (Anonymous,Anonymous) -> alp,sigma
| _ -> raise No_match
let rec match_cases_pattern_binders metas acc pat1 pat2 =
match (pat1,pat2) with
| PatVar (_,na1), PatVar (_,na2) -> match_names metas acc na1 na2
| PatCstr (_,c1,patl1,na1), PatCstr (_,c2,patl2,na2)
when c1 = c2 & List.length patl1 = List.length patl2 ->
List.fold_left2 (match_cases_pattern_binders metas)
(match_names metas acc na1 na2) patl1 patl2
| _ -> raise No_match
let glue_letin_with_decls = true
let rec match_iterated_binders islambda decls = function
| GLambda (_,na,bk,t,b) when islambda ->
match_iterated_binders islambda ((na,bk,None,t)::decls) b
| GProd (_,(Name _ as na),bk,t,b) when not islambda ->
match_iterated_binders islambda ((na,bk,None,t)::decls) b
| GLetIn (loc,na,c,b) when glue_letin_with_decls ->
match_iterated_binders islambda
| b -> (decls,b)
let remove_sigma x (sigmavar,sigmalist,sigmabinders) =
(List.remove_assoc x sigmavar,sigmalist,sigmabinders)
let rec match_abinderlist_with_app match_fun metas sigma rest x iter termin =
let rec aux sigma acc rest =
try
let sigma = match_fun (ldots_var::fst metas,snd metas) sigma rest iter in
let rest = List.assoc ldots_var (pi1 sigma) in
let b = match List.assoc x (pi3 sigma) with [b] -> b | _ ->assert false in
let sigma = remove_sigma x (remove_sigma ldots_var sigma) in
aux sigma (b::acc) rest
with No_match when acc <> [] ->
acc, match_fun metas sigma rest termin in
let bl,sigma = aux sigma [] rest in
bind_binder sigma x bl
let match_alist match_fun metas sigma rest x iter termin lassoc =
let rec aux sigma acc rest =
try
let sigma = match_fun (ldots_var::fst metas,snd metas) sigma rest iter in
let rest = List.assoc ldots_var (pi1 sigma) in
let t = List.assoc x (pi1 sigma) in
let sigma = remove_sigma x (remove_sigma ldots_var sigma) in
aux sigma (t::acc) rest
with No_match when acc <> [] ->
acc, match_fun metas sigma rest termin in
let l,sigma = aux sigma [] rest in
(pi1 sigma, (x,if lassoc then l else List.rev l)::pi2 sigma, pi3 sigma)
let does_not_come_from_already_eta_expanded_var =
function GVar _ -> false | _ -> true
let rec match_ inner u alp (tmetas,blmetas as metas) sigma a1 a2 =
match (a1,a2) with
| r1, AVar id2 when List.mem id2 tmetas -> bind_env alp sigma id2 r1
| r1, AList (x,_,iter,termin,lassoc) ->
match_alist (match_hd u alp) metas sigma r1 x iter termin lassoc
| GLambda (_,na1,bk,t1,b1), ABinderList (x,_,ALambda (Name id2,_,b2),termin)->
let (decls,b) = match_iterated_binders true [(na1,bk,None,t1)] b1 in
match_in u alp metas (bind_binder sigma x decls) b termin
| GProd (_,na1,bk,t1,b1), ABinderList (x,_,AProd (Name id2,_,b2),termin)
when na1 <> Anonymous ->
let (decls,b) = match_iterated_binders false [(na1,bk,None,t1)] b1 in
match_in u alp metas (bind_binder sigma x decls) b termin
| r, ABinderList (x,_,iter,termin) ->
match_abinderlist_with_app (match_hd u alp) metas sigma r x iter termin
| GLambda (_,na,bk,t,b1), ALambda (Name id,_,b2) when List.mem id blmetas ->
match_in u alp metas (bind_binder sigma id [(na,bk,None,t)]) b1 b2
| GProd (_,na,bk,t,b1), AProd (Name id,_,b2)
when List.mem id blmetas & na <> Anonymous ->
match_in u alp metas (bind_binder sigma id [(na,bk,None,t)]) b1 b2
| GVar (_,id1), AVar id2 when alpha_var id1 id2 alp -> sigma
| GRef (_,r1), ARef r2 when (eq_gr r1 r2) -> sigma
| GPatVar (_,(_,n1)), APatVar n2 when n1=n2 -> sigma
| GApp (loc,f1,l1), AApp (f2,l2) ->
let n1 = List.length l1 and n2 = List.length l2 in
let f1,l1,f2,l2 =
if n1 < n2 then
let l21,l22 = list_chop (n2-n1) l2 in f1,l1, AApp (f2,l21), l22
else if n1 > n2 then
let l11,l12 = list_chop (n1-n2) l1 in GApp (loc,f1,l11),l12, f2,l2
else f1,l1, f2, l2 in
let may_use_eta = does_not_come_from_already_eta_expanded_var f1 in
List.fold_left2 (match_ may_use_eta u alp metas)
(match_in u alp metas sigma f1 f2) l1 l2
| GLambda (_,na1,_,t1,b1), ALambda (na2,t2,b2) ->
match_binders u alp metas na1 na2 (match_in u alp metas sigma t1 t2) b1 b2
| GProd (_,na1,_,t1,b1), AProd (na2,t2,b2) ->
match_binders u alp metas na1 na2 (match_in u alp metas sigma t1 t2) b1 b2
| GLetIn (_,na1,t1,b1), ALetIn (na2,t2,b2) ->
match_binders u alp metas na1 na2 (match_in u alp metas sigma t1 t2) b1 b2
| GCases (_,sty1,rtno1,tml1,eqnl1), ACases (sty2,rtno2,tml2,eqnl2)
when sty1 = sty2
& List.length tml1 = List.length tml2
& List.length eqnl1 = List.length eqnl2 ->
let rtno1' = abstract_return_type_context_glob_constr tml1 rtno1 in
let rtno2' = abstract_return_type_context_aconstr tml2 rtno2 in
let sigma =
try Option.fold_left2 (match_in u alp metas) sigma rtno1' rtno2'
with Option.Heterogeneous -> raise No_match
in
let sigma = List.fold_left2
(fun s (tm1,_) (tm2,_) ->
match_in u alp metas s tm1 tm2) sigma tml1 tml2 in
List.fold_left2 (match_equations u alp metas) sigma eqnl1 eqnl2
| GLetTuple (_,nal1,(na1,to1),b1,c1), ALetTuple (nal2,(na2,to2),b2,c2)
when List.length nal1 = List.length nal2 ->
let sigma = match_opt (match_binders u alp metas na1 na2) sigma to1 to2 in
let sigma = match_in u alp metas sigma b1 b2 in
let (alp,sigma) =
List.fold_left2 (match_names metas) (alp,sigma) nal1 nal2 in
match_in u alp metas sigma c1 c2
| GIf (_,a1,(na1,to1),b1,c1), AIf (a2,(na2,to2),b2,c2) ->
let sigma = match_opt (match_binders u alp metas na1 na2) sigma to1 to2 in
List.fold_left2 (match_in u alp metas) sigma [a1;b1;c1] [a2;b2;c2]
| GRec (_,fk1,idl1,dll1,tl1,bl1), ARec (fk2,idl2,dll2,tl2,bl2)
when match_fix_kind fk1 fk2 & Array.length idl1 = Array.length idl2 &
array_for_all2 (fun l1 l2 -> List.length l1 = List.length l2) dll1 dll2
->
let alp,sigma = array_fold_left2
(List.fold_left2 (fun (alp,sigma) (na1,_,oc1,b1) (na2,oc2,b2) ->
let sigma =
match_in u alp metas
(match_opt (match_in u alp metas) sigma oc1 oc2) b1 b2
in match_names metas (alp,sigma) na1 na2)) (alp,sigma) dll1 dll2 in
let sigma = array_fold_left2 (match_in u alp metas) sigma tl1 tl2 in
let alp,sigma = array_fold_right2 (fun id1 id2 alsig ->
match_names metas alsig (Name id1) (Name id2)) idl1 idl2 (alp,sigma) in
array_fold_left2 (match_in u alp metas) sigma bl1 bl2
| GCast(_,c1, CastConv(_,t1)), ACast(c2, CastConv (_,t2)) ->
match_in u alp metas (match_in u alp metas sigma c1 c2) t1 t2
| GCast(_,c1, CastCoerce), ACast(c2, CastCoerce) ->
match_in u alp metas sigma c1 c2
| GSort (_,GType _), ASort (GType None) when not u -> sigma
| GSort (_,s1), ASort s2 when s1 = s2 -> sigma
Do n't hide Metas , they bind in ltac
| a, AHole _ -> sigma
On the fly eta - expansion so as to use notations of the form
" exists x , P x " for " ex P " ; expects type not given because do n't know
otherwise how to ensure it corresponds to a well - typed eta - expansion ;
ensure at least one constructor is consumed to avoid looping
"exists x, P x" for "ex P"; expects type not given because don't know
otherwise how to ensure it corresponds to a well-typed eta-expansion;
ensure at least one constructor is consumed to avoid looping *)
| b1, ALambda (Name id,AHole _,b2) when inner ->
let id' = Namegen.next_ident_away id (free_glob_vars b1) in
match_in u alp metas (bind_binder sigma id
[(Name id',Explicit,None,GHole(dummy_loc,Evd.BinderType (Name id')))])
(mkGApp dummy_loc b1 (GVar (dummy_loc,id'))) b2
| (GRec _ | GEvar _), _
| _,_ -> raise No_match
and match_in u = match_ true u
and match_hd u = match_ false u
and match_binders u alp metas na1 na2 sigma b1 b2 =
let (alp,sigma) = match_names metas (alp,sigma) na1 na2 in
match_in u alp metas sigma b1 b2
and match_equations u alp metas sigma (_,_,patl1,rhs1) (patl2,rhs2) =
patl1 and patl2 have the same length because they respectively
correspond to some tml1 and tml2 that have the same length
correspond to some tml1 and tml2 that have the same length *)
let (alp,sigma) =
List.fold_left2 (match_cases_pattern_binders metas)
(alp,sigma) patl1 patl2 in
match_in u alp metas sigma rhs1 rhs2
let match_aconstr u c (metas,pat) =
let vars = list_split_by (fun (_,(_,x)) -> x <> NtnTypeBinderList) metas in
let vars = (List.map fst (fst vars), List.map fst (snd vars)) in
let terms,termlists,binders = match_ false u [] vars ([],[],[]) c pat in
let find x =
try List.assoc x terms
with Not_found ->
GVar (dummy_loc,x) in
List.fold_right (fun (x,(scl,typ)) (terms',termlists',binders') ->
match typ with
| NtnTypeConstr ->
((find x, scl)::terms',termlists',binders')
| NtnTypeConstrList ->
(terms',(List.assoc x termlists,scl)::termlists',binders')
| NtnTypeBinderList ->
(terms',termlists',(List.assoc x binders,scl)::binders'))
metas ([],[],[])
let add_patterns_for_params (ind,k) l =
let mib,_ = Global.lookup_inductive ind in
let nparams = mib.Declarations.mind_nparams in
Util.list_addn nparams (PatVar (dummy_loc,Anonymous)) l
let bind_env_cases_pattern (sigma,sigmalist,x as fullsigma) var v =
try
let vvar = List.assoc var sigma in
if v=vvar then fullsigma else raise No_match
with Not_found ->
(var,v)::sigma,sigmalist,x
let rec match_cases_pattern metas sigma a1 a2 =
let match_cases_pattern_no_more_args metas sigma a1 a2 =
match match_cases_pattern metas sigma a1 a2 with
|out,[] -> out
|_ -> raise No_match in
match (a1,a2) with
| r1, AVar id2 when List.mem id2 metas -> (bind_env_cases_pattern sigma id2 r1),[]
| PatVar (_,Anonymous), AHole _ -> sigma,[]
| PatCstr (loc,(ind,_ as r1),largs,_), ARef (ConstructRef r2) when r1 = r2 ->
sigma,largs
| PatCstr (loc,(ind,_ as r1),args1,_), AApp (ARef (ConstructRef r2),l2)
when r1 = r2 ->
let l1 = add_patterns_for_params r1 args1 in
let le2 = List.length l2 in
if le2 > List.length l1
then
raise No_match
else
let l1',more_args = Util.list_chop le2 l1 in
(List.fold_left2 (match_cases_pattern_no_more_args metas) sigma l1' l2),more_args
| r1, AList (x,_,iter,termin,lassoc) ->
(match_alist (fun (metas,_) -> match_cases_pattern_no_more_args metas)
(metas,[]) (pi1 sigma,pi2 sigma,()) r1 x iter termin lassoc),[]
| _ -> raise No_match
let match_aconstr_cases_pattern c (metas,pat) =
let vars = List.map fst metas in
let (terms,termlists,()),more_args = match_cases_pattern vars ([],[],()) c pat in
(List.fold_right (fun (x,(scl,typ)) (terms',termlists') ->
match typ with
| NtnTypeConstr -> ((List.assoc x terms, scl)::terms',termlists')
| NtnTypeConstrList -> (terms',(List.assoc x termlists,scl)::termlists')
| NtnTypeBinderList -> assert false)
metas ([],[])),more_args
type notation = string
type explicitation = ExplByPos of int * identifier option | ExplByName of identifier
type binder_kind = Default of binding_kind | Generalized of binding_kind * binding_kind * bool
type abstraction_kind = AbsLambda | AbsPi
type prim_token = Numeral of Bigint.bigint | String of string
type cases_pattern_expr =
| CPatAlias of loc * cases_pattern_expr * identifier
| CPatCstr of loc * reference * cases_pattern_expr list
| CPatCstrExpl of loc * reference * cases_pattern_expr list
| CPatAtom of loc * reference option
| CPatOr of loc * cases_pattern_expr list
| CPatNotation of loc * notation * cases_pattern_notation_substitution
| CPatPrim of loc * prim_token
| CPatRecord of loc * (reference * cases_pattern_expr) list
| CPatDelimiters of loc * string * cases_pattern_expr
and cases_pattern_notation_substitution =
* for
type constr_expr =
| CRef of reference
| CFix of loc * identifier located * fix_expr list
| CCoFix of loc * identifier located * cofix_expr list
| CProdN of loc * (name located list * binder_kind * constr_expr) list * constr_expr
| CLambdaN of loc * (name located list * binder_kind * constr_expr) list * constr_expr
| CLetIn of loc * name located * constr_expr * constr_expr
| CAppExpl of loc * (proj_flag * reference) * constr_expr list
| CApp of loc * (proj_flag * constr_expr) *
(constr_expr * explicitation located option) list
| CRecord of loc * constr_expr option * (reference * constr_expr) list
| CCases of loc * case_style * constr_expr option *
(constr_expr * (name located option * cases_pattern_expr option)) list *
(loc * cases_pattern_expr list located list * constr_expr) list
| CLetTuple of loc * name located list * (name located option * constr_expr option) *
constr_expr * constr_expr
| CIf of loc * constr_expr * (name located option * constr_expr option)
* constr_expr * constr_expr
| CHole of loc * Evd.hole_kind option
| CPatVar of loc * (bool * patvar)
| CEvar of loc * existential_key * constr_expr list option
| CSort of loc * glob_sort
| CCast of loc * constr_expr * constr_expr cast_type
| CNotation of loc * notation * constr_notation_substitution
| CGeneralization of loc * binding_kind * abstraction_kind option * constr_expr
| CPrim of loc * prim_token
| CDelimiters of loc * string * constr_expr
| CNativeArr of loc * constr_expr * constr_expr array
and fix_expr =
identifier located * (identifier located option * recursion_order_expr) * local_binder list * constr_expr * constr_expr
and cofix_expr =
identifier located * local_binder list * constr_expr * constr_expr
and recursion_order_expr =
| CStructRec
| CWfRec of constr_expr
and local_binder =
| LocalRawDef of name located * constr_expr
| LocalRawAssum of name located list * binder_kind * constr_expr
and constr_notation_substitution =
for
type typeclass_constraint = name located * binding_kind * constr_expr
and typeclass_context = typeclass_constraint list
type constr_pattern_expr = constr_expr
let oldfashion_patterns = ref (true)
let write_oldfashion_patterns = Goptions.declare_bool_option {
Goptions.optsync = true; Goptions.optdepr = false;
Goptions.optname =
"Constructors in patterns require all their arguments but no parameters instead of explicit parameters and arguments";
Goptions.optkey = ["Asymmetric";"Patterns"];
Goptions.optread = (fun () -> !oldfashion_patterns);
Goptions.optwrite = (fun a -> oldfashion_patterns:=a);
}
let default_binder_kind = Default Explicit
let names_of_local_assums bl =
List.flatten (List.map (function LocalRawAssum(l,_,_)->l|_->[]) bl)
let names_of_local_binders bl =
List.flatten (List.map (function LocalRawAssum(l,_,_)->l|LocalRawDef(l,_)->[l]) bl)
let error_invalid_pattern_notation loc =
user_err_loc (loc,"",str "Invalid notation for pattern.")
let constr_loc = function
| CRef (Ident (loc,_)) -> loc
| CRef (Qualid (loc,_)) -> loc
| CFix (loc,_,_) -> loc
| CCoFix (loc,_,_) -> loc
| CProdN (loc,_,_) -> loc
| CLambdaN (loc,_,_) -> loc
| CLetIn (loc,_,_,_) -> loc
| CAppExpl (loc,_,_) -> loc
| CApp (loc,_,_) -> loc
| CRecord (loc,_,_) -> loc
| CCases (loc,_,_,_,_) -> loc
| CLetTuple (loc,_,_,_,_) -> loc
| CIf (loc,_,_,_,_) -> loc
| CHole (loc, _) -> loc
| CPatVar (loc,_) -> loc
| CEvar (loc,_,_) -> loc
| CSort (loc,_) -> loc
| CCast (loc,_,_) -> loc
| CNotation (loc,_,_) -> loc
| CGeneralization (loc,_,_,_) -> loc
| CPrim (loc,_) -> loc
| CDelimiters (loc,_,_) -> loc
| CNativeArr (loc, _, _) -> loc
let cases_pattern_expr_loc = function
| CPatAlias (loc,_,_) -> loc
| CPatCstr (loc,_,_) -> loc
| CPatCstrExpl (loc,_,_) -> loc
| CPatAtom (loc,_) -> loc
| CPatOr (loc,_) -> loc
| CPatNotation (loc,_,_) -> loc
| CPatRecord (loc, _) -> loc
| CPatPrim (loc,_) -> loc
| CPatDelimiters (loc,_,_) -> loc
let local_binder_loc = function
| LocalRawAssum ((loc,_)::_,_,t)
| LocalRawDef ((loc,_),t) -> join_loc loc (constr_loc t)
| LocalRawAssum ([],_,_) -> assert false
let local_binders_loc bll =
if bll = [] then dummy_loc else
join_loc (local_binder_loc (List.hd bll)) (local_binder_loc (list_last bll))
let ids_of_cases_indtype =
let rec vars_of ids = function
| (CPatCstr (_,_,l)|CPatCstrExpl (_, _, l)|CPatNotation (_,_,(l,[]))) -> List.fold_left vars_of [] l
| CPatDelimiters(_,_,c) -> vars_of ids c
| CPatAtom (_, Some (Libnames.Ident (_, x))) -> x::ids
| _ -> ids in
vars_of []
let ids_of_cases_tomatch tms =
List.fold_right
(fun (_,(ona,indnal)) l ->
Option.fold_right (fun t -> (@) (ids_of_cases_indtype t))
indnal (Option.fold_right (down_located name_cons) ona l))
tms []
let is_constructor id =
try ignore (Nametab.locate_extended (qualid_of_ident id)); true
with Not_found -> true
let rec cases_pattern_fold_names f a = function
| CPatRecord (_, l) ->
List.fold_left (fun acc (r, cp) -> cases_pattern_fold_names f acc cp) a l
| CPatAlias (_,pat,id) -> f id a
| CPatCstr (_,_,patl) | CPatCstrExpl (_,_,patl) | CPatOr (_,patl) ->
List.fold_left (cases_pattern_fold_names f) a patl
| CPatNotation (_,_,(patl,patll)) ->
List.fold_left (cases_pattern_fold_names f) a ( patll)
| CPatDelimiters (_,_,pat) -> cases_pattern_fold_names f a pat
| CPatAtom (_,Some (Ident (_,id))) when not (is_constructor id) -> f id a
| CPatPrim _ | CPatAtom _ -> a
let ids_of_pattern_list =
List.fold_left
(located_fold_left
(List.fold_left (cases_pattern_fold_names Idset.add)))
Idset.empty
let rec fold_constr_expr_binders g f n acc b = function
| (nal,bk,t)::l ->
let nal = snd (List.split nal) in
let n' = List.fold_right (name_fold g) nal n in
f n (fold_constr_expr_binders g f n' acc b l) t
| [] ->
f n acc b
let rec fold_local_binders g f n acc b = function
| LocalRawAssum (nal,bk,t)::l ->
let nal = snd (List.split nal) in
let n' = List.fold_right (name_fold g) nal n in
f n (fold_local_binders g f n' acc b l) t
| LocalRawDef ((_,na),t)::l ->
f n (fold_local_binders g f (name_fold g na n) acc b l) t
| [] ->
f n acc b
let fold_constr_expr_with_binders g f n acc = function
| CAppExpl (loc,(_,_),l) -> List.fold_left (f n) acc l
| CApp (loc,(_,t),l) -> List.fold_left (f n) (f n acc t) (List.map fst l)
| CProdN (_,l,b) | CLambdaN (_,l,b) -> fold_constr_expr_binders g f n acc b l
| CLetIn (_,na,a,b) -> fold_constr_expr_binders g f n acc b [[na],default_binder_kind,a]
| CCast (loc,a,CastConv(_,b)) -> f n (f n acc a) b
| CCast (loc,a,CastCoerce) -> f n acc a
| CNotation (_,_,(l,ll,bll)) ->
let acc = List.fold_left (f n) acc ( ll) in
List.fold_left (fun acc bl -> fold_local_binders g f n acc (CHole (dummy_loc,None)) bl) acc bll
| CGeneralization (_,_,_,c) -> f n acc c
| CDelimiters (loc,_,a) -> f n acc a
| CHole _ | CEvar _ | CPatVar _ | CSort _ | CPrim _ | CRef _ ->
acc
| CRecord (loc,_,l) -> List.fold_left (fun acc (id, c) -> f n acc c) acc l
| CCases (loc,sty,rtnpo,al,bl) ->
let ids = ids_of_cases_tomatch al in
let acc = Option.fold_left (f (List.fold_right g ids n)) acc rtnpo in
let acc = List.fold_left (f n) acc (List.map fst al) in
List.fold_right (fun (loc,patl,rhs) acc ->
let ids = ids_of_pattern_list patl in
f (Idset.fold g ids n) acc rhs) bl acc
| CLetTuple (loc,nal,(ona,po),b,c) ->
let n' = List.fold_right (down_located (name_fold g)) nal n in
f (Option.fold_right (down_located (name_fold g)) ona n') (f n acc b) c
| CIf (_,c,(ona,po),b1,b2) ->
let acc = f n (f n (f n acc b1) b2) c in
Option.fold_left
(f (Option.fold_right (down_located (name_fold g)) ona n)) acc po
| CFix (loc,_,l) ->
let n' = List.fold_right (fun ((_,id),_,_,_,_) -> g id) l n in
List.fold_right (fun (_,(_,o),lb,t,c) acc ->
fold_local_binders g f n'
(fold_local_binders g f n acc t lb) c lb) l acc
| CCoFix (loc,_,_) ->
Pp.warning "Capture check in multiple binders not done"; acc
| CNativeArr(loc,t,p) ->
Array.fold_left (f n) (f n acc t) p
let free_vars_of_constr_expr c =
let rec aux bdvars l = function
| CRef (Ident (_,id)) -> if List.mem id bdvars then l else Idset.add id l
| c -> fold_constr_expr_with_binders (fun a l -> a::l) aux bdvars l c
in aux [] Idset.empty c
let occur_var_constr_expr id c = Idset.mem id (free_vars_of_constr_expr c)
let mkIdentC id = CRef (Ident (dummy_loc, id))
let mkRefC r = CRef r
let mkCastC (a,k) = CCast (dummy_loc,a,k)
let mkLambdaC (idl,bk,a,b) = CLambdaN (dummy_loc,[idl,bk,a],b)
let mkLetInC (id,a,b) = CLetIn (dummy_loc,id,a,b)
let mkProdC (idl,bk,a,b) = CProdN (dummy_loc,[idl,bk,a],b)
let mkAppC (f,l) =
let l = List.map (fun x -> (x,None)) l in
match f with
| CApp (_,g,l') -> CApp (dummy_loc, g, l' @ l)
| _ -> CApp (dummy_loc, (None, f), l)
let rec mkCProdN loc bll c =
match bll with
| LocalRawAssum ((loc1,_)::_ as idl,bk,t) :: bll ->
CProdN (loc,[idl,bk,t],mkCProdN (join_loc loc1 loc) bll c)
| LocalRawDef ((loc1,_) as id,b) :: bll ->
CLetIn (loc,id,b,mkCProdN (join_loc loc1 loc) bll c)
| [] -> c
| LocalRawAssum ([],_,_) :: bll -> mkCProdN loc bll c
let rec mkCLambdaN loc bll c =
match bll with
| LocalRawAssum ((loc1,_)::_ as idl,bk,t) :: bll ->
CLambdaN (loc,[idl,bk,t],mkCLambdaN (join_loc loc1 loc) bll c)
| LocalRawDef ((loc1,_) as id,b) :: bll ->
CLetIn (loc,id,b,mkCLambdaN (join_loc loc1 loc) bll c)
| [] -> c
| LocalRawAssum ([],_,_) :: bll -> mkCLambdaN loc bll c
let rec abstract_constr_expr c = function
| [] -> c
| LocalRawDef (x,b)::bl -> mkLetInC(x,b,abstract_constr_expr c bl)
| LocalRawAssum (idl,bk,t)::bl ->
List.fold_right (fun x b -> mkLambdaC([x],bk,t,b)) idl
(abstract_constr_expr c bl)
let rec prod_constr_expr c = function
| [] -> c
| LocalRawDef (x,b)::bl -> mkLetInC(x,b,prod_constr_expr c bl)
| LocalRawAssum (idl,bk,t)::bl ->
List.fold_right (fun x b -> mkProdC([x],bk,t,b)) idl
(prod_constr_expr c bl)
let coerce_reference_to_id = function
| Ident (_,id) -> id
| Qualid (loc,_) ->
user_err_loc (loc, "coerce_reference_to_id",
str "This expression should be a simple identifier.")
let coerce_to_id = function
| CRef (Ident (loc,id)) -> (loc,id)
| a -> user_err_loc
(constr_loc a,"coerce_to_id",
str "This expression should be a simple identifier.")
let coerce_to_name = function
| CRef (Ident (loc,id)) -> (loc,Name id)
| CHole (loc,_) -> (loc,Anonymous)
| a -> user_err_loc
(constr_loc a,"coerce_to_name",
str "This expression should be a name.")
let split_at_annot bl na =
let names = List.map snd (names_of_local_assums bl) in
match na with
| None ->
if names = [] then error "A fixpoint needs at least one parameter."
else [], bl
| Some (loc, id) ->
let rec aux acc = function
| LocalRawAssum (bls, k, t) as x :: rest ->
let l, r = list_split_when (fun (loc, na) -> na = Name id) bls in
if r = [] then aux (x :: acc) rest
else
(List.rev (if l = [] then acc else LocalRawAssum (l, k, t) :: acc),
LocalRawAssum (r, k, t) :: rest)
| LocalRawDef _ as x :: rest -> aux (x :: acc) rest
| [] ->
user_err_loc(loc,"",
str "No parameter named " ++ Nameops.pr_id id ++ str".")
in aux [] bl
let map_binder g e nal = List.fold_right (down_located (name_fold g)) nal e
let map_binders f g e bl =
let h (e,bl) (nal,bk,t) = (map_binder g e nal,(nal,bk,f e t)::bl) in
let (e,rbl) = List.fold_left h (e,[]) bl in
(e, List.rev rbl)
let map_local_binders f g e bl =
let h (e,bl) = function
LocalRawAssum(nal,k,ty) ->
(map_binder g e nal, LocalRawAssum(nal,k,f e ty)::bl)
| LocalRawDef((loc,na),ty) ->
(name_fold g na e, LocalRawDef((loc,na),f e ty)::bl) in
let (e,rbl) = List.fold_left h (e,[]) bl in
(e, List.rev rbl)
let map_constr_expr_with_binders g f e = function
| CAppExpl (loc,r,l) -> CAppExpl (loc,r,List.map (f e) l)
| CApp (loc,(p,a),l) ->
CApp (loc,(p,f e a),List.map (fun (a,i) -> (f e a,i)) l)
| CProdN (loc,bl,b) ->
let (e,bl) = map_binders f g e bl in CProdN (loc,bl,f e b)
| CLambdaN (loc,bl,b) ->
let (e,bl) = map_binders f g e bl in CLambdaN (loc,bl,f e b)
| CLetIn (loc,na,a,b) -> CLetIn (loc,na,f e a,f (name_fold g (snd na) e) b)
| CCast (loc,a,CastConv (k,b)) -> CCast (loc,f e a,CastConv(k, f e b))
| CCast (loc,a,CastCoerce) -> CCast (loc,f e a,CastCoerce)
| CNotation (loc,n,(l,ll,bll)) ->
CNotation (loc,n,(List.map (f e) l,List.map (List.map (f e)) ll,
List.map (fun bl -> snd (map_local_binders f g e bl)) bll))
| CGeneralization (loc,b,a,c) -> CGeneralization (loc,b,a,f e c)
| CDelimiters (loc,s,a) -> CDelimiters (loc,s,f e a)
| CHole _ | CEvar _ | CPatVar _ | CSort _
| CPrim _ | CRef _ as x -> x
| CRecord (loc,p,l) -> CRecord (loc,p,List.map (fun (id, c) -> (id, f e c)) l)
| CCases (loc,sty,rtnpo,a,bl) ->
let bl = List.map (fun (loc,pat,rhs) -> (loc,pat,f e rhs)) bl in
let ids = ids_of_cases_tomatch a in
let po = Option.map (f (List.fold_right g ids e)) rtnpo in
CCases (loc, sty, po, List.map (fun (tm,x) -> (f e tm,x)) a,bl)
| CLetTuple (loc,nal,(ona,po),b,c) ->
let e' = List.fold_right (down_located (name_fold g)) nal e in
let e'' = Option.fold_right (down_located (name_fold g)) ona e in
CLetTuple (loc,nal,(ona,Option.map (f e'') po),f e b,f e' c)
| CIf (loc,c,(ona,po),b1,b2) ->
let e' = Option.fold_right (down_located (name_fold g)) ona e in
CIf (loc,f e c,(ona,Option.map (f e') po),f e b1,f e b2)
| CFix (loc,id,dl) ->
CFix (loc,id,List.map (fun (id,n,bl,t,d) ->
let (e',bl') = map_local_binders f g e bl in
let t' = f e' t in
let e'' = List.fold_left (fun e ((_,id),_,_,_,_) -> g id e) e' dl in
let d' = f e'' d in
(id,n,bl',t',d')) dl)
| CCoFix (loc,id,dl) ->
CCoFix (loc,id,List.map (fun (id,bl,t,d) ->
let (e',bl') = map_local_binders f g e bl in
let t' = f e' t in
let e'' = List.fold_left (fun e ((_,id),_,_,_) -> g id e) e' dl in
let d' = f e'' d in
(id,bl',t',d')) dl)
| CNativeArr(loc,t,p) -> CNativeArr(loc,f e t,Array.map (f e) p)
Used in
let rec replace_vars_constr_expr l = function
| CRef (Ident (loc,id)) as x ->
(try CRef (Ident (loc,List.assoc id l)) with Not_found -> x)
| c -> map_constr_expr_with_binders List.remove_assoc
replace_vars_constr_expr l c
type with_declaration_ast =
| CWith_Module of identifier list located * qualid located
| CWith_Definition of identifier list located * constr_expr
type module_ast =
| CMident of qualid located
| CMapply of loc * module_ast * module_ast
| CMwith of loc * module_ast * with_declaration_ast
let locs_of_notation loc locs ntn =
let (bl,el) = unloc loc in
let locs = List.map unloc locs in
let rec aux pos = function
| [] -> if pos = el then [] else [(pos,el-1)]
| (ba,ea)::l ->if pos = ba then aux ea l else (pos,ba-1)::aux ea l
in aux bl (Sort.list (fun l1 l2 -> fst l1 < fst l2) locs)
let ntn_loc loc (args,argslist,binderslist) =
locs_of_notation loc
(List.map constr_loc ( argslist)@
List.map local_binders_loc binderslist)
let patntn_loc loc (args,argslist) =
locs_of_notation loc
(List.map cases_pattern_expr_loc ( argslist))
|
d7a7247e646b93805dfdf35af5d0c9c1d73b669b35a2896a78295d8404ad806b | anmonteiro/ocaml-quic | cID.ml | ----------------------------------------------------------------------------
* Copyright ( c ) 2020
*
* 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 .
*
* 3 . Neither the name of the copyright holder 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
* 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 , 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 .
* ---------------------------------------------------------------------------
* Copyright (c) 2020 António Nuno Monteiro
*
* 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.
*
* 3. Neither the name of the copyright holder 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.
*---------------------------------------------------------------------------*)
type t = string
let empty = Sys.opaque_identity ""
let[@inline] length t = String.length t
let src_length = 20
let is_empty t = t == empty
let is_unset t = t = empty
let parse =
let open Angstrom in
From RFC < QUIC - RFC>§17.2 :
* This length is encoded as an 8 - bit unsigned integer . In QUIC version 1 ,
* this value MUST NOT exceed 20 . Endpoints that receive a version 1 long
* header with a value larger than 20 MUST drop the packet . Servers SHOULD
* be able to read longer connection IDs from other QUIC versions in order
* to properly form a version negotiation packet .
* This length is encoded as an 8-bit unsigned integer. In QUIC version 1,
* this value MUST NOT exceed 20. Endpoints that receive a version 1 long
* header with a value larger than 20 MUST drop the packet. Servers SHOULD
* be able to read longer connection IDs from other QUIC versions in order
* to properly form a version negotiation packet. *)
any_uint8 >>= take
let serialize f t =
Faraday.write_uint8 f (length t);
Faraday.write_string f t
let to_string t = t
let of_string t = t
let compare = String.compare
let equal = String.equal
let generate () =
let random_bytes n = Mirage_crypto_rng.generate n |> Cstruct.to_string in
random_bytes 20
| null | https://raw.githubusercontent.com/anmonteiro/ocaml-quic/6bcd5e4cb2da0a7b8a5274321f08771143373666/lib/cID.ml | ocaml | ----------------------------------------------------------------------------
* Copyright ( c ) 2020
*
* 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 .
*
* 3 . Neither the name of the copyright holder 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
* 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 , 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 .
* ---------------------------------------------------------------------------
* Copyright (c) 2020 António Nuno Monteiro
*
* 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.
*
* 3. Neither the name of the copyright holder 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.
*---------------------------------------------------------------------------*)
type t = string
let empty = Sys.opaque_identity ""
let[@inline] length t = String.length t
let src_length = 20
let is_empty t = t == empty
let is_unset t = t = empty
let parse =
let open Angstrom in
From RFC < QUIC - RFC>§17.2 :
* This length is encoded as an 8 - bit unsigned integer . In QUIC version 1 ,
* this value MUST NOT exceed 20 . Endpoints that receive a version 1 long
* header with a value larger than 20 MUST drop the packet . Servers SHOULD
* be able to read longer connection IDs from other QUIC versions in order
* to properly form a version negotiation packet .
* This length is encoded as an 8-bit unsigned integer. In QUIC version 1,
* this value MUST NOT exceed 20. Endpoints that receive a version 1 long
* header with a value larger than 20 MUST drop the packet. Servers SHOULD
* be able to read longer connection IDs from other QUIC versions in order
* to properly form a version negotiation packet. *)
any_uint8 >>= take
let serialize f t =
Faraday.write_uint8 f (length t);
Faraday.write_string f t
let to_string t = t
let of_string t = t
let compare = String.compare
let equal = String.equal
let generate () =
let random_bytes n = Mirage_crypto_rng.generate n |> Cstruct.to_string in
random_bytes 20
|
|
3bbab8d55cf3694030d8b20a5a975514f5636aadd70bac8c741135c4a12959c4 | quek/paiprolog | othello2.lisp | ;;;; -*- Mode: Lisp; Syntax: Common-Lisp -*-
Code from Paradigms of AI Programming
Copyright ( c ) 1991
;;;; File othello2.lisp: More strategies for othello.lisp,
from section 18.9 onward ( alpha - beta2 , alpha - beta3 , iago ) .
If a compiled version of edge-table.lisp exists , then merely
;;;; load it after you load this file. Otherwise, load this file,
;;;; evaluate (init-edge-table) (this will take a really long time),
then compile edge-table.lisp . This will save the edge - table for
;;;; future use.
(requires "othello")
(defconstant all-squares
(sort (loop for i from 11 to 88
when (<= 1 (mod i 10) 8) collect i)
#'> :key #'(lambda (sq) (elt *weights* sq))))
(defstruct (node) square board value)
(defun alpha-beta-searcher2 (depth eval-fn)
"Return a strategy that does A-B search with sorted moves."
#'(lambda (player board)
(multiple-value-bind (value node)
(alpha-beta2
player (make-node :board board
:value (funcall eval-fn player board))
losing-value winning-value depth eval-fn)
(declare (ignore value))
(node-square node))))
(defun alpha-beta2 (player node achievable cutoff ply eval-fn)
"A-B search, sorting moves by eval-fn"
Returns two values : achievable - value and move - to - make
(if (= ply 0)
(values (node-value node) node)
(let* ((board (node-board node))
(nodes (legal-nodes player board eval-fn)))
(if (null nodes)
(if (any-legal-move? (opponent player) board)
(values (- (alpha-beta2 (opponent player)
(negate-value node)
(- cutoff) (- achievable)
(- ply 1) eval-fn))
nil)
(values (final-value player board) nil))
(let ((best-node (first nodes)))
(loop for move in nodes
for val = (- (alpha-beta2
(opponent player)
(negate-value move)
(- cutoff) (- achievable)
(- ply 1) eval-fn))
do (when (> val achievable)
(setf achievable val)
(setf best-node move))
until (>= achievable cutoff))
(values achievable best-node))))))
(defun negate-value (node)
"Set the value of a node to its negative."
(setf (node-value node) (- (node-value node)))
node)
(defun legal-nodes (player board eval-fn)
"Return a list of legal moves, each one packed into a node."
(let ((moves (legal-moves player board)))
(sort (map-into
moves
#'(lambda (move)
(let ((new-board (make-move move player
(copy-board board))))
(make-node
:square move :board new-board
:value (funcall eval-fn player new-board))))
moves)
#'> :key #'node-value)))
(defvar *ply-boards*
(apply #'vector (loop repeat 40 collect (initial-board))))
(defun alpha-beta3 (player board achievable cutoff ply eval-fn
killer)
"A-B search, putting killer move first."
(if (= ply 0)
(funcall eval-fn player board)
(let ((moves (put-first killer (legal-moves player board))))
(if (null moves)
(if (any-legal-move? (opponent player) board)
(- (alpha-beta3 (opponent player) board
(- cutoff) (- achievable)
(- ply 1) eval-fn nil))
(final-value player board))
(let ((best-move (first moves))
(new-board (aref *ply-boards* ply))
(killer2 nil)
(killer2-val winning-value))
(loop for move in moves
do (multiple-value-bind (val reply)
(alpha-beta3
(opponent player)
(make-move move player
(replace new-board board))
(- cutoff) (- achievable)
(- ply 1) eval-fn killer2)
(setf val (- val))
(when (> val achievable)
(setf achievable val)
(setf best-move move))
(when (and reply (< val killer2-val))
(setf killer2 reply)
(setf killer2-val val)))
until (>= achievable cutoff))
(values achievable best-move))))))
(defun alpha-beta-searcher3 (depth eval-fn)
"Return a strategy that does A-B search with killer moves."
#'(lambda (player board)
(multiple-value-bind (value move)
(alpha-beta3 player board losing-value winning-value
depth eval-fn nil)
(declare (ignore value))
move)))
(defun put-first (killer moves)
"Move the killer move to the front of moves,
if the killer move is in fact a legal move."
(if (member killer moves)
(cons killer (delete killer moves))
moves))
(defun mobility (player board)
"Current Mobility is the number of legal moves.
Potential mobility is the number of blank squares
adjacent to an opponent that are not legal moves.
Returns current and potential mobility for player."
(let ((opp (opponent player))
(current 0) ; player's current mobility
(potential 0)) ; player's potential mobility
(dolist (square all-squares)
(when (eql (bref board square) empty)
(cond ((legal-p square player board)
(incf current))
((some #'(lambda (sq) (eql (bref board sq) opp))
(neighbors square))
(incf potential)))))
(values current (+ current potential))))
(defvar *edge-table* (make-array (expt 3 10))
"Array of values to player-to-move for edge positions.")
(defconstant edge-and-x-lists
'((22 11 12 13 14 15 16 17 18 27)
(72 81 82 83 84 85 86 87 88 77)
(22 11 21 31 41 51 61 71 81 72)
(27 18 28 38 48 58 68 78 88 77))
"The four edges (with their X-squares).")
(defun edge-index (player board squares)
2 for opponent ,
on each square---summed as a base 3 number."
(let ((index 0))
(dolist (sq squares)
(setq index (+ (* index 3)
(cond ((eql (bref board sq) empty) 0)
((eql (bref board sq) player) 1)
(t 2)))))
index))
(defun edge-stability (player board)
"Total edge evaluation for player to move on board."
(loop for edge-list in edge-and-x-lists
sum (aref *edge-table*
(edge-index player board edge-list))))
(defconstant top-edge (first edge-and-x-lists))
(defun init-edge-table ()
"Initialize *edge-table*, starting from the empty board."
Initialize the static values
(loop for n-pieces from 0 to 10 do
(map-edge-n-pieces
#'(lambda (board index)
(setf (aref *edge-table* index)
(static-edge-stability black board)))
black (initial-board) n-pieces top-edge 0))
Now iterate five times trying to improve :
(dotimes (i 5)
;; Do the indexes with most pieces first
(loop for n-pieces from 9 downto 1 do
(map-edge-n-pieces
#'(lambda (board index)
(setf (aref *edge-table* index)
(possible-edge-moves-value
black board index)))
black (initial-board) n-pieces top-edge 0))))
(defun map-edge-n-pieces (fn player board n squares index)
"Call fn on all edges with n pieces."
Index counts 1 for player ; 2 for opponent
(cond
((< (length squares) n) nil)
((null squares) (funcall fn board index))
(t (let ((index3 (* 3 index))
(sq (first squares)))
(map-edge-n-pieces fn player board n (rest squares) index3)
(when (and (> n 0) (eql (bref board sq) empty))
(setf (bref board sq) player)
(map-edge-n-pieces fn player board (- n 1) (rest squares)
(+ 1 index3))
(setf (bref board sq) (opponent player))
(map-edge-n-pieces fn player board (- n 1) (rest squares)
(+ 2 index3))
(setf (bref board sq) empty))))))
(defun possible-edge-moves-value (player board index)
"Consider all possible edge moves.
Combine their values into a single number."
(combine-edge-moves
(cons
(list 1.0 (aref *edge-table* index)) ;; no move
(loop for sq in top-edge ;; possible moves
when (eql (bref board sq) empty)
collect (possible-edge-move player board sq)))
player))
(defun possible-edge-move (player board sq)
"Return a (prob val) pair for a possible edge move."
(let ((new-board (replace (aref *ply-boards* player) board)))
(make-move sq player new-board)
(list (edge-move-probability player board sq)
(- (aref *edge-table*
(edge-index (opponent player)
new-board top-edge))))))
(defun combine-edge-moves (possibilities player)
"Combine the best moves."
(let ((prob 1.0)
(val 0.0)
(fn (if (eql player black) #'> #'<)))
(loop for pair in (sort possibilities fn :key #'second)
while (>= prob 0.0)
do (incf val (* prob (first pair) (second pair)))
(decf prob (* prob (first pair))))
(round val)))
(let ((corner/xsqs '((11 . 22) (18 . 27) (81. 72) (88 . 77))))
(defun corner-p (sq) (assoc sq corner/xsqs))
(defun x-square-p (sq) (rassoc sq corner/xsqs))
(defun x-square-for (corner) (cdr (assoc corner corner/xsqs)))
(defun corner-for (xsq) (car (rassoc xsq corner/xsqs))))
(defun edge-move-probability (player board square)
"What's the probability that player can move to this square?"
(cond
((x-square-p square) .5) ;; X-squares
((legal-p square player board) 1.0) ;; immediate capture
move to corner depends on X - square
(let ((x-sq (x-square-for square)))
(cond
((eql (bref board x-sq) empty) .1)
((eql (bref board x-sq) player) 0.001)
(t .9))))
(t (/ (aref
'#2A((.1 .4 .7)
(.05 .3 *)
(.01 * *))
(count-edge-neighbors player board square)
(count-edge-neighbors (opponent player) board square))
(if (legal-p square (opponent player) board) 2 1)))))
(defun count-edge-neighbors (player board square)
"Count the neighbors of this square occupied by player."
(count-if #'(lambda (inc)
(eql (bref board (+ square inc)) player))
'(+1 -1)))
(defparameter *static-edge-table*
stab semi un
( * 0 -2000) ; X
( 700 * *) ; corner
(1200 200 -25) ; C
(1000 200 75) ; A
(1000 200 50) ; B
(1000 200 50) ; B
(1000 200 75) ; A
(1200 200 -25) ; C
( 700 * *) ; corner
( * 0 -2000) ; X
))
(defun static-edge-stability (player board)
"Compute this edge's static stability"
(loop for sq in top-edge
for i from 0
sum (cond
((eql (bref board sq) empty) 0)
((eql (bref board sq) player)
(aref *static-edge-table* i
(piece-stability board sq)))
(t (- (aref *static-edge-table* i
(piece-stability board sq)))))))
(let ((stable 0) (semi-stable 1) (unstable 2))
(defun piece-stability (board sq)
(cond
((corner-p sq) stable)
((x-square-p sq)
(if (eql (bref board (corner-for sq)) empty)
unstable semi-stable))
(t (let* ((player (bref board sq))
(opp (opponent player))
(p1 (find player board :test-not #'eql
:start sq :end 19))
(p2 (find player board :test-not #'eql
:start 11 :end sq
:from-end t)))
(cond
;; unstable pieces can be captured immediately
;; by playing in the empty square
((or (and (eql p1 empty) (eql p2 opp))
(and (eql p2 empty) (eql p1 opp)))
unstable)
;; Semi-stable pieces might be captured
((and (eql p1 opp) (eql p2 opp)
(find empty board :start 11 :end 19))
semi-stable)
((and (eql p1 empty) (eql p2 empty))
semi-stable)
;; Stable pieces can never be captured
(t stable)))))))
(defun Iago-eval (player board)
"Combine edge-stability, current mobility and
potential mobility to arrive at an evaluation."
The three factors are multiplied by coefficients
;; that vary by move number:
(let ((c-edg (+ 312000 (* 6240 *move-number*)))
(c-cur (if (< *move-number* 25)
(+ 50000 (* 2000 *move-number*))
(+ 75000 (* 1000 *move-number*))))
(c-pot 20000))
(multiple-value-bind (p-cur p-pot)
(mobility player board)
(multiple-value-bind (o-cur o-pot)
(mobility (opponent player) board)
Combine the three factors into one sum :
(+ (round (* c-edg (edge-stability player board)) 32000)
(round (* c-cur (- p-cur o-cur)) (+ p-cur o-cur 2))
(round (* c-pot (- p-pot o-pot)) (+ p-pot o-pot 2)))))))
(defun Iago (depth)
"Use an approximation of Iago's evaluation function."
(alpha-beta-searcher3 depth #'iago-eval))
| null | https://raw.githubusercontent.com/quek/paiprolog/012d6bb255d8af7f1c8b1d061dcd8a474fb3b57a/othello2.lisp | lisp | -*- Mode: Lisp; Syntax: Common-Lisp -*-
File othello2.lisp: More strategies for othello.lisp,
load it after you load this file. Otherwise, load this file,
evaluate (init-edge-table) (this will take a really long time),
future use.
player's current mobility
player's potential mobility
Do the indexes with most pieces first
2 for opponent
no move
possible moves
X-squares
immediate capture
X
corner
C
A
B
B
A
C
corner
X
unstable pieces can be captured immediately
by playing in the empty square
Semi-stable pieces might be captured
Stable pieces can never be captured
that vary by move number: | Code from Paradigms of AI Programming
Copyright ( c ) 1991
from section 18.9 onward ( alpha - beta2 , alpha - beta3 , iago ) .
If a compiled version of edge-table.lisp exists , then merely
then compile edge-table.lisp . This will save the edge - table for
(requires "othello")
(defconstant all-squares
(sort (loop for i from 11 to 88
when (<= 1 (mod i 10) 8) collect i)
#'> :key #'(lambda (sq) (elt *weights* sq))))
(defstruct (node) square board value)
(defun alpha-beta-searcher2 (depth eval-fn)
"Return a strategy that does A-B search with sorted moves."
#'(lambda (player board)
(multiple-value-bind (value node)
(alpha-beta2
player (make-node :board board
:value (funcall eval-fn player board))
losing-value winning-value depth eval-fn)
(declare (ignore value))
(node-square node))))
(defun alpha-beta2 (player node achievable cutoff ply eval-fn)
"A-B search, sorting moves by eval-fn"
Returns two values : achievable - value and move - to - make
(if (= ply 0)
(values (node-value node) node)
(let* ((board (node-board node))
(nodes (legal-nodes player board eval-fn)))
(if (null nodes)
(if (any-legal-move? (opponent player) board)
(values (- (alpha-beta2 (opponent player)
(negate-value node)
(- cutoff) (- achievable)
(- ply 1) eval-fn))
nil)
(values (final-value player board) nil))
(let ((best-node (first nodes)))
(loop for move in nodes
for val = (- (alpha-beta2
(opponent player)
(negate-value move)
(- cutoff) (- achievable)
(- ply 1) eval-fn))
do (when (> val achievable)
(setf achievable val)
(setf best-node move))
until (>= achievable cutoff))
(values achievable best-node))))))
(defun negate-value (node)
"Set the value of a node to its negative."
(setf (node-value node) (- (node-value node)))
node)
(defun legal-nodes (player board eval-fn)
"Return a list of legal moves, each one packed into a node."
(let ((moves (legal-moves player board)))
(sort (map-into
moves
#'(lambda (move)
(let ((new-board (make-move move player
(copy-board board))))
(make-node
:square move :board new-board
:value (funcall eval-fn player new-board))))
moves)
#'> :key #'node-value)))
(defvar *ply-boards*
(apply #'vector (loop repeat 40 collect (initial-board))))
(defun alpha-beta3 (player board achievable cutoff ply eval-fn
killer)
"A-B search, putting killer move first."
(if (= ply 0)
(funcall eval-fn player board)
(let ((moves (put-first killer (legal-moves player board))))
(if (null moves)
(if (any-legal-move? (opponent player) board)
(- (alpha-beta3 (opponent player) board
(- cutoff) (- achievable)
(- ply 1) eval-fn nil))
(final-value player board))
(let ((best-move (first moves))
(new-board (aref *ply-boards* ply))
(killer2 nil)
(killer2-val winning-value))
(loop for move in moves
do (multiple-value-bind (val reply)
(alpha-beta3
(opponent player)
(make-move move player
(replace new-board board))
(- cutoff) (- achievable)
(- ply 1) eval-fn killer2)
(setf val (- val))
(when (> val achievable)
(setf achievable val)
(setf best-move move))
(when (and reply (< val killer2-val))
(setf killer2 reply)
(setf killer2-val val)))
until (>= achievable cutoff))
(values achievable best-move))))))
(defun alpha-beta-searcher3 (depth eval-fn)
"Return a strategy that does A-B search with killer moves."
#'(lambda (player board)
(multiple-value-bind (value move)
(alpha-beta3 player board losing-value winning-value
depth eval-fn nil)
(declare (ignore value))
move)))
(defun put-first (killer moves)
"Move the killer move to the front of moves,
if the killer move is in fact a legal move."
(if (member killer moves)
(cons killer (delete killer moves))
moves))
(defun mobility (player board)
"Current Mobility is the number of legal moves.
Potential mobility is the number of blank squares
adjacent to an opponent that are not legal moves.
Returns current and potential mobility for player."
(let ((opp (opponent player))
(dolist (square all-squares)
(when (eql (bref board square) empty)
(cond ((legal-p square player board)
(incf current))
((some #'(lambda (sq) (eql (bref board sq) opp))
(neighbors square))
(incf potential)))))
(values current (+ current potential))))
(defvar *edge-table* (make-array (expt 3 10))
"Array of values to player-to-move for edge positions.")
(defconstant edge-and-x-lists
'((22 11 12 13 14 15 16 17 18 27)
(72 81 82 83 84 85 86 87 88 77)
(22 11 21 31 41 51 61 71 81 72)
(27 18 28 38 48 58 68 78 88 77))
"The four edges (with their X-squares).")
(defun edge-index (player board squares)
2 for opponent ,
on each square---summed as a base 3 number."
(let ((index 0))
(dolist (sq squares)
(setq index (+ (* index 3)
(cond ((eql (bref board sq) empty) 0)
((eql (bref board sq) player) 1)
(t 2)))))
index))
(defun edge-stability (player board)
"Total edge evaluation for player to move on board."
(loop for edge-list in edge-and-x-lists
sum (aref *edge-table*
(edge-index player board edge-list))))
(defconstant top-edge (first edge-and-x-lists))
(defun init-edge-table ()
"Initialize *edge-table*, starting from the empty board."
Initialize the static values
(loop for n-pieces from 0 to 10 do
(map-edge-n-pieces
#'(lambda (board index)
(setf (aref *edge-table* index)
(static-edge-stability black board)))
black (initial-board) n-pieces top-edge 0))
Now iterate five times trying to improve :
(dotimes (i 5)
(loop for n-pieces from 9 downto 1 do
(map-edge-n-pieces
#'(lambda (board index)
(setf (aref *edge-table* index)
(possible-edge-moves-value
black board index)))
black (initial-board) n-pieces top-edge 0))))
(defun map-edge-n-pieces (fn player board n squares index)
"Call fn on all edges with n pieces."
(cond
((< (length squares) n) nil)
((null squares) (funcall fn board index))
(t (let ((index3 (* 3 index))
(sq (first squares)))
(map-edge-n-pieces fn player board n (rest squares) index3)
(when (and (> n 0) (eql (bref board sq) empty))
(setf (bref board sq) player)
(map-edge-n-pieces fn player board (- n 1) (rest squares)
(+ 1 index3))
(setf (bref board sq) (opponent player))
(map-edge-n-pieces fn player board (- n 1) (rest squares)
(+ 2 index3))
(setf (bref board sq) empty))))))
(defun possible-edge-moves-value (player board index)
"Consider all possible edge moves.
Combine their values into a single number."
(combine-edge-moves
(cons
when (eql (bref board sq) empty)
collect (possible-edge-move player board sq)))
player))
(defun possible-edge-move (player board sq)
"Return a (prob val) pair for a possible edge move."
(let ((new-board (replace (aref *ply-boards* player) board)))
(make-move sq player new-board)
(list (edge-move-probability player board sq)
(- (aref *edge-table*
(edge-index (opponent player)
new-board top-edge))))))
(defun combine-edge-moves (possibilities player)
"Combine the best moves."
(let ((prob 1.0)
(val 0.0)
(fn (if (eql player black) #'> #'<)))
(loop for pair in (sort possibilities fn :key #'second)
while (>= prob 0.0)
do (incf val (* prob (first pair) (second pair)))
(decf prob (* prob (first pair))))
(round val)))
(let ((corner/xsqs '((11 . 22) (18 . 27) (81. 72) (88 . 77))))
(defun corner-p (sq) (assoc sq corner/xsqs))
(defun x-square-p (sq) (rassoc sq corner/xsqs))
(defun x-square-for (corner) (cdr (assoc corner corner/xsqs)))
(defun corner-for (xsq) (car (rassoc xsq corner/xsqs))))
(defun edge-move-probability (player board square)
"What's the probability that player can move to this square?"
(cond
move to corner depends on X - square
(let ((x-sq (x-square-for square)))
(cond
((eql (bref board x-sq) empty) .1)
((eql (bref board x-sq) player) 0.001)
(t .9))))
(t (/ (aref
'#2A((.1 .4 .7)
(.05 .3 *)
(.01 * *))
(count-edge-neighbors player board square)
(count-edge-neighbors (opponent player) board square))
(if (legal-p square (opponent player) board) 2 1)))))
(defun count-edge-neighbors (player board square)
"Count the neighbors of this square occupied by player."
(count-if #'(lambda (inc)
(eql (bref board (+ square inc)) player))
'(+1 -1)))
(defparameter *static-edge-table*
stab semi un
))
(defun static-edge-stability (player board)
"Compute this edge's static stability"
(loop for sq in top-edge
for i from 0
sum (cond
((eql (bref board sq) empty) 0)
((eql (bref board sq) player)
(aref *static-edge-table* i
(piece-stability board sq)))
(t (- (aref *static-edge-table* i
(piece-stability board sq)))))))
(let ((stable 0) (semi-stable 1) (unstable 2))
(defun piece-stability (board sq)
(cond
((corner-p sq) stable)
((x-square-p sq)
(if (eql (bref board (corner-for sq)) empty)
unstable semi-stable))
(t (let* ((player (bref board sq))
(opp (opponent player))
(p1 (find player board :test-not #'eql
:start sq :end 19))
(p2 (find player board :test-not #'eql
:start 11 :end sq
:from-end t)))
(cond
((or (and (eql p1 empty) (eql p2 opp))
(and (eql p2 empty) (eql p1 opp)))
unstable)
((and (eql p1 opp) (eql p2 opp)
(find empty board :start 11 :end 19))
semi-stable)
((and (eql p1 empty) (eql p2 empty))
semi-stable)
(t stable)))))))
(defun Iago-eval (player board)
"Combine edge-stability, current mobility and
potential mobility to arrive at an evaluation."
The three factors are multiplied by coefficients
(let ((c-edg (+ 312000 (* 6240 *move-number*)))
(c-cur (if (< *move-number* 25)
(+ 50000 (* 2000 *move-number*))
(+ 75000 (* 1000 *move-number*))))
(c-pot 20000))
(multiple-value-bind (p-cur p-pot)
(mobility player board)
(multiple-value-bind (o-cur o-pot)
(mobility (opponent player) board)
Combine the three factors into one sum :
(+ (round (* c-edg (edge-stability player board)) 32000)
(round (* c-cur (- p-cur o-cur)) (+ p-cur o-cur 2))
(round (* c-pot (- p-pot o-pot)) (+ p-pot o-pot 2)))))))
(defun Iago (depth)
"Use an approximation of Iago's evaluation function."
(alpha-beta-searcher3 depth #'iago-eval))
|
e5138f51aefeb138aeaf88ba738f4c4bb40bbf7b880c0d7b5925ca1b8dd36473 | ice1000/learn | find-the-odd-int.hs | module Codewars.Kata.FindOdd where
import Data.List
findOddRec :: [Int] -> Int
findOddRec [a] = a
findOddRec (a : (b : c))
|a == b = findOddRec c
|a /= b = a
--
-- | Given a list, find the [Int] that appears an
-- odd number of times. The tests will always
-- provide such a number, and the list will
always contain at least one element .
findOdd :: [Int] -> Int
findOdd xs = findOddRec $ sort xs
--
| null | https://raw.githubusercontent.com/ice1000/learn/4ce5ea1897c97f7b5b3aee46ccd994e3613a58dd/Haskell/CW-Kata/find-the-odd-int.hs | haskell |
| Given a list, find the [Int] that appears an
odd number of times. The tests will always
provide such a number, and the list will
| module Codewars.Kata.FindOdd where
import Data.List
findOddRec :: [Int] -> Int
findOddRec [a] = a
findOddRec (a : (b : c))
|a == b = findOddRec c
|a /= b = a
always contain at least one element .
findOdd :: [Int] -> Int
findOdd xs = findOddRec $ sort xs
|
4dfdbc0f27e3697468ac6b53f6d4d215be8ad4fe29a2d5dd322b1d75565e2801 | okuoku/nausicaa | test-random.sps | ;;;
Part of : / Scheme
;;;Contents: tests for random
Date : Thu Jun 25 , 2009
;;;
;;;Abstract
;;;
;;;
;;;
Copyright ( c ) 2009 < >
;;;
;;;This program is free software: you can redistribute it and/or modify
;;;it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or ( at
;;;your option) any later version.
;;;
;;;This program is distributed in the hope that it will be useful, but
;;;WITHOUT ANY WARRANTY; without even the implied warranty of
;;;MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details .
;;;
You should have received a copy of the GNU General Public License
;;;along with this program. If not, see </>.
;;;
#!r6rs
(import (nausicaa)
(nausicaa checks)
(nausicaa randomisations)
(nausicaa lists)
(nausicaa strings)
(nausicaa char-sets)
(nausicaa vectors)
(nausicaa randomisations distributions)
(nausicaa randomisations lists)
(nausicaa randomisations vectors)
(nausicaa randomisations strings)
(nausicaa randomisations marsaglia)
(nausicaa randomisations mersenne)
(nausicaa randomisations blum-blum-shub)
(nausicaa randomisations borosh)
(nausicaa randomisations cmrg))
(check-set-mode! 'report-failed)
(display "*** testing random\n")
(define const:2^32 (expt 2 32))
(define const:2^32-1 (- const:2^32 1))
(parameterise ((check-test-name 'no-fuss))
(check-for-true (integer? (random-integer 10)))
(check-for-true (real? (random-real)))
)
(parameterise ((check-test-name 'default-source))
(let* ((make-integer (random-source-integers-maker default-random-source)))
(define (integer) (make-integer 100))
(check-for-true (integer? (integer)))
(check-for-true (non-negative? (integer)))
(check-for-true (let ((n (integer)))
(and (<= 0 n) (< n 100)))))
;;; --------------------------------------------------------------------
(let* ((make-real (random-source-reals-maker default-random-source)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((make-real (random-source-reals-maker default-random-source 1e-30)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((make-real (random-source-reals-maker default-random-source 1e-5)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
;;; --------------------------------------------------------------------
(check-for-true
(let* ((source-b ((random-source-maker)))
(make-integer (random-source-integers-maker source-b)))
(random-source-seed! default-random-source make-integer)
(let* ((make-real (random-source-reals-maker default-random-source))
(n (make-real)))
(and (< 0 n) (< n 1)))))
(check
(begin
(random-source-jumpahead! default-random-source 10)
(let ((make-integer (random-source-integers-maker default-random-source)))
(integer? (make-integer 10))))
=> #t)
;;; --------------------------------------------------------------------
(let* ((bytevector-maker (random-source-bytevectors-maker default-random-source))
(obj (bytevector-maker 50)))
( write obj)(newline )
(check-for-true (bytevector? obj)))
;;; --------------------------------------------------------------------
(check-for-true
(let* ((state (random-source-state-ref default-random-source)))
(random-source-state-set! default-random-source state)
(let ((make-integer (random-source-integers-maker default-random-source)))
(integer? (make-integer 10)))))
)
(parameterise ((check-test-name 'default-source-parameter))
(let* ((source ((random-source-maker)))
(make-integer (random-source-integers-maker source)))
(define (integer) (make-integer 100))
(check-for-true (integer? (integer)))
(check-for-true (non-negative? (integer)))
(check-for-true (let ((n (integer)))
(and (<= 0 n) (< n 100)))))
;;; --------------------------------------------------------------------
(let* ((source ((random-source-maker)))
(make-real (random-source-reals-maker source)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source ((random-source-maker)))
(make-real (random-source-reals-maker source 1e-30)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source ((random-source-maker)))
(make-real (random-source-reals-maker source 1e-5)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
;;; --------------------------------------------------------------------
(check-for-true
(let* ((source-a ((random-source-maker)))
(source-b ((random-source-maker)))
(make-integer (random-source-integers-maker source-b)))
(random-source-seed! source-a make-integer)
(let* ((make-real (random-source-reals-maker source-a))
(n (make-real)))
(and (< 0 n) (< n 1)))))
(check
(begin
(random-source-jumpahead! ((random-source-maker)) 10)
(let ((make-integer (random-source-integers-maker ((random-source-maker)))))
(integer? (make-integer 10))))
=> #t)
;;; --------------------------------------------------------------------
(let* ((source ((random-source-maker)))
(bytevector-maker (random-source-bytevectors-maker source))
(obj (bytevector-maker 50)))
( write obj)(newline )
(check-for-true (bytevector? obj)))
;;; --------------------------------------------------------------------
(check-for-true
(let* ((source ((random-source-maker)))
(state (random-source-state-ref source)))
(random-source-state-set! source state)
(let ((make-integer (random-source-integers-maker source)))
(integer? (make-integer 10)))))
)
(parameterise ((check-test-name 'mrg32k3a))
(let* ((source (make-random-source/mrg32k3a))
(make-integer (random-source-integers-maker source)))
(define (integer) (make-integer 100))
(check-for-true (integer? (integer)))
(check-for-true (non-negative? (integer)))
(check-for-true (let ((n (integer)))
(and (<= 0 n) (< n 100)))))
;;; --------------------------------------------------------------------
(let* ((source (make-random-source/mrg32k3a))
(make-real (random-source-reals-maker source)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/mrg32k3a))
(make-real (random-source-reals-maker source 1e-30)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/mrg32k3a))
(make-real (random-source-reals-maker source 1e-5)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
;;; --------------------------------------------------------------------
(check-for-true
(let* ((source-a (make-random-source/mrg32k3a))
(source-b (make-random-source/mrg32k3a))
(make-integer (random-source-integers-maker source-b)))
(random-source-seed! source-a make-integer)
(let* ((make-real (random-source-reals-maker source-a))
(n (make-real)))
(and (< 0 n) (< n 1)))))
(check
(begin
(random-source-jumpahead! (make-random-source/mrg32k3a) 10)
(let ((make-integer (random-source-integers-maker (make-random-source/mrg32k3a))))
(integer? (make-integer 10))))
=> #t)
;;; --------------------------------------------------------------------
(let* ((source (make-random-source/mrg32k3a))
(bytevector-maker (random-source-bytevectors-maker source))
(obj (bytevector-maker 50)))
( write obj)(newline )
(check-for-true (bytevector? obj)))
;;; --------------------------------------------------------------------
(check-for-true
(let* ((source (make-random-source/mrg32k3a))
(state (random-source-state-ref source)))
(random-source-state-set! source state)
(let ((make-integer (random-source-integers-maker source)))
(integer? (make-integer 10)))))
)
(parameterise ((check-test-name 'device))
(let* ((source (make-random-source/device))
(make-integer (random-source-integers-maker source)))
(define (integer) (make-integer 100))
(check-for-true (integer? (integer)))
(check-for-true (non-negative? (integer)))
(check-for-true (let ((n (integer)))
(and (<= 0 n) (< n 100)))))
;;; --------------------------------------------------------------------
(let* ((source (make-random-source/device))
(make-real (random-source-reals-maker source)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
;;; --------------------------------------------------------------------
(check-for-true
(let* ((source-a (make-random-source/device))
(source-b (make-random-source/device))
(make-integer (random-source-integers-maker source-b)))
(random-source-seed! source-a (let ((count 0))
(lambda (U)
(and (< count 100)
(begin
(set! count (+ 1 count))
(make-integer U))))))
(let* ((make-real (random-source-reals-maker source-a))
(n (make-real)))
(and (< 0 n) (< n 1)))))
(check
(begin
(random-source-jumpahead! (make-random-source/device) 10)
(let ((make-integer (random-source-integers-maker (make-random-source/device))))
(integer? (make-integer 10))))
=> #t)
;;; --------------------------------------------------------------------
(let* ((source (make-random-source/device))
(bytevector-maker (random-source-bytevectors-maker source))
(obj (bytevector-maker 50)))
( write obj)(newline )
(check-for-true (bytevector? obj)))
;;; --------------------------------------------------------------------
(check-for-true
(let* ((source (make-random-source/device))
(state (random-source-state-ref source)))
(random-source-state-set! source state)
(let ((make-integer (random-source-integers-maker source)))
(integer? (make-integer 10)))))
)
(parameterise ((check-test-name 'device-low-level))
;;;This will block if "/dev/random" has not enough random bytes.
;; (check
( parameterise ( ( random - device - cache - length 5 ) )
( let * ( ( len 1 )
;; (bv (random-device-bytevector len)))
;; (and (bytevector? bv)
;; (= len (bytevector-length bv)))))
;; => #t)
;;; --------------------------------------------------------------------
(check
(let* ((len 10)
(bv (urandom-device-bytevector len)))
(and (bytevector? bv)
(= len (bytevector-length bv))))
=> #t)
(check
(let* ((len 5000)
(bv (urandom-device-bytevector len)))
(and (bytevector? bv)
(= len (bytevector-length bv))))
=> #t)
)
(parameterise ((check-test-name 'utils))
(define (make-integer) (random-integer 10))
(let ((obj (random-list-unfold-numbers make-integer 10)))
(check-for-true (list? obj))
(check-for-true (every integer? obj))
(check-for-true (every non-negative? obj)))
(let ((obj (random-vector-unfold-numbers make-integer 10)))
(check-for-true (vector? obj))
(check-for-true (vector-every integer? obj))
(check-for-true (vector-every non-negative? obj)))
(let ((obj (random-string-unfold-chars make-integer 10)))
(check-for-true (string? obj)))
;;; --------------------------------------------------------------------
(let* ((perm-maker (random-permutations-maker default-random-source))
(obj (perm-maker 10)))
(check (vector? obj) => #t)
(check (vector-length obj) => 10)
(check (vector-every (lambda (n)
(and (integer? n) (<= 0 n) (< n 10)))
obj)
=> #t)
)
(let* ((exp-maker (random-exponentials-maker default-random-source))
(norm-maker (random-normals-maker default-random-source)))
(check (real? (exp-maker 1)) => #t)
(check (real? (norm-maker 1 2)) => #t))
;;; --------------------------------------------------------------------
(let ((sampler (random-source-integers-maker-from-range default-random-source 0 10)))
(check (integer? (sampler)) => #t)
(check (let ((n (sampler))) (and (<= 0 n) (<= n 10))) => #t))
(let ((sampler (random-source-integers-maker-from-range default-random-source 0 10 2)))
(check (integer? (sampler)) => #t)
(check (let ((n (sampler))) (and (<= 0 n) (<= n 10))) => #t)
(check (mod (sampler) 2) => 0)
(check (mod (sampler) 2) => 0)
(check (mod (sampler) 2) => 0)
(check (mod (sampler) 2) => 0)
(check (mod (sampler) 2) => 0)
(check (mod (sampler) 2) => 0)
)
;;; --------------------------------------------------------------------
(let ((sampler (random-source-reals-maker-from-range default-random-source 0 10)))
(check (real? (sampler)) => #t)
(check (let ((n (sampler))) (and (<= 0 n) (<= n 10))) => #t))
(let ((sampler (random-source-reals-maker-from-range default-random-source 0 10 1.2)))
(check (real? (sampler)) => #t)
(check (let ((n (sampler))) (and (<= 0 n) (<= n 10))) => #t))
)
(parameterise ((check-test-name 'list))
(check
(list? (random-list-shuffle '(0 1 2 3 4 5 6 7 8 9) default-random-source))
=> #t)
(check
(length (random-list-shuffle '(0 1 2 3 4 5 6 7 8 9) default-random-source))
=> 10)
(check
(every (lambda (n)
(and (integer? n) (<= 0 n) (< n 10)))
(random-list-shuffle '(0 1 2 3 4 5 6 7 8 9) default-random-source))
=> #t)
;;; --------------------------------------------------------------------
(let* ((sampler (random-list-sample '(0 1 2 3 4 5 6 7 8 9) default-random-source))
(obj (sampler)))
(check (integer? obj) => #t)
(check (and (<= 0 obj) (< obj 10)) => #t))
;;; --------------------------------------------------------------------
(let ((sampler (random-list-sample-population '(0 1 2 3 4 5 6 7 8 9) 5 default-random-source)))
;; (write (sampler))(newline)
;; (write (sampler))(newline)
;; (write (sampler))(newline)
;; (write (sampler))(newline)
(check
(list? (sampler))
=> #t)
(check
(length (sampler))
=> 5)
(check
(every (lambda (n)
(and (integer? n) (<= 0 n) (< n 10)))
(sampler))
=> #t))
)
(parameterise ((check-test-name 'vector))
(let* ((perm-maker (random-permutations-maker default-random-source)))
(check
(vector? (random-vector-shuffle (perm-maker 10) default-random-source))
=> #t)
(check
(vector-length (random-vector-shuffle (perm-maker 10) default-random-source))
=> 10)
(check
(vector-every (lambda (n)
(and (integer? n) (<= 0 n) (< n 10)))
(random-vector-shuffle (perm-maker 10) default-random-source))
=> #t)
;;; --------------------------------------------------------------------
(let* ((sampler (random-vector-sample (perm-maker 10) default-random-source))
(obj (sampler)))
(check (integer? obj) => #t)
(check (and (<= 0 obj) (< obj 10)) => #t))
;;; --------------------------------------------------------------------
(let ((sampler (random-vector-sample-population (perm-maker 10) 5 default-random-source)))
(check
(vector? (sampler))
=> #t)
(check
(vector-length (sampler))
=> 5)
(check
(vector-every (lambda (n)
(and (integer? n) (<= 0 n) (< n 10)))
(sampler))
=> #t))
)
;;; --------------------------------------------------------------------
(let ()
(define (test-random-integers-with-sum requested-sum number-of-numbers
range-min-inclusive range-max-inclusive)
(let ((obj (random-integers-with-sum requested-sum number-of-numbers
range-min-inclusive range-max-inclusive
default-random-source)))
;; (write (list 'doing requested-sum number-of-numbers
;; range-min-inclusive range-max-inclusive))(newline)
( write obj)(newline )
(check-for-true (vector? obj))
(check-for-true (= number-of-numbers (vector-length obj)))
(check-for-true (vector-every integer? obj))
(do ((i 0 (+ 1 i)))
((= i number-of-numbers))
(check-for-true (let ((n (vector-ref obj i)))
;;; (write (list range-min-inclusive n range-max-inclusive))(newline)
(<= range-min-inclusive n range-max-inclusive))))
(check (vector-fold-left + 0 obj) => requested-sum)))
(test-random-integers-with-sum 25 8 0 10)
(test-random-integers-with-sum 25 8 0 5)
(test-random-integers-with-sum 50 8 0 20)
(test-random-integers-with-sum 50 8 3 10)
(test-random-integers-with-sum 0 8 -10 2)
(test-random-integers-with-sum 50 8 -10 20)
(test-random-integers-with-sum -400 8 -50 -20)
#f)
(let ()
(define (test-random-reals-with-sum requested-sum number-of-numbers
range-min-exclusive range-max-exclusive)
(let* ((epsilon 1e-6)
(obj (random-reals-with-sum requested-sum epsilon
number-of-numbers
range-min-exclusive range-max-exclusive
default-random-source)))
( write obj)(newline )
(check-for-true (vector? obj))
(check-for-true (= number-of-numbers (vector-length obj)))
(check-for-true (vector-every real? obj))
(do ((i 0 (+ 1 i)))
((= i number-of-numbers))
(check-for-true (< range-min-exclusive (vector-ref obj i) range-max-exclusive)))
(check
(vector-fold-left + 0 obj)
(=> (lambda (a b)
(> 1e-6 (abs (- a b)))))
requested-sum)
#f))
(test-random-reals-with-sum 25 8 0 10)
(test-random-reals-with-sum 25 8 0 5)
(test-random-reals-with-sum 50 8 0 20)
(test-random-reals-with-sum 50 8 3 10)
(test-random-reals-with-sum 0 8 -10 2)
(test-random-reals-with-sum 50 8 -10 20)
(test-random-reals-with-sum -400 8 -50 -20)
#f)
#t)
(parameterise ((check-test-name 'string))
(check
(string? (random-string-shuffle "abcdefghlm" default-random-source))
=> #t)
(check
(string-length (random-string-shuffle "abcdefghlm" default-random-source))
=> 10)
(check
(string-every (lambda (n) (and (char<=? #\a n) (char<? n #\n)))
(random-string-shuffle "abcdefghlm" default-random-source))
=> #t)
;;; --------------------------------------------------------------------
(let* ((sampler (random-string-sample "abcdefghlm" default-random-source))
(obj (sampler)))
(check (char? obj) => #t)
(check (and (char<=? #\a obj) (char<? obj #\n)) => #t))
;;; --------------------------------------------------------------------
(let ((sampler (random-string-sample-population "abcdefghlm" 5 default-random-source)))
(check
(string? (sampler))
=> #t)
(check
(string-length (sampler))
=> 5)
(check
(string-every (lambda (n) (and (char<=? #\a n) (char<? n #\n)))
(sampler))
=> #t))
)
(parameterise ((check-test-name 'marsaglia-cong))
;;; This is commented out because it takes a lot of time
;;;
( let * ( ( source ( make - random - source / marsaglia / cong ) )
;;; (make-integer (random-source-integers-maker source))
( uint32 ( lambda ( ) ( make - integer const:2 ^ 32 ) ) ) )
;;; (check
;;; (do ((i 1 (+ 1 i))
( k ( uint32 ) ( uint32 ) ) )
( (= i 1000000 )
;;; k))
= > 1529210297 ) )
(let* ((source (make-random-source/marsaglia/cong))
(make-integer (random-source-integers-maker source)))
(define (integer) (make-integer 100))
;; (do ((i 0 (+ 1 i)))
( (= i 100 ) )
;; (write (integer))
;; (newline))
(check-for-true (integer? (integer)))
(check-for-true (non-negative? (integer)))
(check-for-true (let ((n (integer)))
(and (<= 0 n) (< n 100))))
)
;;; --------------------------------------------------------------------
(let* ((source (make-random-source/marsaglia/cong))
(make-real (random-source-reals-maker source)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/marsaglia/cong))
(make-real (random-source-reals-maker source 1e-30)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/marsaglia/cong))
(make-real (random-source-reals-maker source 1e-5)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
;;; --------------------------------------------------------------------
(check-for-true
(let* ((source-a (make-random-source/marsaglia/cong))
(source-b (make-random-source/marsaglia/cong))
(make-integer (random-source-integers-maker source-b)))
(random-source-seed! source-a make-integer)
(let* ((make-real (random-source-reals-maker source-a))
(n (make-real)))
(and (< 0 n) (< n 1)))))
(check
(begin
(random-source-jumpahead! (make-random-source/marsaglia/cong) 10)
(let ((make-integer (random-source-integers-maker (make-random-source/marsaglia/cong))))
(integer? (make-integer 10))))
=> #t)
;;; --------------------------------------------------------------------
(let* ((source (make-random-source/marsaglia/cong))
(bytevector-maker (random-source-bytevectors-maker source))
(obj (bytevector-maker 50)))
( write obj)(newline )
(check-for-true (bytevector? obj)))
;;; --------------------------------------------------------------------
(check-for-true
(let* ((source (make-random-source/marsaglia/cong))
(state (random-source-state-ref source)))
(random-source-state-set! source state)
(let ((make-integer (random-source-integers-maker source)))
(integer? (make-integer 10)))))
)
(parameterise ((check-test-name 'marsaglia-fib))
;;; This is commented out because it takes a lot of time
;;;
;;; (let* ((source (make-random-source/marsaglia/fib))
;;; (make-integer (random-source-integers-maker source))
( uint32 ( lambda ( ) ( make - integer const:2 ^ 32 ) ) ) )
;;; (check
;;; (do ((i 1 (+ 1 i))
( k ( uint32 ) ( uint32 ) ) )
( (= i 1000000 )
;;; k))
= > 3519793928 ) )
(let* ((source (make-random-source/marsaglia/fib))
(make-integer (random-source-integers-maker source)))
(define (integer) (make-integer 100))
;; (do ((i 0 (+ 1 i)))
( (= i 100 ) )
;; (write (integer))
;; (newline))
(check-for-true (integer? (integer)))
(check-for-true (non-negative? (integer)))
(check-for-true (let ((n (integer)))
(and (<= 0 n) (< n 100))))
)
;;; --------------------------------------------------------------------
(let* ((source (make-random-source/marsaglia/fib))
(make-real (random-source-reals-maker source)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/marsaglia/fib))
(make-real (random-source-reals-maker source 1e-30)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/marsaglia/fib))
(make-real (random-source-reals-maker source 1e-5)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
;;; --------------------------------------------------------------------
(check-for-true
(let* ((source-a (make-random-source/marsaglia/fib))
(source-b (make-random-source/marsaglia/fib))
(make-integer (random-source-integers-maker source-b)))
(random-source-seed! source-a make-integer)
(let* ((make-real (random-source-reals-maker source-a))
(n (make-real)))
(and (< 0 n) (< n 1)))))
(check
(begin
(random-source-jumpahead! (make-random-source/marsaglia/fib) 10)
(let ((make-integer (random-source-integers-maker (make-random-source/marsaglia/fib))))
(integer? (make-integer 10))))
=> #t)
;;; --------------------------------------------------------------------
(let* ((source (make-random-source/marsaglia/fib))
(bytevector-maker (random-source-bytevectors-maker source))
(obj (bytevector-maker 50)))
( write obj)(newline )
(check-for-true (bytevector? obj)))
;;; --------------------------------------------------------------------
(check-for-true
(let* ((source (make-random-source/marsaglia/fib))
(state (random-source-state-ref source)))
(random-source-state-set! source state)
(let ((make-integer (random-source-integers-maker source)))
(integer? (make-integer 10)))))
)
(parameterise ((check-test-name 'marsaglia-kiss))
;;; This is commented out because it takes a lot of time
;;;
;;; (let* ((source (make-random-source/marsaglia/kiss))
;;; (make-integer (random-source-integers-maker source))
( uint32 ( lambda ( ) ( make - integer const:2 ^ 32 ) ) ) )
;;; (check
;;; (do ((i 1 (+ 1 i))
( k ( uint32 ) ( uint32 ) ) )
( (= i 1000000 )
;;; k))
;;; => 1372460312))
(let* ((source (make-random-source/marsaglia/kiss))
(make-integer (random-source-integers-maker source)))
(define (integer) (make-integer 100))
;; (do ((i 0 (+ 1 i)))
( (= i 100 ) )
;; (write (integer))
;; (newline))
(check-for-true (integer? (integer)))
(check-for-true (non-negative? (integer)))
(check-for-true (let ((n (integer)))
(and (<= 0 n) (< n 100))))
)
;;; --------------------------------------------------------------------
(let* ((source (make-random-source/marsaglia/kiss))
(make-real (random-source-reals-maker source)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/marsaglia/kiss))
(make-real (random-source-reals-maker source 1e-30)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/marsaglia/kiss))
(make-real (random-source-reals-maker source 1e-5)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
;;; --------------------------------------------------------------------
(check-for-true
(let* ((source-a (make-random-source/marsaglia/kiss))
(source-b (make-random-source/marsaglia/kiss))
(make-integer (random-source-integers-maker source-b)))
(random-source-seed! source-a make-integer)
(let* ((make-real (random-source-reals-maker source-a))
(n (make-real)))
(and (< 0 n) (< n 1)))))
(check
(begin
(random-source-jumpahead! (make-random-source/marsaglia/kiss) 10)
(let ((make-integer (random-source-integers-maker (make-random-source/marsaglia/kiss))))
(integer? (make-integer 10))))
=> #t)
;;; --------------------------------------------------------------------
(let* ((source (make-random-source/marsaglia/kiss))
(bytevector-maker (random-source-bytevectors-maker source))
(obj (bytevector-maker 50)))
( write obj)(newline )
(check-for-true (bytevector? obj)))
;;; --------------------------------------------------------------------
(check-for-true
(let* ((source (make-random-source/marsaglia/kiss))
(state (random-source-state-ref source)))
(random-source-state-set! source state)
(let ((make-integer (random-source-integers-maker source)))
(integer? (make-integer 10)))))
)
(parameterise ((check-test-name 'marsaglia-lfib4))
;;; This is commented out because it takes a lot of time
;;;
;;; (let* ((source (make-random-source/marsaglia/lfib4))
;;; (make-integer (random-source-integers-maker source))
( uint32 ( lambda ( ) ( make - integer const:2 ^ 32 ) ) ) )
;;; (check
;;; (do ((i 1 (+ 1 i))
( k ( uint32 ) ( uint32 ) ) )
( (= i 1000000 )
;;; k))
= > 1064612766 ) )
(let* ((source (make-random-source/marsaglia/lfib4))
(make-integer (random-source-integers-maker source)))
(define (integer) (make-integer 100))
;; (do ((i 0 (+ 1 i)))
( (= i 100 ) )
;; (write (integer))
;; (newline))
(check-for-true (integer? (integer)))
(check-for-true (non-negative? (integer)))
(check-for-true (let ((n (integer)))
(and (<= 0 n) (< n 100))))
)
;;; --------------------------------------------------------------------
(let* ((source (make-random-source/marsaglia/lfib4))
(make-real (random-source-reals-maker source)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/marsaglia/lfib4))
(make-real (random-source-reals-maker source 1e-30)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/marsaglia/lfib4))
(make-real (random-source-reals-maker source 1e-5)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
;;; --------------------------------------------------------------------
(check-for-true
(let* ((source-a (make-random-source/marsaglia/lfib4))
(source-b (make-random-source/marsaglia/lfib4))
(make-integer (random-source-integers-maker source-b)))
(random-source-seed! source-a make-integer)
(let* ((make-real (random-source-reals-maker source-a))
(n (make-real)))
(and (< 0 n) (< n 1)))))
(check
(begin
(random-source-jumpahead! (make-random-source/marsaglia/lfib4) 10)
(let ((make-integer (random-source-integers-maker (make-random-source/marsaglia/lfib4))))
(integer? (make-integer 10))))
=> #t)
;;; --------------------------------------------------------------------
(let* ((source (make-random-source/marsaglia/lfib4))
(bytevector-maker (random-source-bytevectors-maker source))
(obj (bytevector-maker 50)))
( write obj)(newline )
(check-for-true (bytevector? obj)))
;;; --------------------------------------------------------------------
(check-for-true
(let* ((source (make-random-source/marsaglia/lfib4))
(state (random-source-state-ref source)))
(random-source-state-set! source state)
(let ((make-integer (random-source-integers-maker source)))
(integer? (make-integer 10)))))
)
(parameterise ((check-test-name 'marsaglia-mwc))
;;; This is commented out because it takes a lot of time
;;;
;;; (let* ((source (make-random-source/marsaglia/mwc))
;;; (make-integer (random-source-integers-maker source))
( uint32 ( lambda ( ) ( make - integer const:2 ^ 32 ) ) ) )
;;; (check
;;; (do ((i 1 (+ 1 i))
( k ( uint32 ) ( uint32 ) ) )
( (= i 1000000 )
;;; k))
= > 904977562 ) )
(let* ((source (make-random-source/marsaglia/mwc))
(make-integer (random-source-integers-maker source)))
(define (integer) (make-integer 100))
;; (do ((i 0 (+ 1 i)))
( (= i 100 ) )
;; (write (integer))
;; (newline))
(check-for-true (integer? (integer)))
(check-for-true (non-negative? (integer)))
(check-for-true (let ((n (integer)))
(and (<= 0 n) (< n 100))))
)
;;; --------------------------------------------------------------------
(let* ((source (make-random-source/marsaglia/mwc))
(make-real (random-source-reals-maker source)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/marsaglia/mwc))
(make-real (random-source-reals-maker source 1e-30)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/marsaglia/mwc))
(make-real (random-source-reals-maker source 1e-5)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
;;; --------------------------------------------------------------------
(check-for-true
(let* ((source-a (make-random-source/marsaglia/mwc))
(source-b (make-random-source/marsaglia/mwc))
(make-integer (random-source-integers-maker source-b)))
(random-source-seed! source-a make-integer)
(let* ((make-real (random-source-reals-maker source-a))
(n (make-real)))
(and (< 0 n) (< n 1)))))
(check
(begin
(random-source-jumpahead! (make-random-source/marsaglia/mwc) 10)
(let ((make-integer (random-source-integers-maker (make-random-source/marsaglia/mwc))))
(integer? (make-integer 10))))
=> #t)
;;; --------------------------------------------------------------------
(let* ((source (make-random-source/marsaglia/mwc))
(bytevector-maker (random-source-bytevectors-maker source))
(obj (bytevector-maker 50)))
( write obj)(newline )
(check-for-true (bytevector? obj)))
;;; --------------------------------------------------------------------
(check-for-true
(let* ((source (make-random-source/marsaglia/mwc))
(state (random-source-state-ref source)))
(random-source-state-set! source state)
(let ((make-integer (random-source-integers-maker source)))
(integer? (make-integer 10)))))
)
(parameterise ((check-test-name 'marsaglia-shr3))
;;; This is commented out because it takes a lot of time
;;;
;;; (let* ((source (make-random-source/marsaglia/shr3))
;;; (make-integer (random-source-integers-maker source))
( uint32 ( lambda ( ) ( make - integer const:2 ^ 32 ) ) ) )
;;; (check
;;; (do ((i 1 (+ 1 i))
( k ( uint32 ) ( uint32 ) ) )
( (= i 1000000 )
;;; k))
= > 2642725982 ) )
(let* ((source (make-random-source/marsaglia/shr3))
(make-integer (random-source-integers-maker source)))
(define (integer) (make-integer 100))
;; (do ((i 0 (+ 1 i)))
( (= i 100 ) )
;; (write (integer))
;; (newline))
(check-for-true (integer? (integer)))
(check-for-true (non-negative? (integer)))
(check-for-true (let ((n (integer)))
(and (<= 0 n) (< n 100))))
)
;;; --------------------------------------------------------------------
(let* ((source (make-random-source/marsaglia/shr3))
(make-real (random-source-reals-maker source)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/marsaglia/shr3))
(make-real (random-source-reals-maker source 1e-30)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/marsaglia/shr3))
(make-real (random-source-reals-maker source 1e-5)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
;;; --------------------------------------------------------------------
(check-for-true
(let* ((source-a (make-random-source/marsaglia/shr3))
(source-b (make-random-source/marsaglia/shr3))
(make-integer (random-source-integers-maker source-b)))
(random-source-seed! source-a make-integer)
(let* ((make-real (random-source-reals-maker source-a))
(n (make-real)))
(and (< 0 n) (< n 1)))))
(check
(begin
(random-source-jumpahead! (make-random-source/marsaglia/shr3) 10)
(let ((make-integer (random-source-integers-maker (make-random-source/marsaglia/shr3))))
(integer? (make-integer 10))))
=> #t)
;;; --------------------------------------------------------------------
(let* ((source (make-random-source/marsaglia/shr3))
(bytevector-maker (random-source-bytevectors-maker source))
(obj (bytevector-maker 50)))
( write obj)(newline )
(check-for-true (bytevector? obj)))
;;; --------------------------------------------------------------------
(check-for-true
(let* ((source (make-random-source/marsaglia/shr3))
(state (random-source-state-ref source)))
(random-source-state-set! source state)
(let ((make-integer (random-source-integers-maker source)))
(integer? (make-integer 10)))))
)
(parameterise ((check-test-name 'marsaglia-swb))
;;; This is commented out because it takes a lot of time
;;;
;;; (let* ((source (make-random-source/marsaglia/swb))
;;; (make-integer (random-source-integers-maker source))
( uint32 ( lambda ( ) ( make - integer const:2 ^ 32 ) ) ) )
;;; (check
;;; (do ((i 1 (+ 1 i))
( k ( uint32 ) ( uint32 ) ) )
( (= i 1000000 )
;;; k))
= > 627749721 ) )
(let* ((source (make-random-source/marsaglia/swb))
(make-integer (random-source-integers-maker source)))
(define (integer) (make-integer 100))
;; (do ((i 0 (+ 1 i)))
( (= i 100 ) )
;; (write (integer))
;; (newline))
(check-for-true (integer? (integer)))
(check-for-true (non-negative? (integer)))
(check-for-true (let ((n (integer)))
(and (<= 0 n) (< n 100))))
)
;;; --------------------------------------------------------------------
(let* ((source (make-random-source/marsaglia/swb))
(make-real (random-source-reals-maker source)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/marsaglia/swb))
(make-real (random-source-reals-maker source 1e-30)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/marsaglia/swb))
(make-real (random-source-reals-maker source 1e-5)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
;;; --------------------------------------------------------------------
(check-for-true
(let* ((source-a (make-random-source/marsaglia/swb))
(source-b (make-random-source/marsaglia/swb))
(make-integer (random-source-integers-maker source-b)))
(random-source-seed! source-a make-integer)
(let* ((make-real (random-source-reals-maker source-a))
(n (make-real)))
(and (< 0 n) (< n 1)))))
(check
(begin
(random-source-jumpahead! (make-random-source/marsaglia/swb) 10)
(let ((make-integer (random-source-integers-maker (make-random-source/marsaglia/swb))))
(integer? (make-integer 10))))
=> #t)
;;; --------------------------------------------------------------------
(let* ((source (make-random-source/marsaglia/swb))
(bytevector-maker (random-source-bytevectors-maker source))
(obj (bytevector-maker 50)))
( write obj)(newline )
(check-for-true (bytevector? obj)))
;;; --------------------------------------------------------------------
(check-for-true
(let* ((source (make-random-source/marsaglia/swb))
(state (random-source-state-ref source)))
(random-source-state-set! source state)
(let ((make-integer (random-source-integers-maker source)))
(integer? (make-integer 10)))))
)
(parameterise ((check-test-name 'mersenne))
(let* ((source (make-random-source/mersenne))
(make-integer (random-source-integers-maker source)))
(define (integer) (make-integer 100))
;; (do ((i 0 (+ 1 i)))
( (= i 100 ) )
;; (write (integer))
;; (newline))
(check-for-true (integer? (integer)))
(check-for-true (non-negative? (integer)))
(check-for-true (let ((n (integer)))
(and (<= 0 n) (< n 100)))))
;;; --------------------------------------------------------------------
(let* ((source (make-random-source/mersenne))
(make-real (random-source-reals-maker source)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/mersenne))
(make-real (random-source-reals-maker source 1e-30)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/mersenne))
(make-real (random-source-reals-maker source 1e-5)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
;;; --------------------------------------------------------------------
(check-for-true
(let* ((source-a (make-random-source/mersenne))
(source-b (make-random-source/mersenne))
(make-integer (random-source-integers-maker source-b)))
(random-source-seed! source-a make-integer)
(let* ((make-real (random-source-reals-maker source-a))
(n (make-real)))
(and (< 0 n) (< n 1)))))
(check
(begin
(random-source-jumpahead! (make-random-source/mersenne) 10)
(let ((make-integer (random-source-integers-maker (make-random-source/mersenne))))
(integer? (make-integer 10))))
=> #t)
;;; --------------------------------------------------------------------
(let* ((source (make-random-source/mersenne))
(bytevector-maker (random-source-bytevectors-maker source))
(obj (bytevector-maker 50)))
( write obj)(newline )
(check-for-true (bytevector? obj)))
;;; --------------------------------------------------------------------
(check-for-true
(let* ((source (make-random-source/mersenne))
(state (random-source-state-ref source)))
(random-source-state-set! source state)
(let ((make-integer (random-source-integers-maker source)))
(integer? (make-integer 10)))))
)
(parameterise ((check-test-name 'borosh))
(let* ((source (make-random-source/borosh))
(make-integer (random-source-integers-maker source)))
(define (integer) (make-integer 100))
;; (do ((i 0 (+ 1 i)))
( (= i 100 ) )
;; (write (integer))
;; (newline))
(check-for-true (integer? (integer)))
(check-for-true (non-negative? (integer)))
(check-for-true (let ((n (integer)))
(and (<= 0 n) (< n 100)))))
;;; --------------------------------------------------------------------
(let* ((source (make-random-source/borosh))
(make-real (random-source-reals-maker source)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/borosh))
(make-real (random-source-reals-maker source 1e-30)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/borosh))
(make-real (random-source-reals-maker source 1e-5)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
;;; --------------------------------------------------------------------
(check-for-true
(let* ((source-a (make-random-source/borosh))
(source-b (make-random-source/borosh))
(make-integer (random-source-integers-maker source-b)))
(random-source-seed! source-a make-integer)
(let* ((make-real (random-source-reals-maker source-a))
(n (make-real)))
(and (< 0 n) (< n 1)))))
(check
(begin
(random-source-jumpahead! (make-random-source/borosh) 10)
(let ((make-integer (random-source-integers-maker (make-random-source/borosh))))
(integer? (make-integer 10))))
=> #t)
;;; --------------------------------------------------------------------
(let* ((source (make-random-source/borosh))
(bytevector-maker (random-source-bytevectors-maker source))
(obj (bytevector-maker 50)))
( write obj)(newline )
(check-for-true (bytevector? obj)))
;;; --------------------------------------------------------------------
(check-for-true
(let* ((source (make-random-source/borosh))
(state (random-source-state-ref source)))
(random-source-state-set! source state)
(let ((make-integer (random-source-integers-maker source)))
(integer? (make-integer 10)))))
)
(parameterise ((check-test-name 'cmrg))
(let* ((source (make-random-source/cmrg))
(make-integer (random-source-integers-maker source)))
(define (integer) (make-integer 100))
;; (do ((i 0 (+ 1 i)))
( (= i 100 ) )
;; (write (integer))
;; (newline))
(check-for-true (integer? (integer)))
(check-for-true (non-negative? (integer)))
(check-for-true (let ((n (integer)))
(and (<= 0 n) (< n 100)))))
;;; --------------------------------------------------------------------
(let* ((source (make-random-source/cmrg))
(make-real (random-source-reals-maker source)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/cmrg))
(make-real (random-source-reals-maker source 1e-30)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/cmrg))
(make-real (random-source-reals-maker source 1e-5)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
;;; --------------------------------------------------------------------
(check-for-true
(let* ((source-a (make-random-source/cmrg))
(source-b (make-random-source/cmrg))
(make-integer (random-source-integers-maker source-b)))
(random-source-seed! source-a make-integer)
(let* ((make-real (random-source-reals-maker source-a))
(n (make-real)))
(and (< 0 n) (< n 1)))))
(check
(begin
(random-source-jumpahead! (make-random-source/cmrg) 10)
(let ((make-integer (random-source-integers-maker (make-random-source/cmrg))))
(integer? (make-integer 10))))
=> #t)
;;; --------------------------------------------------------------------
(let* ((source (make-random-source/cmrg))
(bytevector-maker (random-source-bytevectors-maker source))
(obj (bytevector-maker 50)))
( write obj)(newline )
(check-for-true (bytevector? obj)))
;;; --------------------------------------------------------------------
(check-for-true
(let* ((source (make-random-source/cmrg))
(state (random-source-state-ref source)))
(random-source-state-set! source state)
(let ((make-integer (random-source-integers-maker source)))
(integer? (make-integer 10)))))
)
(parameterise ((check-test-name 'blum-blum-shub))
(define (seed-it source)
(random-source-seed! source (let ((ell '(1856429723 162301391051)))
(lambda (U)
(if (null? ell)
(random-integer (bitwise-copy-bit 0 32 1))
(begin0
(car ell)
(set! ell (cdr ell))))))))
(let* ((source (make-random-source/blum-blum-shub))
(make-integer (random-source-integers-maker source)))
(define (integer) (make-integer 100))
(seed-it source)
;; (do ((i 0 (+ 1 i)))
( (= i 100 ) )
;; (write (integer))
;; (newline))
(check-for-true (integer? (integer)))
(check-for-true (non-negative? (integer)))
(check-for-true (let ((n (integer)))
(and (<= 0 n) (< n 100))))
)
;;; --------------------------------------------------------------------
(let* ((source (make-random-source/blum-blum-shub))
(make-real (random-source-reals-maker source)))
(seed-it source)
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/blum-blum-shub))
(make-real (random-source-reals-maker source 1e-30)))
(seed-it source)
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/blum-blum-shub))
(make-real (random-source-reals-maker source 1e-5)))
(seed-it source)
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
;;; --------------------------------------------------------------------
(let* ((source (let ((s (make-random-source/blum-blum-shub)))
(seed-it s)
s))
(bytevector-maker (random-source-bytevectors-maker source))
(obj (bytevector-maker 50)))
( write obj)(newline )
(check-for-true (bytevector? obj)))
;;; --------------------------------------------------------------------
(check-for-true
(let* ((source (let ((s (make-random-source/blum-blum-shub)))
(seed-it s)
s))
(state (random-source-state-ref source)))
(random-source-state-set! source state)
(let ((make-integer (random-source-integers-maker source)))
(integer? (make-integer 10)))))
)
;;;; examples
(when #f
(display "Example of random lists:\n")
(do ((i 0 (+ 1 i)))
((= i 5))
(write (random-list-unfold-numbers (lambda ()
(random-integer 10))
10))
(newline))
(display "Example of random vectors:\n")
(do ((i 0 (+ 1 i)))
((= i 5))
(write (random-vector-unfold-numbers (lambda ()
(random-integer 10))
10))
(newline))
(display "Example of random strings:\n")
(do ((i 0 (+ 1 i)))
((= i 5))
(write (random-string-unfold-chars (lambda ()
(+ 65 (random-integer 21)))
10))
(newline))
(display "Example of random passwords of printable characters:\n")
(do ((i 0 (+ 1 i)))
((= i 5))
(display (random-string-unfold-chars
(lambda ()
(do ((ch (random-integer 127) (random-integer 127)))
((char-set-contains? char-set:ascii/graphic (integer->char ch))
ch)))
10))
(newline))
(let ((sampler (random-source-integers-maker-from-range default-random-source 0 10)))
(display "integer samples from [0, 10]:\n")
(do ((i 0 (+ 1 i)))
((= i 10))
(write (sampler))(newline)))
(let ((sampler (random-source-integers-maker-from-range default-random-source 0 10 2)))
(display "integer samples from [0, 10], step 2:\n")
(do ((i 0 (+ 1 i)))
((= i 10))
(write (sampler))(newline)))
(let ((sampler (random-source-reals-maker-from-range default-random-source 0 10)))
(display "real samples from (0, 10):\n")
(do ((i 0 (+ 1 i)))
((= i 10))
(write (sampler))(newline)))
(let ((sampler (random-source-reals-maker-from-range default-random-source 0 10 1.2)))
(display "real samples from [0, 10), step 1.2:\n")
(do ((i 0 (+ 1 i)))
((= i 10))
(write (sampler))(newline)))
)
;;;; done
(check-report)
;;; end of file
| null | https://raw.githubusercontent.com/okuoku/nausicaa/50e7b4d4141ad4d81051588608677223fe9fb715/scheme/tests/test-random.sps | scheme |
Contents: tests for random
Abstract
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
along with this program. If not, see </>.
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
This will block if "/dev/random" has not enough random bytes.
(check
(bv (random-device-bytevector len)))
(and (bytevector? bv)
(= len (bytevector-length bv)))))
=> #t)
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
(write (sampler))(newline)
(write (sampler))(newline)
(write (sampler))(newline)
(write (sampler))(newline)
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
(write (list 'doing requested-sum number-of-numbers
range-min-inclusive range-max-inclusive))(newline)
(write (list range-min-inclusive n range-max-inclusive))(newline)
--------------------------------------------------------------------
--------------------------------------------------------------------
This is commented out because it takes a lot of time
(make-integer (random-source-integers-maker source))
(check
(do ((i 1 (+ 1 i))
k))
(do ((i 0 (+ 1 i)))
(write (integer))
(newline))
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
This is commented out because it takes a lot of time
(let* ((source (make-random-source/marsaglia/fib))
(make-integer (random-source-integers-maker source))
(check
(do ((i 1 (+ 1 i))
k))
(do ((i 0 (+ 1 i)))
(write (integer))
(newline))
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
This is commented out because it takes a lot of time
(let* ((source (make-random-source/marsaglia/kiss))
(make-integer (random-source-integers-maker source))
(check
(do ((i 1 (+ 1 i))
k))
=> 1372460312))
(do ((i 0 (+ 1 i)))
(write (integer))
(newline))
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
This is commented out because it takes a lot of time
(let* ((source (make-random-source/marsaglia/lfib4))
(make-integer (random-source-integers-maker source))
(check
(do ((i 1 (+ 1 i))
k))
(do ((i 0 (+ 1 i)))
(write (integer))
(newline))
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
This is commented out because it takes a lot of time
(let* ((source (make-random-source/marsaglia/mwc))
(make-integer (random-source-integers-maker source))
(check
(do ((i 1 (+ 1 i))
k))
(do ((i 0 (+ 1 i)))
(write (integer))
(newline))
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
This is commented out because it takes a lot of time
(let* ((source (make-random-source/marsaglia/shr3))
(make-integer (random-source-integers-maker source))
(check
(do ((i 1 (+ 1 i))
k))
(do ((i 0 (+ 1 i)))
(write (integer))
(newline))
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
This is commented out because it takes a lot of time
(let* ((source (make-random-source/marsaglia/swb))
(make-integer (random-source-integers-maker source))
(check
(do ((i 1 (+ 1 i))
k))
(do ((i 0 (+ 1 i)))
(write (integer))
(newline))
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
(do ((i 0 (+ 1 i)))
(write (integer))
(newline))
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
(do ((i 0 (+ 1 i)))
(write (integer))
(newline))
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
(do ((i 0 (+ 1 i)))
(write (integer))
(newline))
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
(do ((i 0 (+ 1 i)))
(write (integer))
(newline))
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
examples
done
end of file | Part of : / Scheme
Date : Thu Jun 25 , 2009
Copyright ( c ) 2009 < >
the Free Software Foundation , either version 3 of the License , or ( at
General Public License for more details .
You should have received a copy of the GNU General Public License
#!r6rs
(import (nausicaa)
(nausicaa checks)
(nausicaa randomisations)
(nausicaa lists)
(nausicaa strings)
(nausicaa char-sets)
(nausicaa vectors)
(nausicaa randomisations distributions)
(nausicaa randomisations lists)
(nausicaa randomisations vectors)
(nausicaa randomisations strings)
(nausicaa randomisations marsaglia)
(nausicaa randomisations mersenne)
(nausicaa randomisations blum-blum-shub)
(nausicaa randomisations borosh)
(nausicaa randomisations cmrg))
(check-set-mode! 'report-failed)
(display "*** testing random\n")
(define const:2^32 (expt 2 32))
(define const:2^32-1 (- const:2^32 1))
(parameterise ((check-test-name 'no-fuss))
(check-for-true (integer? (random-integer 10)))
(check-for-true (real? (random-real)))
)
(parameterise ((check-test-name 'default-source))
(let* ((make-integer (random-source-integers-maker default-random-source)))
(define (integer) (make-integer 100))
(check-for-true (integer? (integer)))
(check-for-true (non-negative? (integer)))
(check-for-true (let ((n (integer)))
(and (<= 0 n) (< n 100)))))
(let* ((make-real (random-source-reals-maker default-random-source)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((make-real (random-source-reals-maker default-random-source 1e-30)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((make-real (random-source-reals-maker default-random-source 1e-5)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(check-for-true
(let* ((source-b ((random-source-maker)))
(make-integer (random-source-integers-maker source-b)))
(random-source-seed! default-random-source make-integer)
(let* ((make-real (random-source-reals-maker default-random-source))
(n (make-real)))
(and (< 0 n) (< n 1)))))
(check
(begin
(random-source-jumpahead! default-random-source 10)
(let ((make-integer (random-source-integers-maker default-random-source)))
(integer? (make-integer 10))))
=> #t)
(let* ((bytevector-maker (random-source-bytevectors-maker default-random-source))
(obj (bytevector-maker 50)))
( write obj)(newline )
(check-for-true (bytevector? obj)))
(check-for-true
(let* ((state (random-source-state-ref default-random-source)))
(random-source-state-set! default-random-source state)
(let ((make-integer (random-source-integers-maker default-random-source)))
(integer? (make-integer 10)))))
)
(parameterise ((check-test-name 'default-source-parameter))
(let* ((source ((random-source-maker)))
(make-integer (random-source-integers-maker source)))
(define (integer) (make-integer 100))
(check-for-true (integer? (integer)))
(check-for-true (non-negative? (integer)))
(check-for-true (let ((n (integer)))
(and (<= 0 n) (< n 100)))))
(let* ((source ((random-source-maker)))
(make-real (random-source-reals-maker source)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source ((random-source-maker)))
(make-real (random-source-reals-maker source 1e-30)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source ((random-source-maker)))
(make-real (random-source-reals-maker source 1e-5)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(check-for-true
(let* ((source-a ((random-source-maker)))
(source-b ((random-source-maker)))
(make-integer (random-source-integers-maker source-b)))
(random-source-seed! source-a make-integer)
(let* ((make-real (random-source-reals-maker source-a))
(n (make-real)))
(and (< 0 n) (< n 1)))))
(check
(begin
(random-source-jumpahead! ((random-source-maker)) 10)
(let ((make-integer (random-source-integers-maker ((random-source-maker)))))
(integer? (make-integer 10))))
=> #t)
(let* ((source ((random-source-maker)))
(bytevector-maker (random-source-bytevectors-maker source))
(obj (bytevector-maker 50)))
( write obj)(newline )
(check-for-true (bytevector? obj)))
(check-for-true
(let* ((source ((random-source-maker)))
(state (random-source-state-ref source)))
(random-source-state-set! source state)
(let ((make-integer (random-source-integers-maker source)))
(integer? (make-integer 10)))))
)
(parameterise ((check-test-name 'mrg32k3a))
(let* ((source (make-random-source/mrg32k3a))
(make-integer (random-source-integers-maker source)))
(define (integer) (make-integer 100))
(check-for-true (integer? (integer)))
(check-for-true (non-negative? (integer)))
(check-for-true (let ((n (integer)))
(and (<= 0 n) (< n 100)))))
(let* ((source (make-random-source/mrg32k3a))
(make-real (random-source-reals-maker source)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/mrg32k3a))
(make-real (random-source-reals-maker source 1e-30)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/mrg32k3a))
(make-real (random-source-reals-maker source 1e-5)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(check-for-true
(let* ((source-a (make-random-source/mrg32k3a))
(source-b (make-random-source/mrg32k3a))
(make-integer (random-source-integers-maker source-b)))
(random-source-seed! source-a make-integer)
(let* ((make-real (random-source-reals-maker source-a))
(n (make-real)))
(and (< 0 n) (< n 1)))))
(check
(begin
(random-source-jumpahead! (make-random-source/mrg32k3a) 10)
(let ((make-integer (random-source-integers-maker (make-random-source/mrg32k3a))))
(integer? (make-integer 10))))
=> #t)
(let* ((source (make-random-source/mrg32k3a))
(bytevector-maker (random-source-bytevectors-maker source))
(obj (bytevector-maker 50)))
( write obj)(newline )
(check-for-true (bytevector? obj)))
(check-for-true
(let* ((source (make-random-source/mrg32k3a))
(state (random-source-state-ref source)))
(random-source-state-set! source state)
(let ((make-integer (random-source-integers-maker source)))
(integer? (make-integer 10)))))
)
(parameterise ((check-test-name 'device))
(let* ((source (make-random-source/device))
(make-integer (random-source-integers-maker source)))
(define (integer) (make-integer 100))
(check-for-true (integer? (integer)))
(check-for-true (non-negative? (integer)))
(check-for-true (let ((n (integer)))
(and (<= 0 n) (< n 100)))))
(let* ((source (make-random-source/device))
(make-real (random-source-reals-maker source)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(check-for-true
(let* ((source-a (make-random-source/device))
(source-b (make-random-source/device))
(make-integer (random-source-integers-maker source-b)))
(random-source-seed! source-a (let ((count 0))
(lambda (U)
(and (< count 100)
(begin
(set! count (+ 1 count))
(make-integer U))))))
(let* ((make-real (random-source-reals-maker source-a))
(n (make-real)))
(and (< 0 n) (< n 1)))))
(check
(begin
(random-source-jumpahead! (make-random-source/device) 10)
(let ((make-integer (random-source-integers-maker (make-random-source/device))))
(integer? (make-integer 10))))
=> #t)
(let* ((source (make-random-source/device))
(bytevector-maker (random-source-bytevectors-maker source))
(obj (bytevector-maker 50)))
( write obj)(newline )
(check-for-true (bytevector? obj)))
(check-for-true
(let* ((source (make-random-source/device))
(state (random-source-state-ref source)))
(random-source-state-set! source state)
(let ((make-integer (random-source-integers-maker source)))
(integer? (make-integer 10)))))
)
(parameterise ((check-test-name 'device-low-level))
( parameterise ( ( random - device - cache - length 5 ) )
( let * ( ( len 1 )
(check
(let* ((len 10)
(bv (urandom-device-bytevector len)))
(and (bytevector? bv)
(= len (bytevector-length bv))))
=> #t)
(check
(let* ((len 5000)
(bv (urandom-device-bytevector len)))
(and (bytevector? bv)
(= len (bytevector-length bv))))
=> #t)
)
(parameterise ((check-test-name 'utils))
(define (make-integer) (random-integer 10))
(let ((obj (random-list-unfold-numbers make-integer 10)))
(check-for-true (list? obj))
(check-for-true (every integer? obj))
(check-for-true (every non-negative? obj)))
(let ((obj (random-vector-unfold-numbers make-integer 10)))
(check-for-true (vector? obj))
(check-for-true (vector-every integer? obj))
(check-for-true (vector-every non-negative? obj)))
(let ((obj (random-string-unfold-chars make-integer 10)))
(check-for-true (string? obj)))
(let* ((perm-maker (random-permutations-maker default-random-source))
(obj (perm-maker 10)))
(check (vector? obj) => #t)
(check (vector-length obj) => 10)
(check (vector-every (lambda (n)
(and (integer? n) (<= 0 n) (< n 10)))
obj)
=> #t)
)
(let* ((exp-maker (random-exponentials-maker default-random-source))
(norm-maker (random-normals-maker default-random-source)))
(check (real? (exp-maker 1)) => #t)
(check (real? (norm-maker 1 2)) => #t))
(let ((sampler (random-source-integers-maker-from-range default-random-source 0 10)))
(check (integer? (sampler)) => #t)
(check (let ((n (sampler))) (and (<= 0 n) (<= n 10))) => #t))
(let ((sampler (random-source-integers-maker-from-range default-random-source 0 10 2)))
(check (integer? (sampler)) => #t)
(check (let ((n (sampler))) (and (<= 0 n) (<= n 10))) => #t)
(check (mod (sampler) 2) => 0)
(check (mod (sampler) 2) => 0)
(check (mod (sampler) 2) => 0)
(check (mod (sampler) 2) => 0)
(check (mod (sampler) 2) => 0)
(check (mod (sampler) 2) => 0)
)
(let ((sampler (random-source-reals-maker-from-range default-random-source 0 10)))
(check (real? (sampler)) => #t)
(check (let ((n (sampler))) (and (<= 0 n) (<= n 10))) => #t))
(let ((sampler (random-source-reals-maker-from-range default-random-source 0 10 1.2)))
(check (real? (sampler)) => #t)
(check (let ((n (sampler))) (and (<= 0 n) (<= n 10))) => #t))
)
(parameterise ((check-test-name 'list))
(check
(list? (random-list-shuffle '(0 1 2 3 4 5 6 7 8 9) default-random-source))
=> #t)
(check
(length (random-list-shuffle '(0 1 2 3 4 5 6 7 8 9) default-random-source))
=> 10)
(check
(every (lambda (n)
(and (integer? n) (<= 0 n) (< n 10)))
(random-list-shuffle '(0 1 2 3 4 5 6 7 8 9) default-random-source))
=> #t)
(let* ((sampler (random-list-sample '(0 1 2 3 4 5 6 7 8 9) default-random-source))
(obj (sampler)))
(check (integer? obj) => #t)
(check (and (<= 0 obj) (< obj 10)) => #t))
(let ((sampler (random-list-sample-population '(0 1 2 3 4 5 6 7 8 9) 5 default-random-source)))
(check
(list? (sampler))
=> #t)
(check
(length (sampler))
=> 5)
(check
(every (lambda (n)
(and (integer? n) (<= 0 n) (< n 10)))
(sampler))
=> #t))
)
(parameterise ((check-test-name 'vector))
(let* ((perm-maker (random-permutations-maker default-random-source)))
(check
(vector? (random-vector-shuffle (perm-maker 10) default-random-source))
=> #t)
(check
(vector-length (random-vector-shuffle (perm-maker 10) default-random-source))
=> 10)
(check
(vector-every (lambda (n)
(and (integer? n) (<= 0 n) (< n 10)))
(random-vector-shuffle (perm-maker 10) default-random-source))
=> #t)
(let* ((sampler (random-vector-sample (perm-maker 10) default-random-source))
(obj (sampler)))
(check (integer? obj) => #t)
(check (and (<= 0 obj) (< obj 10)) => #t))
(let ((sampler (random-vector-sample-population (perm-maker 10) 5 default-random-source)))
(check
(vector? (sampler))
=> #t)
(check
(vector-length (sampler))
=> 5)
(check
(vector-every (lambda (n)
(and (integer? n) (<= 0 n) (< n 10)))
(sampler))
=> #t))
)
(let ()
(define (test-random-integers-with-sum requested-sum number-of-numbers
range-min-inclusive range-max-inclusive)
(let ((obj (random-integers-with-sum requested-sum number-of-numbers
range-min-inclusive range-max-inclusive
default-random-source)))
( write obj)(newline )
(check-for-true (vector? obj))
(check-for-true (= number-of-numbers (vector-length obj)))
(check-for-true (vector-every integer? obj))
(do ((i 0 (+ 1 i)))
((= i number-of-numbers))
(check-for-true (let ((n (vector-ref obj i)))
(<= range-min-inclusive n range-max-inclusive))))
(check (vector-fold-left + 0 obj) => requested-sum)))
(test-random-integers-with-sum 25 8 0 10)
(test-random-integers-with-sum 25 8 0 5)
(test-random-integers-with-sum 50 8 0 20)
(test-random-integers-with-sum 50 8 3 10)
(test-random-integers-with-sum 0 8 -10 2)
(test-random-integers-with-sum 50 8 -10 20)
(test-random-integers-with-sum -400 8 -50 -20)
#f)
(let ()
(define (test-random-reals-with-sum requested-sum number-of-numbers
range-min-exclusive range-max-exclusive)
(let* ((epsilon 1e-6)
(obj (random-reals-with-sum requested-sum epsilon
number-of-numbers
range-min-exclusive range-max-exclusive
default-random-source)))
( write obj)(newline )
(check-for-true (vector? obj))
(check-for-true (= number-of-numbers (vector-length obj)))
(check-for-true (vector-every real? obj))
(do ((i 0 (+ 1 i)))
((= i number-of-numbers))
(check-for-true (< range-min-exclusive (vector-ref obj i) range-max-exclusive)))
(check
(vector-fold-left + 0 obj)
(=> (lambda (a b)
(> 1e-6 (abs (- a b)))))
requested-sum)
#f))
(test-random-reals-with-sum 25 8 0 10)
(test-random-reals-with-sum 25 8 0 5)
(test-random-reals-with-sum 50 8 0 20)
(test-random-reals-with-sum 50 8 3 10)
(test-random-reals-with-sum 0 8 -10 2)
(test-random-reals-with-sum 50 8 -10 20)
(test-random-reals-with-sum -400 8 -50 -20)
#f)
#t)
(parameterise ((check-test-name 'string))
(check
(string? (random-string-shuffle "abcdefghlm" default-random-source))
=> #t)
(check
(string-length (random-string-shuffle "abcdefghlm" default-random-source))
=> 10)
(check
(string-every (lambda (n) (and (char<=? #\a n) (char<? n #\n)))
(random-string-shuffle "abcdefghlm" default-random-source))
=> #t)
(let* ((sampler (random-string-sample "abcdefghlm" default-random-source))
(obj (sampler)))
(check (char? obj) => #t)
(check (and (char<=? #\a obj) (char<? obj #\n)) => #t))
(let ((sampler (random-string-sample-population "abcdefghlm" 5 default-random-source)))
(check
(string? (sampler))
=> #t)
(check
(string-length (sampler))
=> 5)
(check
(string-every (lambda (n) (and (char<=? #\a n) (char<? n #\n)))
(sampler))
=> #t))
)
(parameterise ((check-test-name 'marsaglia-cong))
( let * ( ( source ( make - random - source / marsaglia / cong ) )
( uint32 ( lambda ( ) ( make - integer const:2 ^ 32 ) ) ) )
( k ( uint32 ) ( uint32 ) ) )
( (= i 1000000 )
= > 1529210297 ) )
(let* ((source (make-random-source/marsaglia/cong))
(make-integer (random-source-integers-maker source)))
(define (integer) (make-integer 100))
( (= i 100 ) )
(check-for-true (integer? (integer)))
(check-for-true (non-negative? (integer)))
(check-for-true (let ((n (integer)))
(and (<= 0 n) (< n 100))))
)
(let* ((source (make-random-source/marsaglia/cong))
(make-real (random-source-reals-maker source)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/marsaglia/cong))
(make-real (random-source-reals-maker source 1e-30)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/marsaglia/cong))
(make-real (random-source-reals-maker source 1e-5)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(check-for-true
(let* ((source-a (make-random-source/marsaglia/cong))
(source-b (make-random-source/marsaglia/cong))
(make-integer (random-source-integers-maker source-b)))
(random-source-seed! source-a make-integer)
(let* ((make-real (random-source-reals-maker source-a))
(n (make-real)))
(and (< 0 n) (< n 1)))))
(check
(begin
(random-source-jumpahead! (make-random-source/marsaglia/cong) 10)
(let ((make-integer (random-source-integers-maker (make-random-source/marsaglia/cong))))
(integer? (make-integer 10))))
=> #t)
(let* ((source (make-random-source/marsaglia/cong))
(bytevector-maker (random-source-bytevectors-maker source))
(obj (bytevector-maker 50)))
( write obj)(newline )
(check-for-true (bytevector? obj)))
(check-for-true
(let* ((source (make-random-source/marsaglia/cong))
(state (random-source-state-ref source)))
(random-source-state-set! source state)
(let ((make-integer (random-source-integers-maker source)))
(integer? (make-integer 10)))))
)
(parameterise ((check-test-name 'marsaglia-fib))
( uint32 ( lambda ( ) ( make - integer const:2 ^ 32 ) ) ) )
( k ( uint32 ) ( uint32 ) ) )
( (= i 1000000 )
= > 3519793928 ) )
(let* ((source (make-random-source/marsaglia/fib))
(make-integer (random-source-integers-maker source)))
(define (integer) (make-integer 100))
( (= i 100 ) )
(check-for-true (integer? (integer)))
(check-for-true (non-negative? (integer)))
(check-for-true (let ((n (integer)))
(and (<= 0 n) (< n 100))))
)
(let* ((source (make-random-source/marsaglia/fib))
(make-real (random-source-reals-maker source)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/marsaglia/fib))
(make-real (random-source-reals-maker source 1e-30)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/marsaglia/fib))
(make-real (random-source-reals-maker source 1e-5)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(check-for-true
(let* ((source-a (make-random-source/marsaglia/fib))
(source-b (make-random-source/marsaglia/fib))
(make-integer (random-source-integers-maker source-b)))
(random-source-seed! source-a make-integer)
(let* ((make-real (random-source-reals-maker source-a))
(n (make-real)))
(and (< 0 n) (< n 1)))))
(check
(begin
(random-source-jumpahead! (make-random-source/marsaglia/fib) 10)
(let ((make-integer (random-source-integers-maker (make-random-source/marsaglia/fib))))
(integer? (make-integer 10))))
=> #t)
(let* ((source (make-random-source/marsaglia/fib))
(bytevector-maker (random-source-bytevectors-maker source))
(obj (bytevector-maker 50)))
( write obj)(newline )
(check-for-true (bytevector? obj)))
(check-for-true
(let* ((source (make-random-source/marsaglia/fib))
(state (random-source-state-ref source)))
(random-source-state-set! source state)
(let ((make-integer (random-source-integers-maker source)))
(integer? (make-integer 10)))))
)
(parameterise ((check-test-name 'marsaglia-kiss))
( uint32 ( lambda ( ) ( make - integer const:2 ^ 32 ) ) ) )
( k ( uint32 ) ( uint32 ) ) )
( (= i 1000000 )
(let* ((source (make-random-source/marsaglia/kiss))
(make-integer (random-source-integers-maker source)))
(define (integer) (make-integer 100))
( (= i 100 ) )
(check-for-true (integer? (integer)))
(check-for-true (non-negative? (integer)))
(check-for-true (let ((n (integer)))
(and (<= 0 n) (< n 100))))
)
(let* ((source (make-random-source/marsaglia/kiss))
(make-real (random-source-reals-maker source)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/marsaglia/kiss))
(make-real (random-source-reals-maker source 1e-30)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/marsaglia/kiss))
(make-real (random-source-reals-maker source 1e-5)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(check-for-true
(let* ((source-a (make-random-source/marsaglia/kiss))
(source-b (make-random-source/marsaglia/kiss))
(make-integer (random-source-integers-maker source-b)))
(random-source-seed! source-a make-integer)
(let* ((make-real (random-source-reals-maker source-a))
(n (make-real)))
(and (< 0 n) (< n 1)))))
(check
(begin
(random-source-jumpahead! (make-random-source/marsaglia/kiss) 10)
(let ((make-integer (random-source-integers-maker (make-random-source/marsaglia/kiss))))
(integer? (make-integer 10))))
=> #t)
(let* ((source (make-random-source/marsaglia/kiss))
(bytevector-maker (random-source-bytevectors-maker source))
(obj (bytevector-maker 50)))
( write obj)(newline )
(check-for-true (bytevector? obj)))
(check-for-true
(let* ((source (make-random-source/marsaglia/kiss))
(state (random-source-state-ref source)))
(random-source-state-set! source state)
(let ((make-integer (random-source-integers-maker source)))
(integer? (make-integer 10)))))
)
(parameterise ((check-test-name 'marsaglia-lfib4))
( uint32 ( lambda ( ) ( make - integer const:2 ^ 32 ) ) ) )
( k ( uint32 ) ( uint32 ) ) )
( (= i 1000000 )
= > 1064612766 ) )
(let* ((source (make-random-source/marsaglia/lfib4))
(make-integer (random-source-integers-maker source)))
(define (integer) (make-integer 100))
( (= i 100 ) )
(check-for-true (integer? (integer)))
(check-for-true (non-negative? (integer)))
(check-for-true (let ((n (integer)))
(and (<= 0 n) (< n 100))))
)
(let* ((source (make-random-source/marsaglia/lfib4))
(make-real (random-source-reals-maker source)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/marsaglia/lfib4))
(make-real (random-source-reals-maker source 1e-30)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/marsaglia/lfib4))
(make-real (random-source-reals-maker source 1e-5)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(check-for-true
(let* ((source-a (make-random-source/marsaglia/lfib4))
(source-b (make-random-source/marsaglia/lfib4))
(make-integer (random-source-integers-maker source-b)))
(random-source-seed! source-a make-integer)
(let* ((make-real (random-source-reals-maker source-a))
(n (make-real)))
(and (< 0 n) (< n 1)))))
(check
(begin
(random-source-jumpahead! (make-random-source/marsaglia/lfib4) 10)
(let ((make-integer (random-source-integers-maker (make-random-source/marsaglia/lfib4))))
(integer? (make-integer 10))))
=> #t)
(let* ((source (make-random-source/marsaglia/lfib4))
(bytevector-maker (random-source-bytevectors-maker source))
(obj (bytevector-maker 50)))
( write obj)(newline )
(check-for-true (bytevector? obj)))
(check-for-true
(let* ((source (make-random-source/marsaglia/lfib4))
(state (random-source-state-ref source)))
(random-source-state-set! source state)
(let ((make-integer (random-source-integers-maker source)))
(integer? (make-integer 10)))))
)
(parameterise ((check-test-name 'marsaglia-mwc))
( uint32 ( lambda ( ) ( make - integer const:2 ^ 32 ) ) ) )
( k ( uint32 ) ( uint32 ) ) )
( (= i 1000000 )
= > 904977562 ) )
(let* ((source (make-random-source/marsaglia/mwc))
(make-integer (random-source-integers-maker source)))
(define (integer) (make-integer 100))
( (= i 100 ) )
(check-for-true (integer? (integer)))
(check-for-true (non-negative? (integer)))
(check-for-true (let ((n (integer)))
(and (<= 0 n) (< n 100))))
)
(let* ((source (make-random-source/marsaglia/mwc))
(make-real (random-source-reals-maker source)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/marsaglia/mwc))
(make-real (random-source-reals-maker source 1e-30)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/marsaglia/mwc))
(make-real (random-source-reals-maker source 1e-5)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(check-for-true
(let* ((source-a (make-random-source/marsaglia/mwc))
(source-b (make-random-source/marsaglia/mwc))
(make-integer (random-source-integers-maker source-b)))
(random-source-seed! source-a make-integer)
(let* ((make-real (random-source-reals-maker source-a))
(n (make-real)))
(and (< 0 n) (< n 1)))))
(check
(begin
(random-source-jumpahead! (make-random-source/marsaglia/mwc) 10)
(let ((make-integer (random-source-integers-maker (make-random-source/marsaglia/mwc))))
(integer? (make-integer 10))))
=> #t)
(let* ((source (make-random-source/marsaglia/mwc))
(bytevector-maker (random-source-bytevectors-maker source))
(obj (bytevector-maker 50)))
( write obj)(newline )
(check-for-true (bytevector? obj)))
(check-for-true
(let* ((source (make-random-source/marsaglia/mwc))
(state (random-source-state-ref source)))
(random-source-state-set! source state)
(let ((make-integer (random-source-integers-maker source)))
(integer? (make-integer 10)))))
)
(parameterise ((check-test-name 'marsaglia-shr3))
( uint32 ( lambda ( ) ( make - integer const:2 ^ 32 ) ) ) )
( k ( uint32 ) ( uint32 ) ) )
( (= i 1000000 )
= > 2642725982 ) )
(let* ((source (make-random-source/marsaglia/shr3))
(make-integer (random-source-integers-maker source)))
(define (integer) (make-integer 100))
( (= i 100 ) )
(check-for-true (integer? (integer)))
(check-for-true (non-negative? (integer)))
(check-for-true (let ((n (integer)))
(and (<= 0 n) (< n 100))))
)
(let* ((source (make-random-source/marsaglia/shr3))
(make-real (random-source-reals-maker source)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/marsaglia/shr3))
(make-real (random-source-reals-maker source 1e-30)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/marsaglia/shr3))
(make-real (random-source-reals-maker source 1e-5)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(check-for-true
(let* ((source-a (make-random-source/marsaglia/shr3))
(source-b (make-random-source/marsaglia/shr3))
(make-integer (random-source-integers-maker source-b)))
(random-source-seed! source-a make-integer)
(let* ((make-real (random-source-reals-maker source-a))
(n (make-real)))
(and (< 0 n) (< n 1)))))
(check
(begin
(random-source-jumpahead! (make-random-source/marsaglia/shr3) 10)
(let ((make-integer (random-source-integers-maker (make-random-source/marsaglia/shr3))))
(integer? (make-integer 10))))
=> #t)
(let* ((source (make-random-source/marsaglia/shr3))
(bytevector-maker (random-source-bytevectors-maker source))
(obj (bytevector-maker 50)))
( write obj)(newline )
(check-for-true (bytevector? obj)))
(check-for-true
(let* ((source (make-random-source/marsaglia/shr3))
(state (random-source-state-ref source)))
(random-source-state-set! source state)
(let ((make-integer (random-source-integers-maker source)))
(integer? (make-integer 10)))))
)
(parameterise ((check-test-name 'marsaglia-swb))
( uint32 ( lambda ( ) ( make - integer const:2 ^ 32 ) ) ) )
( k ( uint32 ) ( uint32 ) ) )
( (= i 1000000 )
= > 627749721 ) )
(let* ((source (make-random-source/marsaglia/swb))
(make-integer (random-source-integers-maker source)))
(define (integer) (make-integer 100))
( (= i 100 ) )
(check-for-true (integer? (integer)))
(check-for-true (non-negative? (integer)))
(check-for-true (let ((n (integer)))
(and (<= 0 n) (< n 100))))
)
(let* ((source (make-random-source/marsaglia/swb))
(make-real (random-source-reals-maker source)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/marsaglia/swb))
(make-real (random-source-reals-maker source 1e-30)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/marsaglia/swb))
(make-real (random-source-reals-maker source 1e-5)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(check-for-true
(let* ((source-a (make-random-source/marsaglia/swb))
(source-b (make-random-source/marsaglia/swb))
(make-integer (random-source-integers-maker source-b)))
(random-source-seed! source-a make-integer)
(let* ((make-real (random-source-reals-maker source-a))
(n (make-real)))
(and (< 0 n) (< n 1)))))
(check
(begin
(random-source-jumpahead! (make-random-source/marsaglia/swb) 10)
(let ((make-integer (random-source-integers-maker (make-random-source/marsaglia/swb))))
(integer? (make-integer 10))))
=> #t)
(let* ((source (make-random-source/marsaglia/swb))
(bytevector-maker (random-source-bytevectors-maker source))
(obj (bytevector-maker 50)))
( write obj)(newline )
(check-for-true (bytevector? obj)))
(check-for-true
(let* ((source (make-random-source/marsaglia/swb))
(state (random-source-state-ref source)))
(random-source-state-set! source state)
(let ((make-integer (random-source-integers-maker source)))
(integer? (make-integer 10)))))
)
(parameterise ((check-test-name 'mersenne))
(let* ((source (make-random-source/mersenne))
(make-integer (random-source-integers-maker source)))
(define (integer) (make-integer 100))
( (= i 100 ) )
(check-for-true (integer? (integer)))
(check-for-true (non-negative? (integer)))
(check-for-true (let ((n (integer)))
(and (<= 0 n) (< n 100)))))
(let* ((source (make-random-source/mersenne))
(make-real (random-source-reals-maker source)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/mersenne))
(make-real (random-source-reals-maker source 1e-30)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/mersenne))
(make-real (random-source-reals-maker source 1e-5)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(check-for-true
(let* ((source-a (make-random-source/mersenne))
(source-b (make-random-source/mersenne))
(make-integer (random-source-integers-maker source-b)))
(random-source-seed! source-a make-integer)
(let* ((make-real (random-source-reals-maker source-a))
(n (make-real)))
(and (< 0 n) (< n 1)))))
(check
(begin
(random-source-jumpahead! (make-random-source/mersenne) 10)
(let ((make-integer (random-source-integers-maker (make-random-source/mersenne))))
(integer? (make-integer 10))))
=> #t)
(let* ((source (make-random-source/mersenne))
(bytevector-maker (random-source-bytevectors-maker source))
(obj (bytevector-maker 50)))
( write obj)(newline )
(check-for-true (bytevector? obj)))
(check-for-true
(let* ((source (make-random-source/mersenne))
(state (random-source-state-ref source)))
(random-source-state-set! source state)
(let ((make-integer (random-source-integers-maker source)))
(integer? (make-integer 10)))))
)
(parameterise ((check-test-name 'borosh))
(let* ((source (make-random-source/borosh))
(make-integer (random-source-integers-maker source)))
(define (integer) (make-integer 100))
( (= i 100 ) )
(check-for-true (integer? (integer)))
(check-for-true (non-negative? (integer)))
(check-for-true (let ((n (integer)))
(and (<= 0 n) (< n 100)))))
(let* ((source (make-random-source/borosh))
(make-real (random-source-reals-maker source)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/borosh))
(make-real (random-source-reals-maker source 1e-30)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/borosh))
(make-real (random-source-reals-maker source 1e-5)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(check-for-true
(let* ((source-a (make-random-source/borosh))
(source-b (make-random-source/borosh))
(make-integer (random-source-integers-maker source-b)))
(random-source-seed! source-a make-integer)
(let* ((make-real (random-source-reals-maker source-a))
(n (make-real)))
(and (< 0 n) (< n 1)))))
(check
(begin
(random-source-jumpahead! (make-random-source/borosh) 10)
(let ((make-integer (random-source-integers-maker (make-random-source/borosh))))
(integer? (make-integer 10))))
=> #t)
(let* ((source (make-random-source/borosh))
(bytevector-maker (random-source-bytevectors-maker source))
(obj (bytevector-maker 50)))
( write obj)(newline )
(check-for-true (bytevector? obj)))
(check-for-true
(let* ((source (make-random-source/borosh))
(state (random-source-state-ref source)))
(random-source-state-set! source state)
(let ((make-integer (random-source-integers-maker source)))
(integer? (make-integer 10)))))
)
(parameterise ((check-test-name 'cmrg))
(let* ((source (make-random-source/cmrg))
(make-integer (random-source-integers-maker source)))
(define (integer) (make-integer 100))
( (= i 100 ) )
(check-for-true (integer? (integer)))
(check-for-true (non-negative? (integer)))
(check-for-true (let ((n (integer)))
(and (<= 0 n) (< n 100)))))
(let* ((source (make-random-source/cmrg))
(make-real (random-source-reals-maker source)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/cmrg))
(make-real (random-source-reals-maker source 1e-30)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/cmrg))
(make-real (random-source-reals-maker source 1e-5)))
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(check-for-true
(let* ((source-a (make-random-source/cmrg))
(source-b (make-random-source/cmrg))
(make-integer (random-source-integers-maker source-b)))
(random-source-seed! source-a make-integer)
(let* ((make-real (random-source-reals-maker source-a))
(n (make-real)))
(and (< 0 n) (< n 1)))))
(check
(begin
(random-source-jumpahead! (make-random-source/cmrg) 10)
(let ((make-integer (random-source-integers-maker (make-random-source/cmrg))))
(integer? (make-integer 10))))
=> #t)
(let* ((source (make-random-source/cmrg))
(bytevector-maker (random-source-bytevectors-maker source))
(obj (bytevector-maker 50)))
( write obj)(newline )
(check-for-true (bytevector? obj)))
(check-for-true
(let* ((source (make-random-source/cmrg))
(state (random-source-state-ref source)))
(random-source-state-set! source state)
(let ((make-integer (random-source-integers-maker source)))
(integer? (make-integer 10)))))
)
(parameterise ((check-test-name 'blum-blum-shub))
(define (seed-it source)
(random-source-seed! source (let ((ell '(1856429723 162301391051)))
(lambda (U)
(if (null? ell)
(random-integer (bitwise-copy-bit 0 32 1))
(begin0
(car ell)
(set! ell (cdr ell))))))))
(let* ((source (make-random-source/blum-blum-shub))
(make-integer (random-source-integers-maker source)))
(define (integer) (make-integer 100))
(seed-it source)
( (= i 100 ) )
(check-for-true (integer? (integer)))
(check-for-true (non-negative? (integer)))
(check-for-true (let ((n (integer)))
(and (<= 0 n) (< n 100))))
)
(let* ((source (make-random-source/blum-blum-shub))
(make-real (random-source-reals-maker source)))
(seed-it source)
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/blum-blum-shub))
(make-real (random-source-reals-maker source 1e-30)))
(seed-it source)
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (make-random-source/blum-blum-shub))
(make-real (random-source-reals-maker source 1e-5)))
(seed-it source)
(check-for-true (real? (make-real)))
(check-for-true (let ((n (make-real)))
(and (< 0 n) (< n 1)))))
(let* ((source (let ((s (make-random-source/blum-blum-shub)))
(seed-it s)
s))
(bytevector-maker (random-source-bytevectors-maker source))
(obj (bytevector-maker 50)))
( write obj)(newline )
(check-for-true (bytevector? obj)))
(check-for-true
(let* ((source (let ((s (make-random-source/blum-blum-shub)))
(seed-it s)
s))
(state (random-source-state-ref source)))
(random-source-state-set! source state)
(let ((make-integer (random-source-integers-maker source)))
(integer? (make-integer 10)))))
)
(when #f
(display "Example of random lists:\n")
(do ((i 0 (+ 1 i)))
((= i 5))
(write (random-list-unfold-numbers (lambda ()
(random-integer 10))
10))
(newline))
(display "Example of random vectors:\n")
(do ((i 0 (+ 1 i)))
((= i 5))
(write (random-vector-unfold-numbers (lambda ()
(random-integer 10))
10))
(newline))
(display "Example of random strings:\n")
(do ((i 0 (+ 1 i)))
((= i 5))
(write (random-string-unfold-chars (lambda ()
(+ 65 (random-integer 21)))
10))
(newline))
(display "Example of random passwords of printable characters:\n")
(do ((i 0 (+ 1 i)))
((= i 5))
(display (random-string-unfold-chars
(lambda ()
(do ((ch (random-integer 127) (random-integer 127)))
((char-set-contains? char-set:ascii/graphic (integer->char ch))
ch)))
10))
(newline))
(let ((sampler (random-source-integers-maker-from-range default-random-source 0 10)))
(display "integer samples from [0, 10]:\n")
(do ((i 0 (+ 1 i)))
((= i 10))
(write (sampler))(newline)))
(let ((sampler (random-source-integers-maker-from-range default-random-source 0 10 2)))
(display "integer samples from [0, 10], step 2:\n")
(do ((i 0 (+ 1 i)))
((= i 10))
(write (sampler))(newline)))
(let ((sampler (random-source-reals-maker-from-range default-random-source 0 10)))
(display "real samples from (0, 10):\n")
(do ((i 0 (+ 1 i)))
((= i 10))
(write (sampler))(newline)))
(let ((sampler (random-source-reals-maker-from-range default-random-source 0 10 1.2)))
(display "real samples from [0, 10), step 1.2:\n")
(do ((i 0 (+ 1 i)))
((= i 10))
(write (sampler))(newline)))
)
(check-report)
|
e23185d97ea8e7885310c8833aff11a7276150e860a92f1519c31364e3e94162 | AnyChart/export-server | web_handlers_test.clj | (ns export-server.web-handlers-test
(:use [clojure.test]
[export-server.test-utils]))
;====================================================================================
/png
;====================================================================================
(deftest png-handler-test
(let [response ((call-post "/png" {}) :response)]
(testing "Empty params"
(is (= (response :status) 400))
(is (> (.indexOf (response :body) "error") 0))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/png" {:data-type "json" :response-type "base64"}) :response)]
(testing "No data param"
(is (= (response :status) 400))
(is (> (.indexOf (response :body) "error") 0))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/png" {:data correct-svg-string :response-type "base64"}) :response)]
(testing "No dataType param"
(is (= (response :status) 400))
(is (> (.indexOf (response :body) "error") 0))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/png" {:data correct-svg-string :data-type "json"}) :response)]
(testing "No :response-type param"
(is (= (response :status) 400))
(is (> (.indexOf (response :body) "error") 0))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/png" {:data correct-svg-string :data-type "svg" :response-type "base64"}) :response)]
(testing "Success svg --> base64 image request"
(is (= (response :status) 200))
(is (= (response :body) (str "{\"result\":\"" correct-svg-to-base64-png-string "\"}")))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/png" {:data correct-script-string :data-type "script" :response-type "base64"}) :response)]
(testing "Success sctipt --> base64 image request"
(is (= (response :status) 200))
(is (= (response :body) (str "{\"result\":\"" correct-script-to-base64-png-string "\"}")))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/png" {:data correct-svg-string :data-type "svg" :response-type "file"}) :response)]
(testing "Success svg --> file image request"
(is (= (response :status) 200))
(is (instance? java.io.File (response :body)))
(is (= ((response :headers) "Content-Type") "image/png"))
(is (= ((response :headers) "Content-Description") "File Transfer"))
(is (= ((response :headers) "Content-Transfer-Encoding") "binary"))))
(let [response ((call-post "/png" {:data correct-script-string :data-type "script" :response-type "file"}) :response)]
(testing "Success script --> file image request"
(is (= (response :status) 200))
(is (instance? java.io.File (response :body)))
(is (= ((response :headers) "Content-Type") "image/png"))
(is (= ((response :headers) "Content-Description") "File Transfer"))
(is (= ((response :headers) "Content-Transfer-Encoding") "binary"))))
(let [response ((call-post "/png" {:data correct-script-string :dataType "script" :responseType "file"}) :response)]
(testing "Legacy test"
(is (= (response :status) 200))
(is (instance? java.io.File (response :body)))
(is (= ((response :headers) "Content-Type") "image/png"))
(is (= ((response :headers) "Content-Description") "File Transfer"))
(is (= ((response :headers) "Content-Transfer-Encoding") "binary")))))
;====================================================================================
; /jpg
;====================================================================================
(deftest jpg-handler-test
(let [response ((call-post "/jpg" {}) :response)]
(testing "Empty params"
(is (= (response :status) 400))
(is (> (.indexOf (response :body) "error") 0))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/jpg" {:data-type "json" :response-type "base64"}) :response)]
(testing "No data param"
(is (= (response :status) 400))
(is (> (.indexOf (response :body) "error") 0))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/jpg" {:data correct-svg-string :response-type "base64"}) :response)]
(testing "No dataType param"
(is (= (response :status) 400))
(is (> (.indexOf (response :body) "error") 0))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/jpg" {:data correct-svg-string :data-type "json"}) :response)]
(testing "No :response-type param"
(is (= (response :status) 400))
(is (> (.indexOf (response :body) "error") 0))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/jpg" {:data correct-svg-string :data-type "svg" :response-type "base64"}) :response)]
(testing "Success svg --> base64 image request"
(is (= (response :status) 200))
(is (= (response :body) (str "{\"result\":\"" correct-svg-to-base64-jpg-string "\"}")))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/jpg" {:data correct-script-string :data-type "script" :response-type "base64"}) :response)]
(testing "Success sctipt --> base64 image request"
(is (= (response :status) 200))
(is (= (response :body) (str "{\"result\":\"" correct-script-to-base64-jpg-string "\"}")))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/jpg" {:data correct-svg-string :data-type "svg" :response-type "file"}) :response)]
(testing "Success svg --> file image request"
(is (= (response :status) 200))
(is (instance? java.io.File (response :body)))
(is (= ((response :headers) "Content-Type") "image/jpeg"))
(is (= ((response :headers) "Content-Description") "File Transfer"))
(is (= ((response :headers) "Content-Transfer-Encoding") "binary"))))
(let [response ((call-post "/jpg" {:data correct-script-string :data-type "script" :response-type "file"}) :response)]
(testing "Success script --> file image request"
(is (= (response :status) 200))
(is (instance? java.io.File (response :body)))
(is (= ((response :headers) "Content-Type") "image/jpeg"))
(is (= ((response :headers) "Content-Description") "File Transfer"))
(is (= ((response :headers) "Content-Transfer-Encoding") "binary"))))
(let [response ((call-post "/jpg" {:data correct-script-string :dataType "script" :responseType "file"}) :response)]
(testing "Legacy test"
(is (= (response :status) 200))
(is (instance? java.io.File (response :body)))
(is (= ((response :headers) "Content-Type") "image/jpeg"))
(is (= ((response :headers) "Content-Description") "File Transfer"))
(is (= ((response :headers) "Content-Transfer-Encoding") "binary")))))
;====================================================================================
; /pdf
;====================================================================================
(deftest pdf-handler-test
(let [response ((call-post "/pdf" {}) :response)]
(testing "Empty params"
(is (= (response :status) 400))
(is (> (.indexOf (response :body) "error") 0))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/pdf" {:data-type "json" :response-type "base64"}) :response)]
(testing "No data param"
(is (= (response :status) 400))
(is (> (.indexOf (response :body) "error") 0))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/pdf" {:data correct-svg-string :response-type "base64"}) :response)]
(testing "No dataType param"
(is (= (response :status) 400))
(is (> (.indexOf (response :body) "error") 0))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/pdf" {:data correct-svg-string :data-type "json"}) :response)]
(testing "No :response-type param"
(is (= (response :status) 400))
(is (> (.indexOf (response :body) "error") 0))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/pdf" {:data correct-svg-string :data-type "svg" :response-type "base64"}) :response)]
(testing "Success svg --> base64 image request"
(is (= (response :status) 200))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/pdf" {:data correct-script-string :data-type "script" :response-type "base64"}) :response)]
(testing "Success sctipt --> base64 image request"
(is (= (response :status) 200))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/pdf" {:data correct-svg-string :data-type "svg" :response-type "file"}) :response)]
(testing "Success svg --> file image request"
(is (= (response :status) 200))
(is (instance? java.io.File (response :body)))
(is (= ((response :headers) "Content-Type") "application/pdf"))
(is (= ((response :headers) "Content-Description") "File Transfer"))
(is (= ((response :headers) "Content-Transfer-Encoding") "binary"))))
(let [response ((call-post "/pdf" {:data correct-script-string :data-type "script" :response-type "file"}) :response)]
(testing "Success script --> file image request"
(is (= (response :status) 200))
(is (instance? java.io.File (response :body)))
(is (= ((response :headers) "Content-Type") "application/pdf"))
(is (= ((response :headers) "Content-Description") "File Transfer"))
(is (= ((response :headers) "Content-Transfer-Encoding") "binary"))))
(let [response ((call-post "/pdf" {:data correct-script-string :dataType "script" :responseType "file"}) :response)]
(testing "Legacy test"
(is (= (response :status) 200))
(is (instance? java.io.File (response :body)))
(is (= ((response :headers) "Content-Type") "application/pdf"))
(is (= ((response :headers) "Content-Description") "File Transfer"))
(is (= ((response :headers) "Content-Transfer-Encoding") "binary")))))
;====================================================================================
; /svg
;====================================================================================
(deftest svg-handler-test
(let [response ((call-post "/svg" {}) :response)]
(testing "Empty params"
(is (= (response :status) 400))
(is (> (.indexOf (response :body) "error") 0))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/svg" {:data-type "json" :response-type "base64"}) :response)]
(testing "No data param"
(is (= (response :status) 400))
(is (> (.indexOf (response :body) "error") 0))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/svg" {:data correct-svg-string :response-type "base64"}) :response)]
(testing "No dataType param"
(is (= (response :status) 400))
(is (> (.indexOf (response :body) "error") 0))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/svg" {:data correct-svg-string :data-type "json"}) :response)]
(testing "No :response-type param"
(is (= (response :status) 400))
(is (> (.indexOf (response :body) "error") 0))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/svg" {:data correct-svg-string :data-type "svg" :response-type "base64"}) :response)]
(testing "Success svg --> base64 image request"
(is (= (response :status) 200))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/svg" {:data correct-script-string :data-type "script" :response-type "base64"}) :response)]
(testing "Success sctipt --> base64 image request"
(is (= (response :status) 200))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/svg" {:data correct-svg-string :data-type "svg" :response-type "file"}) :response)]
(testing "Success svg --> file image request"
(is (= (response :status) 200))
(is (instance? java.io.File (response :body)))
(is (= ((response :headers) "Content-Type") "image/svg+xml"))
(is (= ((response :headers) "Content-Description") "File Transfer"))
(is (= ((response :headers) "Content-Transfer-Encoding") "binary"))))
(let [response ((call-post "/svg" {:data correct-script-string :data-type "script" :response-type "file"}) :response)]
(testing "Success script --> file image request"
(is (= (response :status) 200))
(is (instance? java.io.File (response :body)))
(is (= ((response :headers) "Content-Type") "image/svg+xml"))
(is (= ((response :headers) "Content-Description") "File Transfer"))
(is (= ((response :headers) "Content-Transfer-Encoding") "binary"))))
(let [response ((call-post "/svg" {:data correct-script-string :dataType "script" :responseType "file"}) :response)]
(testing "Legacy test"
(is (= (response :status) 200))
(is (instance? java.io.File (response :body)))
(is (= ((response :headers) "Content-Type") "image/svg+xml"))
(is (= ((response :headers) "Content-Description") "File Transfer"))
(is (= ((response :headers) "Content-Transfer-Encoding") "binary")))))
;====================================================================================
; /status
;====================================================================================
(deftest status-handler-test
(let [response ((call-post "/status" {}) :response)]
(testing "POST status request"
(is (= (response :status) 200))
(is (= (response :body) "ok"))))
(let [response ((call-get "/status" {}) :response)]
(testing "POST status request"
(is (= (response :status) 200))
(is (= (response :body) "ok")))))
| null | https://raw.githubusercontent.com/AnyChart/export-server/0ef2f084e07aaa144e38dff30e3283f686de1108/test/export_server/web_handlers_test.clj | clojure | ====================================================================================
====================================================================================
====================================================================================
/jpg
====================================================================================
====================================================================================
/pdf
====================================================================================
====================================================================================
/svg
====================================================================================
====================================================================================
/status
==================================================================================== | (ns export-server.web-handlers-test
(:use [clojure.test]
[export-server.test-utils]))
/png
(deftest png-handler-test
(let [response ((call-post "/png" {}) :response)]
(testing "Empty params"
(is (= (response :status) 400))
(is (> (.indexOf (response :body) "error") 0))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/png" {:data-type "json" :response-type "base64"}) :response)]
(testing "No data param"
(is (= (response :status) 400))
(is (> (.indexOf (response :body) "error") 0))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/png" {:data correct-svg-string :response-type "base64"}) :response)]
(testing "No dataType param"
(is (= (response :status) 400))
(is (> (.indexOf (response :body) "error") 0))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/png" {:data correct-svg-string :data-type "json"}) :response)]
(testing "No :response-type param"
(is (= (response :status) 400))
(is (> (.indexOf (response :body) "error") 0))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/png" {:data correct-svg-string :data-type "svg" :response-type "base64"}) :response)]
(testing "Success svg --> base64 image request"
(is (= (response :status) 200))
(is (= (response :body) (str "{\"result\":\"" correct-svg-to-base64-png-string "\"}")))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/png" {:data correct-script-string :data-type "script" :response-type "base64"}) :response)]
(testing "Success sctipt --> base64 image request"
(is (= (response :status) 200))
(is (= (response :body) (str "{\"result\":\"" correct-script-to-base64-png-string "\"}")))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/png" {:data correct-svg-string :data-type "svg" :response-type "file"}) :response)]
(testing "Success svg --> file image request"
(is (= (response :status) 200))
(is (instance? java.io.File (response :body)))
(is (= ((response :headers) "Content-Type") "image/png"))
(is (= ((response :headers) "Content-Description") "File Transfer"))
(is (= ((response :headers) "Content-Transfer-Encoding") "binary"))))
(let [response ((call-post "/png" {:data correct-script-string :data-type "script" :response-type "file"}) :response)]
(testing "Success script --> file image request"
(is (= (response :status) 200))
(is (instance? java.io.File (response :body)))
(is (= ((response :headers) "Content-Type") "image/png"))
(is (= ((response :headers) "Content-Description") "File Transfer"))
(is (= ((response :headers) "Content-Transfer-Encoding") "binary"))))
(let [response ((call-post "/png" {:data correct-script-string :dataType "script" :responseType "file"}) :response)]
(testing "Legacy test"
(is (= (response :status) 200))
(is (instance? java.io.File (response :body)))
(is (= ((response :headers) "Content-Type") "image/png"))
(is (= ((response :headers) "Content-Description") "File Transfer"))
(is (= ((response :headers) "Content-Transfer-Encoding") "binary")))))
(deftest jpg-handler-test
(let [response ((call-post "/jpg" {}) :response)]
(testing "Empty params"
(is (= (response :status) 400))
(is (> (.indexOf (response :body) "error") 0))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/jpg" {:data-type "json" :response-type "base64"}) :response)]
(testing "No data param"
(is (= (response :status) 400))
(is (> (.indexOf (response :body) "error") 0))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/jpg" {:data correct-svg-string :response-type "base64"}) :response)]
(testing "No dataType param"
(is (= (response :status) 400))
(is (> (.indexOf (response :body) "error") 0))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/jpg" {:data correct-svg-string :data-type "json"}) :response)]
(testing "No :response-type param"
(is (= (response :status) 400))
(is (> (.indexOf (response :body) "error") 0))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/jpg" {:data correct-svg-string :data-type "svg" :response-type "base64"}) :response)]
(testing "Success svg --> base64 image request"
(is (= (response :status) 200))
(is (= (response :body) (str "{\"result\":\"" correct-svg-to-base64-jpg-string "\"}")))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/jpg" {:data correct-script-string :data-type "script" :response-type "base64"}) :response)]
(testing "Success sctipt --> base64 image request"
(is (= (response :status) 200))
(is (= (response :body) (str "{\"result\":\"" correct-script-to-base64-jpg-string "\"}")))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/jpg" {:data correct-svg-string :data-type "svg" :response-type "file"}) :response)]
(testing "Success svg --> file image request"
(is (= (response :status) 200))
(is (instance? java.io.File (response :body)))
(is (= ((response :headers) "Content-Type") "image/jpeg"))
(is (= ((response :headers) "Content-Description") "File Transfer"))
(is (= ((response :headers) "Content-Transfer-Encoding") "binary"))))
(let [response ((call-post "/jpg" {:data correct-script-string :data-type "script" :response-type "file"}) :response)]
(testing "Success script --> file image request"
(is (= (response :status) 200))
(is (instance? java.io.File (response :body)))
(is (= ((response :headers) "Content-Type") "image/jpeg"))
(is (= ((response :headers) "Content-Description") "File Transfer"))
(is (= ((response :headers) "Content-Transfer-Encoding") "binary"))))
(let [response ((call-post "/jpg" {:data correct-script-string :dataType "script" :responseType "file"}) :response)]
(testing "Legacy test"
(is (= (response :status) 200))
(is (instance? java.io.File (response :body)))
(is (= ((response :headers) "Content-Type") "image/jpeg"))
(is (= ((response :headers) "Content-Description") "File Transfer"))
(is (= ((response :headers) "Content-Transfer-Encoding") "binary")))))
(deftest pdf-handler-test
(let [response ((call-post "/pdf" {}) :response)]
(testing "Empty params"
(is (= (response :status) 400))
(is (> (.indexOf (response :body) "error") 0))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/pdf" {:data-type "json" :response-type "base64"}) :response)]
(testing "No data param"
(is (= (response :status) 400))
(is (> (.indexOf (response :body) "error") 0))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/pdf" {:data correct-svg-string :response-type "base64"}) :response)]
(testing "No dataType param"
(is (= (response :status) 400))
(is (> (.indexOf (response :body) "error") 0))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/pdf" {:data correct-svg-string :data-type "json"}) :response)]
(testing "No :response-type param"
(is (= (response :status) 400))
(is (> (.indexOf (response :body) "error") 0))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/pdf" {:data correct-svg-string :data-type "svg" :response-type "base64"}) :response)]
(testing "Success svg --> base64 image request"
(is (= (response :status) 200))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/pdf" {:data correct-script-string :data-type "script" :response-type "base64"}) :response)]
(testing "Success sctipt --> base64 image request"
(is (= (response :status) 200))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/pdf" {:data correct-svg-string :data-type "svg" :response-type "file"}) :response)]
(testing "Success svg --> file image request"
(is (= (response :status) 200))
(is (instance? java.io.File (response :body)))
(is (= ((response :headers) "Content-Type") "application/pdf"))
(is (= ((response :headers) "Content-Description") "File Transfer"))
(is (= ((response :headers) "Content-Transfer-Encoding") "binary"))))
(let [response ((call-post "/pdf" {:data correct-script-string :data-type "script" :response-type "file"}) :response)]
(testing "Success script --> file image request"
(is (= (response :status) 200))
(is (instance? java.io.File (response :body)))
(is (= ((response :headers) "Content-Type") "application/pdf"))
(is (= ((response :headers) "Content-Description") "File Transfer"))
(is (= ((response :headers) "Content-Transfer-Encoding") "binary"))))
(let [response ((call-post "/pdf" {:data correct-script-string :dataType "script" :responseType "file"}) :response)]
(testing "Legacy test"
(is (= (response :status) 200))
(is (instance? java.io.File (response :body)))
(is (= ((response :headers) "Content-Type") "application/pdf"))
(is (= ((response :headers) "Content-Description") "File Transfer"))
(is (= ((response :headers) "Content-Transfer-Encoding") "binary")))))
(deftest svg-handler-test
(let [response ((call-post "/svg" {}) :response)]
(testing "Empty params"
(is (= (response :status) 400))
(is (> (.indexOf (response :body) "error") 0))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/svg" {:data-type "json" :response-type "base64"}) :response)]
(testing "No data param"
(is (= (response :status) 400))
(is (> (.indexOf (response :body) "error") 0))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/svg" {:data correct-svg-string :response-type "base64"}) :response)]
(testing "No dataType param"
(is (= (response :status) 400))
(is (> (.indexOf (response :body) "error") 0))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/svg" {:data correct-svg-string :data-type "json"}) :response)]
(testing "No :response-type param"
(is (= (response :status) 400))
(is (> (.indexOf (response :body) "error") 0))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/svg" {:data correct-svg-string :data-type "svg" :response-type "base64"}) :response)]
(testing "Success svg --> base64 image request"
(is (= (response :status) 200))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/svg" {:data correct-script-string :data-type "script" :response-type "base64"}) :response)]
(testing "Success sctipt --> base64 image request"
(is (= (response :status) 200))
(is (= ((response :headers) "Content-Type") "json"))))
(let [response ((call-post "/svg" {:data correct-svg-string :data-type "svg" :response-type "file"}) :response)]
(testing "Success svg --> file image request"
(is (= (response :status) 200))
(is (instance? java.io.File (response :body)))
(is (= ((response :headers) "Content-Type") "image/svg+xml"))
(is (= ((response :headers) "Content-Description") "File Transfer"))
(is (= ((response :headers) "Content-Transfer-Encoding") "binary"))))
(let [response ((call-post "/svg" {:data correct-script-string :data-type "script" :response-type "file"}) :response)]
(testing "Success script --> file image request"
(is (= (response :status) 200))
(is (instance? java.io.File (response :body)))
(is (= ((response :headers) "Content-Type") "image/svg+xml"))
(is (= ((response :headers) "Content-Description") "File Transfer"))
(is (= ((response :headers) "Content-Transfer-Encoding") "binary"))))
(let [response ((call-post "/svg" {:data correct-script-string :dataType "script" :responseType "file"}) :response)]
(testing "Legacy test"
(is (= (response :status) 200))
(is (instance? java.io.File (response :body)))
(is (= ((response :headers) "Content-Type") "image/svg+xml"))
(is (= ((response :headers) "Content-Description") "File Transfer"))
(is (= ((response :headers) "Content-Transfer-Encoding") "binary")))))
(deftest status-handler-test
(let [response ((call-post "/status" {}) :response)]
(testing "POST status request"
(is (= (response :status) 200))
(is (= (response :body) "ok"))))
(let [response ((call-get "/status" {}) :response)]
(testing "POST status request"
(is (= (response :status) 200))
(is (= (response :body) "ok")))))
|
d52e3a5fbd132bac3336747381a105787147a5fda25d5c871f270ff7c4ed0387 | falgon/htcc | Generate.hs | |
Module : Htcc . Asm . Generate
Description : The modules of intrinsic ( x86_64 ) assembly
Copyright : ( c ) roki , 2019
License : MIT
Maintainer :
Stability : experimental
Portability : POSIX
The executable module for compilation
Module : Htcc.Asm.Generate
Description : The modules of intrinsic (x86_64) assembly
Copyright : (c) roki, 2019
License : MIT
Maintainer :
Stability : experimental
Portability : POSIX
The executable module for compilation
-}
{-# LANGUAGE OverloadedStrings #-}
module Htcc.Asm.Generate (
InputCCode,
-- * Generator
casm',
buildAST,
execAST
) where
import Control.Monad (unless, (>=>))
import Data.Bits (Bits)
import Data.Foldable (toList)
import qualified Data.Sequence as S
import qualified Data.Text as T
import System.Exit (exitFailure)
import Text.PrettyPrint.ANSI.Leijen (Doc, blue,
bold, char,
empty,
magenta, red,
text, (<+>))
import Htcc.Parser (ASTResult,
ASTs, parse)
import Htcc.Parser.ConstructionData.Scope.ManagedScope (ASTError)
import Htcc.Parser.ConstructionData.Scope.Var (GlobalVars,
Literals)
import qualified Htcc.Tokenizer as HT
import Htcc.Asm.Generate.Core
import Htcc.Asm.Intrinsic.Operand
import qualified Htcc.Asm.Intrinsic.Structure as SI
import qualified Htcc.Asm.Intrinsic.Structure.Section.Text as IT
import Htcc.Utils (dropFst4,
putDocErr,
putDocLnErr,
putStrErr,
putStrLnErr,
toInts, tshow)
-- | input string, C source code
type InputCCode = T.Text
data MessageType = ErrorMessage | WarningMessage
deriving (Eq, Ord, Enum, Bounded)
instance Show MessageType where
show ErrorMessage = "error"
show WarningMessage = "warning"
# INLINE messageColor #
messageColor :: MessageType -> Doc -> Doc
messageColor ErrorMessage = red
messageColor WarningMessage = magenta
# INLINE repSpace #
repSpace :: Integral i => i -> MessageType -> IO ()
repSpace i mest = do
mapM_ (putStrErr . T.pack . flip replicate ' ' . pred) $ toInts i
putDocErr $ messageColor mest $ char '^'
# INLINE format #
format :: T.Text -> Int -> InputCCode -> IO ()
format errMesPre e xs = do
putDocErr $ blue (text $ T.unpack errMesPre) <+> blue (char '|') <+> empty
putStrLnErr (T.lines xs !! max 0 (fromIntegral e))
putStrErr $ T.replicate (T.length errMesPre) " "
putDocErr $ empty <+> blue (char '|') <+> empty
parsedMessage :: (Integral i, Show i) => MessageType -> FilePath -> InputCCode -> ASTError i -> IO ()
parsedMessage mest fpath xs (s, (i, etk)) = do
putDocLnErr $
bold (text fpath) <> bold (char ':') <>
bold (text (show i)) <> bold (char ':') <+>
messageColor mest (text $ show mest) <> messageColor mest (char ':') <+>
text (T.unpack s)
format (T.replicate 4 " " <> tshow (HT.tkLn i)) (pred $ fromIntegral $ HT.tkLn i) xs
repSpace (HT.tkCn i) mest
putDocLnErr $ messageColor mest (text $ replicate (pred $ HT.length etk) '~')
-- | the function to output error message
parsedErrExit :: (Integral i, Show i) => FilePath -> InputCCode -> ASTError i -> IO ()
parsedErrExit fpath ccode err = parsedMessage ErrorMessage fpath ccode err >> exitFailure
-- | the function to output warning message
parsedWarn :: (Integral i, Show i) => FilePath -> InputCCode -> S.Seq (ASTError i) -> IO ()
parsedWarn fpath xs warns = mapM_ (parsedMessage WarningMessage fpath xs) (toList warns)
| Executor that receives information about the constructed AST ,
-- global variables, and literals and composes assembly code
casm' :: (Integral e, Show e, Integral i, IsOperand i, IT.UnaryInstruction i, IT.BinaryInstruction i) => ASTs i -> GlobalVars i -> Literals i -> SI.Asm SI.AsmCodeCtx e ()
casm' atl gvars lits = dataSection gvars lits >> textSection atl
-- | Build AST from string of C source code
buildAST :: (Integral i, Read i, Show i, Bits i) => InputCCode -> ASTResult i
buildAST = HT.tokenize >=> parse
| Print warning or error message if building AST from string of C source code has some problems
execAST :: (Integral i, Read i, Show i, Bits i) => Bool -> FilePath -> InputCCode -> IO (Maybe (ASTs i, GlobalVars i, Literals i))
execAST supWarns fpath ccode = flip (either ((<$) Nothing . parsedErrExit fpath ccode)) (buildAST ccode) $ \xs@(warns, _, _, _) ->
Just (dropFst4 xs) <$ unless supWarns (parsedWarn fpath ccode warns)
| null | https://raw.githubusercontent.com/falgon/htcc/3cef6fc362b00d4bc0ae261cba567bfd9c69b3c5/src/Htcc/Asm/Generate.hs | haskell | # LANGUAGE OverloadedStrings #
* Generator
| input string, C source code
| the function to output error message
| the function to output warning message
global variables, and literals and composes assembly code
| Build AST from string of C source code | |
Module : Htcc . Asm . Generate
Description : The modules of intrinsic ( x86_64 ) assembly
Copyright : ( c ) roki , 2019
License : MIT
Maintainer :
Stability : experimental
Portability : POSIX
The executable module for compilation
Module : Htcc.Asm.Generate
Description : The modules of intrinsic (x86_64) assembly
Copyright : (c) roki, 2019
License : MIT
Maintainer :
Stability : experimental
Portability : POSIX
The executable module for compilation
-}
module Htcc.Asm.Generate (
InputCCode,
casm',
buildAST,
execAST
) where
import Control.Monad (unless, (>=>))
import Data.Bits (Bits)
import Data.Foldable (toList)
import qualified Data.Sequence as S
import qualified Data.Text as T
import System.Exit (exitFailure)
import Text.PrettyPrint.ANSI.Leijen (Doc, blue,
bold, char,
empty,
magenta, red,
text, (<+>))
import Htcc.Parser (ASTResult,
ASTs, parse)
import Htcc.Parser.ConstructionData.Scope.ManagedScope (ASTError)
import Htcc.Parser.ConstructionData.Scope.Var (GlobalVars,
Literals)
import qualified Htcc.Tokenizer as HT
import Htcc.Asm.Generate.Core
import Htcc.Asm.Intrinsic.Operand
import qualified Htcc.Asm.Intrinsic.Structure as SI
import qualified Htcc.Asm.Intrinsic.Structure.Section.Text as IT
import Htcc.Utils (dropFst4,
putDocErr,
putDocLnErr,
putStrErr,
putStrLnErr,
toInts, tshow)
type InputCCode = T.Text
data MessageType = ErrorMessage | WarningMessage
deriving (Eq, Ord, Enum, Bounded)
instance Show MessageType where
show ErrorMessage = "error"
show WarningMessage = "warning"
# INLINE messageColor #
messageColor :: MessageType -> Doc -> Doc
messageColor ErrorMessage = red
messageColor WarningMessage = magenta
# INLINE repSpace #
repSpace :: Integral i => i -> MessageType -> IO ()
repSpace i mest = do
mapM_ (putStrErr . T.pack . flip replicate ' ' . pred) $ toInts i
putDocErr $ messageColor mest $ char '^'
# INLINE format #
format :: T.Text -> Int -> InputCCode -> IO ()
format errMesPre e xs = do
putDocErr $ blue (text $ T.unpack errMesPre) <+> blue (char '|') <+> empty
putStrLnErr (T.lines xs !! max 0 (fromIntegral e))
putStrErr $ T.replicate (T.length errMesPre) " "
putDocErr $ empty <+> blue (char '|') <+> empty
parsedMessage :: (Integral i, Show i) => MessageType -> FilePath -> InputCCode -> ASTError i -> IO ()
parsedMessage mest fpath xs (s, (i, etk)) = do
putDocLnErr $
bold (text fpath) <> bold (char ':') <>
bold (text (show i)) <> bold (char ':') <+>
messageColor mest (text $ show mest) <> messageColor mest (char ':') <+>
text (T.unpack s)
format (T.replicate 4 " " <> tshow (HT.tkLn i)) (pred $ fromIntegral $ HT.tkLn i) xs
repSpace (HT.tkCn i) mest
putDocLnErr $ messageColor mest (text $ replicate (pred $ HT.length etk) '~')
parsedErrExit :: (Integral i, Show i) => FilePath -> InputCCode -> ASTError i -> IO ()
parsedErrExit fpath ccode err = parsedMessage ErrorMessage fpath ccode err >> exitFailure
parsedWarn :: (Integral i, Show i) => FilePath -> InputCCode -> S.Seq (ASTError i) -> IO ()
parsedWarn fpath xs warns = mapM_ (parsedMessage WarningMessage fpath xs) (toList warns)
| Executor that receives information about the constructed AST ,
casm' :: (Integral e, Show e, Integral i, IsOperand i, IT.UnaryInstruction i, IT.BinaryInstruction i) => ASTs i -> GlobalVars i -> Literals i -> SI.Asm SI.AsmCodeCtx e ()
casm' atl gvars lits = dataSection gvars lits >> textSection atl
buildAST :: (Integral i, Read i, Show i, Bits i) => InputCCode -> ASTResult i
buildAST = HT.tokenize >=> parse
| Print warning or error message if building AST from string of C source code has some problems
execAST :: (Integral i, Read i, Show i, Bits i) => Bool -> FilePath -> InputCCode -> IO (Maybe (ASTs i, GlobalVars i, Literals i))
execAST supWarns fpath ccode = flip (either ((<$) Nothing . parsedErrExit fpath ccode)) (buildAST ccode) $ \xs@(warns, _, _, _) ->
Just (dropFst4 xs) <$ unless supWarns (parsedWarn fpath ccode warns)
|
e75901a94e37895fb909438f91a57fd551009994719c5c15f5d0d9d92fdbd0c3 | ermine-language/ermine | Syntax.hs | # OPTIONS_GHC -fno - warn - missing - signatures #
# LANGUAGE TemplateHaskell #
module Syntax where
import Ermine.Syntax.Kind as Kind
import Ermine.Syntax.Type as Type
import Ermine.Syntax.Term as Term
import Test.QuickCheck
import Test.QuickCheck.Function
import Test.QuickCheck.Instances
import Test.Framework.TH
import Test.Framework.Providers.QuickCheck2
import Arbitrary.Arbitrary
import Arbitrary.SyntaxArbitrary
eq_reflexive :: Eq a => a -> Bool
eq_reflexive x = x == x
prop_kind_eq_reflexive :: Kind Int -> Bool
prop_kind_eq_reflexive = eq_reflexive
prop_type_eq_reflexive :: Type Int Int -> Bool
prop_type_eq_reflexive = eq_reflexive
prop_term_eq_reflexive :: Term Int Int -> Bool
prop_term_eq_reflexive = eq_reflexive
tests = $testGroupGenerator
| null | https://raw.githubusercontent.com/ermine-language/ermine/bd58949ab56311be9e0d2506a900f3d77652566b/tests/properties/Syntax.hs | haskell | # OPTIONS_GHC -fno - warn - missing - signatures #
# LANGUAGE TemplateHaskell #
module Syntax where
import Ermine.Syntax.Kind as Kind
import Ermine.Syntax.Type as Type
import Ermine.Syntax.Term as Term
import Test.QuickCheck
import Test.QuickCheck.Function
import Test.QuickCheck.Instances
import Test.Framework.TH
import Test.Framework.Providers.QuickCheck2
import Arbitrary.Arbitrary
import Arbitrary.SyntaxArbitrary
eq_reflexive :: Eq a => a -> Bool
eq_reflexive x = x == x
prop_kind_eq_reflexive :: Kind Int -> Bool
prop_kind_eq_reflexive = eq_reflexive
prop_type_eq_reflexive :: Type Int Int -> Bool
prop_type_eq_reflexive = eq_reflexive
prop_term_eq_reflexive :: Term Int Int -> Bool
prop_term_eq_reflexive = eq_reflexive
tests = $testGroupGenerator
|
|
5735f277c27f0f8fb646741ff9d873c71052764d7dc2be74136b59e84ff063c1 | niquola/reframe-template | layout.cljs | (ns ui.layout
(:require-macros [reagent.ratom :refer [reaction]])
(:require
[reagent.core :as reagent]
[ui.styles :as styles]
[re-frame.core :as rf]
[ui.routes :refer [href]]
[ui.styles :as styles]
[ui.widgets :as wgt]
[clojure.string :as str]))
(rf/reg-sub-raw
:auth
(fn [db _] (reaction (:auth @db))))
(defn current-page? [route key]
(= (:match route) key))
(defn nav-item [route k path title]
[:li.nav-item {:class (when (current-page? @route k) "active")}
[:a.nav-link {:href (apply href path)} title]])
(defn menu []
(let [auth (rf/subscribe [:auth])
route (rf/subscribe [:route-map/current-route])]
(fn []
[:nav.navbar.navbar-toggleable-md.navbar-light.bg-faded
(styles/style [:nav.navbar {:border-bottom "1px solid #ddd"
:padding-bottom 0}
[:li.nav-item {:border-bottom "3px solid transparent"}
[:&.active {:border-color "#555"}]]
[:.avatar {:width "20px"
:height "20px"
:margin "0 5px"
:border-radius "50%"}]])
[:div.container
[:a.navbar-brand {:href "#/"} "MyEHR"]
[:div.collapse.navbar-collapse
[:ul.nav.navbar-nav.mr-auto
[nav-item route :patients/index [:patients] "Patients"]
[nav-item route :patients/new [:patients :new] "New Patient"]]
[:ul.nav.navbar-nav.my-2.my-lg-0
[nav-item route :core/notifications [:notifications] (wgt/icon :bell)]
[nav-item route :database/index [:db] (wgt/icon :database)]
[nav-item route :profile/index [:profile]
[:span
(if-let [pic (:picture @auth)] [:img.avatar {:src pic}] "(*_*)")
(when-let [a @auth] (or (:nickname a) (:email a)))]]]]]])))
(defn human-name [n]
(str/join " "
(concat
(or (:given (first n)) [])
(or (:family (first n)) []))))
(defn badge [pt]
[:div.badge
[styles/style
[:.badge
{:text-align "center"}
[:.inform {:text-align "center" :font-size "18px"}]
[:.avatar {:text-align "center"}
[:i {:font-size "80px" :color "gray"}]]]]
[:div.avatar [wgt/icon :user-circle]]
[:br]
[:div.inform
[:a.nav-link {:href (href :patients (:id pt))}
(human-name (:name pt))]]])
(defn layout [content]
(let [current-pt (rf/subscribe [:patients/current-patient])
breadcrumbs (rf/subscribe [:route-map/breadcrumbs]) ]
(fn []
[:div.app
[:style styles/basic-style]
[styles/style [:.secondary-nav {:border-left "1px solid #ddd"}]]
[styles/style [:.breadcrumb {:background "transparent"}]]
[menu]
[:div.container
[:ol.breadcrumb
(for [b @breadcrumbs]
[:li.breadcrumb-item
[:a {:href (str "#" (:uri b))} (:breadcrumb b)]])] ]
(if-let [pt @current-pt]
[:div.container
[:div.row
[:div.col-md-9 content]
[:div.col-md-3.secondary-nav
[badge pt]
[:hr]
[:ul.nav.flex-column
[:li.nav-item
[:a.nav-link {:href (href :patients (:id pt) :edit)}
(wgt/icon :user)
" Demographics"]]
[:li.nav-item
[:a.nav-link {:href (href :patients (:id pt) :coverages)}
(wgt/icon :usd)
" Insurances"]]
[:li.nav-item
[:a.nav-link {:href (href :patients (:id pt) :coverages)}
(wgt/icon :ambulance)
" Encounters"]]
[:li.nav-item
[:a.nav-link {:href (href :patients (:id pt) :coverages)}
(wgt/icon :ambulance)
" Allergies"]]
]]]]
[:div.container content])])))
| null | https://raw.githubusercontent.com/niquola/reframe-template/6482afabc1967d2b6cb39ddc3fc0158075535700/srcs/ui/layout.cljs | clojure | (ns ui.layout
(:require-macros [reagent.ratom :refer [reaction]])
(:require
[reagent.core :as reagent]
[ui.styles :as styles]
[re-frame.core :as rf]
[ui.routes :refer [href]]
[ui.styles :as styles]
[ui.widgets :as wgt]
[clojure.string :as str]))
(rf/reg-sub-raw
:auth
(fn [db _] (reaction (:auth @db))))
(defn current-page? [route key]
(= (:match route) key))
(defn nav-item [route k path title]
[:li.nav-item {:class (when (current-page? @route k) "active")}
[:a.nav-link {:href (apply href path)} title]])
(defn menu []
(let [auth (rf/subscribe [:auth])
route (rf/subscribe [:route-map/current-route])]
(fn []
[:nav.navbar.navbar-toggleable-md.navbar-light.bg-faded
(styles/style [:nav.navbar {:border-bottom "1px solid #ddd"
:padding-bottom 0}
[:li.nav-item {:border-bottom "3px solid transparent"}
[:&.active {:border-color "#555"}]]
[:.avatar {:width "20px"
:height "20px"
:margin "0 5px"
:border-radius "50%"}]])
[:div.container
[:a.navbar-brand {:href "#/"} "MyEHR"]
[:div.collapse.navbar-collapse
[:ul.nav.navbar-nav.mr-auto
[nav-item route :patients/index [:patients] "Patients"]
[nav-item route :patients/new [:patients :new] "New Patient"]]
[:ul.nav.navbar-nav.my-2.my-lg-0
[nav-item route :core/notifications [:notifications] (wgt/icon :bell)]
[nav-item route :database/index [:db] (wgt/icon :database)]
[nav-item route :profile/index [:profile]
[:span
(if-let [pic (:picture @auth)] [:img.avatar {:src pic}] "(*_*)")
(when-let [a @auth] (or (:nickname a) (:email a)))]]]]]])))
(defn human-name [n]
(str/join " "
(concat
(or (:given (first n)) [])
(or (:family (first n)) []))))
(defn badge [pt]
[:div.badge
[styles/style
[:.badge
{:text-align "center"}
[:.inform {:text-align "center" :font-size "18px"}]
[:.avatar {:text-align "center"}
[:i {:font-size "80px" :color "gray"}]]]]
[:div.avatar [wgt/icon :user-circle]]
[:br]
[:div.inform
[:a.nav-link {:href (href :patients (:id pt))}
(human-name (:name pt))]]])
(defn layout [content]
(let [current-pt (rf/subscribe [:patients/current-patient])
breadcrumbs (rf/subscribe [:route-map/breadcrumbs]) ]
(fn []
[:div.app
[:style styles/basic-style]
[styles/style [:.secondary-nav {:border-left "1px solid #ddd"}]]
[styles/style [:.breadcrumb {:background "transparent"}]]
[menu]
[:div.container
[:ol.breadcrumb
(for [b @breadcrumbs]
[:li.breadcrumb-item
[:a {:href (str "#" (:uri b))} (:breadcrumb b)]])] ]
(if-let [pt @current-pt]
[:div.container
[:div.row
[:div.col-md-9 content]
[:div.col-md-3.secondary-nav
[badge pt]
[:hr]
[:ul.nav.flex-column
[:li.nav-item
[:a.nav-link {:href (href :patients (:id pt) :edit)}
(wgt/icon :user)
" Demographics"]]
[:li.nav-item
[:a.nav-link {:href (href :patients (:id pt) :coverages)}
(wgt/icon :usd)
" Insurances"]]
[:li.nav-item
[:a.nav-link {:href (href :patients (:id pt) :coverages)}
(wgt/icon :ambulance)
" Encounters"]]
[:li.nav-item
[:a.nav-link {:href (href :patients (:id pt) :coverages)}
(wgt/icon :ambulance)
" Allergies"]]
]]]]
[:div.container content])])))
|
|
e5c4603c0a05ed0127cbd6a2d30ff75f734a5093f0b2d1ac420bc689291f119b | gregtatcam/imaplet-lwt | test_lightparse.ml | open Lwt
open Sexplib
open Imaplet
open Commands
open Lightparsemail
let pr message ent msg =
let len = ent.size in
let offset = ent.offset in
let prfx = if len > 50 then String.sub message offset 50 else
String.sub message offset len in
let pstfx = if len > 100 then String.sub message (offset+len - 50) 50 else "" in
Printf.printf " %s: %d %s...%s\n%!" msg ent.size prfx pstfx
let rec walk message (email:lightmail) =
pr message email.headers.position "Headers";
match email.body.content with
| `Data -> pr message email.body.position "Data"
| `Message m -> pr message email.body.position "Message"; walk message m
| `Multipart l -> pr message email.body.position "Multipart";
List.iteri (fun cnt (email:lightmail) ->
pr message email.position (Printf.sprintf "Part %d" cnt);
walk message email
) l
let () =
Lwt_main.run (
Utils.fold_email_with_file Sys.argv.(1) (fun cnt message ->
Printf.fprintf stderr "%d\r%!" cnt;
Message.parse message >>= fun light ->
Printf.printf "--> start\n%!";
Printf.printf "Full message %d\n%!" light.message_.position.size;
pr message light.message_.postmark "Postmark";
pr message light.message_.email.position "Email";
walk message light.message_.email;
Printf.printf "<-- end\n%!";
return (`Ok (cnt+1))
) 1 >>= fun _ ->
return ()
)
| null | https://raw.githubusercontent.com/gregtatcam/imaplet-lwt/d7b51253e79cffa97e98ab899ed833cd7cb44bb6/test/test_lightparse.ml | ocaml | open Lwt
open Sexplib
open Imaplet
open Commands
open Lightparsemail
let pr message ent msg =
let len = ent.size in
let offset = ent.offset in
let prfx = if len > 50 then String.sub message offset 50 else
String.sub message offset len in
let pstfx = if len > 100 then String.sub message (offset+len - 50) 50 else "" in
Printf.printf " %s: %d %s...%s\n%!" msg ent.size prfx pstfx
let rec walk message (email:lightmail) =
pr message email.headers.position "Headers";
match email.body.content with
| `Data -> pr message email.body.position "Data"
| `Message m -> pr message email.body.position "Message"; walk message m
| `Multipart l -> pr message email.body.position "Multipart";
List.iteri (fun cnt (email:lightmail) ->
pr message email.position (Printf.sprintf "Part %d" cnt);
walk message email
) l
let () =
Lwt_main.run (
Utils.fold_email_with_file Sys.argv.(1) (fun cnt message ->
Printf.fprintf stderr "%d\r%!" cnt;
Message.parse message >>= fun light ->
Printf.printf "--> start\n%!";
Printf.printf "Full message %d\n%!" light.message_.position.size;
pr message light.message_.postmark "Postmark";
pr message light.message_.email.position "Email";
walk message light.message_.email;
Printf.printf "<-- end\n%!";
return (`Ok (cnt+1))
) 1 >>= fun _ ->
return ()
)
|
|
b80ff1515af5e85bd011d9bb60218f5dd0f7122a554e18faddd58730bfe90e71 | simonjbeaumont/ocaml-pci | ffi_bindings.ml | open Ctypes
module Types (F: Cstubs.Types.TYPE) = struct
module Lookup_mode = struct
let lookup_vendor = F.constant "PCI_LOOKUP_VENDOR" F.int
let lookup_device = F.constant "PCI_LOOKUP_DEVICE" F.int
let lookup_class = F.constant "PCI_LOOKUP_CLASS" F.int
let lookup_subsystem = F.constant "PCI_LOOKUP_SUBSYSTEM" F.int
let lookup_progif = F.constant "PCI_LOOKUP_PROGIF" F.int
let lookup_numeric = F.constant "PCI_LOOKUP_NUMERIC" F.int
let lookup_no_numbers = F.constant "PCI_LOOKUP_NO_NUMBERS" F.int
let lookup_mixed = F.constant "PCI_LOOKUP_MIXED" F.int
let lookup_network = F.constant "PCI_LOOKUP_NETWORK" F.int
let lookup_skip_local = F.constant "PCI_LOOKUP_SKIP_LOCAL" F.int
let lookup_cache = F.constant "PCI_LOOKUP_CACHE" F.int
let lookup_refresh_cache = F.constant "PCI_LOOKUP_REFRESH_CACHE" F.int
end
module Fill_flag = struct
let fill_ident = F.constant "PCI_FILL_IDENT" F.int
let fill_irq = F.constant "PCI_FILL_IRQ" F.int
let fill_bases = F.constant "PCI_FILL_BASES" F.int
let fill_rom_base = F.constant "PCI_FILL_ROM_BASE" F.int
let fill_sizes = F.constant "PCI_FILL_SIZES" F.int
let fill_class = F.constant "PCI_FILL_CLASS" F.int
let fill_caps = F.constant "PCI_FILL_CAPS" F.int
let fill_ext_caps = F.constant "PCI_FILL_EXT_CAPS" F.int
let fill_phys_slot = F.constant "PCI_FILL_PHYS_SLOT" F.int
let fill_module_alias = F.constant "PCI_FILL_MODULE_ALIAS" F.int
let fill_rescan = F.constant "PCI_FILL_RESCAN" F.int
end
module Pci_class = struct
let class_not_defined = F.constant "PCI_CLASS_NOT_DEFINED" F.int
let base_class_storage = F.constant "PCI_BASE_CLASS_STORAGE" F.int
let base_class_network = F.constant "PCI_BASE_CLASS_NETWORK" F.int
let base_class_display = F.constant "PCI_BASE_CLASS_DISPLAY" F.int
let base_class_multimedia = F.constant "PCI_BASE_CLASS_MULTIMEDIA" F.int
let base_class_memory = F.constant "PCI_BASE_CLASS_MEMORY" F.int
let base_class_bridge = F.constant "PCI_BASE_CLASS_BRIDGE" F.int
let base_class_communication = F.constant "PCI_BASE_CLASS_COMMUNICATION" F.int
let base_class_system = F.constant "PCI_BASE_CLASS_SYSTEM" F.int
let base_class_input = F.constant "PCI_BASE_CLASS_INPUT" F.int
let base_class_docking = F.constant "PCI_BASE_CLASS_DOCKING" F.int
let base_class_processor = F.constant "PCI_BASE_CLASS_PROCESSOR" F.int
let base_class_serial = F.constant "PCI_BASE_CLASS_SERIAL" F.int
let base_class_wireless = F.constant "PCI_BASE_CLASS_WIRELESS" F.int
let base_class_intelligent = F.constant "PCI_BASE_CLASS_INTELLIGENT" F.int
let base_class_satellite = F.constant "PCI_BASE_CLASS_SATELLITE" F.int
let base_class_crypt = F.constant "PCI_BASE_CLASS_CRYPT" F.int
let base_class_signal = F.constant "PCI_BASE_CLASS_SIGNAL" F.int
let class_others = F.constant "PCI_CLASS_OTHERS" F.int
end
module Header = struct
A subset of the PCI configuration address space ( see pci / header.h )
let header_type = F.constant "PCI_HEADER_TYPE" F.int
let header_type_normal = F.constant "PCI_HEADER_TYPE_NORMAL" F.int
let subsystem_vendor_id = F.constant "PCI_SUBSYSTEM_VENDOR_ID" F.int
let subsystem_id = F.constant "PCI_SUBSYSTEM_ID" F.int
let header_type_cardbus = F.constant "PCI_HEADER_TYPE_CARDBUS" F.int
let cb_subsystem_vendor_id = F.constant "PCI_CB_SUBSYSTEM_VENDOR_ID" F.int
let cb_subsystem_id = F.constant "PCI_CB_SUBSYSTEM_ID" F.int
end
module Access_type = struct
(* Just a subset of the access types we'll need internally *)
let auto = F.constant "PCI_ACCESS_AUTO" F.uint
let dump = F.constant "PCI_ACCESS_DUMP" F.uint
end
end
module Bindings (F : Cstubs.FOREIGN) = struct
open F
module Pci_cap = struct
type pci_cap
let pci_cap : pci_cap structure typ = structure "pci_cap"
let (-:) ty label = field pci_cap label ty
let next = (ptr_opt pci_cap) -: "next"
let id = uint16_t -: "id"
let type_ = uint16_t -: "type"
let addr = int -: "addr"
let () = seal pci_cap
type t = pci_cap structure ptr
let t = ptr pci_cap
end
module Pci_dev = struct
type pci_dev
let pci_dev : pci_dev structure typ = structure "pci_dev"
let (-:) ty label = field pci_dev label ty
let next = (ptr_opt pci_dev) -: "next"
let domain = uint16_t -: "domain"
let bus = uint8_t -: "bus"
let dev = uint8_t -: "dev"
let func = uint8_t -: "func"
let known_fields = int -: "known_fields"
let vendor_id = uint16_t -: "vendor_id"
let device_id = uint16_t -: "device_id"
let device_class = uint16_t -: "device_class"
let irq = int -: "irq"
TODO : this is derived at compile time in pci / types.h ...
let base_addr = (array 6 pciaddr_t) -: "base_addr"
let size = (array 6 pciaddr_t) -: "size"
let rom_base_addr = pciaddr_t -: "rom_base_addr"
let rom_size = pciaddr_t -: "rom_size"
let first_cap = Pci_cap.t -: "first_cap"
let phy_slot = string_opt -: "phy_slot"
let module_alias = string_opt -: "module_alias"
Fields used internally
let access = (ptr void) -: "access"
let methods = (ptr void) -: "methods"
let cache = (ptr uint8_t) -: "cache"
let cache_len = int -: "cache_len"
let hdrtype = int -: "hdrtype"
let aux = (ptr void) -: "aux"
let () = seal pci_dev
type t = pci_dev structure ptr
let t = ptr pci_dev
end
module Pci_param = struct
type pci_param
let pci_param : pci_param structure typ = structure "pci_param"
let (-:) ty label = field pci_param label ty
let next = ptr_opt pci_param -: "next"
let param = string -: "param"
let value = string -: "value"
let value_malloced = int -: "value_malloced"
let help = string -: "help"
let () = seal pci_param
type t = pci_param structure ptr
let t = ptr pci_param
end
module Pci_filter = struct
type pci_filter
let pci_filter : pci_filter structure typ = structure "pci_filter"
let (-:) ty label = field pci_filter label ty
let domain = int -: "domain"
let bus = int -: "bus"
let slot = int -: "slot"
let func = int -: "func"
let vendor = int -: "vendor"
let device = int -: "device"
let () = seal pci_filter
type t = pci_filter structure ptr
let t = ptr pci_filter
end
module Pci_access = struct
open Pci_dev
type pci_access
let pci_access : pci_access structure typ = structure "pci_access"
let (-:) ty label = field pci_access label ty
let method_ = uint -: "method"
let writeable = int -: "writeable"
let buscentric = int -: "buscentric"
let id_file_name = string -: "id_file_name"
let free_id_name = int -: "free_id_name"
let numeric_ids = int -: "numeric_ids"
let lookup_mode = uint -: "lookup_mode"
let debugging = int -: "debugging"
let error = (ptr void) -: "error"
let warning = (ptr void) -: "warning"
let debug = (ptr void) -: "debug"
let devices = field pci_access "devices" (ptr_opt pci_dev)
Fields used internally
let methods = (ptr void) -: "methods"
let params = (ptr void) -: "params"
let id_hash = (ptr (ptr void)) -: "id_hash"
let current_id_bucket = (ptr void) -: "current_id_bucket"
let id_load_failed = int -: "id_load_failed"
let id_cache_status = int -: "id_cache_status"
let fd = int -: "fd"
let fd_rw = int -: "fd_rw"
let fd_pos = int -: "fd_pos"
let fd_vpd = int -: "fd_vpd"
let cached_dev = (ptr_opt pci_dev) -: "cached_dev"
let () = seal pci_access
type t = pci_access structure ptr
let t = ptr pci_access
end
let pci_alloc =
foreign "pci_alloc" (void @-> returning Pci_access.t)
let pci_init =
foreign "pci_init" (Pci_access.t @-> returning void)
let pci_cleanup =
foreign "pci_cleanup" (Pci_access.t @-> returning void)
let pci_scan_bus =
foreign "pci_scan_bus" (Pci_access.t @-> returning void)
let pci_get_dev =
foreign "pci_get_dev" (Pci_access.t @-> int @-> int @-> int @-> int @-> returning Pci_dev.t)
let pci_free_dev =
foreign "pci_free_dev" (Pci_dev.t @-> returning void)
let pci_lookup_method =
foreign "pci_lookup_method" (string @-> returning int)
let pci_get_method_name =
foreign "pci_get_method_name" (int @-> returning string)
let pci_get_param =
foreign "pci_get_param" (Pci_access.t @-> string @-> returning string)
let pci_set_param =
foreign "pci_set_param" (Pci_access.t @-> string @-> string @-> returning int)
let pci_walk_params =
foreign "pci_walk_params" (Pci_access.t @-> Pci_param.t @-> returning Pci_param.t)
let pci_read_byte =
foreign "pci_read_byte" (Pci_dev.t @-> int @-> returning uint8_t)
let pci_read_word =
foreign "pci_read_word" (Pci_dev.t @-> int @-> returning uint16_t)
let pci_read_long =
foreign "pci_read_long" (Pci_dev.t @-> int @-> returning uint32_t)
let pci_read_block =
foreign "pci_read_block" (Pci_dev.t @-> int @-> ptr uint8_t @-> int @-> returning int)
let pci_read_vpd =
foreign "pci_read_vpd" (Pci_dev.t @-> int @-> ptr uint8_t @-> int @-> returning int)
let pci_write_byte =
foreign "pci_write_byte" (Pci_dev.t @-> int @-> uint8_t @-> returning int)
let pci_write_long =
foreign "pci_write_long" (Pci_dev.t @-> int @-> uint16_t @-> returning int)
let pci_write_block =
foreign "pci_write_block" (Pci_dev.t @-> int @-> ptr uint8_t @-> int @-> returning int)
let pci_fill_info =
foreign "pci_fill_info" (Pci_dev.t @-> int @-> returning int)
let pci_setup_cache =
foreign "pci_setup_cache" (Pci_dev.t @-> ptr uint8_t @-> int @-> returning void)
let pci_find_cap =
foreign "pci_find_cap" (Pci_dev.t @-> uint @-> uint @-> returning Pci_cap.t)
let pci_filter_init =
foreign "pci_filter_init" (Pci_access.t @-> Pci_filter.t @-> returning void)
let pci_filter_parse_slot =
foreign "pci_filter_parse_slot" (Pci_filter.t @-> string @-> returning string)
let pci_filter_parse_id =
foreign "pci_filter_parse_id" (Pci_filter.t @-> string @-> returning string)
let pci_filter_match =
foreign "pci_filter_match" (Pci_filter.t @-> Pci_dev.t @-> returning int)
let pci_lookup_name_1_ary =
foreign "pci_lookup_name"
(Pci_access.t @-> ptr char @-> int @-> int @-> int @-> returning string)
let pci_lookup_name_2_ary =
foreign "pci_lookup_name"
(Pci_access.t @-> ptr char @-> int @-> int @-> int @-> int @-> returning string)
let pci_lookup_name_4_ary =
foreign "pci_lookup_name"
(Pci_access.t @-> ptr char @-> int @-> int @-> int @-> int @-> int @-> int @-> returning string)
let pci_load_name_list =
foreign "pci_load_name_list" (Pci_access.t @-> returning int)
let pci_free_name_list =
foreign "pci_free_name_list" (Pci_access.t @-> returning void)
let pci_set_name_list_path =
foreign "pci_set_name_list_path" (Pci_access.t @-> string @-> int @-> returning void)
let pci_id_cache_flush =
foreign "pci_id_cache_flush" (Pci_access.t @-> returning void)
end
| null | https://raw.githubusercontent.com/simonjbeaumont/ocaml-pci/936cff8794bcb2ac0c4de6f8431f1810ba4e6941/bindings/ffi_bindings.ml | ocaml | Just a subset of the access types we'll need internally | open Ctypes
module Types (F: Cstubs.Types.TYPE) = struct
module Lookup_mode = struct
let lookup_vendor = F.constant "PCI_LOOKUP_VENDOR" F.int
let lookup_device = F.constant "PCI_LOOKUP_DEVICE" F.int
let lookup_class = F.constant "PCI_LOOKUP_CLASS" F.int
let lookup_subsystem = F.constant "PCI_LOOKUP_SUBSYSTEM" F.int
let lookup_progif = F.constant "PCI_LOOKUP_PROGIF" F.int
let lookup_numeric = F.constant "PCI_LOOKUP_NUMERIC" F.int
let lookup_no_numbers = F.constant "PCI_LOOKUP_NO_NUMBERS" F.int
let lookup_mixed = F.constant "PCI_LOOKUP_MIXED" F.int
let lookup_network = F.constant "PCI_LOOKUP_NETWORK" F.int
let lookup_skip_local = F.constant "PCI_LOOKUP_SKIP_LOCAL" F.int
let lookup_cache = F.constant "PCI_LOOKUP_CACHE" F.int
let lookup_refresh_cache = F.constant "PCI_LOOKUP_REFRESH_CACHE" F.int
end
module Fill_flag = struct
let fill_ident = F.constant "PCI_FILL_IDENT" F.int
let fill_irq = F.constant "PCI_FILL_IRQ" F.int
let fill_bases = F.constant "PCI_FILL_BASES" F.int
let fill_rom_base = F.constant "PCI_FILL_ROM_BASE" F.int
let fill_sizes = F.constant "PCI_FILL_SIZES" F.int
let fill_class = F.constant "PCI_FILL_CLASS" F.int
let fill_caps = F.constant "PCI_FILL_CAPS" F.int
let fill_ext_caps = F.constant "PCI_FILL_EXT_CAPS" F.int
let fill_phys_slot = F.constant "PCI_FILL_PHYS_SLOT" F.int
let fill_module_alias = F.constant "PCI_FILL_MODULE_ALIAS" F.int
let fill_rescan = F.constant "PCI_FILL_RESCAN" F.int
end
module Pci_class = struct
let class_not_defined = F.constant "PCI_CLASS_NOT_DEFINED" F.int
let base_class_storage = F.constant "PCI_BASE_CLASS_STORAGE" F.int
let base_class_network = F.constant "PCI_BASE_CLASS_NETWORK" F.int
let base_class_display = F.constant "PCI_BASE_CLASS_DISPLAY" F.int
let base_class_multimedia = F.constant "PCI_BASE_CLASS_MULTIMEDIA" F.int
let base_class_memory = F.constant "PCI_BASE_CLASS_MEMORY" F.int
let base_class_bridge = F.constant "PCI_BASE_CLASS_BRIDGE" F.int
let base_class_communication = F.constant "PCI_BASE_CLASS_COMMUNICATION" F.int
let base_class_system = F.constant "PCI_BASE_CLASS_SYSTEM" F.int
let base_class_input = F.constant "PCI_BASE_CLASS_INPUT" F.int
let base_class_docking = F.constant "PCI_BASE_CLASS_DOCKING" F.int
let base_class_processor = F.constant "PCI_BASE_CLASS_PROCESSOR" F.int
let base_class_serial = F.constant "PCI_BASE_CLASS_SERIAL" F.int
let base_class_wireless = F.constant "PCI_BASE_CLASS_WIRELESS" F.int
let base_class_intelligent = F.constant "PCI_BASE_CLASS_INTELLIGENT" F.int
let base_class_satellite = F.constant "PCI_BASE_CLASS_SATELLITE" F.int
let base_class_crypt = F.constant "PCI_BASE_CLASS_CRYPT" F.int
let base_class_signal = F.constant "PCI_BASE_CLASS_SIGNAL" F.int
let class_others = F.constant "PCI_CLASS_OTHERS" F.int
end
module Header = struct
A subset of the PCI configuration address space ( see pci / header.h )
let header_type = F.constant "PCI_HEADER_TYPE" F.int
let header_type_normal = F.constant "PCI_HEADER_TYPE_NORMAL" F.int
let subsystem_vendor_id = F.constant "PCI_SUBSYSTEM_VENDOR_ID" F.int
let subsystem_id = F.constant "PCI_SUBSYSTEM_ID" F.int
let header_type_cardbus = F.constant "PCI_HEADER_TYPE_CARDBUS" F.int
let cb_subsystem_vendor_id = F.constant "PCI_CB_SUBSYSTEM_VENDOR_ID" F.int
let cb_subsystem_id = F.constant "PCI_CB_SUBSYSTEM_ID" F.int
end
module Access_type = struct
let auto = F.constant "PCI_ACCESS_AUTO" F.uint
let dump = F.constant "PCI_ACCESS_DUMP" F.uint
end
end
module Bindings (F : Cstubs.FOREIGN) = struct
open F
module Pci_cap = struct
type pci_cap
let pci_cap : pci_cap structure typ = structure "pci_cap"
let (-:) ty label = field pci_cap label ty
let next = (ptr_opt pci_cap) -: "next"
let id = uint16_t -: "id"
let type_ = uint16_t -: "type"
let addr = int -: "addr"
let () = seal pci_cap
type t = pci_cap structure ptr
let t = ptr pci_cap
end
module Pci_dev = struct
type pci_dev
let pci_dev : pci_dev structure typ = structure "pci_dev"
let (-:) ty label = field pci_dev label ty
let next = (ptr_opt pci_dev) -: "next"
let domain = uint16_t -: "domain"
let bus = uint8_t -: "bus"
let dev = uint8_t -: "dev"
let func = uint8_t -: "func"
let known_fields = int -: "known_fields"
let vendor_id = uint16_t -: "vendor_id"
let device_id = uint16_t -: "device_id"
let device_class = uint16_t -: "device_class"
let irq = int -: "irq"
TODO : this is derived at compile time in pci / types.h ...
let base_addr = (array 6 pciaddr_t) -: "base_addr"
let size = (array 6 pciaddr_t) -: "size"
let rom_base_addr = pciaddr_t -: "rom_base_addr"
let rom_size = pciaddr_t -: "rom_size"
let first_cap = Pci_cap.t -: "first_cap"
let phy_slot = string_opt -: "phy_slot"
let module_alias = string_opt -: "module_alias"
Fields used internally
let access = (ptr void) -: "access"
let methods = (ptr void) -: "methods"
let cache = (ptr uint8_t) -: "cache"
let cache_len = int -: "cache_len"
let hdrtype = int -: "hdrtype"
let aux = (ptr void) -: "aux"
let () = seal pci_dev
type t = pci_dev structure ptr
let t = ptr pci_dev
end
module Pci_param = struct
type pci_param
let pci_param : pci_param structure typ = structure "pci_param"
let (-:) ty label = field pci_param label ty
let next = ptr_opt pci_param -: "next"
let param = string -: "param"
let value = string -: "value"
let value_malloced = int -: "value_malloced"
let help = string -: "help"
let () = seal pci_param
type t = pci_param structure ptr
let t = ptr pci_param
end
module Pci_filter = struct
type pci_filter
let pci_filter : pci_filter structure typ = structure "pci_filter"
let (-:) ty label = field pci_filter label ty
let domain = int -: "domain"
let bus = int -: "bus"
let slot = int -: "slot"
let func = int -: "func"
let vendor = int -: "vendor"
let device = int -: "device"
let () = seal pci_filter
type t = pci_filter structure ptr
let t = ptr pci_filter
end
module Pci_access = struct
open Pci_dev
type pci_access
let pci_access : pci_access structure typ = structure "pci_access"
let (-:) ty label = field pci_access label ty
let method_ = uint -: "method"
let writeable = int -: "writeable"
let buscentric = int -: "buscentric"
let id_file_name = string -: "id_file_name"
let free_id_name = int -: "free_id_name"
let numeric_ids = int -: "numeric_ids"
let lookup_mode = uint -: "lookup_mode"
let debugging = int -: "debugging"
let error = (ptr void) -: "error"
let warning = (ptr void) -: "warning"
let debug = (ptr void) -: "debug"
let devices = field pci_access "devices" (ptr_opt pci_dev)
Fields used internally
let methods = (ptr void) -: "methods"
let params = (ptr void) -: "params"
let id_hash = (ptr (ptr void)) -: "id_hash"
let current_id_bucket = (ptr void) -: "current_id_bucket"
let id_load_failed = int -: "id_load_failed"
let id_cache_status = int -: "id_cache_status"
let fd = int -: "fd"
let fd_rw = int -: "fd_rw"
let fd_pos = int -: "fd_pos"
let fd_vpd = int -: "fd_vpd"
let cached_dev = (ptr_opt pci_dev) -: "cached_dev"
let () = seal pci_access
type t = pci_access structure ptr
let t = ptr pci_access
end
let pci_alloc =
foreign "pci_alloc" (void @-> returning Pci_access.t)
let pci_init =
foreign "pci_init" (Pci_access.t @-> returning void)
let pci_cleanup =
foreign "pci_cleanup" (Pci_access.t @-> returning void)
let pci_scan_bus =
foreign "pci_scan_bus" (Pci_access.t @-> returning void)
let pci_get_dev =
foreign "pci_get_dev" (Pci_access.t @-> int @-> int @-> int @-> int @-> returning Pci_dev.t)
let pci_free_dev =
foreign "pci_free_dev" (Pci_dev.t @-> returning void)
let pci_lookup_method =
foreign "pci_lookup_method" (string @-> returning int)
let pci_get_method_name =
foreign "pci_get_method_name" (int @-> returning string)
let pci_get_param =
foreign "pci_get_param" (Pci_access.t @-> string @-> returning string)
let pci_set_param =
foreign "pci_set_param" (Pci_access.t @-> string @-> string @-> returning int)
let pci_walk_params =
foreign "pci_walk_params" (Pci_access.t @-> Pci_param.t @-> returning Pci_param.t)
let pci_read_byte =
foreign "pci_read_byte" (Pci_dev.t @-> int @-> returning uint8_t)
let pci_read_word =
foreign "pci_read_word" (Pci_dev.t @-> int @-> returning uint16_t)
let pci_read_long =
foreign "pci_read_long" (Pci_dev.t @-> int @-> returning uint32_t)
let pci_read_block =
foreign "pci_read_block" (Pci_dev.t @-> int @-> ptr uint8_t @-> int @-> returning int)
let pci_read_vpd =
foreign "pci_read_vpd" (Pci_dev.t @-> int @-> ptr uint8_t @-> int @-> returning int)
let pci_write_byte =
foreign "pci_write_byte" (Pci_dev.t @-> int @-> uint8_t @-> returning int)
let pci_write_long =
foreign "pci_write_long" (Pci_dev.t @-> int @-> uint16_t @-> returning int)
let pci_write_block =
foreign "pci_write_block" (Pci_dev.t @-> int @-> ptr uint8_t @-> int @-> returning int)
let pci_fill_info =
foreign "pci_fill_info" (Pci_dev.t @-> int @-> returning int)
let pci_setup_cache =
foreign "pci_setup_cache" (Pci_dev.t @-> ptr uint8_t @-> int @-> returning void)
let pci_find_cap =
foreign "pci_find_cap" (Pci_dev.t @-> uint @-> uint @-> returning Pci_cap.t)
let pci_filter_init =
foreign "pci_filter_init" (Pci_access.t @-> Pci_filter.t @-> returning void)
let pci_filter_parse_slot =
foreign "pci_filter_parse_slot" (Pci_filter.t @-> string @-> returning string)
let pci_filter_parse_id =
foreign "pci_filter_parse_id" (Pci_filter.t @-> string @-> returning string)
let pci_filter_match =
foreign "pci_filter_match" (Pci_filter.t @-> Pci_dev.t @-> returning int)
let pci_lookup_name_1_ary =
foreign "pci_lookup_name"
(Pci_access.t @-> ptr char @-> int @-> int @-> int @-> returning string)
let pci_lookup_name_2_ary =
foreign "pci_lookup_name"
(Pci_access.t @-> ptr char @-> int @-> int @-> int @-> int @-> returning string)
let pci_lookup_name_4_ary =
foreign "pci_lookup_name"
(Pci_access.t @-> ptr char @-> int @-> int @-> int @-> int @-> int @-> int @-> returning string)
let pci_load_name_list =
foreign "pci_load_name_list" (Pci_access.t @-> returning int)
let pci_free_name_list =
foreign "pci_free_name_list" (Pci_access.t @-> returning void)
let pci_set_name_list_path =
foreign "pci_set_name_list_path" (Pci_access.t @-> string @-> int @-> returning void)
let pci_id_cache_flush =
foreign "pci_id_cache_flush" (Pci_access.t @-> returning void)
end
|
aaf01714c565df496a1b7bcff853fe711b010b6c2a680809dd8396c9bab8dc1c | GaloisInc/tower | Document.hs |
module Ivory.Tower.Config.Document where
import Ivory.Tower.Config.Preprocess
import Ivory.Tower.Config.TOML
getDocument :: FilePath -> [FilePath] -> IO (Either String TOML)
getDocument root path = do
b <- getPreprocessedFile root path
case b of
Right bs -> return (tomlParse bs)
Left e -> return (Left e)
| null | https://raw.githubusercontent.com/GaloisInc/tower/a43f5e36c6443472ea2dc15bbd49faf8643a6f87/tower-config/src/Ivory/Tower/Config/Document.hs | haskell |
module Ivory.Tower.Config.Document where
import Ivory.Tower.Config.Preprocess
import Ivory.Tower.Config.TOML
getDocument :: FilePath -> [FilePath] -> IO (Either String TOML)
getDocument root path = do
b <- getPreprocessedFile root path
case b of
Right bs -> return (tomlParse bs)
Left e -> return (Left e)
|
|
d8bd013e3006e5559a9b15324e2095a2a436c6ece74ff1f50fe21a0cf45d21ed | CrossRef/cayenne | user.clj | (ns cayenne.user
(:require [clojure.string :as str]
[cayenne.conf :as conf]
[cayenne.ids.doi :as doi-id]
[cayenne.schedule :as schedule]
[cayenne.api.route :as route]
[cayenne.action :as action]
[taoensso.timbre.appenders.irc :as irc-appender]
[taoensso.timbre :as timbre])
(:import [org.apache.solr.client.solrj SolrQuery]))
(defn begin [& profiles]
(timbre/set-config! [:appenders :standard-out :enabled?] false)
(timbre/set-config! [:appenders :spit :enabled?] true)
(timbre/set-config! [:shared-appender-config :spit-filename] "log/log.txt")
(schedule/start)
(conf/create-core-from! :user :default)
(conf/set-core! :user)
(apply conf/start-core! :user profiles))
(defn status []
(println
(str "Status = " (conf/get-param [:status])))
(println
(str "Running services = "
(str/join ", " (-> @conf/cores
(get-in [conf/*core-name* :services])
keys)))))
(defn print-solr-doi [doi]
(-> (conf/get-service :solr)
(.query
(doto (SolrQuery.)
(.setQuery (str "doi_key:\"" (doi-id/to-long-doi-uri doi) "\""))))
(.getResults)
first
prn)
nil)
| null | https://raw.githubusercontent.com/CrossRef/cayenne/02321ad23dbb1edd3f203a415f4a4b11ebf810d7/src/cayenne/user.clj | clojure | (ns cayenne.user
(:require [clojure.string :as str]
[cayenne.conf :as conf]
[cayenne.ids.doi :as doi-id]
[cayenne.schedule :as schedule]
[cayenne.api.route :as route]
[cayenne.action :as action]
[taoensso.timbre.appenders.irc :as irc-appender]
[taoensso.timbre :as timbre])
(:import [org.apache.solr.client.solrj SolrQuery]))
(defn begin [& profiles]
(timbre/set-config! [:appenders :standard-out :enabled?] false)
(timbre/set-config! [:appenders :spit :enabled?] true)
(timbre/set-config! [:shared-appender-config :spit-filename] "log/log.txt")
(schedule/start)
(conf/create-core-from! :user :default)
(conf/set-core! :user)
(apply conf/start-core! :user profiles))
(defn status []
(println
(str "Status = " (conf/get-param [:status])))
(println
(str "Running services = "
(str/join ", " (-> @conf/cores
(get-in [conf/*core-name* :services])
keys)))))
(defn print-solr-doi [doi]
(-> (conf/get-service :solr)
(.query
(doto (SolrQuery.)
(.setQuery (str "doi_key:\"" (doi-id/to-long-doi-uri doi) "\""))))
(.getResults)
first
prn)
nil)
|
|
a55c14451f255674d9f6e3940585daecf7efc72f1161a6b263c4cfd5b763e8e4 | faylang/fay | json.hs | module Console where
import FFI
import Prelude
import Fay.Text
data MyData = MyData { xVar :: Text, yVar :: Int }
myData :: MyData
myData = MyData { xVar = pack "asdfasd", yVar = 9 }
main = do
jsonSerialized <- toJSON myData
jsonDeserialized <- toMyData jsonSerialized
-- The "instance" field below is required for reliable parsing.
-- If your JSON source doesn't have an "instance" field, you can
add one like this : ffi " % 1['instance']='MyData',%1 " : : Json - > MyData
fromStringData <- toMyData "{\"xVar\":3,\"yVar\":-1,\"instance\":\"MyData\"}"
print' jsonSerialized
-- | Print using console.log.
print' :: String -> Fay ()
print' = ffi "console.log(%1)"
printBool :: Bool -> Fay ()
printBool = ffi "console.log(%1)"
printInt :: Int -> Fay ()
printInt = ffi "console.log(%1)"
toMyData :: String -> Fay MyData
toMyData = ffi "JSON.parse(%1)"
toJSON :: MyData -> Fay String
toJSON = ffi "JSON.stringify(%1)"
| null | https://raw.githubusercontent.com/faylang/fay/8455d975f9f0db2ecc922410e43e484fbd134699/examples/json.hs | haskell | The "instance" field below is required for reliable parsing.
If your JSON source doesn't have an "instance" field, you can
| Print using console.log. | module Console where
import FFI
import Prelude
import Fay.Text
data MyData = MyData { xVar :: Text, yVar :: Int }
myData :: MyData
myData = MyData { xVar = pack "asdfasd", yVar = 9 }
main = do
jsonSerialized <- toJSON myData
jsonDeserialized <- toMyData jsonSerialized
add one like this : ffi " % 1['instance']='MyData',%1 " : : Json - > MyData
fromStringData <- toMyData "{\"xVar\":3,\"yVar\":-1,\"instance\":\"MyData\"}"
print' jsonSerialized
print' :: String -> Fay ()
print' = ffi "console.log(%1)"
printBool :: Bool -> Fay ()
printBool = ffi "console.log(%1)"
printInt :: Int -> Fay ()
printInt = ffi "console.log(%1)"
toMyData :: String -> Fay MyData
toMyData = ffi "JSON.parse(%1)"
toJSON :: MyData -> Fay String
toJSON = ffi "JSON.stringify(%1)"
|
601815f00bc24fde898cfee2375c7b8752dd98635578d20b2c1e52aabf412001 | JacquesCarette/Drasil | Body.hs | -- | Gathers and organizes all the information for the [Drasil website](/).
module Drasil.Website.Body where
import Language.Drasil.Printers (PrintingInformation(..), defaultConfiguration)
import Database.Drasil
import SysInfo.Drasil
import Language.Drasil
import Drasil.DocLang (findAllRefs)
import Drasil.Website.Introduction (introSec)
import Drasil.Website.About (aboutSec)
import Drasil.Website.CaseStudy (caseStudySec)
import Drasil.Website.Example (exampleSec, exampleRefs, allExampleSI)
import Drasil.Website.Documentation (docsSec, docRefs)
import Drasil.Website.Analysis (analysisSec, analysisRefs)
import Drasil.Website.GettingStarted (gettingStartedSec)
* Functions to Generate the Website Through
-- | Printing info to get document to generate. Takes in the 'FolderLocation'.
printSetting :: FolderLocation -> PrintingInformation
printSetting fl = PI (symbMap fl) Equational defaultConfiguration
-- | Instead of being an 'SRSDecl', this takes the folder locations and generates the document from there.
mkWebsite :: FolderLocation -> Document
mkWebsite fl =
--Document -- Title -- author (hack for now to show up in proper spot) -- no table of contents -- [Section]
Document (S websiteTitle) (namedRef gitHubRef (S "Link to GitHub Repository")) NoToC $ sections fl
| Folder locations based on environment variables ( using ' getEnv ' in " . Website . Main " ) .
data FolderLocation = Folder {
-- | Deploy location. Currently unused, but may be needed in the future.
depL :: FilePath
-- | Haddock documentation root file path. After using @make deploy@, this should be @deploy/docs@.
, docsRt :: FilePath
-- | Example root file path. After using @make deploy@, this should be @deploy/examples@.
, exRt :: FilePath
| Package dependency graph root file path . After using @make deploy@ , this should be @deploy / graphs@.
, graphRt :: FilePath
-- | Analysis root file path. After using @make deploy@, this should be @deploy/analysis@.
, analysisRt :: FilePath
| Type graphs root file path . After using @make deploy@ , this should be @deploy\/analysis\/TypeDependencyGraphs@.
, typeGraphFolder :: FilePath
-- | Class-instance graphs root file path. After using @make deploy@, this should be @deploy\/analysis\/DataTable\/packagegraphs@.
, classInstFolder :: FilePath
| Repository root , used for linking to generated code in GitHub .
, repoRt :: FilePath
-- | Deploy build number. Currently unused.
, buildNum :: FilePath
-- | Deploy build path. Currently unused.
, buildPth :: FilePath
| List of packages taken from the @Makefile@.
, packages :: [String]
}
TODO : Should the website be using a ` ` SystemInformation '' ? This is primarily for the SmithEtAl template .
-- It seems like the website is primarily that functions on a chunkdb.
-- | System information.
si :: FolderLocation -> SystemInformation
si fl = SI {
_sys = webName,
_kind = web,
_authors = [] :: [Person],
_quants = [] :: [QuantityDict],
_purpose = [],
_background = [],
_concepts = [] :: [UnitalChunk],
_instModels = [],
_datadefs = [],
_configFiles = [],
_inputs = [] :: [QuantityDict],
_outputs = [] :: [QuantityDict],
_defSequence = [] :: [Block SimpleQDef],
_constraints = [] :: [ConstrainedChunk],
_constants = [] :: [ConstQDef],
_sysinfodb = symbMap fl,
_usedinfodb = usedDB,
refdb = rdb [] []
}
| Puts all the sections in order . Basically the website version of the SRS declaration .
sections :: FolderLocation -> [Section]
sections fl = [headerSec, introSec, gettingStartedSec quickStartWiki newWorkspaceSetupWiki contribGuideWiki workflowWiki
createProjWiki debuggingWiki, aboutSec (ref caseStudySec) (ref $ docsSec $ docsRt fl) (ref $ analysisSec (analysisRt fl)
(typeGraphFolder fl) (classInstFolder fl) (graphRt fl) $ packages fl) gitHubRef wikiRef infoEncodingWiki chunksWiki recipesWiki
paperGOOL papersWiki, exampleSec (repoRt fl) (exRt fl), caseStudySec, docsSec (docsRt fl), analysisSec (analysisRt fl)
(typeGraphFolder fl) (classInstFolder fl) (graphRt fl) $ packages fl, footer fl]
-- | Needed for references and terms to work.
symbMap :: FolderLocation -> ChunkDB
symbMap fl = cdb ([] :: [QuantityDict]) (map nw [webName, web] ++ map getSysName allExampleSI)
([] :: [ConceptChunk]) ([] :: [UnitDefn]) [] [] [] [] [] [] [] $ allRefs fl
| Helper to get the system name as an ' IdeaDict ' from ' SystemInformation ' .
getSysName :: SystemInformation -> IdeaDict
getSysName SI{_sys = nm} = nw nm
-- | Empty database needed for 'si' to work.
usedDB :: ChunkDB
usedDB = cdb ([] :: [QuantityDict]) ([] :: [IdeaDict])
([] :: [ConceptChunk]) ([] :: [UnitDefn]) [] [] [] [] [] [] [] ([] :: [Reference])
-- | Holds all references and links used in the website.
allRefs :: FolderLocation -> [Reference]
allRefs fl = [gitHubRef, wikiRef, infoEncodingWiki, chunksWiki, recipesWiki, paperGOOL, papersWiki,
quickStartWiki, newWorkspaceSetupWiki, contribGuideWiki, workflowWiki, createProjWiki, debuggingWiki]
++ exampleRefs (repoRt fl) (exRt fl)
++ docRefs (docsRt fl)
++ analysisRefs (analysisRt fl) (typeGraphFolder fl) (classInstFolder fl) (graphRt fl) (packages fl)
++ concatMap findAllRefs (sections fl)
-- | Used for system name and kind inside of 'si'.
webName, web :: CI
webName = commonIdea "websiteName" (cn websiteTitle) "Drasil" []
web = commonIdea "website" (cn "website") "web" []
-- * Header Section
-- | Header section creator.
headerSec :: Section
headerSec =
section EmptyS -- No title
[LlC imageContent] -- Contents
[] $ makeSecRef "Header" $ S "Header" -- Section reference
-- | For the drasil tree image on the website.
imageContent :: LabelledContent
imageContent = llcc (makeFigRef "Drasil") $ figWithWidth EmptyS imagePath 50
-- | Used for the repository link.
gitHubRef :: Reference
gitHubRef = makeURI "gitHubRepo" gitHubInfoURL (shortname' $ S "gitHubRepo")
wikiRef :: Reference
wikiRef = makeURI "gitHubWiki" (gitHubInfoURL ++ "/wiki") (shortname' $ S "gitHubWiki")
infoEncodingWiki :: Reference
infoEncodingWiki = makeURI "InfoEncodingWiki" (gitHubInfoURL ++ "/wiki/Information-Encoding") (shortname' $ S "InfoEncodingWiki")
chunksWiki :: Reference
chunksWiki = makeURI "chunksWiki" (gitHubInfoURL ++ "/wiki/Chunks") (shortname' $ S "chunksWiki")
recipesWiki :: Reference
recipesWiki = makeURI "recipesWiki" (gitHubInfoURL ++ "/wiki/Recipes") (shortname' $ S "recipesWiki")
paperGOOL :: Reference
paperGOOL = makeURI "GOOLPaper" (gitHubInfoURL ++ "/blob/master/Papers/GOOL/GOOL.pdf") (shortname' $ S "GOOLPaper")
papersWiki :: Reference
papersWiki = makeURI "papersWiki" (gitHubInfoURL ++ "/wiki/Drasil-Papers-and-Documents") (shortname' $ S "papersWiki")
quickStartWiki :: Reference
quickStartWiki = makeURI "quickStartWiki" (gitHubInfoURL ++ "#quick-start") (shortname' $ S "quickStartWiki")
newWorkspaceSetupWiki :: Reference
newWorkspaceSetupWiki = makeURI "newWorkspaceSetupWiki" (gitHubInfoURL ++ "/wiki/New-Workspace-Setup") (shortname' $ S "newWorkspaceSetupWiki")
contribGuideWiki :: Reference
contribGuideWiki = makeURI "contribGuideWiki" (gitHubInfoURL ++ "/wiki/Contributor's-Guide") (shortname' $ S "contribGuideWiki")
workflowWiki :: Reference
workflowWiki = makeURI "workflowWiki" (gitHubInfoURL ++ "/wiki/Workflow") (shortname' $ S "workflowWiki")
createProjWiki :: Reference
createProjWiki = makeURI "createProjWiki" (gitHubInfoURL ++ "/wiki/Creating-Your-Project-in-Drasil") (shortname' $ S "createProjWiki")
debuggingWiki :: Reference
debuggingWiki = makeURI "debuggingWiki" (gitHubInfoURL ++ "/wiki/Debugging-in-Drasil") (shortname' $ S "debuggingWiki")
-- | Hardcoded info for the title, URL, and image path.
websiteTitle :: String
gitHubInfoURL, imagePath :: FilePath
websiteTitle = "Drasil - Generate All the Things!"
gitHubInfoURL = ""
imagePath = "./images/Icon.png"
-- * Footer Section
-- | Create the footer section.
footer :: FolderLocation -> Section
footer _ = section EmptyS [mkParagraph copyrightInfo] [] $ makeSecRef "Footer" $ S "Footer"
-- | 'footer' contents.
copyrightInfo :: Sentence
copyrightInfo = S "Copyright (c) Jacques Carette, 2021. All rights reserved. This website is a software artifact generated by Drasil."
-- uncomment to add in build number and path information
--buildInfo :: String -> String -> Sentence
" Build number : " + + bnum + + " . Generated from " + + bPath + + " . " | null | https://raw.githubusercontent.com/JacquesCarette/Drasil/84272acccc09574dec70d8d96c6ea994f15f8b22/code/drasil-website/lib/Drasil/Website/Body.hs | haskell | | Gathers and organizes all the information for the [Drasil website](/).
| Printing info to get document to generate. Takes in the 'FolderLocation'.
| Instead of being an 'SRSDecl', this takes the folder locations and generates the document from there.
Document -- Title -- author (hack for now to show up in proper spot) -- no table of contents -- [Section]
| Deploy location. Currently unused, but may be needed in the future.
| Haddock documentation root file path. After using @make deploy@, this should be @deploy/docs@.
| Example root file path. After using @make deploy@, this should be @deploy/examples@.
| Analysis root file path. After using @make deploy@, this should be @deploy/analysis@.
| Class-instance graphs root file path. After using @make deploy@, this should be @deploy\/analysis\/DataTable\/packagegraphs@.
| Deploy build number. Currently unused.
| Deploy build path. Currently unused.
It seems like the website is primarily that functions on a chunkdb.
| System information.
| Needed for references and terms to work.
| Empty database needed for 'si' to work.
| Holds all references and links used in the website.
| Used for system name and kind inside of 'si'.
* Header Section
| Header section creator.
No title
Contents
Section reference
| For the drasil tree image on the website.
| Used for the repository link.
| Hardcoded info for the title, URL, and image path.
* Footer Section
| Create the footer section.
| 'footer' contents.
uncomment to add in build number and path information
buildInfo :: String -> String -> Sentence | module Drasil.Website.Body where
import Language.Drasil.Printers (PrintingInformation(..), defaultConfiguration)
import Database.Drasil
import SysInfo.Drasil
import Language.Drasil
import Drasil.DocLang (findAllRefs)
import Drasil.Website.Introduction (introSec)
import Drasil.Website.About (aboutSec)
import Drasil.Website.CaseStudy (caseStudySec)
import Drasil.Website.Example (exampleSec, exampleRefs, allExampleSI)
import Drasil.Website.Documentation (docsSec, docRefs)
import Drasil.Website.Analysis (analysisSec, analysisRefs)
import Drasil.Website.GettingStarted (gettingStartedSec)
* Functions to Generate the Website Through
printSetting :: FolderLocation -> PrintingInformation
printSetting fl = PI (symbMap fl) Equational defaultConfiguration
mkWebsite :: FolderLocation -> Document
mkWebsite fl =
Document (S websiteTitle) (namedRef gitHubRef (S "Link to GitHub Repository")) NoToC $ sections fl
| Folder locations based on environment variables ( using ' getEnv ' in " . Website . Main " ) .
data FolderLocation = Folder {
depL :: FilePath
, docsRt :: FilePath
, exRt :: FilePath
| Package dependency graph root file path . After using @make deploy@ , this should be @deploy / graphs@.
, graphRt :: FilePath
, analysisRt :: FilePath
| Type graphs root file path . After using @make deploy@ , this should be @deploy\/analysis\/TypeDependencyGraphs@.
, typeGraphFolder :: FilePath
, classInstFolder :: FilePath
| Repository root , used for linking to generated code in GitHub .
, repoRt :: FilePath
, buildNum :: FilePath
, buildPth :: FilePath
| List of packages taken from the @Makefile@.
, packages :: [String]
}
TODO : Should the website be using a ` ` SystemInformation '' ? This is primarily for the SmithEtAl template .
si :: FolderLocation -> SystemInformation
si fl = SI {
_sys = webName,
_kind = web,
_authors = [] :: [Person],
_quants = [] :: [QuantityDict],
_purpose = [],
_background = [],
_concepts = [] :: [UnitalChunk],
_instModels = [],
_datadefs = [],
_configFiles = [],
_inputs = [] :: [QuantityDict],
_outputs = [] :: [QuantityDict],
_defSequence = [] :: [Block SimpleQDef],
_constraints = [] :: [ConstrainedChunk],
_constants = [] :: [ConstQDef],
_sysinfodb = symbMap fl,
_usedinfodb = usedDB,
refdb = rdb [] []
}
| Puts all the sections in order . Basically the website version of the SRS declaration .
sections :: FolderLocation -> [Section]
sections fl = [headerSec, introSec, gettingStartedSec quickStartWiki newWorkspaceSetupWiki contribGuideWiki workflowWiki
createProjWiki debuggingWiki, aboutSec (ref caseStudySec) (ref $ docsSec $ docsRt fl) (ref $ analysisSec (analysisRt fl)
(typeGraphFolder fl) (classInstFolder fl) (graphRt fl) $ packages fl) gitHubRef wikiRef infoEncodingWiki chunksWiki recipesWiki
paperGOOL papersWiki, exampleSec (repoRt fl) (exRt fl), caseStudySec, docsSec (docsRt fl), analysisSec (analysisRt fl)
(typeGraphFolder fl) (classInstFolder fl) (graphRt fl) $ packages fl, footer fl]
symbMap :: FolderLocation -> ChunkDB
symbMap fl = cdb ([] :: [QuantityDict]) (map nw [webName, web] ++ map getSysName allExampleSI)
([] :: [ConceptChunk]) ([] :: [UnitDefn]) [] [] [] [] [] [] [] $ allRefs fl
| Helper to get the system name as an ' IdeaDict ' from ' SystemInformation ' .
getSysName :: SystemInformation -> IdeaDict
getSysName SI{_sys = nm} = nw nm
usedDB :: ChunkDB
usedDB = cdb ([] :: [QuantityDict]) ([] :: [IdeaDict])
([] :: [ConceptChunk]) ([] :: [UnitDefn]) [] [] [] [] [] [] [] ([] :: [Reference])
allRefs :: FolderLocation -> [Reference]
allRefs fl = [gitHubRef, wikiRef, infoEncodingWiki, chunksWiki, recipesWiki, paperGOOL, papersWiki,
quickStartWiki, newWorkspaceSetupWiki, contribGuideWiki, workflowWiki, createProjWiki, debuggingWiki]
++ exampleRefs (repoRt fl) (exRt fl)
++ docRefs (docsRt fl)
++ analysisRefs (analysisRt fl) (typeGraphFolder fl) (classInstFolder fl) (graphRt fl) (packages fl)
++ concatMap findAllRefs (sections fl)
webName, web :: CI
webName = commonIdea "websiteName" (cn websiteTitle) "Drasil" []
web = commonIdea "website" (cn "website") "web" []
headerSec :: Section
headerSec =
imageContent :: LabelledContent
imageContent = llcc (makeFigRef "Drasil") $ figWithWidth EmptyS imagePath 50
gitHubRef :: Reference
gitHubRef = makeURI "gitHubRepo" gitHubInfoURL (shortname' $ S "gitHubRepo")
wikiRef :: Reference
wikiRef = makeURI "gitHubWiki" (gitHubInfoURL ++ "/wiki") (shortname' $ S "gitHubWiki")
infoEncodingWiki :: Reference
infoEncodingWiki = makeURI "InfoEncodingWiki" (gitHubInfoURL ++ "/wiki/Information-Encoding") (shortname' $ S "InfoEncodingWiki")
chunksWiki :: Reference
chunksWiki = makeURI "chunksWiki" (gitHubInfoURL ++ "/wiki/Chunks") (shortname' $ S "chunksWiki")
recipesWiki :: Reference
recipesWiki = makeURI "recipesWiki" (gitHubInfoURL ++ "/wiki/Recipes") (shortname' $ S "recipesWiki")
paperGOOL :: Reference
paperGOOL = makeURI "GOOLPaper" (gitHubInfoURL ++ "/blob/master/Papers/GOOL/GOOL.pdf") (shortname' $ S "GOOLPaper")
papersWiki :: Reference
papersWiki = makeURI "papersWiki" (gitHubInfoURL ++ "/wiki/Drasil-Papers-and-Documents") (shortname' $ S "papersWiki")
quickStartWiki :: Reference
quickStartWiki = makeURI "quickStartWiki" (gitHubInfoURL ++ "#quick-start") (shortname' $ S "quickStartWiki")
newWorkspaceSetupWiki :: Reference
newWorkspaceSetupWiki = makeURI "newWorkspaceSetupWiki" (gitHubInfoURL ++ "/wiki/New-Workspace-Setup") (shortname' $ S "newWorkspaceSetupWiki")
contribGuideWiki :: Reference
contribGuideWiki = makeURI "contribGuideWiki" (gitHubInfoURL ++ "/wiki/Contributor's-Guide") (shortname' $ S "contribGuideWiki")
workflowWiki :: Reference
workflowWiki = makeURI "workflowWiki" (gitHubInfoURL ++ "/wiki/Workflow") (shortname' $ S "workflowWiki")
createProjWiki :: Reference
createProjWiki = makeURI "createProjWiki" (gitHubInfoURL ++ "/wiki/Creating-Your-Project-in-Drasil") (shortname' $ S "createProjWiki")
debuggingWiki :: Reference
debuggingWiki = makeURI "debuggingWiki" (gitHubInfoURL ++ "/wiki/Debugging-in-Drasil") (shortname' $ S "debuggingWiki")
websiteTitle :: String
gitHubInfoURL, imagePath :: FilePath
websiteTitle = "Drasil - Generate All the Things!"
gitHubInfoURL = ""
imagePath = "./images/Icon.png"
footer :: FolderLocation -> Section
footer _ = section EmptyS [mkParagraph copyrightInfo] [] $ makeSecRef "Footer" $ S "Footer"
copyrightInfo :: Sentence
copyrightInfo = S "Copyright (c) Jacques Carette, 2021. All rights reserved. This website is a software artifact generated by Drasil."
" Build number : " + + bnum + + " . Generated from " + + bPath + + " . " |
b42b86d0ac84ab2e8393d33a8c2516ca5b803399198eafd50ebe9c4a54fb1d31 | zwizwa/staapl | sim-tools.rkt | #lang racket/base
(require "../tools.rkt"
"../target/rep.rkt"
racket/dict
racket/control
racket/match
racket/pretty
)
(provide (all-defined-out))
;; Reusable tools for writing machine emulators.
;; abstract register access
;; Convenient interface for register access
(define (register-fn reg [arg #f])
(cond
((procedure? arg)
((register-read-modify-write reg) arg))
(arg
((register-write reg) arg))
(else
((register-read reg)))))
(define (register-print reg port write?)
(write-string (format "#<register>") port))
(define-values
(struct:register make-register register? register-ref register-set!)
(begin
(make-struct-type
'register ;; name-symbol
#f ;; super-struct-type
3 ;; init-field-k
0 ;; auto-field-k
#f ;; auto-v
(list (cons prop:custom-write register-print))
#f ;; inspector or false
register-fn ;; word-run or 0
)))
(define (register-read r) (register-ref r 0))
(define (register-write r) (register-ref r 1))
(define (register-read-modify-write r) (register-ref r 2))
#;(define-struct register
(read
write
read-modify-write ;; separate due to pre/post inc/dec on FSRs
))
;; if register access does not have side effects (see FSRs), just
;; implement rmw in terms of read & write
(define (make-rw-register read write)
(define (read-modify-write update)
(let ((v (update (read))))
(write v)
v))
(make-register read write read-modify-write))
(define (make-r-register read)
(make-rw-register read (lambda (v) (error 'read-only))))
(define (make-w-register write)
(make-rw-register (lambda () (error 'write-only)) write))
(define (make-param-register param)
(make-rw-register param param))
(define (make-ni-register tag)
(define (ni . _) (error 'register-not-implemented "~s" tag))
(make-register ni ni ni))
Represent a list of bool parameters as a 8 - bit register interface .
(define (make-flags-register flags-params)
(define flags (reverse flags-params))
(define (read)
(for/fold
((s 0))
((b (in-naturals))
(f flags))
(let ((v (f)))
(unless (boolean? v)
(error 'flag-type "~s" v))
(bior s (<<< (bool->bit (f)) b)))))
(define (write bits)
(if (empty? bits)
(for ((f flags))
(f (make-empty)))
(for ((b (in-naturals))
(f flags))
(f (bit->bool (band 1 (>>> bits b)))))))
(make-rw-register read write))
;; Some macros for defining machine state parameters.
;; Was called uninitialized but that name is just too long.
(define-struct empty ())
(define (undefined-params lst)
(apply values (for/list ((e lst))
(make-parameter (empty)))))
(define-syntax-rule (params . ps)
(define-values ps (undefined-params 'ps)))
(define-syntax-rule (flag-params (reg bits) ...)
(begin
(define-values bits (undefined-params 'bits)) ...
(begin (define reg (make-flags-register (list . bits))) ...)
))
;; LATER: abstract memory access as well.
;; Convenient interface for memory access
(define (memory-fn reg addr [arg #f])
(cond
#;((procedure? arg)
((memory-read-modify-write reg) addr arg))
(arg
((memory-write reg) addr arg))
(else
((memory-read addr reg)))))
(define (memory-print reg port write?)
(write-string (format "#<memory>") port))
(define-values
(struct:memory make-memory memory? memory-ref memory-set!)
(begin
(make-struct-type
'memory ;; name-symbol
#f ;; super-struct-type
2 ;; init-field-k
0 ;; auto-field-k
#f ;; auto-v
(list (cons prop:custom-write memory-print))
#f ;; inspector or false
memory-fn ;; word-run or 0
)))
(define (memory-read mem) (memory-ref mem 0))
(define (memory-write mem) (memory-ref mem 1))
(define (vector-memory vec)
(make-memory
(lambda (addr) (vector-ref vec addr))
(lambda (addr val) (vector-set! vec addr val))))
;; Memory inspector wrapper.
(define (memory-inspect mem read-notify write-notify)
(define (read addr)
(let ((v ((memory-read mem) addr)))
(read-notify addr v)
v))
(define (write addr vnew)
(let ((vold ((memory-read mem) addr)))
((memory-write mem) addr vnew)
(write-notify addr vold vnew)))
(make-memory read write))
(define (memory-dump ram from to)
(let ((rd (memory-read ram)))
(for ((p (in-hex-printer from 3 2 16 (lambda _ ".")))
(i (in-range from to)))
(p (rd i)))))
datastructure .
;; "Binary" files are (list-of (list-of addr (list-of byte)))
;; The way they come out of code->binary.
(define (load-binary filename)
(read (open-input-file filename)))
;; Translate lists to vectors for faster access.
(define (binary->flash code-chunks)
(for/list ((chunk code-chunks))
(list (list-ref chunk 0)
(apply vector (list-ref chunk 1)))))
(define (flash-extend flash a v)
(cons (list a v) flash))
Support target words and ( listof byte - addr vector )
(define (chunk-addr chunk)
(if (target-word? chunk)
(2* (target-word-address chunk))
(car chunk)))
(define (chunk-length chunk)
(if (target-word? chunk)
(2* (apply + (map length (target-word-bin chunk))))
(vector-length (cadr chunk))))
(define (target-word->bytes w)
(words->bytes (reverse (apply append (target-word-bin w)))))
(define (chunk-ref chunk offset)
Memoize ? Probably not necessary since code is jitted .
(if (target-word? chunk)
(list-ref (target-word->bytes chunk) offset)
(vector-ref (cadr chunk) offset)))
(define (flash-find-chunk flash addr)
(define (find)
(prompt
(for ((chunk flash))
(let ((offset (- addr (chunk-addr chunk))))
(when (and (>= offset 0)
(< offset (chunk-length chunk)))
(abort (list chunk offset)))))
'(#f #f)))
(apply values (find)))
(define (flash-ref flash addr)
(let-values (((chunk offset) (flash-find-chunk flash addr)))
(if chunk
(chunk-ref chunk offset)
#xFF)))
(define (flash-ref-word flash addr)
(let ((lo (flash-ref flash addr))
(hi (flash-ref flash (add1 addr))))
(+ lo (* #x100 hi))))
(define (flash-code flash addr)
(let-values (((chunk offset) (flash-find-chunk flash addr)))
(if (not (target-word? chunk)) #f
(let* ((offsets (map 2* (target-word-offsets chunk)))
(code (target-word-code chunk))
(dict (reverse (map cons offsets code))))
(dict-ref dict offset)))))
| null | https://raw.githubusercontent.com/zwizwa/staapl/e30e6ae6ac45de7141b97ad3cebf9b5a51bcda52/pic18/sim-tools.rkt | racket | Reusable tools for writing machine emulators.
abstract register access
Convenient interface for register access
name-symbol
super-struct-type
init-field-k
auto-field-k
auto-v
inspector or false
word-run or 0
(define-struct register
separate due to pre/post inc/dec on FSRs
if register access does not have side effects (see FSRs), just
implement rmw in terms of read & write
Some macros for defining machine state parameters.
Was called uninitialized but that name is just too long.
LATER: abstract memory access as well.
Convenient interface for memory access
((procedure? arg)
name-symbol
super-struct-type
init-field-k
auto-field-k
auto-v
inspector or false
word-run or 0
Memory inspector wrapper.
"Binary" files are (list-of (list-of addr (list-of byte)))
The way they come out of code->binary.
Translate lists to vectors for faster access. | #lang racket/base
(require "../tools.rkt"
"../target/rep.rkt"
racket/dict
racket/control
racket/match
racket/pretty
)
(provide (all-defined-out))
(define (register-fn reg [arg #f])
(cond
((procedure? arg)
((register-read-modify-write reg) arg))
(arg
((register-write reg) arg))
(else
((register-read reg)))))
(define (register-print reg port write?)
(write-string (format "#<register>") port))
(define-values
(struct:register make-register register? register-ref register-set!)
(begin
(make-struct-type
(list (cons prop:custom-write register-print))
)))
(define (register-read r) (register-ref r 0))
(define (register-write r) (register-ref r 1))
(define (register-read-modify-write r) (register-ref r 2))
(read
write
))
(define (make-rw-register read write)
(define (read-modify-write update)
(let ((v (update (read))))
(write v)
v))
(make-register read write read-modify-write))
(define (make-r-register read)
(make-rw-register read (lambda (v) (error 'read-only))))
(define (make-w-register write)
(make-rw-register (lambda () (error 'write-only)) write))
(define (make-param-register param)
(make-rw-register param param))
(define (make-ni-register tag)
(define (ni . _) (error 'register-not-implemented "~s" tag))
(make-register ni ni ni))
Represent a list of bool parameters as a 8 - bit register interface .
(define (make-flags-register flags-params)
(define flags (reverse flags-params))
(define (read)
(for/fold
((s 0))
((b (in-naturals))
(f flags))
(let ((v (f)))
(unless (boolean? v)
(error 'flag-type "~s" v))
(bior s (<<< (bool->bit (f)) b)))))
(define (write bits)
(if (empty? bits)
(for ((f flags))
(f (make-empty)))
(for ((b (in-naturals))
(f flags))
(f (bit->bool (band 1 (>>> bits b)))))))
(make-rw-register read write))
(define-struct empty ())
(define (undefined-params lst)
(apply values (for/list ((e lst))
(make-parameter (empty)))))
(define-syntax-rule (params . ps)
(define-values ps (undefined-params 'ps)))
(define-syntax-rule (flag-params (reg bits) ...)
(begin
(define-values bits (undefined-params 'bits)) ...
(begin (define reg (make-flags-register (list . bits))) ...)
))
(define (memory-fn reg addr [arg #f])
(cond
((memory-read-modify-write reg) addr arg))
(arg
((memory-write reg) addr arg))
(else
((memory-read addr reg)))))
(define (memory-print reg port write?)
(write-string (format "#<memory>") port))
(define-values
(struct:memory make-memory memory? memory-ref memory-set!)
(begin
(make-struct-type
(list (cons prop:custom-write memory-print))
)))
(define (memory-read mem) (memory-ref mem 0))
(define (memory-write mem) (memory-ref mem 1))
(define (vector-memory vec)
(make-memory
(lambda (addr) (vector-ref vec addr))
(lambda (addr val) (vector-set! vec addr val))))
(define (memory-inspect mem read-notify write-notify)
(define (read addr)
(let ((v ((memory-read mem) addr)))
(read-notify addr v)
v))
(define (write addr vnew)
(let ((vold ((memory-read mem) addr)))
((memory-write mem) addr vnew)
(write-notify addr vold vnew)))
(make-memory read write))
(define (memory-dump ram from to)
(let ((rd (memory-read ram)))
(for ((p (in-hex-printer from 3 2 16 (lambda _ ".")))
(i (in-range from to)))
(p (rd i)))))
datastructure .
(define (load-binary filename)
(read (open-input-file filename)))
(define (binary->flash code-chunks)
(for/list ((chunk code-chunks))
(list (list-ref chunk 0)
(apply vector (list-ref chunk 1)))))
(define (flash-extend flash a v)
(cons (list a v) flash))
Support target words and ( listof byte - addr vector )
(define (chunk-addr chunk)
(if (target-word? chunk)
(2* (target-word-address chunk))
(car chunk)))
(define (chunk-length chunk)
(if (target-word? chunk)
(2* (apply + (map length (target-word-bin chunk))))
(vector-length (cadr chunk))))
(define (target-word->bytes w)
(words->bytes (reverse (apply append (target-word-bin w)))))
(define (chunk-ref chunk offset)
Memoize ? Probably not necessary since code is jitted .
(if (target-word? chunk)
(list-ref (target-word->bytes chunk) offset)
(vector-ref (cadr chunk) offset)))
(define (flash-find-chunk flash addr)
(define (find)
(prompt
(for ((chunk flash))
(let ((offset (- addr (chunk-addr chunk))))
(when (and (>= offset 0)
(< offset (chunk-length chunk)))
(abort (list chunk offset)))))
'(#f #f)))
(apply values (find)))
(define (flash-ref flash addr)
(let-values (((chunk offset) (flash-find-chunk flash addr)))
(if chunk
(chunk-ref chunk offset)
#xFF)))
(define (flash-ref-word flash addr)
(let ((lo (flash-ref flash addr))
(hi (flash-ref flash (add1 addr))))
(+ lo (* #x100 hi))))
(define (flash-code flash addr)
(let-values (((chunk offset) (flash-find-chunk flash addr)))
(if (not (target-word? chunk)) #f
(let* ((offsets (map 2* (target-word-offsets chunk)))
(code (target-word-code chunk))
(dict (reverse (map cons offsets code))))
(dict-ref dict offset)))))
|
63b8b3e953fab09a13fd183247b348a46860050752f2811cee23f5ace7893a3e | scarvalhojr/haskellbook | section21.12.hs |
import Control.Applicative (liftA, liftA2, liftA3)
newtype Identity a = Identity a
deriving (Eq, Ord, Show)
instance Functor Identity where
fmap f (Identity x) = Identity (f x)
-- The following isn't necessary
instance Applicative Identity where
pure = Identity
Identity f <*> Identity x = Identity (f x)
instance Foldable Identity where
foldr f z (Identity x) = f x z
instance Traversable Identity where
traverse f (Identity x) = Identity <$> f x
---
newtype Constant a b = Constant { getConstant :: a }
deriving (Show)
instance Functor (Constant a) where
fmap _ (Constant x) = Constant x
instance Foldable (Constant a) where
foldMap _ _ = mempty
instance Traversable (Constant a) where
-- traverse :: (Applicative f) => (a -> f b) -> Constant a -> f (Constant b)
traverse f (Constant x) = liftA Constant (pure x)
---
data Optional a = Nada | Yep a
deriving Show
instance Functor Optional where
fmap _ Nada = Nada
fmap f (Yep x) = Yep (f x)
instance Foldable Optional where
-- foldMap :: (Monoid m) => (a -> m) -> Optional a -> m
foldMap _ Nada = mempty
foldMap f (Yep x) = f x
instance Traversable Optional where
-- traverse :: (Applicative f) => (a -> f b) -> Optional a -> f (Optional b)
traverse _ Nada = pure Nada
traverse f (Yep x) = liftA Yep (f x)
---
data List a = Nil | Cons a (List a)
deriving Show
instance Functor List where
fmap _ Nil = Nil
fmap f (Cons x t) = Cons (f x) (fmap f t)
instance Foldable List where
foldMap _ Nil = mempty
foldMap f (Cons x t) = (f x) `mappend` (foldMap f t)
instance Traversable List where
traverse _ Nil = pure Nil
traverse f (Cons x t) = liftA2 Cons (f x) (traverse f t)
---
data Three a b c = Three a b c
deriving Show
instance Functor (Three a b) where
fmap f (Three a b c) = Three a b (f c)
instance Foldable (Three a b) where
foldMap f (Three a b c) = f c
instance Traversable (Three a b) where
traverse f (Three a b c) = liftA (Three a b) (f c)
---
data Pair a b = Pair a b
deriving Show
instance Functor (Pair a) where
fmap f (Pair x y) = Pair x (f y)
instance Foldable (Pair a) where
foldMap f (Pair x y) = f y
instance Traversable (Pair a) where
traverse f (Pair x y) = liftA (Pair x) (f y)
---
data Big a b = Big a b b
deriving Show
instance Functor (Big a) where
fmap f (Big x y z) = Big x (f y) (f z)
instance Foldable (Big a) where
foldMap f (Big x y z) = f y `mappend` f z
instance Traversable (Big a) where
traverse f (Big x y z) = liftA2 (Big x) (f y) (f z)
---
data S n a = S (n a) a
deriving Show
instance (Functor n) => Functor (S n) where
-- fmap :: (a -> b) -> S n a -> S n b
fmap f (S na a) = S (fmap f na) (f a)
instance (Foldable n) => Foldable (S n) where
-- foldr :: (a -> b -> b) -> b -> S n a -> b
foldr f z (S na a) = f a (foldr f z na)
instance Traversable n => Traversable (S n) where
-- traverse :: Applicative f => (a -> f b) -> S n a -> f (S n b)
traverse f (S na a) = S <$> (traverse f na) <*> (f a)
---
data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)
deriving Show
instance Functor Tree where
fmap _ Empty = Empty
fmap f (Leaf x) = Leaf (f x)
fmap f (Node l x r) = Node (fmap f l) (f x) (fmap f r)
instance Foldable Tree where
-- foldMap :: (Monoid m) => (a -> m) -> Tree a -> m
foldMap _ Empty = mempty
foldMap f (Leaf x) = f x
foldMap f (Node l x r) = (foldMap f l) `mappend` (f x) `mappend` (foldMap f r)
instance Traversable Tree where
-- traverse :: (Applicative f) => (a -> f b) -> Tree a -> f (Tree b)
traverse _ Empty = pure Empty
traverse f (Leaf x) = liftA Leaf (f x)
traverse f (Node l x r) = liftA3 Node (traverse f l) (f x) (traverse f r)
| null | https://raw.githubusercontent.com/scarvalhojr/haskellbook/6016a5a78da3fc4a29f5ea68b239563895c448d5/chapter21/section21.12.hs | haskell | The following isn't necessary
-
traverse :: (Applicative f) => (a -> f b) -> Constant a -> f (Constant b)
-
foldMap :: (Monoid m) => (a -> m) -> Optional a -> m
traverse :: (Applicative f) => (a -> f b) -> Optional a -> f (Optional b)
-
-
-
-
-
fmap :: (a -> b) -> S n a -> S n b
foldr :: (a -> b -> b) -> b -> S n a -> b
traverse :: Applicative f => (a -> f b) -> S n a -> f (S n b)
-
foldMap :: (Monoid m) => (a -> m) -> Tree a -> m
traverse :: (Applicative f) => (a -> f b) -> Tree a -> f (Tree b) |
import Control.Applicative (liftA, liftA2, liftA3)
newtype Identity a = Identity a
deriving (Eq, Ord, Show)
instance Functor Identity where
fmap f (Identity x) = Identity (f x)
instance Applicative Identity where
pure = Identity
Identity f <*> Identity x = Identity (f x)
instance Foldable Identity where
foldr f z (Identity x) = f x z
instance Traversable Identity where
traverse f (Identity x) = Identity <$> f x
newtype Constant a b = Constant { getConstant :: a }
deriving (Show)
instance Functor (Constant a) where
fmap _ (Constant x) = Constant x
instance Foldable (Constant a) where
foldMap _ _ = mempty
instance Traversable (Constant a) where
traverse f (Constant x) = liftA Constant (pure x)
data Optional a = Nada | Yep a
deriving Show
instance Functor Optional where
fmap _ Nada = Nada
fmap f (Yep x) = Yep (f x)
instance Foldable Optional where
foldMap _ Nada = mempty
foldMap f (Yep x) = f x
instance Traversable Optional where
traverse _ Nada = pure Nada
traverse f (Yep x) = liftA Yep (f x)
data List a = Nil | Cons a (List a)
deriving Show
instance Functor List where
fmap _ Nil = Nil
fmap f (Cons x t) = Cons (f x) (fmap f t)
instance Foldable List where
foldMap _ Nil = mempty
foldMap f (Cons x t) = (f x) `mappend` (foldMap f t)
instance Traversable List where
traverse _ Nil = pure Nil
traverse f (Cons x t) = liftA2 Cons (f x) (traverse f t)
data Three a b c = Three a b c
deriving Show
instance Functor (Three a b) where
fmap f (Three a b c) = Three a b (f c)
instance Foldable (Three a b) where
foldMap f (Three a b c) = f c
instance Traversable (Three a b) where
traverse f (Three a b c) = liftA (Three a b) (f c)
data Pair a b = Pair a b
deriving Show
instance Functor (Pair a) where
fmap f (Pair x y) = Pair x (f y)
instance Foldable (Pair a) where
foldMap f (Pair x y) = f y
instance Traversable (Pair a) where
traverse f (Pair x y) = liftA (Pair x) (f y)
data Big a b = Big a b b
deriving Show
instance Functor (Big a) where
fmap f (Big x y z) = Big x (f y) (f z)
instance Foldable (Big a) where
foldMap f (Big x y z) = f y `mappend` f z
instance Traversable (Big a) where
traverse f (Big x y z) = liftA2 (Big x) (f y) (f z)
data S n a = S (n a) a
deriving Show
instance (Functor n) => Functor (S n) where
fmap f (S na a) = S (fmap f na) (f a)
instance (Foldable n) => Foldable (S n) where
foldr f z (S na a) = f a (foldr f z na)
instance Traversable n => Traversable (S n) where
traverse f (S na a) = S <$> (traverse f na) <*> (f a)
data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)
deriving Show
instance Functor Tree where
fmap _ Empty = Empty
fmap f (Leaf x) = Leaf (f x)
fmap f (Node l x r) = Node (fmap f l) (f x) (fmap f r)
instance Foldable Tree where
foldMap _ Empty = mempty
foldMap f (Leaf x) = f x
foldMap f (Node l x r) = (foldMap f l) `mappend` (f x) `mappend` (foldMap f r)
instance Traversable Tree where
traverse _ Empty = pure Empty
traverse f (Leaf x) = liftA Leaf (f x)
traverse f (Node l x r) = liftA3 Node (traverse f l) (f x) (traverse f r)
|
01e1e6a5442e2338eb33dbe6057b67541460aa559f242204706daff26f70db82 | metaocaml/ber-metaocaml | opttoploop.mli | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
open Format
(* Set the load paths, before running anything *)
val set_paths : unit -> unit
(* The interactive toplevel loop *)
val loop : formatter -> unit
(* Read and execute a script from the given file *)
val run_script : formatter -> string -> string array -> bool
(* true if successful, false if error *)
Interface with toplevel directives
type directive_fun =
| Directive_none of (unit -> unit)
| Directive_string of (string -> unit)
| Directive_int of (int -> unit)
| Directive_ident of (Longident.t -> unit)
| Directive_bool of (bool -> unit)
val directive_table : (string, directive_fun) Hashtbl.t
(* Table of known directives, with their execution function *)
val toplevel_env : Env.t ref
(* Typing environment for the toplevel *)
val initialize_toplevel_env : unit -> unit
Initialize the typing environment for the toplevel
val print_exception_outcome : formatter -> exn -> unit
(* Print an exception resulting from the evaluation of user code. *)
val execute_phrase : bool -> formatter -> Parsetree.toplevel_phrase -> bool
(* Execute the given toplevel phrase. Return [true] if the
phrase executed with no errors and [false] otherwise.
First bool says whether the values and types of the results
should be printed. Uncaught exceptions are always printed. *)
val preprocess_phrase :
formatter -> Parsetree.toplevel_phrase -> Parsetree.toplevel_phrase
Preprocess the given toplevel phrase using regular and ppx
preprocessors . Return the updated phrase .
preprocessors. Return the updated phrase. *)
val use_file : formatter -> string -> bool
val use_output : formatter -> string -> bool
val use_silently : formatter -> string -> bool
val mod_use_file : formatter -> string -> bool
(* Read and execute commands from a file.
[use_file] prints the types and values of the results.
[use_silently] does not print them.
[mod_use_file] wrap the file contents into a module. *)
val eval_module_path: Env.t -> Path.t -> Obj.t
val eval_value_path: Env.t -> Path.t -> Obj.t
val eval_extension_path: Env.t -> Path.t -> Obj.t
val eval_class_path: Env.t -> Path.t -> Obj.t
(* Return the toplevel object referred to by the given path *)
(* Printing of values *)
val print_value: Env.t -> Obj.t -> formatter -> Types.type_expr -> unit
val print_untyped_exception: formatter -> Obj.t -> unit
type ('a, 'b) gen_printer =
| Zero of 'b
| Succ of ('a -> ('a, 'b) gen_printer)
val install_printer :
Path.t -> Types.type_expr -> (formatter -> Obj.t -> unit) -> unit
val install_generic_printer :
Path.t -> Path.t ->
(int -> (int -> Obj.t -> Outcometree.out_value,
Obj.t -> Outcometree.out_value) gen_printer) -> unit
val install_generic_printer' :
Path.t -> Path.t -> (formatter -> Obj.t -> unit,
formatter -> Obj.t -> unit) gen_printer -> unit
val remove_printer : Path.t -> unit
val max_printer_depth: int ref
val max_printer_steps: int ref
(* Hooks for external parsers and printers *)
val parse_toplevel_phrase : (Lexing.lexbuf -> Parsetree.toplevel_phrase) ref
val parse_use_file : (Lexing.lexbuf -> Parsetree.toplevel_phrase list) ref
val print_location : formatter -> Location.t -> unit
val print_error : formatter -> Location.error -> unit
val print_warning : Location.t -> formatter -> Warnings.t -> unit
val input_name : string ref
val print_out_value :
(formatter -> Outcometree.out_value -> unit) ref
val print_out_type :
(formatter -> Outcometree.out_type -> unit) ref
val print_out_class_type :
(formatter -> Outcometree.out_class_type -> unit) ref
val print_out_module_type :
(formatter -> Outcometree.out_module_type -> unit) ref
val print_out_type_extension :
(formatter -> Outcometree.out_type_extension -> unit) ref
val print_out_sig_item :
(formatter -> Outcometree.out_sig_item -> unit) ref
val print_out_signature :
(formatter -> Outcometree.out_sig_item list -> unit) ref
val print_out_phrase :
(formatter -> Outcometree.out_phrase -> unit) ref
(* Hooks for external line editor *)
val read_interactive_input : (string -> bytes -> int -> int * bool) ref
(* Hooks *)
val toplevel_startup_hook : (unit -> unit) ref
type event = ..
type event +=
| Startup
| After_setup
Just after the setup , when the toplevel is ready to evaluate user
input . This happens before the toplevel has evaluated any kind of
user input , in particular this happens before loading the
[ .ocamlinit ] file .
input. This happens before the toplevel has evaluated any kind of
user input, in particular this happens before loading the
[.ocamlinit] file. *)
val add_hook : (event -> unit) -> unit
(* Add a function that will be called at key points of the toplevel
initialization process. *)
val run_hooks : event -> unit
(* Run all the registered hooks. *)
(* Misc *)
val override_sys_argv : string array -> unit
[ override_sys_argv args ] replaces the contents of [ Sys.argv ] by [ args ]
and reset [ Arg.current ] to [ 0 ] .
This is called by [ run_script ] so that [ Sys.argv ] represents
" script.ml args ... " instead of the full command line :
" ocamlrun unix.cma ... script.ml args ... " .
and reset [Arg.current] to [0].
This is called by [run_script] so that [Sys.argv] represents
"script.ml args..." instead of the full command line:
"ocamlrun unix.cma ... script.ml args...". *)
| null | https://raw.githubusercontent.com/metaocaml/ber-metaocaml/4992d1f87fc08ccb958817926cf9d1d739caf3a2/toplevel/opttoploop.mli | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
Set the load paths, before running anything
The interactive toplevel loop
Read and execute a script from the given file
true if successful, false if error
Table of known directives, with their execution function
Typing environment for the toplevel
Print an exception resulting from the evaluation of user code.
Execute the given toplevel phrase. Return [true] if the
phrase executed with no errors and [false] otherwise.
First bool says whether the values and types of the results
should be printed. Uncaught exceptions are always printed.
Read and execute commands from a file.
[use_file] prints the types and values of the results.
[use_silently] does not print them.
[mod_use_file] wrap the file contents into a module.
Return the toplevel object referred to by the given path
Printing of values
Hooks for external parsers and printers
Hooks for external line editor
Hooks
Add a function that will be called at key points of the toplevel
initialization process.
Run all the registered hooks.
Misc | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Format
val set_paths : unit -> unit
val loop : formatter -> unit
val run_script : formatter -> string -> string array -> bool
Interface with toplevel directives
type directive_fun =
| Directive_none of (unit -> unit)
| Directive_string of (string -> unit)
| Directive_int of (int -> unit)
| Directive_ident of (Longident.t -> unit)
| Directive_bool of (bool -> unit)
val directive_table : (string, directive_fun) Hashtbl.t
val toplevel_env : Env.t ref
val initialize_toplevel_env : unit -> unit
Initialize the typing environment for the toplevel
val print_exception_outcome : formatter -> exn -> unit
val execute_phrase : bool -> formatter -> Parsetree.toplevel_phrase -> bool
val preprocess_phrase :
formatter -> Parsetree.toplevel_phrase -> Parsetree.toplevel_phrase
Preprocess the given toplevel phrase using regular and ppx
preprocessors . Return the updated phrase .
preprocessors. Return the updated phrase. *)
val use_file : formatter -> string -> bool
val use_output : formatter -> string -> bool
val use_silently : formatter -> string -> bool
val mod_use_file : formatter -> string -> bool
val eval_module_path: Env.t -> Path.t -> Obj.t
val eval_value_path: Env.t -> Path.t -> Obj.t
val eval_extension_path: Env.t -> Path.t -> Obj.t
val eval_class_path: Env.t -> Path.t -> Obj.t
val print_value: Env.t -> Obj.t -> formatter -> Types.type_expr -> unit
val print_untyped_exception: formatter -> Obj.t -> unit
type ('a, 'b) gen_printer =
| Zero of 'b
| Succ of ('a -> ('a, 'b) gen_printer)
val install_printer :
Path.t -> Types.type_expr -> (formatter -> Obj.t -> unit) -> unit
val install_generic_printer :
Path.t -> Path.t ->
(int -> (int -> Obj.t -> Outcometree.out_value,
Obj.t -> Outcometree.out_value) gen_printer) -> unit
val install_generic_printer' :
Path.t -> Path.t -> (formatter -> Obj.t -> unit,
formatter -> Obj.t -> unit) gen_printer -> unit
val remove_printer : Path.t -> unit
val max_printer_depth: int ref
val max_printer_steps: int ref
val parse_toplevel_phrase : (Lexing.lexbuf -> Parsetree.toplevel_phrase) ref
val parse_use_file : (Lexing.lexbuf -> Parsetree.toplevel_phrase list) ref
val print_location : formatter -> Location.t -> unit
val print_error : formatter -> Location.error -> unit
val print_warning : Location.t -> formatter -> Warnings.t -> unit
val input_name : string ref
val print_out_value :
(formatter -> Outcometree.out_value -> unit) ref
val print_out_type :
(formatter -> Outcometree.out_type -> unit) ref
val print_out_class_type :
(formatter -> Outcometree.out_class_type -> unit) ref
val print_out_module_type :
(formatter -> Outcometree.out_module_type -> unit) ref
val print_out_type_extension :
(formatter -> Outcometree.out_type_extension -> unit) ref
val print_out_sig_item :
(formatter -> Outcometree.out_sig_item -> unit) ref
val print_out_signature :
(formatter -> Outcometree.out_sig_item list -> unit) ref
val print_out_phrase :
(formatter -> Outcometree.out_phrase -> unit) ref
val read_interactive_input : (string -> bytes -> int -> int * bool) ref
val toplevel_startup_hook : (unit -> unit) ref
type event = ..
type event +=
| Startup
| After_setup
Just after the setup , when the toplevel is ready to evaluate user
input . This happens before the toplevel has evaluated any kind of
user input , in particular this happens before loading the
[ .ocamlinit ] file .
input. This happens before the toplevel has evaluated any kind of
user input, in particular this happens before loading the
[.ocamlinit] file. *)
val add_hook : (event -> unit) -> unit
val run_hooks : event -> unit
val override_sys_argv : string array -> unit
[ override_sys_argv args ] replaces the contents of [ Sys.argv ] by [ args ]
and reset [ Arg.current ] to [ 0 ] .
This is called by [ run_script ] so that [ Sys.argv ] represents
" script.ml args ... " instead of the full command line :
" ocamlrun unix.cma ... script.ml args ... " .
and reset [Arg.current] to [0].
This is called by [run_script] so that [Sys.argv] represents
"script.ml args..." instead of the full command line:
"ocamlrun unix.cma ... script.ml args...". *)
|
a95f9b138518422666a367d86e2ea35d2e9f9bbf4d21245c1d953a797873715e | ThoughtWorksInc/clj-http-s3 | middleware.clj | (ns clj-http-s3.middleware
(:require [clj-http-s3.s3 :as s3]
[clj-time.format :as format-time]
[clj-time.local :as local-time]
[clojure.set :as set])
(:import [com.amazonaws.auth
DefaultAWSCredentialsProviderChain]))
(defn- request-date-time [] (format-time/unparse (format-time/formatters :rfc822) (local-time/local-now)))
(defn wrap-request-date
"Middleware that adds a header with the date of the request in rfc822 format"
[client]
(fn [req]
(client (assoc-in req [:headers "Date"] (request-date-time)))))
(defn- assoc-security-token [req]
(if-let [session-token (:session-token (:aws-credentials req))]
(assoc-in req
[:headers "x-amz-security-token"]
session-token)
req))
(defn- assoc-authorization-header [req]
(assoc-in req
[:headers "authorization"]
(s3/authorization-header-token
"GET"
(:access-key (:aws-credentials req))
(:secret-key (:aws-credentials req))
(req :uri)
(req :headers))))
(defn wrap-aws-s3-auth
"Middleware converting the :aws-credentials option into an AWS Authorization header."
[client]
(fn [req]
(if-let [aws-credentials (:aws-credentials req)]
(client (-> req
assoc-security-token
assoc-authorization-header
(dissoc :aws-credentials)))
(client req))))
(defn- provider->credentials [provider]
(-> (.getCredentials provider)
bean
(set/rename-keys
{:AWSAccessKeyId :access-key
:AWSSecretKey :secret-key
:sessionToken :session-token})
(dissoc :class)))
(def provider (DefaultAWSCredentialsProviderChain.))
(defn wrap-aws-credentials
"Middleware which provides :aws-credentials from the ProviderChain."
[client]
(fn [req]
(if-not (:aws-credentials req)
(-> req
(assoc :aws-credentials (provider->credentials provider))
client)
(client req))))
| null | https://raw.githubusercontent.com/ThoughtWorksInc/clj-http-s3/d5523b9448d3910978f09c709697adc167c9496c/src/clj_http_s3/middleware.clj | clojure | (ns clj-http-s3.middleware
(:require [clj-http-s3.s3 :as s3]
[clj-time.format :as format-time]
[clj-time.local :as local-time]
[clojure.set :as set])
(:import [com.amazonaws.auth
DefaultAWSCredentialsProviderChain]))
(defn- request-date-time [] (format-time/unparse (format-time/formatters :rfc822) (local-time/local-now)))
(defn wrap-request-date
"Middleware that adds a header with the date of the request in rfc822 format"
[client]
(fn [req]
(client (assoc-in req [:headers "Date"] (request-date-time)))))
(defn- assoc-security-token [req]
(if-let [session-token (:session-token (:aws-credentials req))]
(assoc-in req
[:headers "x-amz-security-token"]
session-token)
req))
(defn- assoc-authorization-header [req]
(assoc-in req
[:headers "authorization"]
(s3/authorization-header-token
"GET"
(:access-key (:aws-credentials req))
(:secret-key (:aws-credentials req))
(req :uri)
(req :headers))))
(defn wrap-aws-s3-auth
"Middleware converting the :aws-credentials option into an AWS Authorization header."
[client]
(fn [req]
(if-let [aws-credentials (:aws-credentials req)]
(client (-> req
assoc-security-token
assoc-authorization-header
(dissoc :aws-credentials)))
(client req))))
(defn- provider->credentials [provider]
(-> (.getCredentials provider)
bean
(set/rename-keys
{:AWSAccessKeyId :access-key
:AWSSecretKey :secret-key
:sessionToken :session-token})
(dissoc :class)))
(def provider (DefaultAWSCredentialsProviderChain.))
(defn wrap-aws-credentials
"Middleware which provides :aws-credentials from the ProviderChain."
[client]
(fn [req]
(if-not (:aws-credentials req)
(-> req
(assoc :aws-credentials (provider->credentials provider))
client)
(client req))))
|
|
fe0ce3b9dd9300ef202b5159e1e1aec5d76a0c3370ab35f59dba040ecdcfb3a7 | flavioc/cl-hurd | getcttyid.lisp |
(in-package :hurd)
(defcfun ("getcttyid" %getcttyid) port)
(defun getcttyid ()
"Get the CTTY port."
(%getcttyid))
| null | https://raw.githubusercontent.com/flavioc/cl-hurd/982232f47d1a0ff4df5fde2edad03b9df871470a/hurd/libc/getcttyid.lisp | lisp |
(in-package :hurd)
(defcfun ("getcttyid" %getcttyid) port)
(defun getcttyid ()
"Get the CTTY port."
(%getcttyid))
|
|
d26c79e4c8eb5856cbb50a482f7a5e827d9dff768458cf2fd297b128637fd83f | bi1yeu/generation-p | biology.clj | (ns generation-p.biology
(:require [clojure.data.generators :as data.gen]
[generation-p.model :as m]
[generation-p.social :as social]
[generation-p.image :as image]))
(def ^:const desired-generation-population-count 60)
(def ^:const ^:private crossover-mutation-rate 0.0001)
(def ^:const ^:private mutation-rate 0.0001)
;; width is desired dimensions of resultant square image -- the return val of
this function is a 1D vector of size width^2
(defn- random-chromosome
([]
(random-chromosome image/img-width))
([width]
(-> width
(Math/pow 2)
(take (repeatedly #(apply data.gen/one-of image/palette))))))
(defn spawn-random-individual []
{::m/id (java.util.UUID/randomUUID)
::m/social-id nil
::m/generation-num 0
::m/chromosome (random-chromosome)
::m/parent0-id nil
::m/parent1-id nil
::m/crossover-method nil
::m/crossover-params nil})
;; ==============================================================================
Selection
;; ==============================================================================
(defn- normalize-fitness [population]
(let [fitness-sum (reduce (fn [acc el] (+ (:fitness el) acc))
0
population)]
(pmap #(assoc %
:norm-fitness
(if (zero? fitness-sum)
0
(/
(:fitness %)
fitness-sum)))
population)))
(defn- accumulate-normalized-fitnesses [population]
(reduce (fn [acc el]
(if (empty? acc)
[(assoc el :acc-norm-fitness (:norm-fitness el))]
(conj acc (assoc el :acc-norm-fitness
(+ (:norm-fitness el)
(:acc-norm-fitness (last acc)))))))
[]
population))
(defn- choose-parent-from-population
([population]
(choose-parent-from-population population (data.gen/float)))
([population cutoff]
;; individuals in `population` should already have an accumulated normalized
;; fitness and be sorted in ascending order
note : there is an edge case where fewer than two individuals have any
;; fitness at all; in that case just randomly pick a parent
(let [num-fit (reduce (fn [acc el]
(if (> 0 (:acc-norm-fitness el))
(inc acc)
acc))
0
population)]
(if (< num-fit 2)
(apply data.gen/one-of population)
(->> population
(filter #(>= (:acc-norm-fitness %) cutoff))
first)))))
(defn matchmake [population]
;; Fitness proportionate selection
Given a population , choose two individuals to reproduce .
;; (genetic_algorithm)
(let [accumulated-normalized-fitnesses
(->> population
;; The fitness function is evaluated for each individual, providing
;; fitness values, which are then normalized.
(mapv #(assoc % :fitness (social/get-fitness %)))
normalize-fitness
;; The population is sorted by ascending fitness values.
(sort-by :norm-fitness)
;; Accumulated normalized fitness values are computed: the
;; accumulated fitness value of an individual is the sum of its own
;; fitness value plus the fitness values of all the previous
;; individuals
accumulate-normalized-fitnesses)
;; A random number R between 0 and 1 is chosen
The selected individual is the first one whose accumulated normalized
;; value is greater than or equal to R.
choose-parent #(choose-parent-from-population
accumulated-normalized-fitnesses)
parent0 (choose-parent)
Ensure parent1 is different from . One ca n't reproduce with
;; oneself, unfortunately.
parent1 (loop [p (choose-parent)]
(if (= (::m/id p) (::m/id parent0))
(recur (choose-parent))
p))]
[parent0 parent1]))
;; ==============================================================================
;; Mutation
;; ==============================================================================
(defn- maybe-mutate-pixel [pixel]
(if (< (data.gen/float) mutation-rate)
(let [remaining-colors (remove (partial = (vec pixel)) image/palette)]
(apply data.gen/one-of remaining-colors))
pixel))
(defn- mutate [chromosome]
(->> chromosome
(map maybe-mutate-pixel)))
;; ==============================================================================
Crossover
;; ==============================================================================
;; like k-point crossover, but instead of k points, (randomly) crossover after
;; runs of length n
(defn- crossover [{:keys [n]} parent0 parent1]
(let [parent0-partitioned (partition n parent0)
parent1-partitioned (partition n parent1)]
(apply
concat
(for [i (range (count parent0-partitioned))]
(data.gen/one-of
(nth parent0-partitioned i)
(nth parent1-partitioned i))))))
;; get the coords of n x n sized patches that evenly cover a width x height 2D
;; array, e.g.:
;;
( patches 2 4 4 )
;;
;; nw nw | ne ne
;; nw nw | ne ne
;; -------------
;; sw sw | se se
;; sw sw | se se
;;
( ( [ 0 0 ] [ 0 1 ] [ 1 0 ] [ 1 1 ] ) NW patch
( [ 0 2 ] [ 0 3 ] [ 1 2 ] [ 1 3 ] ) NE patch
( [ 2 0 ] [ 2 1 ] [ 3 0 ] [ 3 1 ] ) SW patch
( [ 2 2 ] [ 2 3 ] [ 3 2 ] [ 3 3 ] ) ) SE patch
(defn- patches [n width height]
(for [patch-indices-i (partition n (range height))
patch-indices-j (partition n (range width))]
(for [i patch-indices-i
j patch-indices-j]
[i j])))
(def patches-memo (memoize patches))
(defn- reshape [width flattened-arr]
(->> flattened-arr
(partition width)
(pmap vec)
vec))
TODO refactor ?
;; This is a specialized crossover approach, which treats 2D patches of size nxn
as genes in the chromosome / individual . Given two parents , these patches are
;; randomly exchanged to form a new individual.
;; e.g., if n=1 and each digit in the grid represents a pixel in the image
0 0 0
0 0 0
0 0 0
;; parent1
;; 1 1 1
;; 1 1 1
;; 1 1 1
;; possible child
0 1 0
;; 1 1 0
1 0 1
(defn- patch-crossover
[{:keys [n]} parent0 parent1]
;; loop over the reshaped vector, patch by patch, taking a given patch from
;; either parent randomly
;; note: vector dimensions ideally are evenly divided by n
: assumes square image
(let [width (-> parent0
count
Math/sqrt
int)
parent0-2d (reshape width parent0)
parent1-2d (reshape width parent1)]
(apply
concat
(loop [[patch & rest-patches] (patches-memo n
(count (first parent0-2d))
(count parent0-2d))
img parent0-2d]
(if patch
(recur
rest-patches
(let [src-img (data.gen/one-of parent0-2d parent1-2d)]
(reduce
(fn [res-img pixel]
(->> (get-in src-img pixel)
(assoc-in res-img pixel)))
img
patch)))
img)))))
(defn- random-crossover-method []
(data.gen/one-of ::m/crossover ::m/patch-crossover))
(defn- crossover-n-vals []
(let [vec-width (-> image/img-width
(Math/pow 2)
int)
half-vec-width (int (/ vec-width 2))]
(->> (range 1 (inc half-vec-width))
(filter #(zero? (mod vec-width %))))))
(def ^:private crossover-n-vals-memo (memoize crossover-n-vals))
(defn- patch-crossover-n-vals []
(let [half-width (/ image/img-width 2)]
(->> (range 1 (inc half-width))
(filter #(zero? (mod image/img-width %))))))
(def ^:private patch-crossover-n-vals-memo (memoize patch-crossover-n-vals))
(defn- random-crossover-params [crossover-method]
(case crossover-method
::m/crossover
{:n (apply data.gen/one-of (crossover-n-vals-memo))}
::m/patch-crossover
{:n (apply data.gen/one-of (patch-crossover-n-vals-memo))}))
(defn- crossover-method->fn [crossover-method crossover-params]
(case crossover-method
::m/crossover
(partial crossover crossover-params)
::m/patch-crossover
(partial patch-crossover crossover-params)))
(defn breed [parent0 parent1]
;; nsfw
(let [crossover-parent (data.gen/one-of parent0 parent1)
mutate-crossover? (< (data.gen/float) crossover-mutation-rate)
crossover-method (or
(and (not mutate-crossover?)
(::m/crossover-method crossover-parent))
(random-crossover-method))
crossover-params (or
(and (not mutate-crossover?)
(::m/crossover-params crossover-parent))
(random-crossover-params crossover-method))
crossover-fn (crossover-method->fn crossover-method crossover-params)
child-chromosome (->> [(::m/chromosome parent0) (::m/chromosome parent1)]
(apply crossover-fn)
mutate)]
(merge (spawn-random-individual)
{::m/generation-num (inc (::m/generation-num parent0))
::m/chromosome child-chromosome
::m/parent0-id (::m/id parent0)
::m/parent1-id (::m/id parent1)
::m/crossover-method crossover-method
::m/crossover-params crossover-params})))
| null | https://raw.githubusercontent.com/bi1yeu/generation-p/1a00cd2138a77967dc72fc4315c3d50878580fe7/src/generation_p/biology.clj | clojure | width is desired dimensions of resultant square image -- the return val of
==============================================================================
==============================================================================
individuals in `population` should already have an accumulated normalized
fitness and be sorted in ascending order
fitness at all; in that case just randomly pick a parent
Fitness proportionate selection
(genetic_algorithm)
The fitness function is evaluated for each individual, providing
fitness values, which are then normalized.
The population is sorted by ascending fitness values.
Accumulated normalized fitness values are computed: the
accumulated fitness value of an individual is the sum of its own
fitness value plus the fitness values of all the previous
individuals
A random number R between 0 and 1 is chosen
value is greater than or equal to R.
oneself, unfortunately.
==============================================================================
Mutation
==============================================================================
==============================================================================
==============================================================================
like k-point crossover, but instead of k points, (randomly) crossover after
runs of length n
get the coords of n x n sized patches that evenly cover a width x height 2D
array, e.g.:
nw nw | ne ne
nw nw | ne ne
-------------
sw sw | se se
sw sw | se se
This is a specialized crossover approach, which treats 2D patches of size nxn
randomly exchanged to form a new individual.
e.g., if n=1 and each digit in the grid represents a pixel in the image
parent1
1 1 1
1 1 1
1 1 1
possible child
1 1 0
loop over the reshaped vector, patch by patch, taking a given patch from
either parent randomly
note: vector dimensions ideally are evenly divided by n
nsfw | (ns generation-p.biology
(:require [clojure.data.generators :as data.gen]
[generation-p.model :as m]
[generation-p.social :as social]
[generation-p.image :as image]))
(def ^:const desired-generation-population-count 60)
(def ^:const ^:private crossover-mutation-rate 0.0001)
(def ^:const ^:private mutation-rate 0.0001)
this function is a 1D vector of size width^2
(defn- random-chromosome
([]
(random-chromosome image/img-width))
([width]
(-> width
(Math/pow 2)
(take (repeatedly #(apply data.gen/one-of image/palette))))))
(defn spawn-random-individual []
{::m/id (java.util.UUID/randomUUID)
::m/social-id nil
::m/generation-num 0
::m/chromosome (random-chromosome)
::m/parent0-id nil
::m/parent1-id nil
::m/crossover-method nil
::m/crossover-params nil})
Selection
(defn- normalize-fitness [population]
(let [fitness-sum (reduce (fn [acc el] (+ (:fitness el) acc))
0
population)]
(pmap #(assoc %
:norm-fitness
(if (zero? fitness-sum)
0
(/
(:fitness %)
fitness-sum)))
population)))
(defn- accumulate-normalized-fitnesses [population]
(reduce (fn [acc el]
(if (empty? acc)
[(assoc el :acc-norm-fitness (:norm-fitness el))]
(conj acc (assoc el :acc-norm-fitness
(+ (:norm-fitness el)
(:acc-norm-fitness (last acc)))))))
[]
population))
(defn- choose-parent-from-population
([population]
(choose-parent-from-population population (data.gen/float)))
([population cutoff]
note : there is an edge case where fewer than two individuals have any
(let [num-fit (reduce (fn [acc el]
(if (> 0 (:acc-norm-fitness el))
(inc acc)
acc))
0
population)]
(if (< num-fit 2)
(apply data.gen/one-of population)
(->> population
(filter #(>= (:acc-norm-fitness %) cutoff))
first)))))
(defn matchmake [population]
Given a population , choose two individuals to reproduce .
(let [accumulated-normalized-fitnesses
(->> population
(mapv #(assoc % :fitness (social/get-fitness %)))
normalize-fitness
(sort-by :norm-fitness)
accumulate-normalized-fitnesses)
The selected individual is the first one whose accumulated normalized
choose-parent #(choose-parent-from-population
accumulated-normalized-fitnesses)
parent0 (choose-parent)
Ensure parent1 is different from . One ca n't reproduce with
parent1 (loop [p (choose-parent)]
(if (= (::m/id p) (::m/id parent0))
(recur (choose-parent))
p))]
[parent0 parent1]))
(defn- maybe-mutate-pixel [pixel]
(if (< (data.gen/float) mutation-rate)
(let [remaining-colors (remove (partial = (vec pixel)) image/palette)]
(apply data.gen/one-of remaining-colors))
pixel))
(defn- mutate [chromosome]
(->> chromosome
(map maybe-mutate-pixel)))
Crossover
(defn- crossover [{:keys [n]} parent0 parent1]
(let [parent0-partitioned (partition n parent0)
parent1-partitioned (partition n parent1)]
(apply
concat
(for [i (range (count parent0-partitioned))]
(data.gen/one-of
(nth parent0-partitioned i)
(nth parent1-partitioned i))))))
( patches 2 4 4 )
( ( [ 0 0 ] [ 0 1 ] [ 1 0 ] [ 1 1 ] ) NW patch
( [ 0 2 ] [ 0 3 ] [ 1 2 ] [ 1 3 ] ) NE patch
( [ 2 0 ] [ 2 1 ] [ 3 0 ] [ 3 1 ] ) SW patch
( [ 2 2 ] [ 2 3 ] [ 3 2 ] [ 3 3 ] ) ) SE patch
(defn- patches [n width height]
(for [patch-indices-i (partition n (range height))
patch-indices-j (partition n (range width))]
(for [i patch-indices-i
j patch-indices-j]
[i j])))
(def patches-memo (memoize patches))
(defn- reshape [width flattened-arr]
(->> flattened-arr
(partition width)
(pmap vec)
vec))
TODO refactor ?
as genes in the chromosome / individual . Given two parents , these patches are
0 0 0
0 0 0
0 0 0
0 1 0
1 0 1
(defn- patch-crossover
[{:keys [n]} parent0 parent1]
: assumes square image
(let [width (-> parent0
count
Math/sqrt
int)
parent0-2d (reshape width parent0)
parent1-2d (reshape width parent1)]
(apply
concat
(loop [[patch & rest-patches] (patches-memo n
(count (first parent0-2d))
(count parent0-2d))
img parent0-2d]
(if patch
(recur
rest-patches
(let [src-img (data.gen/one-of parent0-2d parent1-2d)]
(reduce
(fn [res-img pixel]
(->> (get-in src-img pixel)
(assoc-in res-img pixel)))
img
patch)))
img)))))
(defn- random-crossover-method []
(data.gen/one-of ::m/crossover ::m/patch-crossover))
(defn- crossover-n-vals []
(let [vec-width (-> image/img-width
(Math/pow 2)
int)
half-vec-width (int (/ vec-width 2))]
(->> (range 1 (inc half-vec-width))
(filter #(zero? (mod vec-width %))))))
(def ^:private crossover-n-vals-memo (memoize crossover-n-vals))
(defn- patch-crossover-n-vals []
(let [half-width (/ image/img-width 2)]
(->> (range 1 (inc half-width))
(filter #(zero? (mod image/img-width %))))))
(def ^:private patch-crossover-n-vals-memo (memoize patch-crossover-n-vals))
(defn- random-crossover-params [crossover-method]
(case crossover-method
::m/crossover
{:n (apply data.gen/one-of (crossover-n-vals-memo))}
::m/patch-crossover
{:n (apply data.gen/one-of (patch-crossover-n-vals-memo))}))
(defn- crossover-method->fn [crossover-method crossover-params]
(case crossover-method
::m/crossover
(partial crossover crossover-params)
::m/patch-crossover
(partial patch-crossover crossover-params)))
(defn breed [parent0 parent1]
(let [crossover-parent (data.gen/one-of parent0 parent1)
mutate-crossover? (< (data.gen/float) crossover-mutation-rate)
crossover-method (or
(and (not mutate-crossover?)
(::m/crossover-method crossover-parent))
(random-crossover-method))
crossover-params (or
(and (not mutate-crossover?)
(::m/crossover-params crossover-parent))
(random-crossover-params crossover-method))
crossover-fn (crossover-method->fn crossover-method crossover-params)
child-chromosome (->> [(::m/chromosome parent0) (::m/chromosome parent1)]
(apply crossover-fn)
mutate)]
(merge (spawn-random-individual)
{::m/generation-num (inc (::m/generation-num parent0))
::m/chromosome child-chromosome
::m/parent0-id (::m/id parent0)
::m/parent1-id (::m/id parent1)
::m/crossover-method crossover-method
::m/crossover-params crossover-params})))
|
3a6bc4af98c10b26130612028155d9ed0b519e426cefd98dbb51dffcb416e1d0 | Mathnerd314/stroscot | Resource.hs | # LANGUAGE LambdaCase , BlockArguments , ScopedTypeVariables #
# LANGUAGE RecordWildCards , ViewPatterns #
module Resource where
import Data.Function
import Data.List.Extra
import Data.Maybe(fromJust)
import Unsafe.Coerce
import Control.Concurrent.Extra
import Control.Exception.Extra
import Data.Tuple.Extra
import Data.IORef
import Control.Monad.Extra
import Pool
import Control.Monad.IO.Class
import System.Clock
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.Heap as Heap
import Data.Map(Map)
import Data.Set(Set)
import Data.Heap(Heap)
import GHC.Exts(Any)
import Types
import Control.Monad.State
import Control.Monad.IO.Unlift
import GHC.Stack
type Seconds = Integer
| A Double with its instance flipped , so that higher priorities are pulled first from the minimum - biased priority queue
newtype Priority = Priority Double
deriving (Eq)
instance Ord Priority where
compare (Priority x) (Priority y) = case compare x y of
LT -> GT
GT -> LT
EQ -> EQ
(Priority x) < (Priority y) = x > y
(Priority x) <= (Priority y) = x >= y
(Priority x) >= (Priority y) = x <= y
(Priority x) > (Priority y) = x < y
-- In shake: Exception > Resume > Start > Batch > Deprioritize
-- batch runs with Batch
-- * this is terribly non-deterministic, as the batches change each run depending on which files are modified
-- * better is to collect the files in a list and then split the list into batches
-- * if the file list is generated sequentially, then the batches can be spawned as soon as each is complete
-- * the behavior on rebuild can be minimized with a complex rule that disentangles the dependencies
-- initial tasks and building a new key uses Start
-- parallel runs tasks with Resume
reschedule runs with
the stuff after a callCC runs with Exception or Resume depending on whether the actions threw an exception
the logic seems to be that resumed resources may be holding resources so finishing them first is better
-- Cot's scheduler is different enough that benchmarking it again seems necessary
type PoolPriority = (Priority, Int, Int) -- ^ priority, random position, sequential unique ID
how our threading model works :
let 's say 4 threads max
initial task A starts , acquires 1 thread
A spawns 7 tasks BCDEFGH using 1 thread
BCD acquire threads and spawn with addPool
EFGH fail to acquire and add themselves to the queue
A finishes and its thread executes the highest - priority among EFGH ( say EFGH is the order )
B finishes and its thread executes F
C finishes and its thread executes G
D finishes and its thread executes H
so we 've had 4 threads running continuously
then all threads finish up and quit .
how our threading model works:
let's say 4 threads max
initial task A starts, acquires 1 thread
A spawns 7 tasks BCDEFGH using 1 thread
BCD acquire threads and spawn with addPool
EFGH fail to acquire and add themselves to the queue
A finishes and its thread executes the highest-priority among EFGH (say EFGH is the order)
B finishes and its thread executes F
C finishes and its thread executes G
D finishes and its thread executes H
so we've had 4 threads running continuously
then all threads finish up and quit.
-}
| A type representing a limited resource which the build system should conserve . ' ' and ' newThrottle ' create resources . These resources are used with ' withResource ' .
data Resource = Resource
{resourceOrd :: !Int
^ Key used for Eq / Ord operations .
,resourceName :: !String
-- ^ String used for Show / error messages
,resourceI :: !ResourceI
}
instance Show Resource where
show Resource{..} = "<Resource " ++ resourceName ++ " #" ++ show resourceOrd ++ ">"
instance Eq Resource where (==) = (==) `on` resourceOrd
instance Ord Resource where compare = compare `on` resourceOrd
data ResourceI
= Finite { resourceVarF :: !(Var (ResourceVar ())), finiteCapacity :: !Int }
| Throttle { resourceVarT :: !(Var (ResourceVar (Seconds,Bool))), -- ^ var extra is last_reset, waiter thread running
throttleMax :: !Int, throttleGain :: !Int, throttlePeriod :: !Seconds }
-- maximum tokens, tokens per period, period length
isFinite :: Resource -> Bool
isFinite r | Finite{} <- resourceI r = True
| otherwise = False
toAnyFinite :: ResourceVar () -> Any
toAnyFinite = unsafeCoerce
fromAnyFinite :: Any -> ResourceVar ()
fromAnyFinite = unsafeCoerce
toAnyThrottle :: ResourceVar (Seconds,Bool) -> Any
toAnyThrottle = unsafeCoerce
fromAnyThrottle :: Any -> ResourceVar (Seconds,Bool)
fromAnyThrottle = unsafeCoerce
-- | Priority, how much the action wants, and the action when it is allocated to them
type E = Heap.Entry PoolPriority (Map Resource Int, IO ())
wanted :: E -> Map Resource Int
wanted e = fst . Heap.payload $ e
action :: E -> IO ()
action e = snd . Heap.payload $ e
priority :: E -> PoolPriority
priority e = Heap.priority e
data ResourceVar f = ResourceVar {
waiting :: !(Set.Set E),
-- ^ Each resource is equipped with a priority queue that stores
-- tasks which are waiting for the resource.
-- We use a Set though as its split operation is more useful.
available :: !Int,
extra :: !f
}
-- | Create a resource with a given name and availability type.
newResource :: String -> ResourceI -> M Resource
newResource s i = do
key <- resourceId
pure $ Resource key s i
newResourceVar :: Int -> f -> IO (Var (ResourceVar f))
newResourceVar mx e = newVar $ ResourceVar Set.empty mx e
-- | Creates a finite resource, stopping too many actions running
-- simultaneously. The capacity is the maximum number of units that may be used concurrently.
newFinite :: String -> Int -> M Resource
newFinite name mx = do
when (mx <= 0) $
liftIO . errorIO $ "You cannot create a finite resource named " ++ name ++ " with a non-positive capacity, you used " ++ show mx
var <- liftIO $ newResourceVar mx ()
newResource name (Finite var mx)
-- | Creates a throttled resource, stopping too many actions running
-- over a short time period.
newThrottle :: String -> Int -> Int -> Seconds -> M Resource
newThrottle name count gain period = do
when (count <= 0) $
liftIO . errorIO $ "You cannot create a throttle named " ++ name ++ " with a non-positive quantity, you used " ++ show count
t <- liftIO now
var <- liftIO $ newResourceVar count (t,False)
newResource name (Throttle var count gain period)
-- | Checks for out-of-bounds resource requests
checkError (r,want) =
case resourceI r of
Finite v cap
| want <= 0 -> errorIO $ "You cannot acquire a non-positive quantity of " ++ show r ++ ", requested " ++ show want
| want > cap -> errorIO $ "You cannot acquire more than " ++ show cap ++ " of " ++ show r ++ ", requested " ++ show want
| otherwise -> pure ()
Throttle var count gain period
| want <= 0 -> errorIO $ "You cannot acquire a non-positive quantity of " ++ show r ++ ", requested " ++ show want
| want > count -> errorIO $ "You cannot acquire more than " ++ show count ++ " of " ++ show r ++ ", requested " ++ show want
| otherwise -> pure ()
-- | Locks some resources. The resources must be in ascending order to prevent deadlocks, and similarly calls cannot be nested.
withVarsT :: [Resource] -> StateT (Map Resource Any) IO a -> StateT (Map Resource Any) IO a
withVarsT [] f = f
withVarsT (r:rs) f = do
mp <- get
case r `Map.member` mp of
True -> withVarsT rs f
False -> StateT $ \mp_o -> case resourceI r of
Finite var cap -> modifyVar var $ \x -> do
let mp = Map.insert r (toAnyFinite x) mp_o
(a, mp') <- runStateT (withVarsT rs f) mp
pure (fromAnyFinite . fromJust $ Map.lookup r mp', (a, Map.delete r mp'))
Throttle var count gain period -> modifyVar var $ \x -> do
let mp = Map.insert r (toAnyThrottle x) mp_o
(a, mp') <- runStateT (withVarsT rs f) mp
pure (fromAnyThrottle . fromJust $ Map.lookup r mp', (a, Map.delete r mp'))
withVars :: [Resource] -> StateT (Map Resource Any) IO a -> IO a
withVars rs f = evalStateT (withVarsT rs f) Map.empty
lookupVar :: Resource -> StateT (Map Resource Any) IO Any
lookupVar r = do
mp <- get
pure (fromJust $ Map.lookup r mp)
-- | Run an action which uses some multiset of resources. If the resources are available the action is run in the thread pool,
-- otherwise it is added to the waiting queue with the given priority. In either case the function returns quickly.
-- The action should only do "productive" work, otherwise the resource may be held while the action is waiting on something.
-- The Action monad implements an acquire-work-release-block-acquire pattern that releases resources while blocking.
spawnWithResource :: Map Resource Int -> Priority -> IO () -> M ()
spawnWithResource mp prio act = do
pool <- globalPool
spawnWithResourceInner (addPool pool) mp prio act
-- | Similar to 'withResource' but runs the worker directly.
-- Used for saving a thread when running the initial task.
spawnWithResourceWorker :: Map Resource Int -> Priority -> IO () -> M ()
spawnWithResourceWorker = spawnWithResourceInner id
| inner method to share code between withResource and withResourceWorker
spawnWithResourceInner :: (IO () -> IO ()) -> Map Resource Int -> Priority -> IO () -> M ()
spawnWithResourceInner spawn wants priority act = do
pool <- globalPool
mapM_ (liftIO . checkError) (Map.toList wants)
i <- resourceRand
tid <- taskId
let e = Heap.Entry (priority, i, tid) (wants,act)
acquireSucceeded <- liftIO $ acquire pool e
when acquireSucceeded $ liftIO $ spawn $ act `finally` release pool wants
-- | Check if ent can obtain sufficient resources.
-- It may not consume the resources of any higher-priority tasks,
-- but can preempt any lower-priority requests waiting for resources.
canPreempt :: Resource -> E -> Int -> Int -> Set E -> Bool
canPreempt r ent want available queue | want > available = False
canPreempt r ent want available queue = do
let lt = Set.takeWhileAntitone (<= ent) queue
let f _ Nothing = Nothing
f e b = do
avail <- b
let avail' = avail - (fromJust . Map.lookup r $ wanted e)
pureIf (avail' >= 0) avail'
case Set.foldr f (Just (available - want)) lt of
Nothing -> False
Just _ -> True
canPreemptM :: Resource -> E -> Int -> StateT (Map Resource Any) IO Bool
canPreemptM r ent want = do
v <- lookupVar r
pure $ case resourceI r of
Finite{} -> let ResourceVar{..} = fromAnyFinite v in canPreempt r ent want available waiting
Throttle{} -> let ResourceVar{..} = fromAnyThrottle v in canPreempt r ent want available waiting
-- don't bother with checking the throttle period,
-- the waiter thread will handle it if necessary as soon as it is scheduled
newtype AllM m = AllM (m Bool)
instance Monad m => Semigroup (AllM m) where
AllM x <> AllM y = AllM $ do
b <- x
case b of
False -> pure False
True -> y
instance Monad m => Monoid (AllM m) where
mempty = AllM $ pure True
-- | Checks if the task is ready to run (can obtain its wanted resources).
checkPreempt :: E -> StateT (Map Resource Any) IO Bool
checkPreempt ent = case Map.foldMapWithKey (\r want -> AllM $ canPreemptM r ent want) (wanted ent) of
AllM x -> x
-- | Checks if the task is ready to run (can obtain its wanted resources).
-- If so, the resources are reserved and True is returned.
-- Otherwise the task is inserted into each resource's queue and False is returned.
-- This action locks all of the relevant resource queues while running.
acquire :: Pool -> E -> IO Bool
acquire pool ent = let rs = wanted ent in withVars (Map.keys rs) $ do
acquireSucceeded <- checkPreempt ent
forM_ (Map.toList rs) $ \(r,want) -> do
v <- lookupVar r
updated <- case resourceI r of
Finite{} -> do
let x@ResourceVar{..} = fromAnyFinite v
pure . toAnyFinite $
if acquireSucceeded then
x{available = available - want}
else x{waiting = Set.insert ent waiting}
Throttle{..} -> do
let x@ResourceVar{..} = fromAnyThrottle v
toAnyThrottle <$>
if acquireSucceeded then
pure x{available = available - want}
else do
-- spawn thread to run waiting tasks when limit resets, unless already spawned
let (last_reset,running) = extra
liftIO $ unless running $ do
t <- now
addPool pool $ do
sleep (throttlePeriod - (t - last_reset))
recheckThrottle pool r
pure x{waiting = Set.insert ent waiting,extra=(last_reset,True)}
modify $ Map.insert r updated
pure acquireSucceeded
-- Determine if there are any tasks that can be newly run (freed from the queue) due to released units.
example : queue [ 3,2,1,4 ] going from 4 to 7 units available .
the 3 task is runnable but not newly , 2,1 are newly runnable , 4 is not runnable ( insufficient units ) .
newlyRunnable :: Resource -> Int -> Int -> [E] -> [E]
newlyRunnable r newAvailable oldAvailable queue
| newAvailable <= oldAvailable = []
| newAvailable <= 0 = []
| otherwise =
case queue of
[] -> [] -- no more tasks to check
e:es -> let want = fromJust . Map.lookup r $ wanted e in
if want <= oldAvailable then
-- resource runnable but blocked on something else, not newly runnable
newlyRunnable r (newAvailable - want) (oldAvailable - want) es
else if want <= newAvailable then
-- newly runnable
e : newlyRunnable r (newAvailable - want) (oldAvailable - want) es
else
-- not runnable at all, all further resources blocked
[]
mergePairs :: Ord a => [[a]] -> [[a]]
mergePairs [] = []
mergePairs [ls] = [ls]
mergePairs (x:y:ls) = (merge x y):mergePairs ls
mergeLists :: Ord a => [[a]] -> [a]
mergeLists [] = []
mergeLists [x] = x
mergeLists ls = mergeLists $ mergePairs ls
-- | Release the resources held after running a task. (Only relevant to finite resources)
release pool rs = do
requestsToCheckL <- withVars (Map.keys rs) $ forM (Map.toList rs) $ \(r,want) -> do
case resourceI r of
Finite{} -> do
v <- lookupVar r
let x@ResourceVar{..} = fromAnyFinite v
modify $ Map.insert r (toAnyFinite $ x{available =available + want})
pure $ newlyRunnable r (available+want) available (Set.toAscList waiting)
Throttle{} -> pure [] -- handled in releaseThrottle on the waiter thread
let requestsToCheck = mergeLists requestsToCheckL
reqs <- recheckRequests requestsToCheck pure
case reqs of
[] -> pure ()
x:xs -> do
forM_ xs $ \x -> addPool pool $ action x `finally` release pool (wanted x)
action x `finally` release pool (wanted x)
-- | Check if the given tasks are ready to execute.
-- The ones that ready are removed from the resource queues and returned, and the resources are reserved.
-- The rest are left in the queues.
-- f is used to run an action with all the resources held
recheckRequests :: [E] -> ([E] -> StateT (Map Resource Any) IO a) -> IO a
recheckRequests requestsToCheck f = do
let allResources = Set.toAscList . Set.unions $ map (Map.keysSet . fst . Heap.payload) requestsToCheck
withVars allResources $ foldr tryTake (pure []) requestsToCheck >>= f
where
tryTake :: E -> StateT (Map Resource Any) IO [E] -> StateT (Map Resource Any) IO [E]
tryTake request rest = do
acquireSucceeded <- checkPreempt request
if not acquireSucceeded then rest else do
forM_ (Map.toList $ wanted request) $ \(r,want) -> do
v <- lookupVar r
updated <- case resourceI r of
Finite{} -> do
let x@ResourceVar{..} = fromAnyFinite v
pure . toAnyFinite $ x{available = available - want, waiting = Set.delete request waiting}
Throttle{} -> do
let x@ResourceVar{..} = fromAnyThrottle v
pure . toAnyThrottle $ x{available = available - want, waiting = Set.delete request waiting}
modify $ Map.insert r updated
(request :) <$> rest
recheckThrottle :: Pool -> Resource -> IO ()
recheckThrottle pool r = do
let Throttle{..} = resourceI r
(requestsToCheck, nextCheckWait) <- modifyVar resourceVarT $
\v@ResourceVar{..} -> do
let (last_reset,running) = extra
assertIO running
n <- now
let periods_elapsed = fromIntegral $ (n - last_reset) `div` throttlePeriod
let newAvailable = throttleMax `min` (available + periods_elapsed * throttleGain)
let nR = newlyRunnable r newAvailable available (Set.toAscList waiting)
let (var,nextCheckWait) = if periods_elapsed > 0
then
(v{available=newAvailable,extra=(n,True)}, throttlePeriod)
else
(v, last_reset + throttlePeriod - n)
pure (v,(nR,nextCheckWait))
(reqs, running) <- recheckRequests requestsToCheck $ \reqs -> do
x@ResourceVar{extra=(last_reset,True),..} <- fromAnyThrottle <$> lookupVar r
let running = not $ Set.null waiting
modify $ Map.insert r (toAnyThrottle $ x{extra=(last_reset,running)})
pure (reqs,running)
forM_ reqs $ \x -> addPool pool $ action x `finally` release pool (wanted x)
if running then do
sleep nextCheckWait
recheckThrottle pool r
else
pure ()
---------------------------------------------------------------------
THROTTLE TIMING HELPERS
-- number from /-/issues/7087
-- in microseconds
maxDelay :: Int
maxDelay = ((maxBound :: Int) `div` 10^7 - 1) * 10^4
maxDelayT :: Seconds
maxDelayT = fromIntegral maxDelay * 1000
-- | Sleep for the given number of nanoseconds
sleep :: Seconds -> IO ()
sleep s
threadDelay 0 does putMVar takeMvar , basically nothing
| s > maxDelayT = do
threadDelay maxDelay
sleep $ s - maxDelayT
| s < 1000 = yield -- TODO: is this a short delay?
| otherwise = threadDelay (fromIntegral $ s `div` 1000)
now :: IO Seconds
now = toNanoSecs <$> getTime Monotonic
-- | An 'IO' action that when evaluated calls 'assert' in the 'IO' monad, which throws an 'AssertionFailed' exception if the argument is 'False'.
--
> catch ( assertIO True > > pure 1 ) ( \(x : : AssertionFailed ) - > pure 2 ) = = pure 1
> catch ( assertIO False > > pure 1 ) ( \(x : : AssertionFailed ) - > pure 2 ) = = pure 2
> seq ( assertIO False ) ( print 1 ) = = print 1
assertIO :: Partial => Bool -> IO ()
assertIO x = withFrozenCallStack $ evaluate $ assert x () | null | https://raw.githubusercontent.com/Mathnerd314/stroscot/47638b8609bf6b7539e187120f7d8be3438893bf/src/build/Resource.hs | haskell | In shake: Exception > Resume > Start > Batch > Deprioritize
batch runs with Batch
* this is terribly non-deterministic, as the batches change each run depending on which files are modified
* better is to collect the files in a list and then split the list into batches
* if the file list is generated sequentially, then the batches can be spawned as soon as each is complete
* the behavior on rebuild can be minimized with a complex rule that disentangles the dependencies
initial tasks and building a new key uses Start
parallel runs tasks with Resume
Cot's scheduler is different enough that benchmarking it again seems necessary
^ priority, random position, sequential unique ID
^ String used for Show / error messages
^ var extra is last_reset, waiter thread running
maximum tokens, tokens per period, period length
| Priority, how much the action wants, and the action when it is allocated to them
^ Each resource is equipped with a priority queue that stores
tasks which are waiting for the resource.
We use a Set though as its split operation is more useful.
| Create a resource with a given name and availability type.
| Creates a finite resource, stopping too many actions running
simultaneously. The capacity is the maximum number of units that may be used concurrently.
| Creates a throttled resource, stopping too many actions running
over a short time period.
| Checks for out-of-bounds resource requests
| Locks some resources. The resources must be in ascending order to prevent deadlocks, and similarly calls cannot be nested.
| Run an action which uses some multiset of resources. If the resources are available the action is run in the thread pool,
otherwise it is added to the waiting queue with the given priority. In either case the function returns quickly.
The action should only do "productive" work, otherwise the resource may be held while the action is waiting on something.
The Action monad implements an acquire-work-release-block-acquire pattern that releases resources while blocking.
| Similar to 'withResource' but runs the worker directly.
Used for saving a thread when running the initial task.
| Check if ent can obtain sufficient resources.
It may not consume the resources of any higher-priority tasks,
but can preempt any lower-priority requests waiting for resources.
don't bother with checking the throttle period,
the waiter thread will handle it if necessary as soon as it is scheduled
| Checks if the task is ready to run (can obtain its wanted resources).
| Checks if the task is ready to run (can obtain its wanted resources).
If so, the resources are reserved and True is returned.
Otherwise the task is inserted into each resource's queue and False is returned.
This action locks all of the relevant resource queues while running.
spawn thread to run waiting tasks when limit resets, unless already spawned
Determine if there are any tasks that can be newly run (freed from the queue) due to released units.
no more tasks to check
resource runnable but blocked on something else, not newly runnable
newly runnable
not runnable at all, all further resources blocked
| Release the resources held after running a task. (Only relevant to finite resources)
handled in releaseThrottle on the waiter thread
| Check if the given tasks are ready to execute.
The ones that ready are removed from the resource queues and returned, and the resources are reserved.
The rest are left in the queues.
f is used to run an action with all the resources held
-------------------------------------------------------------------
number from /-/issues/7087
in microseconds
| Sleep for the given number of nanoseconds
TODO: is this a short delay?
| An 'IO' action that when evaluated calls 'assert' in the 'IO' monad, which throws an 'AssertionFailed' exception if the argument is 'False'.
| # LANGUAGE LambdaCase , BlockArguments , ScopedTypeVariables #
# LANGUAGE RecordWildCards , ViewPatterns #
module Resource where
import Data.Function
import Data.List.Extra
import Data.Maybe(fromJust)
import Unsafe.Coerce
import Control.Concurrent.Extra
import Control.Exception.Extra
import Data.Tuple.Extra
import Data.IORef
import Control.Monad.Extra
import Pool
import Control.Monad.IO.Class
import System.Clock
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.Heap as Heap
import Data.Map(Map)
import Data.Set(Set)
import Data.Heap(Heap)
import GHC.Exts(Any)
import Types
import Control.Monad.State
import Control.Monad.IO.Unlift
import GHC.Stack
type Seconds = Integer
| A Double with its instance flipped , so that higher priorities are pulled first from the minimum - biased priority queue
newtype Priority = Priority Double
deriving (Eq)
instance Ord Priority where
compare (Priority x) (Priority y) = case compare x y of
LT -> GT
GT -> LT
EQ -> EQ
(Priority x) < (Priority y) = x > y
(Priority x) <= (Priority y) = x >= y
(Priority x) >= (Priority y) = x <= y
(Priority x) > (Priority y) = x < y
reschedule runs with
the stuff after a callCC runs with Exception or Resume depending on whether the actions threw an exception
the logic seems to be that resumed resources may be holding resources so finishing them first is better
how our threading model works :
let 's say 4 threads max
initial task A starts , acquires 1 thread
A spawns 7 tasks BCDEFGH using 1 thread
BCD acquire threads and spawn with addPool
EFGH fail to acquire and add themselves to the queue
A finishes and its thread executes the highest - priority among EFGH ( say EFGH is the order )
B finishes and its thread executes F
C finishes and its thread executes G
D finishes and its thread executes H
so we 've had 4 threads running continuously
then all threads finish up and quit .
how our threading model works:
let's say 4 threads max
initial task A starts, acquires 1 thread
A spawns 7 tasks BCDEFGH using 1 thread
BCD acquire threads and spawn with addPool
EFGH fail to acquire and add themselves to the queue
A finishes and its thread executes the highest-priority among EFGH (say EFGH is the order)
B finishes and its thread executes F
C finishes and its thread executes G
D finishes and its thread executes H
so we've had 4 threads running continuously
then all threads finish up and quit.
-}
| A type representing a limited resource which the build system should conserve . ' ' and ' newThrottle ' create resources . These resources are used with ' withResource ' .
data Resource = Resource
{resourceOrd :: !Int
^ Key used for Eq / Ord operations .
,resourceName :: !String
,resourceI :: !ResourceI
}
instance Show Resource where
show Resource{..} = "<Resource " ++ resourceName ++ " #" ++ show resourceOrd ++ ">"
instance Eq Resource where (==) = (==) `on` resourceOrd
instance Ord Resource where compare = compare `on` resourceOrd
data ResourceI
= Finite { resourceVarF :: !(Var (ResourceVar ())), finiteCapacity :: !Int }
throttleMax :: !Int, throttleGain :: !Int, throttlePeriod :: !Seconds }
isFinite :: Resource -> Bool
isFinite r | Finite{} <- resourceI r = True
| otherwise = False
toAnyFinite :: ResourceVar () -> Any
toAnyFinite = unsafeCoerce
fromAnyFinite :: Any -> ResourceVar ()
fromAnyFinite = unsafeCoerce
toAnyThrottle :: ResourceVar (Seconds,Bool) -> Any
toAnyThrottle = unsafeCoerce
fromAnyThrottle :: Any -> ResourceVar (Seconds,Bool)
fromAnyThrottle = unsafeCoerce
type E = Heap.Entry PoolPriority (Map Resource Int, IO ())
wanted :: E -> Map Resource Int
wanted e = fst . Heap.payload $ e
action :: E -> IO ()
action e = snd . Heap.payload $ e
priority :: E -> PoolPriority
priority e = Heap.priority e
data ResourceVar f = ResourceVar {
waiting :: !(Set.Set E),
available :: !Int,
extra :: !f
}
newResource :: String -> ResourceI -> M Resource
newResource s i = do
key <- resourceId
pure $ Resource key s i
newResourceVar :: Int -> f -> IO (Var (ResourceVar f))
newResourceVar mx e = newVar $ ResourceVar Set.empty mx e
newFinite :: String -> Int -> M Resource
newFinite name mx = do
when (mx <= 0) $
liftIO . errorIO $ "You cannot create a finite resource named " ++ name ++ " with a non-positive capacity, you used " ++ show mx
var <- liftIO $ newResourceVar mx ()
newResource name (Finite var mx)
newThrottle :: String -> Int -> Int -> Seconds -> M Resource
newThrottle name count gain period = do
when (count <= 0) $
liftIO . errorIO $ "You cannot create a throttle named " ++ name ++ " with a non-positive quantity, you used " ++ show count
t <- liftIO now
var <- liftIO $ newResourceVar count (t,False)
newResource name (Throttle var count gain period)
checkError (r,want) =
case resourceI r of
Finite v cap
| want <= 0 -> errorIO $ "You cannot acquire a non-positive quantity of " ++ show r ++ ", requested " ++ show want
| want > cap -> errorIO $ "You cannot acquire more than " ++ show cap ++ " of " ++ show r ++ ", requested " ++ show want
| otherwise -> pure ()
Throttle var count gain period
| want <= 0 -> errorIO $ "You cannot acquire a non-positive quantity of " ++ show r ++ ", requested " ++ show want
| want > count -> errorIO $ "You cannot acquire more than " ++ show count ++ " of " ++ show r ++ ", requested " ++ show want
| otherwise -> pure ()
withVarsT :: [Resource] -> StateT (Map Resource Any) IO a -> StateT (Map Resource Any) IO a
withVarsT [] f = f
withVarsT (r:rs) f = do
mp <- get
case r `Map.member` mp of
True -> withVarsT rs f
False -> StateT $ \mp_o -> case resourceI r of
Finite var cap -> modifyVar var $ \x -> do
let mp = Map.insert r (toAnyFinite x) mp_o
(a, mp') <- runStateT (withVarsT rs f) mp
pure (fromAnyFinite . fromJust $ Map.lookup r mp', (a, Map.delete r mp'))
Throttle var count gain period -> modifyVar var $ \x -> do
let mp = Map.insert r (toAnyThrottle x) mp_o
(a, mp') <- runStateT (withVarsT rs f) mp
pure (fromAnyThrottle . fromJust $ Map.lookup r mp', (a, Map.delete r mp'))
withVars :: [Resource] -> StateT (Map Resource Any) IO a -> IO a
withVars rs f = evalStateT (withVarsT rs f) Map.empty
lookupVar :: Resource -> StateT (Map Resource Any) IO Any
lookupVar r = do
mp <- get
pure (fromJust $ Map.lookup r mp)
spawnWithResource :: Map Resource Int -> Priority -> IO () -> M ()
spawnWithResource mp prio act = do
pool <- globalPool
spawnWithResourceInner (addPool pool) mp prio act
spawnWithResourceWorker :: Map Resource Int -> Priority -> IO () -> M ()
spawnWithResourceWorker = spawnWithResourceInner id
| inner method to share code between withResource and withResourceWorker
spawnWithResourceInner :: (IO () -> IO ()) -> Map Resource Int -> Priority -> IO () -> M ()
spawnWithResourceInner spawn wants priority act = do
pool <- globalPool
mapM_ (liftIO . checkError) (Map.toList wants)
i <- resourceRand
tid <- taskId
let e = Heap.Entry (priority, i, tid) (wants,act)
acquireSucceeded <- liftIO $ acquire pool e
when acquireSucceeded $ liftIO $ spawn $ act `finally` release pool wants
canPreempt :: Resource -> E -> Int -> Int -> Set E -> Bool
canPreempt r ent want available queue | want > available = False
canPreempt r ent want available queue = do
let lt = Set.takeWhileAntitone (<= ent) queue
let f _ Nothing = Nothing
f e b = do
avail <- b
let avail' = avail - (fromJust . Map.lookup r $ wanted e)
pureIf (avail' >= 0) avail'
case Set.foldr f (Just (available - want)) lt of
Nothing -> False
Just _ -> True
canPreemptM :: Resource -> E -> Int -> StateT (Map Resource Any) IO Bool
canPreemptM r ent want = do
v <- lookupVar r
pure $ case resourceI r of
Finite{} -> let ResourceVar{..} = fromAnyFinite v in canPreempt r ent want available waiting
Throttle{} -> let ResourceVar{..} = fromAnyThrottle v in canPreempt r ent want available waiting
newtype AllM m = AllM (m Bool)
instance Monad m => Semigroup (AllM m) where
AllM x <> AllM y = AllM $ do
b <- x
case b of
False -> pure False
True -> y
instance Monad m => Monoid (AllM m) where
mempty = AllM $ pure True
checkPreempt :: E -> StateT (Map Resource Any) IO Bool
checkPreempt ent = case Map.foldMapWithKey (\r want -> AllM $ canPreemptM r ent want) (wanted ent) of
AllM x -> x
acquire :: Pool -> E -> IO Bool
acquire pool ent = let rs = wanted ent in withVars (Map.keys rs) $ do
acquireSucceeded <- checkPreempt ent
forM_ (Map.toList rs) $ \(r,want) -> do
v <- lookupVar r
updated <- case resourceI r of
Finite{} -> do
let x@ResourceVar{..} = fromAnyFinite v
pure . toAnyFinite $
if acquireSucceeded then
x{available = available - want}
else x{waiting = Set.insert ent waiting}
Throttle{..} -> do
let x@ResourceVar{..} = fromAnyThrottle v
toAnyThrottle <$>
if acquireSucceeded then
pure x{available = available - want}
else do
let (last_reset,running) = extra
liftIO $ unless running $ do
t <- now
addPool pool $ do
sleep (throttlePeriod - (t - last_reset))
recheckThrottle pool r
pure x{waiting = Set.insert ent waiting,extra=(last_reset,True)}
modify $ Map.insert r updated
pure acquireSucceeded
example : queue [ 3,2,1,4 ] going from 4 to 7 units available .
the 3 task is runnable but not newly , 2,1 are newly runnable , 4 is not runnable ( insufficient units ) .
newlyRunnable :: Resource -> Int -> Int -> [E] -> [E]
newlyRunnable r newAvailable oldAvailable queue
| newAvailable <= oldAvailable = []
| newAvailable <= 0 = []
| otherwise =
case queue of
e:es -> let want = fromJust . Map.lookup r $ wanted e in
if want <= oldAvailable then
newlyRunnable r (newAvailable - want) (oldAvailable - want) es
else if want <= newAvailable then
e : newlyRunnable r (newAvailable - want) (oldAvailable - want) es
else
[]
mergePairs :: Ord a => [[a]] -> [[a]]
mergePairs [] = []
mergePairs [ls] = [ls]
mergePairs (x:y:ls) = (merge x y):mergePairs ls
mergeLists :: Ord a => [[a]] -> [a]
mergeLists [] = []
mergeLists [x] = x
mergeLists ls = mergeLists $ mergePairs ls
release pool rs = do
requestsToCheckL <- withVars (Map.keys rs) $ forM (Map.toList rs) $ \(r,want) -> do
case resourceI r of
Finite{} -> do
v <- lookupVar r
let x@ResourceVar{..} = fromAnyFinite v
modify $ Map.insert r (toAnyFinite $ x{available =available + want})
pure $ newlyRunnable r (available+want) available (Set.toAscList waiting)
let requestsToCheck = mergeLists requestsToCheckL
reqs <- recheckRequests requestsToCheck pure
case reqs of
[] -> pure ()
x:xs -> do
forM_ xs $ \x -> addPool pool $ action x `finally` release pool (wanted x)
action x `finally` release pool (wanted x)
recheckRequests :: [E] -> ([E] -> StateT (Map Resource Any) IO a) -> IO a
recheckRequests requestsToCheck f = do
let allResources = Set.toAscList . Set.unions $ map (Map.keysSet . fst . Heap.payload) requestsToCheck
withVars allResources $ foldr tryTake (pure []) requestsToCheck >>= f
where
tryTake :: E -> StateT (Map Resource Any) IO [E] -> StateT (Map Resource Any) IO [E]
tryTake request rest = do
acquireSucceeded <- checkPreempt request
if not acquireSucceeded then rest else do
forM_ (Map.toList $ wanted request) $ \(r,want) -> do
v <- lookupVar r
updated <- case resourceI r of
Finite{} -> do
let x@ResourceVar{..} = fromAnyFinite v
pure . toAnyFinite $ x{available = available - want, waiting = Set.delete request waiting}
Throttle{} -> do
let x@ResourceVar{..} = fromAnyThrottle v
pure . toAnyThrottle $ x{available = available - want, waiting = Set.delete request waiting}
modify $ Map.insert r updated
(request :) <$> rest
recheckThrottle :: Pool -> Resource -> IO ()
recheckThrottle pool r = do
let Throttle{..} = resourceI r
(requestsToCheck, nextCheckWait) <- modifyVar resourceVarT $
\v@ResourceVar{..} -> do
let (last_reset,running) = extra
assertIO running
n <- now
let periods_elapsed = fromIntegral $ (n - last_reset) `div` throttlePeriod
let newAvailable = throttleMax `min` (available + periods_elapsed * throttleGain)
let nR = newlyRunnable r newAvailable available (Set.toAscList waiting)
let (var,nextCheckWait) = if periods_elapsed > 0
then
(v{available=newAvailable,extra=(n,True)}, throttlePeriod)
else
(v, last_reset + throttlePeriod - n)
pure (v,(nR,nextCheckWait))
(reqs, running) <- recheckRequests requestsToCheck $ \reqs -> do
x@ResourceVar{extra=(last_reset,True),..} <- fromAnyThrottle <$> lookupVar r
let running = not $ Set.null waiting
modify $ Map.insert r (toAnyThrottle $ x{extra=(last_reset,running)})
pure (reqs,running)
forM_ reqs $ \x -> addPool pool $ action x `finally` release pool (wanted x)
if running then do
sleep nextCheckWait
recheckThrottle pool r
else
pure ()
THROTTLE TIMING HELPERS
maxDelay :: Int
maxDelay = ((maxBound :: Int) `div` 10^7 - 1) * 10^4
maxDelayT :: Seconds
maxDelayT = fromIntegral maxDelay * 1000
sleep :: Seconds -> IO ()
sleep s
threadDelay 0 does putMVar takeMvar , basically nothing
| s > maxDelayT = do
threadDelay maxDelay
sleep $ s - maxDelayT
| otherwise = threadDelay (fromIntegral $ s `div` 1000)
now :: IO Seconds
now = toNanoSecs <$> getTime Monotonic
> catch ( assertIO True > > pure 1 ) ( \(x : : AssertionFailed ) - > pure 2 ) = = pure 1
> catch ( assertIO False > > pure 1 ) ( \(x : : AssertionFailed ) - > pure 2 ) = = pure 2
> seq ( assertIO False ) ( print 1 ) = = print 1
assertIO :: Partial => Bool -> IO ()
assertIO x = withFrozenCallStack $ evaluate $ assert x () |
1d2984d814544b2648874ca40ce8cd48dfae9ff6935a37952e09d8b6d08a7a97 | amnh/ocamion | subplex.ml | open Internal
open Numerical
* The strategy contains a simplex strategy and added features
type subplex_strategy =
{ simplex : Simplex.simplex_strategy;
psi : float; (** The Simplex Reduction coefficient *)
omega : float; (** The Step Reduction coefficient *)
* Minimum subspace dimension ; or 2
* Maximum subspace dimension ; or 5
}
(** Default Simplex Strategy defined by FSAoNA paper *)
let default_subplex =
{ simplex = Simplex.default_simplex; omega = 0.1; psi = 0.25; nsmin = 2; nsmax = 5; }
* Takes a function [ f ] for an array [ ray ] , and a subpsace [ sub ] , like ( 0,2 ) ,
that replaces the elements of the new array into [ ray ] according to the
subspace association . We keep this function functional by copying the array
each time , although it may not be necessary .
that replaces the elements of the new array into [ray] according to the
subspace association. We keep this function functional by copying the array
each time, although it may not be necessary. *)
let function_of_subspace f ray sub_assoc =
(fun sub ->
let ray = Array.copy ray in
let () = Array.iteri (fun i x -> ray.(x) <- sub.(i) ) sub_assoc in
f ray)
(** Return the vector that represents the subspace *)
let make_subspace_vector subs x =
Array.init (Array.length subs) (fun i -> x.( subs.(i) ))
(** Replace elements of a subspace vector into the main vector *)
let replace_subspace_vector sub nx x =
Array.iteri (fun i _ -> x.( sub.(i) ) <- nx.(i)) sub
* A subplex routine to find the optimal step - size for the next iteration of
the algorithm . The process is outlined in 5.3.2 . Each step , the vector is
re - scaled in proportion to how much progress was made previously . If little
progress is made then step is reduced and if onsiderable progress is made
then it is increased . Lower and Upper Bounds in the strategy ensure we do
not do anything rash .
the algorithm. The process is outlined in 5.3.2. Each step, the vector is
re-scaled in proportion to how much progress was made previously. If little
progress is made then step is reduced and if onsiderable progress is made
then it is increased. Lower and Upper Bounds in the strategy ensure we do
not do anything rash. *)
let find_stepsize strat nsubs x dx steps =
let n = Array.length x
and sign x = if x >= 0.0 then 1.0 else -1.0
and minmax x lo hi =
let lo = min lo hi and hi = max lo hi in
max lo (min x hi)
in
(* find the scale factor for new step *)
let stepscale =
if nsubs > 1 then begin
let stepscale = (one_norm_vec dx) /. (one_norm_vec steps) in
minmax stepscale (1.0/.strat.omega) strat.omega
end else begin
strat.psi
end
in
scale step vector by stepscale
let nstep = Array.map (fun x -> x *. stepscale) steps in
(* orient step in the proper direction *)
for i = 0 to n-1 do
if dx.(i) = 0.0
then nstep.(i) <- ~-. (nstep.(i))
else nstep.(i) <- (sign dx.(i)) *. (nstep.(i))
done;
nstep
(** Determine the subspaces by a randomization of the vector, and randomizing
the size of the subspaces; conditions will match the strategy *)
let rand_subspace strat vec : int array list =
let randomize ar =
let l = Array.length ar - 1 in
for i = 0 to l do
let rnd = i + Random.int (l - i + 1) in
let tmp = ar.(i) in
ar.(i) <- ar.(rnd);
ar.(rnd) <- tmp;
done;
ar
in
let n = Array.length vec in
let rec take acc n lst = match lst with
| _ when n = 0 -> List.rev acc,lst
| [] -> assert false
| x::lst -> take (x::acc) (n-1) lst
in
let rec continually_take taken acc lst =
if taken = n then
List.rev acc
else if (n - taken) < 2 * strat.nsmin then
continually_take (n) (lst::acc) []
else begin
let lo = min strat.nsmax (n-taken) in
let r = strat.nsmin + (Random.int (lo - strat.nsmin)) in
if n-(r+taken) < strat.nsmin
then continually_take taken acc lst
else begin
let f,l = take [] r lst in
continually_take (taken+r) (f::acc) l
end
end
in
vec |> Array.mapi (fun i _ -> i)
|> randomize
|> Array.to_list
|> continually_take 0 []
|> List.map (Array.of_list)
* A subplex routine that splits up an delta array into subspaces that match
the criteria found in the subplex paper section 5.3.3
the criteria found in the subplex paper section 5.3.3 *)
let find_subspace strat vec =
let n = Array.length vec in
(* resolve a specific value of k *)
let rec resolve_k k lvec : float =
let rec left (acc:float) (i:int) lvec : float = match lvec with
| [] -> acc /. (float_of_int k)
| xs when i = k -> right (acc /. (float_of_int k)) 0.0 xs
| (_,x)::tl -> left (acc +. (abs_float x)) (i+1) tl
and right leftval acc = function
| [] -> leftval -. (acc /. (float_of_int (n - k)))
| (_,x)::t -> right leftval (acc +. (abs_float x)) t
in
left 0.0 0 lvec
and apply_ks nleft k lvec : (int * float) list =
if nleft < k then []
else (k,resolve_k k lvec)::(apply_ks nleft (k+1) lvec)
and take acc n lst = match lst with
| _ when n = 0 -> List.rev acc,lst
| [] -> assert false
| x::lst -> take (x::acc) (n-1) lst
in
(* return a list of lengths for subspaces *)
let rec partition acc nsubs nused nleft lvec : int list =
let sorted_ks =
List.sort (fun (_,kv1) (_,kv2) -> compare kv2 kv1) (apply_ks nleft 1 lvec)
in
let constraint_1 k = (* fall in appropriate range *)
(strat.nsmin <= k) && (k <= strat.nsmax)
and constraint_2 k = (* can be partitioned further *)
let r =
strat.nsmin * (int_of_float
(ceil ((float_of_int (n-nused-k)) /. (float_of_int strat.nsmax))))
in
r <= (n-nused-k)
in
let rec get_next_k = function
| (k,_)::_ when (constraint_1 k) && (constraint_2 k) ->
if (nused+k) = n then
List.rev (k::acc)
else
partition (k::acc) (nsubs+1) (nused+k) (nleft-k) (snd (take [] k lvec))
| _::tl -> get_next_k tl
| [] -> assert false
in
get_next_k sorted_ks
(* take a list of size of subspaces and build association vectors for
subspaces *)
and build_association_arrays lvec = function
| [] -> []
| h::tl ->
let this,oth = take [] h lvec in
this::(build_association_arrays oth tl)
in
let lvec =
vec |> Array.mapi (fun i x -> (i,x))
|> Array.to_list
|> List.sort (fun (_,x) (_,y) -> compare (abs_float y) (abs_float x))
in
lvec |> partition [] 0 0 n
|> build_association_arrays lvec
|> List.map (List.map fst)
|> List.map (Array.of_list)
* Define how termination of the algorithm should be done . This is outlined in
the paper , section 5.3.4 , This test , because of a noisy function , uses the
distance between the vertices of the simplex to see if the function has
converged .
the paper, section 5.3.4, This test, because of a noisy function, uses the
distance between the vertices of the simplex to see if the function has
converged. *)
let subplex_termination strat tol dx x stp =
let ret = ref false in
Array.iteri
(fun i _ ->
let numr = max dx.(i) (abs_float (stp.(i) *. strat.psi))
and denm = max (abs_float x.(i)) 1.0 in
ret := !ret || ((numr /. denm) > tol))
x;
not (!ret)
* The method is a generalization to a number of algorithms , paramount
the Nelder - Mead simplex method , with alternating variables , and Nelder - Mead
Simplex with restart . The advantages are outlined in the previously
mentioned paper , in section 5.3.6 .
the Nelder-Mead simplex method, with alternating variables, and Nelder-Mead
Simplex with restart. The advantages are outlined in the previously
mentioned paper, in section 5.3.6. *)
let optimize ?(subplex_strategy=default_subplex) ?(tol=tolerance) ?(max_iter=50)
?(select_subspace=find_subspace) ~f (p,fp) =
let i = ref 0 in
let rec subplex_loop step subs ((x,_) as xfx) dx =
incr i;
let step = find_stepsize subplex_strategy (List.length subs) x dx step in
let subs = select_subspace subplex_strategy dx in
let (nx,_) as nxnfx =
let simplex_strategy = subplex_strategy.simplex in
List.fold_left
(fun (x,fx) sub ->
let sub_vec = make_subspace_vector sub x in
let step = Some (make_subspace_vector sub step) in
let (nx,nfx) =
Simplex.optimize ~simplex_strategy ~step ~f:(function_of_subspace f x sub) (sub_vec,fx)
in
replace_subspace_vector sub nx x;
(x,nfx))
xfx
subs
in
let dx = sub_vec x nx in
if (subplex_termination subplex_strategy tol dx nx step) || (!i > max_iter)
then nxnfx
else subplex_loop step subs nxnfx dx
in
let dx = Array.make (Array.length p) 0.0 in
subplex_loop
(find_stepsize subplex_strategy 1 p dx (Array.make (Array.length p) 1.0))
[(Array.init (Array.length p) (fun x -> x))]
(p,fp)
(dx)
| null | https://raw.githubusercontent.com/amnh/ocamion/699c2471b7fdac12f061cf24b588f9eef5bf5cb8/lib/subplex.ml | ocaml | * The Simplex Reduction coefficient
* The Step Reduction coefficient
* Default Simplex Strategy defined by FSAoNA paper
* Return the vector that represents the subspace
* Replace elements of a subspace vector into the main vector
find the scale factor for new step
orient step in the proper direction
* Determine the subspaces by a randomization of the vector, and randomizing
the size of the subspaces; conditions will match the strategy
resolve a specific value of k
return a list of lengths for subspaces
fall in appropriate range
can be partitioned further
take a list of size of subspaces and build association vectors for
subspaces | open Internal
open Numerical
* The strategy contains a simplex strategy and added features
type subplex_strategy =
{ simplex : Simplex.simplex_strategy;
* Minimum subspace dimension ; or 2
* Maximum subspace dimension ; or 5
}
let default_subplex =
{ simplex = Simplex.default_simplex; omega = 0.1; psi = 0.25; nsmin = 2; nsmax = 5; }
* Takes a function [ f ] for an array [ ray ] , and a subpsace [ sub ] , like ( 0,2 ) ,
that replaces the elements of the new array into [ ray ] according to the
subspace association . We keep this function functional by copying the array
each time , although it may not be necessary .
that replaces the elements of the new array into [ray] according to the
subspace association. We keep this function functional by copying the array
each time, although it may not be necessary. *)
let function_of_subspace f ray sub_assoc =
(fun sub ->
let ray = Array.copy ray in
let () = Array.iteri (fun i x -> ray.(x) <- sub.(i) ) sub_assoc in
f ray)
let make_subspace_vector subs x =
Array.init (Array.length subs) (fun i -> x.( subs.(i) ))
let replace_subspace_vector sub nx x =
Array.iteri (fun i _ -> x.( sub.(i) ) <- nx.(i)) sub
* A subplex routine to find the optimal step - size for the next iteration of
the algorithm . The process is outlined in 5.3.2 . Each step , the vector is
re - scaled in proportion to how much progress was made previously . If little
progress is made then step is reduced and if onsiderable progress is made
then it is increased . Lower and Upper Bounds in the strategy ensure we do
not do anything rash .
the algorithm. The process is outlined in 5.3.2. Each step, the vector is
re-scaled in proportion to how much progress was made previously. If little
progress is made then step is reduced and if onsiderable progress is made
then it is increased. Lower and Upper Bounds in the strategy ensure we do
not do anything rash. *)
let find_stepsize strat nsubs x dx steps =
let n = Array.length x
and sign x = if x >= 0.0 then 1.0 else -1.0
and minmax x lo hi =
let lo = min lo hi and hi = max lo hi in
max lo (min x hi)
in
let stepscale =
if nsubs > 1 then begin
let stepscale = (one_norm_vec dx) /. (one_norm_vec steps) in
minmax stepscale (1.0/.strat.omega) strat.omega
end else begin
strat.psi
end
in
scale step vector by stepscale
let nstep = Array.map (fun x -> x *. stepscale) steps in
for i = 0 to n-1 do
if dx.(i) = 0.0
then nstep.(i) <- ~-. (nstep.(i))
else nstep.(i) <- (sign dx.(i)) *. (nstep.(i))
done;
nstep
let rand_subspace strat vec : int array list =
let randomize ar =
let l = Array.length ar - 1 in
for i = 0 to l do
let rnd = i + Random.int (l - i + 1) in
let tmp = ar.(i) in
ar.(i) <- ar.(rnd);
ar.(rnd) <- tmp;
done;
ar
in
let n = Array.length vec in
let rec take acc n lst = match lst with
| _ when n = 0 -> List.rev acc,lst
| [] -> assert false
| x::lst -> take (x::acc) (n-1) lst
in
let rec continually_take taken acc lst =
if taken = n then
List.rev acc
else if (n - taken) < 2 * strat.nsmin then
continually_take (n) (lst::acc) []
else begin
let lo = min strat.nsmax (n-taken) in
let r = strat.nsmin + (Random.int (lo - strat.nsmin)) in
if n-(r+taken) < strat.nsmin
then continually_take taken acc lst
else begin
let f,l = take [] r lst in
continually_take (taken+r) (f::acc) l
end
end
in
vec |> Array.mapi (fun i _ -> i)
|> randomize
|> Array.to_list
|> continually_take 0 []
|> List.map (Array.of_list)
* A subplex routine that splits up an delta array into subspaces that match
the criteria found in the subplex paper section 5.3.3
the criteria found in the subplex paper section 5.3.3 *)
let find_subspace strat vec =
let n = Array.length vec in
let rec resolve_k k lvec : float =
let rec left (acc:float) (i:int) lvec : float = match lvec with
| [] -> acc /. (float_of_int k)
| xs when i = k -> right (acc /. (float_of_int k)) 0.0 xs
| (_,x)::tl -> left (acc +. (abs_float x)) (i+1) tl
and right leftval acc = function
| [] -> leftval -. (acc /. (float_of_int (n - k)))
| (_,x)::t -> right leftval (acc +. (abs_float x)) t
in
left 0.0 0 lvec
and apply_ks nleft k lvec : (int * float) list =
if nleft < k then []
else (k,resolve_k k lvec)::(apply_ks nleft (k+1) lvec)
and take acc n lst = match lst with
| _ when n = 0 -> List.rev acc,lst
| [] -> assert false
| x::lst -> take (x::acc) (n-1) lst
in
let rec partition acc nsubs nused nleft lvec : int list =
let sorted_ks =
List.sort (fun (_,kv1) (_,kv2) -> compare kv2 kv1) (apply_ks nleft 1 lvec)
in
(strat.nsmin <= k) && (k <= strat.nsmax)
let r =
strat.nsmin * (int_of_float
(ceil ((float_of_int (n-nused-k)) /. (float_of_int strat.nsmax))))
in
r <= (n-nused-k)
in
let rec get_next_k = function
| (k,_)::_ when (constraint_1 k) && (constraint_2 k) ->
if (nused+k) = n then
List.rev (k::acc)
else
partition (k::acc) (nsubs+1) (nused+k) (nleft-k) (snd (take [] k lvec))
| _::tl -> get_next_k tl
| [] -> assert false
in
get_next_k sorted_ks
and build_association_arrays lvec = function
| [] -> []
| h::tl ->
let this,oth = take [] h lvec in
this::(build_association_arrays oth tl)
in
let lvec =
vec |> Array.mapi (fun i x -> (i,x))
|> Array.to_list
|> List.sort (fun (_,x) (_,y) -> compare (abs_float y) (abs_float x))
in
lvec |> partition [] 0 0 n
|> build_association_arrays lvec
|> List.map (List.map fst)
|> List.map (Array.of_list)
* Define how termination of the algorithm should be done . This is outlined in
the paper , section 5.3.4 , This test , because of a noisy function , uses the
distance between the vertices of the simplex to see if the function has
converged .
the paper, section 5.3.4, This test, because of a noisy function, uses the
distance between the vertices of the simplex to see if the function has
converged. *)
let subplex_termination strat tol dx x stp =
let ret = ref false in
Array.iteri
(fun i _ ->
let numr = max dx.(i) (abs_float (stp.(i) *. strat.psi))
and denm = max (abs_float x.(i)) 1.0 in
ret := !ret || ((numr /. denm) > tol))
x;
not (!ret)
* The method is a generalization to a number of algorithms , paramount
the Nelder - Mead simplex method , with alternating variables , and Nelder - Mead
Simplex with restart . The advantages are outlined in the previously
mentioned paper , in section 5.3.6 .
the Nelder-Mead simplex method, with alternating variables, and Nelder-Mead
Simplex with restart. The advantages are outlined in the previously
mentioned paper, in section 5.3.6. *)
let optimize ?(subplex_strategy=default_subplex) ?(tol=tolerance) ?(max_iter=50)
?(select_subspace=find_subspace) ~f (p,fp) =
let i = ref 0 in
let rec subplex_loop step subs ((x,_) as xfx) dx =
incr i;
let step = find_stepsize subplex_strategy (List.length subs) x dx step in
let subs = select_subspace subplex_strategy dx in
let (nx,_) as nxnfx =
let simplex_strategy = subplex_strategy.simplex in
List.fold_left
(fun (x,fx) sub ->
let sub_vec = make_subspace_vector sub x in
let step = Some (make_subspace_vector sub step) in
let (nx,nfx) =
Simplex.optimize ~simplex_strategy ~step ~f:(function_of_subspace f x sub) (sub_vec,fx)
in
replace_subspace_vector sub nx x;
(x,nfx))
xfx
subs
in
let dx = sub_vec x nx in
if (subplex_termination subplex_strategy tol dx nx step) || (!i > max_iter)
then nxnfx
else subplex_loop step subs nxnfx dx
in
let dx = Array.make (Array.length p) 0.0 in
subplex_loop
(find_stepsize subplex_strategy 1 p dx (Array.make (Array.length p) 1.0))
[(Array.init (Array.length p) (fun x -> x))]
(p,fp)
(dx)
|
a5e7108b98da6499815359b4580735ab8804e8e8bc422598f9f94b5eba1bf4de | dragonmark/util | project.clj | (defproject dragonmark/util "0.1.4"
:description "A bunch of useful functions"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
; {:name "GNU LESSER GENERAL PUBLIC LICENSE"
; :url ""}]
:dependencies [[org.clojure/clojure "1.6.0"]]
:plugins [[codox "0.8.10"]
[lein-cljsbuild "1.0.3"]
[com.keminglabs/cljx "0.4.0"]
[com.cemerick/clojurescript.test "0.3.1"]]
:codox {:defaults {:doc/format :markdown}
:sources ["target/generated/src"]
:output-dir "doc/codox"
:src-linenum-anchor-prefix "L"
:src-uri-mapping {#"target/generated/src" #(str "src/" % "x")}}
:jar-exclusions [#"\.cljx|\.swp|\.swo|\.DS_Store|\.props"]
:cljx
{:builds
[{:source-paths ["src"], :output-path "target/generated/src", :rules :clj}
{:source-paths ["test"], :output-path "target/generated/test", :rules :clj}
{:source-paths ["src"], :output-path "target/generated/src", :rules :cljs}
{:source-paths ["test"], :output-path "target/generated/test", :rules :cljs}]}
:source-paths ["src" "target/generated/src"]
:test-paths ["test" "target/generated/test"]
:hooks [cljx.hooks]
:cljsbuild
{:builds
[{:source-paths ["target/generated/src" "target/generated/test"]
:compiler {:output-to "target/main.js"}}]
:test-commands {"unit-tests" ["phantomjs" :runner "target/main.js"]}}
:aliases
{"test-cljs" ["do" ["cljx" "once"] ["cljsbuild" "test"]]
"test-all" ["do" ["test"] ["cljsbuild" "test"]]}
:profiles
{:provided {:dependencies [[org.clojure/clojurescript "0.0-2268"]]}})
| null | https://raw.githubusercontent.com/dragonmark/util/2f3e4161e2268c0665219b06fba274eacbbbe960/project.clj | clojure | {:name "GNU LESSER GENERAL PUBLIC LICENSE"
:url ""}] | (defproject dragonmark/util "0.1.4"
:description "A bunch of useful functions"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.6.0"]]
:plugins [[codox "0.8.10"]
[lein-cljsbuild "1.0.3"]
[com.keminglabs/cljx "0.4.0"]
[com.cemerick/clojurescript.test "0.3.1"]]
:codox {:defaults {:doc/format :markdown}
:sources ["target/generated/src"]
:output-dir "doc/codox"
:src-linenum-anchor-prefix "L"
:src-uri-mapping {#"target/generated/src" #(str "src/" % "x")}}
:jar-exclusions [#"\.cljx|\.swp|\.swo|\.DS_Store|\.props"]
:cljx
{:builds
[{:source-paths ["src"], :output-path "target/generated/src", :rules :clj}
{:source-paths ["test"], :output-path "target/generated/test", :rules :clj}
{:source-paths ["src"], :output-path "target/generated/src", :rules :cljs}
{:source-paths ["test"], :output-path "target/generated/test", :rules :cljs}]}
:source-paths ["src" "target/generated/src"]
:test-paths ["test" "target/generated/test"]
:hooks [cljx.hooks]
:cljsbuild
{:builds
[{:source-paths ["target/generated/src" "target/generated/test"]
:compiler {:output-to "target/main.js"}}]
:test-commands {"unit-tests" ["phantomjs" :runner "target/main.js"]}}
:aliases
{"test-cljs" ["do" ["cljx" "once"] ["cljsbuild" "test"]]
"test-all" ["do" ["test"] ["cljsbuild" "test"]]}
:profiles
{:provided {:dependencies [[org.clojure/clojurescript "0.0-2268"]]}})
|
68d10681bec4f18f452348d12fe069ac0ab60b4f4677a5a4ebcfd020646cc57d | hiroshi-unno/coar | RLConfig.ml | open Core
open Common.Util
type t = {
enable: bool;
show_num_constrs: bool;
show_num_pvars: bool;
show_num_args: bool;
show_user_time: bool;
show_elapsed_time: bool;
show_constraints: bool;
show_candidates: bool;
show_examples: bool;
show_unsat_core: bool;
ask_smt_timeout: bool
} [@@ deriving yojson]
module type ConfigType = sig val config: t end
let instantiate_ext_files cfg = Ok cfg
let load_ext_file = function
| ExtFile.Filename filename ->
begin
let open Or_error in
try_with (fun () -> Yojson.Safe.from_file filename)
>>= fun raw_json ->
match of_yojson raw_json with
| Ok x ->
instantiate_ext_files x >>= fun x ->
Ok (ExtFile.Instance x)
| Error msg ->
error_string @@ Printf.sprintf
"Invalid RL Configuration (%s): %s" filename msg
end
| Instance x -> Ok (Instance x)
let disabled : t = {
enable = false;
show_num_constrs = false;
show_num_pvars = false;
show_num_args = false;
show_user_time = false;
show_elapsed_time = false;
show_constraints = false;
show_candidates = false;
show_examples = false;
show_unsat_core = false;
ask_smt_timeout = false
}
| null | https://raw.githubusercontent.com/hiroshi-unno/coar/90a23a09332c68f380efd4115b3f6fdc825f413d/lib/PCSat/common/RLConfig.ml | ocaml | open Core
open Common.Util
type t = {
enable: bool;
show_num_constrs: bool;
show_num_pvars: bool;
show_num_args: bool;
show_user_time: bool;
show_elapsed_time: bool;
show_constraints: bool;
show_candidates: bool;
show_examples: bool;
show_unsat_core: bool;
ask_smt_timeout: bool
} [@@ deriving yojson]
module type ConfigType = sig val config: t end
let instantiate_ext_files cfg = Ok cfg
let load_ext_file = function
| ExtFile.Filename filename ->
begin
let open Or_error in
try_with (fun () -> Yojson.Safe.from_file filename)
>>= fun raw_json ->
match of_yojson raw_json with
| Ok x ->
instantiate_ext_files x >>= fun x ->
Ok (ExtFile.Instance x)
| Error msg ->
error_string @@ Printf.sprintf
"Invalid RL Configuration (%s): %s" filename msg
end
| Instance x -> Ok (Instance x)
let disabled : t = {
enable = false;
show_num_constrs = false;
show_num_pvars = false;
show_num_args = false;
show_user_time = false;
show_elapsed_time = false;
show_constraints = false;
show_candidates = false;
show_examples = false;
show_unsat_core = false;
ask_smt_timeout = false
}
|
|
a16811e0bda17fae3c2a52eff960b144b0408d12259ff1ca1236f02fae2a65a8 | openbadgefactory/salava | export_test.clj | (ns salava.badge.export-test
(:require [clojure.test :refer :all]
[midje.sweet :refer :all]
[salava.test-utils :as ts ]))
;;[get-system stop-system test-api-request login! logout! test-user-credentials]
(def test-user 1)
(def user-with-no-badges 3)
(def system (ts/get-system))
(facts "about exporting badges"
(fact "user must be logged in to export badges"
(:status (ts/test-api-request system :get "/app/obpv1/badge/export")) => 401)
(apply ts/login! (test-user-credentials test-user))
(fact "user has a badge which can be exported"
(let [{:keys [status body]} (test-api-request :get "/badge/export")]
status => 200
(count (:badges body)) => 0))
(ts/logout!)
(apply ts/login! (test-user-credentials user-with-no-badges))
(fact "user does not have a badge which can be exported"
(let [{:keys [status body]} (test-api-request :get "/badge/export")]
status => 200
(:badges body) => []))
(ts/logout!))
(ts/stop-system system)
| null | https://raw.githubusercontent.com/openbadgefactory/salava/97f05992406e4dcbe3c4bff75c04378d19606b61/test_old/clj/salava/badge/export_test.clj | clojure | [get-system stop-system test-api-request login! logout! test-user-credentials] | (ns salava.badge.export-test
(:require [clojure.test :refer :all]
[midje.sweet :refer :all]
[salava.test-utils :as ts ]))
(def test-user 1)
(def user-with-no-badges 3)
(def system (ts/get-system))
(facts "about exporting badges"
(fact "user must be logged in to export badges"
(:status (ts/test-api-request system :get "/app/obpv1/badge/export")) => 401)
(apply ts/login! (test-user-credentials test-user))
(fact "user has a badge which can be exported"
(let [{:keys [status body]} (test-api-request :get "/badge/export")]
status => 200
(count (:badges body)) => 0))
(ts/logout!)
(apply ts/login! (test-user-credentials user-with-no-badges))
(fact "user does not have a badge which can be exported"
(let [{:keys [status body]} (test-api-request :get "/badge/export")]
status => 200
(:badges body) => []))
(ts/logout!))
(ts/stop-system system)
|
aecc688e0815abeee07a12ce4e740375c592b6c2330fce042138430b0e47a72c | gebi/jungerl | rdbms_wsearch.erl | %%%
The contents of this file are subject to the Erlang Public License ,
Version 1.0 , ( the " License " ) ; you may not use this file except in
%%% compliance with the License. You may obtain a copy of the License at
%%%
%%%
Software distributed under the License is distributed on an " AS IS "
%%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%%% the License for the specific language governing rights and limitations
%%% under the License.
%%%
The Original Code is rdbms-1.2 .
%%%
The Initial Developer of the Original Code is Ericsson Telecom
AB . Portions created by Ericsson are Copyright ( C ) , 1998 , Ericsson
Telecom AB . All Rights Reserved .
%%%
%%% Contributor(s): ______________________________________.
%%%----------------------------------------------------------------------
# 0 . BASIC INFORMATION
%%%----------------------------------------------------------------------
%%%-------------------------------------------------------------------
%%% File : rdbms_wsearch.erl
Author : < >
%%% Ulf Wiger <> (moved into rdbms)
%%% Description : Word search indexing support
%%% Uses the Porter Stemming Algorithm
%%%
Created : 26 Jan 2006 by
%%%-------------------------------------------------------------------
-module(rdbms_wsearch).
-export([search/4,
word_report/2]).
-export([sort_search_result_TFIDF/3,
sort_search_result_most_occurences/3,
sort_search_result_weighted_most_occurences/3]).
-import(rdbms_wsearch_porter, [lower_case/1]).
search(Sentence, Tab, Index, SortFun) when is_function(SortFun, 2) ->
Stems = lists:usort(rdbms_wsearch_idx:idx_sentence(Sentence)),
SearchResult = do_search(Stems, Tab, Index, SortFun),
AllMatchingStems =
lists:usort(
lists:concat(
lists:map(fun({_Weight,{_Key,MS}}) ->
elements(1,MS)
end, SearchResult))),
{Stems, AllMatchingStems, SearchResult}.
Stems must be usort : ed ! !
do_search(Stems, Tab, Index, SortFun) ->
Tab = ets:new(tmptab, [bag]),
try begin
lists:foreach(
fun(Stem) ->
lists:foreach(
fun({Key,N}) when integer(Key) ->
ets:insert(Tab,{Key,Stem,N});
(_) ->
ok
end, mnesia:index_read(Tab, Stem, Index))
end, Stems),
SortFun(read_values(Tab,ets:first(Tab),[]), Stems)
end of
R ->
lists:reverse( lists:keysort(1,R) )
after
ets:delete(Tab)
end.
read_values(_Tab, '$end_of_table', Acc) -> Acc;
read_values(Tab, Key, Acc) ->
StemsN = lists:sort(
lists:map(fun({_,Stem,N}) -> {Stem,N} end,
ets:lookup(Tab,Key))),
read_values(Tab, ets:next(Tab,Key), [{Key,StemsN}|Acc]).
%%%----------------
%% L = [ {Key, [{Stem,N}]} ] (N = number of times the stem is in the item)
SearchedStems and Ws * must be usorted ( or at least sorted in the same way )
%% Joachims, Thorsten: A Probabilistic Analysis of the Rocchio Algorithm
%% with TFIDF for Text Categorization
March , 1996 CMU - CS-96 - 118
sort_search_result_TFIDF(Tab, L, SearchedStems) ->
Sz = mnesia:table_info(Tab, size),
IDF_W = lists:map(fun(Stem) ->
{Stem, 'IDF'(Stem, Sz)}
end, SearchedStems),
TF_WDprim = stem_ocurrences( lists:append(elements(2,L)) ),
SP1 = scalar_prod(TF_WDprim, IDF_W),
lists:map(fun(E={_,TF_WC}) ->
Weigth =
( SP1 * scalar_prod(TF_WC,IDF_W))
/ math:sqrt( sum_prod2(TF_WC,IDF_W) ),
{Weigth,E}
end, L).
'IDF'(W, Sz) -> R = math:log( Sz / 'DF'(W) ),
R*R.
'DF'(W) -> element(1, rdbms_wsearch_db:stems_doc(W)).
stem_ocurrences(L) -> so(lists:sort(L), []).
so([], Acc) -> lists:reverse(Acc);
so([{Stem,N}|L], [{Stem,Sum}|Acc]) -> so(L, [{Stem,Sum+N}|Acc]);
so([{Stem,N}|L], Acc) -> so(L, [{Stem,N}|Acc]).
%%% quad_sum(V) -> lists:foldl(fun({_,N},S) -> S + N*N end, 0, V).
sum_prod2(V1, V2) -> sum_prod2(V1, V2, 0).
sum_prod2([{S,N1}|V1], [{S,N2}|V2], Sum) -> sum_prod2(V1,V2, N1*N2*N2 + Sum);
sum_prod2(V1, [{_S,_N2}|V2], Sum) -> sum_prod2(V1,V2, Sum);
sum_prod2(_, _, Sum) -> Sum.
scalar_prod(V1,V2) -> scal_prod(V1, V2, 0).
scal_prod([{S,N1}|V1], [{S,N2}|V2], Sum) -> scal_prod(V1,V2, N1*N2 + Sum );
scal_prod(V1, [{_S,_N2}|V2], Sum) -> scal_prod(V1,V2, Sum);
scal_prod(_, _, Sum) -> Sum.
%%%----------------
%% A very simple one.
sort_search_result_most_occurences(Tab, L, _SearchedStems) ->
lists:map(fun(E={_K,Ws}) ->
{length(Ws),E}
end, L).
%%%----------------
%% A very simple one but weight after the importence in the whole db of the
%% words
sort_search_result_weighted_most_occurences(Tab, L, _SearchedStems) ->
Sz = mnesia:table_info(Tab, size),
lists:map(fun(E={_K,Ws}) ->
Weight =
lists:foldr(
fun({Stem,N}, S) ->
N*'IDF'(Stem, Sz) + S
end, 0, Ws),
{Weight,E}
end, L).
%%%----
MS = [ { Stem , N } ]
word_report(String, MS) ->
MatchingWords = lists:sort(matching_words(String, MS)),
word_list_and(
lists:map(fun({Stem,1}) -> Stem;
({Stem,N}) -> [Stem,"(",integer_to_list(N),")"]
end, count(MatchingWords))).
count(L) ->
lists:foldl(fun(W,[{W,N}|Acc]) -> [{W,N+1}|Acc];
(W,Acc) -> [{W,1}|Acc]
end, [], lists:sort(L)).
matching_words(Text, MatchingStems) ->
Words = rdbms_wsearch_idx:words(Text),
Stems = lists:map(fun(W) ->
lists:flatten(rdbms_wsearch_idx:idx_sentence(W))
end, Words),
matching_words(Stems, Words, MatchingStems, []).
matching_words([Stem|Stems], [Word|Words], MatchingStems, Acc) ->
case lists:member(Stem,MatchingStems) of
true ->
matching_words(
Stems, Words, MatchingStems, [lower_case(Word)|Acc]);
false ->
matching_words(Stems, Words, MatchingStems, Acc)
end;
matching_words([], [], _, Acc) ->
Acc.
elements(N, L) ->
[element(N, T) || T <- L].
word_list_and(Ws) -> word_list(Ws,"and").
word_list(Ws, Last) -> insert_delims(Ws, ", ", [" ",Last," "]).
insert_delims(Ws , ) - > insert_delims(Ws , Delim , Delim ) .
insert_delims(Ws, Delim, LastDelim) ->
lists:foldr(fun(W,A=[_,_|_]) -> [[W,Delim]|A];
(W,A=[_|_]) -> [[W,LastDelim]|A];
(W,A) -> [W|A]
end, [], Ws).
| null | https://raw.githubusercontent.com/gebi/jungerl/8f5c102295dbe903f47d79fd64714b7de17026ec/lib/rdbms/src/rdbms_wsearch.erl | erlang |
compliance with the License. You may obtain a copy of the License at
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
Contributor(s): ______________________________________.
----------------------------------------------------------------------
----------------------------------------------------------------------
-------------------------------------------------------------------
File : rdbms_wsearch.erl
Ulf Wiger <> (moved into rdbms)
Description : Word search indexing support
Uses the Porter Stemming Algorithm
-------------------------------------------------------------------
----------------
L = [ {Key, [{Stem,N}]} ] (N = number of times the stem is in the item)
Joachims, Thorsten: A Probabilistic Analysis of the Rocchio Algorithm
with TFIDF for Text Categorization
quad_sum(V) -> lists:foldl(fun({_,N},S) -> S + N*N end, 0, V).
----------------
A very simple one.
----------------
A very simple one but weight after the importence in the whole db of the
words
---- | The contents of this file are subject to the Erlang Public License ,
Version 1.0 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
The Original Code is rdbms-1.2 .
The Initial Developer of the Original Code is Ericsson Telecom
AB . Portions created by Ericsson are Copyright ( C ) , 1998 , Ericsson
Telecom AB . All Rights Reserved .
# 0 . BASIC INFORMATION
Author : < >
Created : 26 Jan 2006 by
-module(rdbms_wsearch).
-export([search/4,
word_report/2]).
-export([sort_search_result_TFIDF/3,
sort_search_result_most_occurences/3,
sort_search_result_weighted_most_occurences/3]).
-import(rdbms_wsearch_porter, [lower_case/1]).
search(Sentence, Tab, Index, SortFun) when is_function(SortFun, 2) ->
Stems = lists:usort(rdbms_wsearch_idx:idx_sentence(Sentence)),
SearchResult = do_search(Stems, Tab, Index, SortFun),
AllMatchingStems =
lists:usort(
lists:concat(
lists:map(fun({_Weight,{_Key,MS}}) ->
elements(1,MS)
end, SearchResult))),
{Stems, AllMatchingStems, SearchResult}.
Stems must be usort : ed ! !
do_search(Stems, Tab, Index, SortFun) ->
Tab = ets:new(tmptab, [bag]),
try begin
lists:foreach(
fun(Stem) ->
lists:foreach(
fun({Key,N}) when integer(Key) ->
ets:insert(Tab,{Key,Stem,N});
(_) ->
ok
end, mnesia:index_read(Tab, Stem, Index))
end, Stems),
SortFun(read_values(Tab,ets:first(Tab),[]), Stems)
end of
R ->
lists:reverse( lists:keysort(1,R) )
after
ets:delete(Tab)
end.
read_values(_Tab, '$end_of_table', Acc) -> Acc;
read_values(Tab, Key, Acc) ->
StemsN = lists:sort(
lists:map(fun({_,Stem,N}) -> {Stem,N} end,
ets:lookup(Tab,Key))),
read_values(Tab, ets:next(Tab,Key), [{Key,StemsN}|Acc]).
SearchedStems and Ws * must be usorted ( or at least sorted in the same way )
March , 1996 CMU - CS-96 - 118
sort_search_result_TFIDF(Tab, L, SearchedStems) ->
Sz = mnesia:table_info(Tab, size),
IDF_W = lists:map(fun(Stem) ->
{Stem, 'IDF'(Stem, Sz)}
end, SearchedStems),
TF_WDprim = stem_ocurrences( lists:append(elements(2,L)) ),
SP1 = scalar_prod(TF_WDprim, IDF_W),
lists:map(fun(E={_,TF_WC}) ->
Weigth =
( SP1 * scalar_prod(TF_WC,IDF_W))
/ math:sqrt( sum_prod2(TF_WC,IDF_W) ),
{Weigth,E}
end, L).
'IDF'(W, Sz) -> R = math:log( Sz / 'DF'(W) ),
R*R.
'DF'(W) -> element(1, rdbms_wsearch_db:stems_doc(W)).
stem_ocurrences(L) -> so(lists:sort(L), []).
so([], Acc) -> lists:reverse(Acc);
so([{Stem,N}|L], [{Stem,Sum}|Acc]) -> so(L, [{Stem,Sum+N}|Acc]);
so([{Stem,N}|L], Acc) -> so(L, [{Stem,N}|Acc]).
sum_prod2(V1, V2) -> sum_prod2(V1, V2, 0).
sum_prod2([{S,N1}|V1], [{S,N2}|V2], Sum) -> sum_prod2(V1,V2, N1*N2*N2 + Sum);
sum_prod2(V1, [{_S,_N2}|V2], Sum) -> sum_prod2(V1,V2, Sum);
sum_prod2(_, _, Sum) -> Sum.
scalar_prod(V1,V2) -> scal_prod(V1, V2, 0).
scal_prod([{S,N1}|V1], [{S,N2}|V2], Sum) -> scal_prod(V1,V2, N1*N2 + Sum );
scal_prod(V1, [{_S,_N2}|V2], Sum) -> scal_prod(V1,V2, Sum);
scal_prod(_, _, Sum) -> Sum.
sort_search_result_most_occurences(Tab, L, _SearchedStems) ->
lists:map(fun(E={_K,Ws}) ->
{length(Ws),E}
end, L).
sort_search_result_weighted_most_occurences(Tab, L, _SearchedStems) ->
Sz = mnesia:table_info(Tab, size),
lists:map(fun(E={_K,Ws}) ->
Weight =
lists:foldr(
fun({Stem,N}, S) ->
N*'IDF'(Stem, Sz) + S
end, 0, Ws),
{Weight,E}
end, L).
MS = [ { Stem , N } ]
word_report(String, MS) ->
MatchingWords = lists:sort(matching_words(String, MS)),
word_list_and(
lists:map(fun({Stem,1}) -> Stem;
({Stem,N}) -> [Stem,"(",integer_to_list(N),")"]
end, count(MatchingWords))).
count(L) ->
lists:foldl(fun(W,[{W,N}|Acc]) -> [{W,N+1}|Acc];
(W,Acc) -> [{W,1}|Acc]
end, [], lists:sort(L)).
matching_words(Text, MatchingStems) ->
Words = rdbms_wsearch_idx:words(Text),
Stems = lists:map(fun(W) ->
lists:flatten(rdbms_wsearch_idx:idx_sentence(W))
end, Words),
matching_words(Stems, Words, MatchingStems, []).
matching_words([Stem|Stems], [Word|Words], MatchingStems, Acc) ->
case lists:member(Stem,MatchingStems) of
true ->
matching_words(
Stems, Words, MatchingStems, [lower_case(Word)|Acc]);
false ->
matching_words(Stems, Words, MatchingStems, Acc)
end;
matching_words([], [], _, Acc) ->
Acc.
elements(N, L) ->
[element(N, T) || T <- L].
word_list_and(Ws) -> word_list(Ws,"and").
word_list(Ws, Last) -> insert_delims(Ws, ", ", [" ",Last," "]).
insert_delims(Ws , ) - > insert_delims(Ws , Delim , Delim ) .
insert_delims(Ws, Delim, LastDelim) ->
lists:foldr(fun(W,A=[_,_|_]) -> [[W,Delim]|A];
(W,A=[_|_]) -> [[W,LastDelim]|A];
(W,A) -> [W|A]
end, [], Ws).
|
437ff2bf10950832d5d9d647bd5bdb4c81fec1b024bceb1c89df4e203dc47933 | madstap/recex | cron_test.clj | (ns madstap.recex.cron-test
(:require
[clojure.string :as str]
[clojure.test :refer [deftest testing is are run-tests test-var]]
[madstap.recex :as recex]))
(defn recex= [& recexes]
(when-not (every? recex/valid? recexes)
(throw (ex-info (-> (keep recex/explain-str recexes) (str/join "\n"))
{:invalid-recexes (remove recex/valid? recexes)})))
(apply = (map recex/normalize recexes)))
(def every-min {:m {0 59} :h {0 23}})
(deftest cron->recex
(is (recex= #{[2 {:m 0 :h 2} "Europe/Oslo"]
[:tue {:m 0 :h 2} "Europe/Oslo"]} (recex/cron->recex "0 2 2 * 2" "Europe/Oslo")))
(is (recex= [{:m 0 :h 2} "Europe/Oslo"] (recex/cron->recex "0 2 * * *" "Europe/Oslo")))
(is (recex= [{:s 30 :m {0 59}, :h {0 23}}] (recex/cron->recex "30 * * * * *")))
(is (recex= [{:m {0 59}, :h #{0 20 10}}] (recex/cron->recex "* /10 * * *")))
(is (recex= [{:m {2 4}, :h #{4 6 2}}] (recex/cron->recex "2-4 2-6/2 * * *")))
(is (recex= [{:m {2 4}, :h #{20 22}}] (recex/cron->recex "2-4 20/2 * * *")))
(is (recex= [{:m {2 4}, :h #{1 2 20 22}}] (recex/cron->recex "2-4 1,2,20/2 * * *")))
(is (recex= [{:m #{56 58}, :h {0 23}}] (recex/cron->recex "56/2 * * * *")))
(is (recex= [:sun every-min] (recex/cron->recex "* * * * 7")))
(is (recex= [{:tue :fri} every-min] (recex/cron->recex "* * * * 2-5")))
(is (recex= [{:sun :fri} every-min] (recex/cron->recex "* * * * 0-5")))
(is (recex= [{:fri :sun} every-min] (recex/cron->recex "* * * * 5-7")))
(is (recex= [:feb every-min] (recex/cron->recex "* * * 2 *")))
(is (recex= [:feb every-min] (recex/cron->recex "* * * 2 *")))
(is (recex= [#{:aug :oct :dec} every-min] (recex/cron->recex "* * * 8/2 *")))
(is (recex= [#{:feb #{:aug :oct :dec}} every-min] (recex/cron->recex "* * * 2,8/2 *")))
(is (recex= [#{:feb #{:aug :oct}} every-min] (recex/cron->recex "* * * 2,8-10/2 *")))
(is (recex= [#{:feb #{:aug :oct}} every-min] (recex/cron->recex "* * * feb,aug-oct/2 *")))
(is (recex= [#{:feb #{:aug :oct}} :mon every-min] (recex/cron->recex "* * * feb,aug-oct/2 mon")))
(is (recex= [#{#{:aug :oct :dec}} every-min] (recex/cron->recex "* * * aug/2 *")))
(is (recex= [#{29 30 31} every-min] (recex/cron->recex "* * 29/1 * *")))
(is (recex= [#{#{:aug :sep :oct :nov :dec}} every-min] (recex/cron->recex "* * * aug/1 *")))
(is (recex= #{[:feb {:tue :thur} every-min]
[:feb 2 every-min] } (recex/cron->recex "* * 2 2 2-4")))
(is (recex= #{[{:tue :thur} every-min]
[{2 10} every-min] } (recex/cron->recex "* * 2-10 * 2-4")))
(is (recex= [[1 :mon] {:m 0 :h 0}] (recex/cron->recex "0 0 * * mon#1")))
(is (recex= [[-1 :fri] {:m 0 :h 0}] (recex/cron->recex "0 0 * * friL")))
(is (recex= [[-3 :fri] {:m 0 :h 0}] (recex/cron->recex "0 0 * * friL-3")))
(is (recex= [-1 {:m 0 :h 0}] (recex/cron->recex "0 0 L * *")))
(is (recex= [-20 {:m 0 :h 0}] (recex/cron->recex "0 0 L-20 * *"))))
| null | https://raw.githubusercontent.com/madstap/recex/8414f9779e6444e6c1d442ca24b46db1d48f7dae/test/madstap/recex/cron_test.clj | clojure | (ns madstap.recex.cron-test
(:require
[clojure.string :as str]
[clojure.test :refer [deftest testing is are run-tests test-var]]
[madstap.recex :as recex]))
(defn recex= [& recexes]
(when-not (every? recex/valid? recexes)
(throw (ex-info (-> (keep recex/explain-str recexes) (str/join "\n"))
{:invalid-recexes (remove recex/valid? recexes)})))
(apply = (map recex/normalize recexes)))
(def every-min {:m {0 59} :h {0 23}})
(deftest cron->recex
(is (recex= #{[2 {:m 0 :h 2} "Europe/Oslo"]
[:tue {:m 0 :h 2} "Europe/Oslo"]} (recex/cron->recex "0 2 2 * 2" "Europe/Oslo")))
(is (recex= [{:m 0 :h 2} "Europe/Oslo"] (recex/cron->recex "0 2 * * *" "Europe/Oslo")))
(is (recex= [{:s 30 :m {0 59}, :h {0 23}}] (recex/cron->recex "30 * * * * *")))
(is (recex= [{:m {0 59}, :h #{0 20 10}}] (recex/cron->recex "* /10 * * *")))
(is (recex= [{:m {2 4}, :h #{4 6 2}}] (recex/cron->recex "2-4 2-6/2 * * *")))
(is (recex= [{:m {2 4}, :h #{20 22}}] (recex/cron->recex "2-4 20/2 * * *")))
(is (recex= [{:m {2 4}, :h #{1 2 20 22}}] (recex/cron->recex "2-4 1,2,20/2 * * *")))
(is (recex= [{:m #{56 58}, :h {0 23}}] (recex/cron->recex "56/2 * * * *")))
(is (recex= [:sun every-min] (recex/cron->recex "* * * * 7")))
(is (recex= [{:tue :fri} every-min] (recex/cron->recex "* * * * 2-5")))
(is (recex= [{:sun :fri} every-min] (recex/cron->recex "* * * * 0-5")))
(is (recex= [{:fri :sun} every-min] (recex/cron->recex "* * * * 5-7")))
(is (recex= [:feb every-min] (recex/cron->recex "* * * 2 *")))
(is (recex= [:feb every-min] (recex/cron->recex "* * * 2 *")))
(is (recex= [#{:aug :oct :dec} every-min] (recex/cron->recex "* * * 8/2 *")))
(is (recex= [#{:feb #{:aug :oct :dec}} every-min] (recex/cron->recex "* * * 2,8/2 *")))
(is (recex= [#{:feb #{:aug :oct}} every-min] (recex/cron->recex "* * * 2,8-10/2 *")))
(is (recex= [#{:feb #{:aug :oct}} every-min] (recex/cron->recex "* * * feb,aug-oct/2 *")))
(is (recex= [#{:feb #{:aug :oct}} :mon every-min] (recex/cron->recex "* * * feb,aug-oct/2 mon")))
(is (recex= [#{#{:aug :oct :dec}} every-min] (recex/cron->recex "* * * aug/2 *")))
(is (recex= [#{29 30 31} every-min] (recex/cron->recex "* * 29/1 * *")))
(is (recex= [#{#{:aug :sep :oct :nov :dec}} every-min] (recex/cron->recex "* * * aug/1 *")))
(is (recex= #{[:feb {:tue :thur} every-min]
[:feb 2 every-min] } (recex/cron->recex "* * 2 2 2-4")))
(is (recex= #{[{:tue :thur} every-min]
[{2 10} every-min] } (recex/cron->recex "* * 2-10 * 2-4")))
(is (recex= [[1 :mon] {:m 0 :h 0}] (recex/cron->recex "0 0 * * mon#1")))
(is (recex= [[-1 :fri] {:m 0 :h 0}] (recex/cron->recex "0 0 * * friL")))
(is (recex= [[-3 :fri] {:m 0 :h 0}] (recex/cron->recex "0 0 * * friL-3")))
(is (recex= [-1 {:m 0 :h 0}] (recex/cron->recex "0 0 L * *")))
(is (recex= [-20 {:m 0 :h 0}] (recex/cron->recex "0 0 L-20 * *"))))
|
|
ed02d3f846660a03dd6a6a39e1324fbb4a5e0767f1706a0bce99d76f0b4c41bb | dsorokin/aivika | MachRep2.hs |
It corresponds to model MachRep2 described in document
-- Introduction to Discrete-Event Simulation and the SimPy Language
-- [/~matloff/156/PLN/DESimIntro.pdf].
SimPy is available on [ / ] .
--
-- The model description is as follows.
--
Two machines , but sometimes break down . Up time is exponentially
distributed with mean 1.0 , and repair time is exponentially distributed
with mean 0.5 . In this example , there is only one repairperson , so
the two machines can not be repaired simultaneously if they are down
-- at the same time.
--
-- In addition to finding the long-run proportion of up time as in
-- model MachRep1, let’s also find the long-run proportion of the time
-- that a given machine does not have immediate access to the repairperson
when the machine breaks down . Output values should be about 0.6 and 0.67 .
import Control.Monad
import Control.Monad.Trans
import Simulation.Aivika
meanUpTime = 1.0
meanRepairTime = 0.5
specs = Specs { spcStartTime = 0.0,
spcStopTime = 1000.0,
spcDT = 1.0,
spcMethod = RungeKutta4,
spcGeneratorType = SimpleGenerator }
model :: Simulation Results
model =
do -- number of times the machines have broken down
nRep <- newRef 0
-- number of breakdowns in which the machine
-- started repair service right away
nImmedRep <- newRef 0
-- total up time for all machines
totalUpTime <- newRef 0.0
repairPerson <- newFCFSResource 1
let machine :: Process ()
machine =
do upTime <-
randomExponentialProcess meanUpTime
liftEvent $
modifyRef totalUpTime (+ upTime)
-- check the resource availability
liftEvent $
do modifyRef nRep (+ 1)
n <- resourceCount repairPerson
when (n == 1) $
modifyRef nImmedRep (+ 1)
requestResource repairPerson
repairTime <-
randomExponentialProcess meanRepairTime
releaseResource repairPerson
machine
runProcessInStartTime machine
runProcessInStartTime machine
let upTimeProp =
do x <- readRef totalUpTime
y <- liftDynamics time
return $ x / (2 * y)
immedProp :: Event Double
immedProp =
do n <- readRef nRep
nImmed <- readRef nImmedRep
return $
fromIntegral nImmed /
fromIntegral n
return $
results
[resultSource
"upTimeProp"
"The long-run proportion of up time (~ 0.6)"
upTimeProp,
--
resultSource
"immedProp"
"The proption of time of immediate access (~0.67)"
immedProp]
main =
printSimulationResultsInStopTime
printResultSourceInEnglish
model specs
| null | https://raw.githubusercontent.com/dsorokin/aivika/7a14f460ab114b0f8cdfcd05d5cc889fdc2db0a4/examples/MachRep2.hs | haskell | Introduction to Discrete-Event Simulation and the SimPy Language
[/~matloff/156/PLN/DESimIntro.pdf].
The model description is as follows.
at the same time.
In addition to finding the long-run proportion of up time as in
model MachRep1, let’s also find the long-run proportion of the time
that a given machine does not have immediate access to the repairperson
number of times the machines have broken down
number of breakdowns in which the machine
started repair service right away
total up time for all machines
check the resource availability
|
It corresponds to model MachRep2 described in document
SimPy is available on [ / ] .
Two machines , but sometimes break down . Up time is exponentially
distributed with mean 1.0 , and repair time is exponentially distributed
with mean 0.5 . In this example , there is only one repairperson , so
the two machines can not be repaired simultaneously if they are down
when the machine breaks down . Output values should be about 0.6 and 0.67 .
import Control.Monad
import Control.Monad.Trans
import Simulation.Aivika
meanUpTime = 1.0
meanRepairTime = 0.5
specs = Specs { spcStartTime = 0.0,
spcStopTime = 1000.0,
spcDT = 1.0,
spcMethod = RungeKutta4,
spcGeneratorType = SimpleGenerator }
model :: Simulation Results
model =
nRep <- newRef 0
nImmedRep <- newRef 0
totalUpTime <- newRef 0.0
repairPerson <- newFCFSResource 1
let machine :: Process ()
machine =
do upTime <-
randomExponentialProcess meanUpTime
liftEvent $
modifyRef totalUpTime (+ upTime)
liftEvent $
do modifyRef nRep (+ 1)
n <- resourceCount repairPerson
when (n == 1) $
modifyRef nImmedRep (+ 1)
requestResource repairPerson
repairTime <-
randomExponentialProcess meanRepairTime
releaseResource repairPerson
machine
runProcessInStartTime machine
runProcessInStartTime machine
let upTimeProp =
do x <- readRef totalUpTime
y <- liftDynamics time
return $ x / (2 * y)
immedProp :: Event Double
immedProp =
do n <- readRef nRep
nImmed <- readRef nImmedRep
return $
fromIntegral nImmed /
fromIntegral n
return $
results
[resultSource
"upTimeProp"
"The long-run proportion of up time (~ 0.6)"
upTimeProp,
resultSource
"immedProp"
"The proption of time of immediate access (~0.67)"
immedProp]
main =
printSimulationResultsInStopTime
printResultSourceInEnglish
model specs
|
af59d0b371ffc14cd8ecdcd05dac34618e5d41fe9a336a76d6f4435c02fa5b6b | reanimate/reanimate | doc_linear.hs | #!/usr/bin/env stack
-- stack runghc --package reanimate
{-# LANGUAGE OverloadedStrings #-}
module Main(main) where
import Reanimate
import Reanimate.Builtin.Documentation
import Reanimate.Morph.Common
import Reanimate.Morph.Linear
import Graphics.SvgTree
main :: IO ()
main = reanimate $ docEnv $ playThenReverseA $ pauseAround 0.5 0.5 $ mkAnimation 3 $ \t ->
withStrokeLineJoin JoinRound $
let src = scale 8 $ center $ latex "X"
dst = scale 8 $ center $ latex "H"
in morph linear src dst t
| null | https://raw.githubusercontent.com/reanimate/reanimate/5ea023980ff7f488934d40593cc5069f5fd038b0/examples/doc_linear.hs | haskell | stack runghc --package reanimate
# LANGUAGE OverloadedStrings # | #!/usr/bin/env stack
module Main(main) where
import Reanimate
import Reanimate.Builtin.Documentation
import Reanimate.Morph.Common
import Reanimate.Morph.Linear
import Graphics.SvgTree
main :: IO ()
main = reanimate $ docEnv $ playThenReverseA $ pauseAround 0.5 0.5 $ mkAnimation 3 $ \t ->
withStrokeLineJoin JoinRound $
let src = scale 8 $ center $ latex "X"
dst = scale 8 $ center $ latex "H"
in morph linear src dst t
|
05ad6bb339bd7802546100213958ec95f8e969a5c5182a2ba30e92a122842952 | grasswire/chat-app | DataStore.hs | {-# LANGUAGE OverloadedStrings #-}
module DataStore
(
RedisAction
, runRedisAction
, numUsersPresent
, setChannelPresence
, incrChannelPresence
, decrChannelPresence
, getPresenceForChannels
) where
import ClassyPrelude
import Database.Redis
import qualified Types as TP
import Control.Monad.Trans.Except
import qualified Data.ByteString.Char8 as C8
import Taplike.Schema (ChannelSlug, unSlug)
import Data.Typeable
import Control.Monad.Catch
import Control.Monad.IO.Class
type RedisAction a = ExceptT Reply (ReaderT Connection IO) a
runRedisAction :: Connection -> RedisAction a -> IO (Either Reply a)
runRedisAction conn action = runReaderT (runExceptT action) conn
withRedisExcept :: (Connection -> IO (Either Reply a)) -> RedisAction a
withRedisExcept = ExceptT . ReaderT
channelPresenceSetKey :: ByteString
channelPresenceSetKey = C8.pack "channels:presence"
channelPresenceKey :: ChannelSlug -> ByteString
channelPresenceKey = encodeUtf8 . (\slug -> "channel:" <> slug <> ":presence") . unSlug
numUsersPresent :: ChannelSlug -> RedisAction (Maybe TP.NumberUsersPresent)
numUsersPresent key = listToMaybe <$> getPresenceForChannels [key]
toUsersPresent :: Double -> TP.NumberUsersPresent
toUsersPresent = TP.NumberUsersPresent . fromIntegral . round
-- setChannelPresence :: Integer -> ChannelSlug -> RedisAction Integer
setChannelPresence score channelId = withRedisExcept $ \conn - > do
let key = channelPresenceKey channelId
-- runRedis conn $ do
-- currentPresence <- hget channelPresenceSetKey key
-- case currentPresence of
-- Left err -> pure $ Left err
-- Right x ->
-- case x of
-- Just p -> do
let = fst < $ > C8.readInteger p
case of
-- Just i -> hincrby channelPresenceSetKey key (score - i)
-- _ -> pure $ Left (Error $ C8.pack "could not parse hash field as an integer")
-- _ -> pure $ Left (Error $ C8.pack "received Nothing for hash field")
data RedisException = RedisException String
deriving (Show, Typeable)
instance Exception RedisException
setChannelPresence :: (MonadIO m, MonadThrow m) => Integer -> ChannelSlug -> ReaderT Connection m Integer
setChannelPresence score channelId = do
let key = channelPresenceKey channelId
conn <- ask
currentPresence <- liftIO $ runRedis conn (hget channelPresenceSetKey key)
case currentPresence of
Left e -> throwM (RedisException $ show e)
Right x -> case x of
Nothing -> throwM (RedisException "received Nothing for hash field")
Just p -> do
let maybeInteger = fst <$> C8.readInteger p
case maybeInteger of
Just i -> do
result <- liftIO $ runRedis conn (hincrby channelPresenceSetKey key (score - i))
either (throwM . RedisException . show) return result
Nothing -> throwM (RedisException "could not parse hash field as an integer")
incrChannelPresence :: ChannelSlug -> RedisAction Integer
incrChannelPresence channelId = withRedisExcept $ \conn -> do
let action = hincrby channelPresenceSetKey (channelPresenceKey channelId) 1
runRedis conn action
decrChannelPresence :: ChannelSlug -> RedisAction Integer
decrChannelPresence channelId = withRedisExcept $ \conn -> do
let action = hincrby channelPresenceSetKey (channelPresenceKey channelId) (-1)
runRedis conn action
getPresenceForChannels :: [ChannelSlug] -> RedisAction [TP.NumberUsersPresent]
getPresenceForChannels channelIds = withRedisExcept $ \conn -> do
let fields = fmap channelPresenceKey channelIds
action = hmget channelPresenceSetKey fields
defaultPresence = TP.NumberUsersPresent 0
result <- runRedis conn action
case result of
Right xs -> return $ Right $ fmap (maybe defaultPresence (\x -> fromMaybe defaultPresence (TP.NumberUsersPresent <$> readMay (C8.unpack x)))) xs
_ -> return $ Right (replicate (length channelIds) defaultPresence) | null | https://raw.githubusercontent.com/grasswire/chat-app/a8ae4e782cacd902d7ec9c68c40a939cc5cabb0a/backend/DataStore.hs | haskell | # LANGUAGE OverloadedStrings #
setChannelPresence :: Integer -> ChannelSlug -> RedisAction Integer
runRedis conn $ do
currentPresence <- hget channelPresenceSetKey key
case currentPresence of
Left err -> pure $ Left err
Right x ->
case x of
Just p -> do
Just i -> hincrby channelPresenceSetKey key (score - i)
_ -> pure $ Left (Error $ C8.pack "could not parse hash field as an integer")
_ -> pure $ Left (Error $ C8.pack "received Nothing for hash field") |
module DataStore
(
RedisAction
, runRedisAction
, numUsersPresent
, setChannelPresence
, incrChannelPresence
, decrChannelPresence
, getPresenceForChannels
) where
import ClassyPrelude
import Database.Redis
import qualified Types as TP
import Control.Monad.Trans.Except
import qualified Data.ByteString.Char8 as C8
import Taplike.Schema (ChannelSlug, unSlug)
import Data.Typeable
import Control.Monad.Catch
import Control.Monad.IO.Class
type RedisAction a = ExceptT Reply (ReaderT Connection IO) a
runRedisAction :: Connection -> RedisAction a -> IO (Either Reply a)
runRedisAction conn action = runReaderT (runExceptT action) conn
withRedisExcept :: (Connection -> IO (Either Reply a)) -> RedisAction a
withRedisExcept = ExceptT . ReaderT
channelPresenceSetKey :: ByteString
channelPresenceSetKey = C8.pack "channels:presence"
channelPresenceKey :: ChannelSlug -> ByteString
channelPresenceKey = encodeUtf8 . (\slug -> "channel:" <> slug <> ":presence") . unSlug
numUsersPresent :: ChannelSlug -> RedisAction (Maybe TP.NumberUsersPresent)
numUsersPresent key = listToMaybe <$> getPresenceForChannels [key]
toUsersPresent :: Double -> TP.NumberUsersPresent
toUsersPresent = TP.NumberUsersPresent . fromIntegral . round
setChannelPresence score channelId = withRedisExcept $ \conn - > do
let key = channelPresenceKey channelId
let = fst < $ > C8.readInteger p
case of
data RedisException = RedisException String
deriving (Show, Typeable)
instance Exception RedisException
setChannelPresence :: (MonadIO m, MonadThrow m) => Integer -> ChannelSlug -> ReaderT Connection m Integer
setChannelPresence score channelId = do
let key = channelPresenceKey channelId
conn <- ask
currentPresence <- liftIO $ runRedis conn (hget channelPresenceSetKey key)
case currentPresence of
Left e -> throwM (RedisException $ show e)
Right x -> case x of
Nothing -> throwM (RedisException "received Nothing for hash field")
Just p -> do
let maybeInteger = fst <$> C8.readInteger p
case maybeInteger of
Just i -> do
result <- liftIO $ runRedis conn (hincrby channelPresenceSetKey key (score - i))
either (throwM . RedisException . show) return result
Nothing -> throwM (RedisException "could not parse hash field as an integer")
incrChannelPresence :: ChannelSlug -> RedisAction Integer
incrChannelPresence channelId = withRedisExcept $ \conn -> do
let action = hincrby channelPresenceSetKey (channelPresenceKey channelId) 1
runRedis conn action
decrChannelPresence :: ChannelSlug -> RedisAction Integer
decrChannelPresence channelId = withRedisExcept $ \conn -> do
let action = hincrby channelPresenceSetKey (channelPresenceKey channelId) (-1)
runRedis conn action
getPresenceForChannels :: [ChannelSlug] -> RedisAction [TP.NumberUsersPresent]
getPresenceForChannels channelIds = withRedisExcept $ \conn -> do
let fields = fmap channelPresenceKey channelIds
action = hmget channelPresenceSetKey fields
defaultPresence = TP.NumberUsersPresent 0
result <- runRedis conn action
case result of
Right xs -> return $ Right $ fmap (maybe defaultPresence (\x -> fromMaybe defaultPresence (TP.NumberUsersPresent <$> readMay (C8.unpack x)))) xs
_ -> return $ Right (replicate (length channelIds) defaultPresence) |
22836b3866efeadedb8c179c47a6db0a6dce90c8469cad7c5a80e9d0aa060ea5 | austral/austral | BuiltIn.ml |
Part of the Austral project , under the Apache License v2.0 with LLVM Exceptions .
See LICENSE file for details .
SPDX - License - Identifier : Apache-2.0 WITH LLVM - exception
Part of the Austral project, under the Apache License v2.0 with LLVM Exceptions.
See LICENSE file for details.
SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*)
open Identifier
open Cst
open Names
Austral . Pervasive
let pervasive_module_name = make_mod_name "Austral.Pervasive"
let pervasive_imports =
ConcreteImportList (
pervasive_module_name,
[
ConcreteImport (make_ident "Option", None);
ConcreteImport (make_ident "Some", None);
ConcreteImport (make_ident "None", None);
ConcreteImport (make_ident "Either", None);
ConcreteImport (make_ident "Left", None);
ConcreteImport (make_ident "Right", None);
ConcreteImport (make_ident "swap", None);
ConcreteImport (make_ident "fixedArraySize", None);
ConcreteImport (make_ident "abort", None);
ConcreteImport (make_ident "RootCapability", None);
ConcreteImport (make_ident "surrenderRoot", None);
ConcreteImport (make_ident "ExitCode", None);
ConcreteImport (make_ident "ExitSuccess", None);
ConcreteImport (make_ident "ExitFailure", None);
ConcreteImport (make_ident "maximum_nat8", None);
ConcreteImport (make_ident "maximum_nat16", None);
ConcreteImport (make_ident "maximum_nat32", None);
ConcreteImport (make_ident "maximum_nat64", None);
ConcreteImport (make_ident "minimum_int8", None);
ConcreteImport (make_ident "minimum_int16", None);
ConcreteImport (make_ident "minimum_int32", None);
ConcreteImport (make_ident "minimum_int64", None);
ConcreteImport (make_ident "maximum_int8", None);
ConcreteImport (make_ident "maximum_int16", None);
ConcreteImport (make_ident "maximum_int32", None);
ConcreteImport (make_ident "maximum_int64", None);
ConcreteImport (make_ident "minimum_bytesize", None);
ConcreteImport (make_ident "maximum_bytesize", None);
ConcreteImport (make_ident "minimum_index", None);
ConcreteImport (make_ident "maximum_index", None);
ConcreteImport (make_ident "TrappingArithmetic", None);
ConcreteImport (make_ident "trappingAdd", None);
ConcreteImport (make_ident "trappingSubtract", None);
ConcreteImport (make_ident "trappingMultiply", None);
ConcreteImport (make_ident "trappingDivide", None);
ConcreteImport (make_ident "ModularArithmetic", None);
ConcreteImport (make_ident "modularAdd", None);
ConcreteImport (make_ident "modularSubtract", None);
ConcreteImport (make_ident "modularMultiply", None);
ConcreteImport (make_ident "modularDivide", None);
ConcreteImport (make_ident "BitwiseOperations", None);
ConcreteImport (make_ident "bitwiseAnd", None);
ConcreteImport (make_ident "bitwiseOr", None);
ConcreteImport (make_ident "bitwiseXor", None);
ConcreteImport (make_ident "bitwiseNot", None);
ConcreteImport (make_ident "Printable", None);
ConcreteImport (make_ident "print", None);
ConcreteImport (make_ident "printLn", None);
ConcreteImport (make_ident "argumentCount", None);
ConcreteImport (make_ident "nthArgument", None);
ConcreteImport (make_ident "ToNat8", None);
ConcreteImport (make_ident "toNat8", None);
ConcreteImport (make_ident "ToNat16", None);
ConcreteImport (make_ident "toNat16", None);
ConcreteImport (make_ident "ToNat32", None);
ConcreteImport (make_ident "toNat32", None);
ConcreteImport (make_ident "ToNat64", None);
ConcreteImport (make_ident "toNat64", None);
ConcreteImport (make_ident "ToInt8", None);
ConcreteImport (make_ident "toInt8", None);
ConcreteImport (make_ident "ToInt16", None);
ConcreteImport (make_ident "toInt16", None);
ConcreteImport (make_ident "ToInt32", None);
ConcreteImport (make_ident "toInt32", None);
ConcreteImport (make_ident "ToInt64", None);
ConcreteImport (make_ident "toInt64", None);
ConcreteImport (make_ident "ToIndex", None);
ConcreteImport (make_ident "toIndex", None);
]
)
(* Austral.Memory *)
let memory_module_name = make_mod_name "Austral.Memory"
let is_address_type (name: qident): bool =
let s = source_module_name name
and o = original_name name
in
(equal_module_name s memory_module_name)
&& (equal_identifier o (make_ident address_name))
let is_pointer_type (name: qident): bool =
let s = source_module_name name
and o = original_name name
in
(equal_module_name s memory_module_name)
&& (equal_identifier o (make_ident pointer_name))
| null | https://raw.githubusercontent.com/austral/austral/69b6f7de36cc9576483acd1ac4a31bf52074dbd1/lib/BuiltIn.ml | ocaml | Austral.Memory |
Part of the Austral project , under the Apache License v2.0 with LLVM Exceptions .
See LICENSE file for details .
SPDX - License - Identifier : Apache-2.0 WITH LLVM - exception
Part of the Austral project, under the Apache License v2.0 with LLVM Exceptions.
See LICENSE file for details.
SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*)
open Identifier
open Cst
open Names
Austral . Pervasive
let pervasive_module_name = make_mod_name "Austral.Pervasive"
let pervasive_imports =
ConcreteImportList (
pervasive_module_name,
[
ConcreteImport (make_ident "Option", None);
ConcreteImport (make_ident "Some", None);
ConcreteImport (make_ident "None", None);
ConcreteImport (make_ident "Either", None);
ConcreteImport (make_ident "Left", None);
ConcreteImport (make_ident "Right", None);
ConcreteImport (make_ident "swap", None);
ConcreteImport (make_ident "fixedArraySize", None);
ConcreteImport (make_ident "abort", None);
ConcreteImport (make_ident "RootCapability", None);
ConcreteImport (make_ident "surrenderRoot", None);
ConcreteImport (make_ident "ExitCode", None);
ConcreteImport (make_ident "ExitSuccess", None);
ConcreteImport (make_ident "ExitFailure", None);
ConcreteImport (make_ident "maximum_nat8", None);
ConcreteImport (make_ident "maximum_nat16", None);
ConcreteImport (make_ident "maximum_nat32", None);
ConcreteImport (make_ident "maximum_nat64", None);
ConcreteImport (make_ident "minimum_int8", None);
ConcreteImport (make_ident "minimum_int16", None);
ConcreteImport (make_ident "minimum_int32", None);
ConcreteImport (make_ident "minimum_int64", None);
ConcreteImport (make_ident "maximum_int8", None);
ConcreteImport (make_ident "maximum_int16", None);
ConcreteImport (make_ident "maximum_int32", None);
ConcreteImport (make_ident "maximum_int64", None);
ConcreteImport (make_ident "minimum_bytesize", None);
ConcreteImport (make_ident "maximum_bytesize", None);
ConcreteImport (make_ident "minimum_index", None);
ConcreteImport (make_ident "maximum_index", None);
ConcreteImport (make_ident "TrappingArithmetic", None);
ConcreteImport (make_ident "trappingAdd", None);
ConcreteImport (make_ident "trappingSubtract", None);
ConcreteImport (make_ident "trappingMultiply", None);
ConcreteImport (make_ident "trappingDivide", None);
ConcreteImport (make_ident "ModularArithmetic", None);
ConcreteImport (make_ident "modularAdd", None);
ConcreteImport (make_ident "modularSubtract", None);
ConcreteImport (make_ident "modularMultiply", None);
ConcreteImport (make_ident "modularDivide", None);
ConcreteImport (make_ident "BitwiseOperations", None);
ConcreteImport (make_ident "bitwiseAnd", None);
ConcreteImport (make_ident "bitwiseOr", None);
ConcreteImport (make_ident "bitwiseXor", None);
ConcreteImport (make_ident "bitwiseNot", None);
ConcreteImport (make_ident "Printable", None);
ConcreteImport (make_ident "print", None);
ConcreteImport (make_ident "printLn", None);
ConcreteImport (make_ident "argumentCount", None);
ConcreteImport (make_ident "nthArgument", None);
ConcreteImport (make_ident "ToNat8", None);
ConcreteImport (make_ident "toNat8", None);
ConcreteImport (make_ident "ToNat16", None);
ConcreteImport (make_ident "toNat16", None);
ConcreteImport (make_ident "ToNat32", None);
ConcreteImport (make_ident "toNat32", None);
ConcreteImport (make_ident "ToNat64", None);
ConcreteImport (make_ident "toNat64", None);
ConcreteImport (make_ident "ToInt8", None);
ConcreteImport (make_ident "toInt8", None);
ConcreteImport (make_ident "ToInt16", None);
ConcreteImport (make_ident "toInt16", None);
ConcreteImport (make_ident "ToInt32", None);
ConcreteImport (make_ident "toInt32", None);
ConcreteImport (make_ident "ToInt64", None);
ConcreteImport (make_ident "toInt64", None);
ConcreteImport (make_ident "ToIndex", None);
ConcreteImport (make_ident "toIndex", None);
]
)
let memory_module_name = make_mod_name "Austral.Memory"
let is_address_type (name: qident): bool =
let s = source_module_name name
and o = original_name name
in
(equal_module_name s memory_module_name)
&& (equal_identifier o (make_ident address_name))
let is_pointer_type (name: qident): bool =
let s = source_module_name name
and o = original_name name
in
(equal_module_name s memory_module_name)
&& (equal_identifier o (make_ident pointer_name))
|
c4010b49ca8666450d0d13e069d287b5905f46c701b7e3273519163322cdf982 | evturn/haskellbook | 19.02-templating-content-in-scotty.hs | {-# LANGUAGE OverloadedStrings #-}
import Web.Scotty
import Data.Monoid (mconcat)
main = scotty 3000 $ do
get "/word" $ do
beam <- param "word"
html
(mconcat
[ "<h1>Scotty, "
, beam
, " me up!</h1>"])
| null | https://raw.githubusercontent.com/evturn/haskellbook/3d310d0ddd4221ffc5b9fd7ec6476b2a0731274a/19/19.02-templating-content-in-scotty.hs | haskell | # LANGUAGE OverloadedStrings # |
import Web.Scotty
import Data.Monoid (mconcat)
main = scotty 3000 $ do
get "/word" $ do
beam <- param "word"
html
(mconcat
[ "<h1>Scotty, "
, beam
, " me up!</h1>"])
|
65ab5c6971182fd2e0a8f01fe47c0a860f2e7b0b532878a19cd7012008f0563b | ates/radius | radius_service.erl | -module(radius_service).
-behaviour(gen_server).
%% API
-export([start_link/5]).
-export([name/1]).
-export([stop/1]).
-export([stats/1]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2,
handle_info/2, code_change/3, terminate/2]).
-include("radius.hrl").
-callback handle_request(Type :: non_neg_integer(),
Request :: #radius_packet{},
Client :: #nas_spec{}) ->
{ok, Response :: #radius_packet{}} | noreply.
-callback handle_error(Reason :: term(), Data :: term()) -> any().
-record(state, {
name :: atom(),
socket :: inet:socket(),
requests :: ets:tid(), %% table used to store requests from clients
callback :: module()
}).
start_link(Name, IP, Port, Callback, SocketOpts) ->
gen_server:start_link(?MODULE, [Name, IP, Port, Callback, SocketOpts], []).
name(Pid) -> gen_server:call(Pid, name).
stop(Pid) -> gen_server:call(Pid, stop).
stats(Pid) -> gen_server:call(Pid, stats).
init([Name, IP, Port, Callback, SocketOpts]) ->
process_flag(trap_exit, true),
case gen_udp:open(Port, [binary, {ip, IP}, {reuseaddr, true} | SocketOpts]) of
{ok, Socket} ->
%% creates the table to store requests from clients
%% made it public to allow access from spawned processes(callback)
Requests = ets:new(radius_requests, [public]),
{ok, #state{name = Name, socket = Socket, requests = Requests, callback = Callback}};
{error, Reason} ->
{error, Reason}
end.
handle_call(stats, _From, State) ->
{reply, inet:getstat(State#state.socket), State};
handle_call(name, _From, State) ->
{reply, State#state.name, State};
handle_call(stop, _From, State) ->
{stop, normal, ok, State};
handle_call(_Request, _From, State) -> {reply, ok, State}.
handle_cast(_Msg, State) -> {noreply, State}.
handle_info({udp, Socket, SrcIP, SrcPort, Bin}, State) ->
Opts = [SrcIP, SrcPort, Socket, Bin, State],
proc_lib:spawn_link(fun() -> do_callback(Opts) end),
{noreply, State};
handle_info({'EXIT', _Pid, normal}, State) -> {noreply, State};
handle_info({'EXIT', Pid, _Reason}, #state{requests = Requests} = State) ->
case ets:match_object(Requests, {'_', Pid}) of
[{{IP, Port, Ident}, Pid}] ->
ets:delete(Requests, {IP, Port, Ident});
[] -> ok
end,
{noreply, State}.
code_change(_OldVsn, State, _Extra) -> {ok, State}.
terminate(Reason, State) ->
case Reason of
normal ->
true = ets:delete(radius_clients, State#state.name);
_ -> ok
end,
gen_udp:close(State#state.socket).
Internal functions
do_callback([SrcIP, SrcPort, Socket, Bin, #state{requests = Requests, callback = Callback} = State]) ->
case lookup_client(SrcIP, State#state.name) of
{ok, #nas_spec{secret = Secret} = Client} ->
case radius_codec:decode_packet(Bin, Secret) of
{ok, #radius_packet{ident = Ident} = Packet} ->
case ets:member(Requests, {SrcIP, SrcPort, Ident}) of
false ->
%% store request in the table to avoid duplicates
true = ets:insert(Requests, {{SrcIP, SrcPort, Ident}, self()}),
PacketType = radius_codec:identify_packet(Packet#radius_packet.code),
case Callback:handle_request(PacketType, Packet, Client) of
{ok, Response} ->
{ok, Data} = radius_codec:encode_response(Packet, Response, Secret),
ok = gen_udp:send(Socket, SrcIP, SrcPort, Data);
noreply -> ok
end;
true ->
Callback:handle_error(duplicate_request, [Packet, Client])
end,
ets:delete(Requests, {SrcIP, SrcPort, Ident});
{error, Reason} ->
Callback:handle_error(Reason, [Bin, Client])
end;
undefined ->
Callback:handle_error(unknown_client, [SrcIP, SrcPort, Bin])
end.
lookup_client(IP, Name) ->
case ets:lookup(radius_clients, Name) of
[] ->
undefined;
[{Name, Clients}] ->
check_client_ip(Clients, IP)
end.
check_client_ip([], _IP) -> undefined;
check_client_ip([#nas_spec{ip = {ip, IP}} = Client | _Rest], IP) ->
{ok, Client#nas_spec{ip = IP}};
check_client_ip([#nas_spec{ip = {net, {Network, Mask}}} = Client | Rest], IP) ->
case in_range(IP, {Network, Mask}) of
true -> {ok, Client#nas_spec{ip = IP}};
false ->
check_client_ip(Rest, IP)
end;
check_client_ip([_Client| Rest], IP) ->
check_client_ip(Rest, IP).
-spec aton(inet:ip_address()) -> non_neg_integer().
aton({A, B, C, D}) ->
(A bsl 24) bor (B bsl 16) bor (C bsl 8) bor D.
-spec in_range(IP :: inet:ip_address(), {Network :: inet:ip_address(), Mask :: 0..32 | inet:ip_address()}) -> boolean().
in_range(IP, {Network, Mask}) ->
{Network0, Mask0} = parse_address(Network, Mask),
(aton(IP) band Mask0) == (Network0 band Mask0).
-spec parse_address(IP :: inet:ip_address(), Mask :: 0..32 | inet:ip_address()) -> {0..4294967295, 0..4294967295}.
parse_address(IP, Mask) ->
NetMask = case Mask of
N when is_tuple(N) andalso tuple_size(N) == 4 ->
aton(Mask);
N when N >= 0 andalso N =< 32 ->
(16#ffffffff bsr (32 - Mask)) bsl (32 - Mask)
end,
{aton(IP), NetMask}.
| null | https://raw.githubusercontent.com/ates/radius/2145a5f79aef8b81b3b77b5beccb29d31044e272/src/radius_service.erl | erlang | API
gen_server callbacks
table used to store requests from clients
creates the table to store requests from clients
made it public to allow access from spawned processes(callback)
store request in the table to avoid duplicates | -module(radius_service).
-behaviour(gen_server).
-export([start_link/5]).
-export([name/1]).
-export([stop/1]).
-export([stats/1]).
-export([init/1, handle_call/3, handle_cast/2,
handle_info/2, code_change/3, terminate/2]).
-include("radius.hrl").
-callback handle_request(Type :: non_neg_integer(),
Request :: #radius_packet{},
Client :: #nas_spec{}) ->
{ok, Response :: #radius_packet{}} | noreply.
-callback handle_error(Reason :: term(), Data :: term()) -> any().
-record(state, {
name :: atom(),
socket :: inet:socket(),
callback :: module()
}).
start_link(Name, IP, Port, Callback, SocketOpts) ->
gen_server:start_link(?MODULE, [Name, IP, Port, Callback, SocketOpts], []).
name(Pid) -> gen_server:call(Pid, name).
stop(Pid) -> gen_server:call(Pid, stop).
stats(Pid) -> gen_server:call(Pid, stats).
init([Name, IP, Port, Callback, SocketOpts]) ->
process_flag(trap_exit, true),
case gen_udp:open(Port, [binary, {ip, IP}, {reuseaddr, true} | SocketOpts]) of
{ok, Socket} ->
Requests = ets:new(radius_requests, [public]),
{ok, #state{name = Name, socket = Socket, requests = Requests, callback = Callback}};
{error, Reason} ->
{error, Reason}
end.
handle_call(stats, _From, State) ->
{reply, inet:getstat(State#state.socket), State};
handle_call(name, _From, State) ->
{reply, State#state.name, State};
handle_call(stop, _From, State) ->
{stop, normal, ok, State};
handle_call(_Request, _From, State) -> {reply, ok, State}.
handle_cast(_Msg, State) -> {noreply, State}.
handle_info({udp, Socket, SrcIP, SrcPort, Bin}, State) ->
Opts = [SrcIP, SrcPort, Socket, Bin, State],
proc_lib:spawn_link(fun() -> do_callback(Opts) end),
{noreply, State};
handle_info({'EXIT', _Pid, normal}, State) -> {noreply, State};
handle_info({'EXIT', Pid, _Reason}, #state{requests = Requests} = State) ->
case ets:match_object(Requests, {'_', Pid}) of
[{{IP, Port, Ident}, Pid}] ->
ets:delete(Requests, {IP, Port, Ident});
[] -> ok
end,
{noreply, State}.
code_change(_OldVsn, State, _Extra) -> {ok, State}.
terminate(Reason, State) ->
case Reason of
normal ->
true = ets:delete(radius_clients, State#state.name);
_ -> ok
end,
gen_udp:close(State#state.socket).
Internal functions
do_callback([SrcIP, SrcPort, Socket, Bin, #state{requests = Requests, callback = Callback} = State]) ->
case lookup_client(SrcIP, State#state.name) of
{ok, #nas_spec{secret = Secret} = Client} ->
case radius_codec:decode_packet(Bin, Secret) of
{ok, #radius_packet{ident = Ident} = Packet} ->
case ets:member(Requests, {SrcIP, SrcPort, Ident}) of
false ->
true = ets:insert(Requests, {{SrcIP, SrcPort, Ident}, self()}),
PacketType = radius_codec:identify_packet(Packet#radius_packet.code),
case Callback:handle_request(PacketType, Packet, Client) of
{ok, Response} ->
{ok, Data} = radius_codec:encode_response(Packet, Response, Secret),
ok = gen_udp:send(Socket, SrcIP, SrcPort, Data);
noreply -> ok
end;
true ->
Callback:handle_error(duplicate_request, [Packet, Client])
end,
ets:delete(Requests, {SrcIP, SrcPort, Ident});
{error, Reason} ->
Callback:handle_error(Reason, [Bin, Client])
end;
undefined ->
Callback:handle_error(unknown_client, [SrcIP, SrcPort, Bin])
end.
lookup_client(IP, Name) ->
case ets:lookup(radius_clients, Name) of
[] ->
undefined;
[{Name, Clients}] ->
check_client_ip(Clients, IP)
end.
check_client_ip([], _IP) -> undefined;
check_client_ip([#nas_spec{ip = {ip, IP}} = Client | _Rest], IP) ->
{ok, Client#nas_spec{ip = IP}};
check_client_ip([#nas_spec{ip = {net, {Network, Mask}}} = Client | Rest], IP) ->
case in_range(IP, {Network, Mask}) of
true -> {ok, Client#nas_spec{ip = IP}};
false ->
check_client_ip(Rest, IP)
end;
check_client_ip([_Client| Rest], IP) ->
check_client_ip(Rest, IP).
-spec aton(inet:ip_address()) -> non_neg_integer().
aton({A, B, C, D}) ->
(A bsl 24) bor (B bsl 16) bor (C bsl 8) bor D.
-spec in_range(IP :: inet:ip_address(), {Network :: inet:ip_address(), Mask :: 0..32 | inet:ip_address()}) -> boolean().
in_range(IP, {Network, Mask}) ->
{Network0, Mask0} = parse_address(Network, Mask),
(aton(IP) band Mask0) == (Network0 band Mask0).
-spec parse_address(IP :: inet:ip_address(), Mask :: 0..32 | inet:ip_address()) -> {0..4294967295, 0..4294967295}.
parse_address(IP, Mask) ->
NetMask = case Mask of
N when is_tuple(N) andalso tuple_size(N) == 4 ->
aton(Mask);
N when N >= 0 andalso N =< 32 ->
(16#ffffffff bsr (32 - Mask)) bsl (32 - Mask)
end,
{aton(IP), NetMask}.
|
e1d8b21e7934a54db9db652c3ea4b40f4fa3d0bf360ea6a1e210da480ff7f578 | orionsbelt-battlegrounds/obb-rules | driller.cljc | (ns ^{:added "1.8"
:author "Pedro Santos"}
obb-rules.units.driller
"Metadata information for the Driller unit")
(def metadata
{:name "driller"
:code "d"
:attack 1500
:after-attack [[:triple]]
:defense 1500
:range 1
:value 32
:type :mechanic
:category :medium
:displacement :ground
:movement-type :all
:movement-cost 2})
| null | https://raw.githubusercontent.com/orionsbelt-battlegrounds/obb-rules/97fad6506eb81142f74f4722aca58b80d618bf45/src/obb_rules/units/driller.cljc | clojure | (ns ^{:added "1.8"
:author "Pedro Santos"}
obb-rules.units.driller
"Metadata information for the Driller unit")
(def metadata
{:name "driller"
:code "d"
:attack 1500
:after-attack [[:triple]]
:defense 1500
:range 1
:value 32
:type :mechanic
:category :medium
:displacement :ground
:movement-type :all
:movement-cost 2})
|
|
85636a69310b0336103f70fecb8b102ac03903e65be2d0ed80d32289f2fc35e0 | seantempesta/expo-cljs-template | core.cljs | (ns {{name}}.core
(:require [om.next :as om :refer-macros [defui]]
[re-natal.support :as sup]
[oops.core :refer [ocall]]
[{{name}}.state :as state]))
(def logo-img (js/require "./assets/images/cljs.png"))
(set! js/window.React (js/require "react"))
(def ReactNative (js/require "react-native"))
(defn create-element [rn-comp opts & children]
(apply js/React.createElement rn-comp (clj->js opts) children))
(def expo (js/require "expo"))
(def app-registry (.-AppRegistry ReactNative))
(def view (partial create-element (.-View ReactNative)))
(def text (partial create-element (.-Text ReactNative)))
(def image (partial create-element (.-Image ReactNative)))
(def touchable-highlight (partial create-element (.-TouchableHighlight ReactNative)))
(defn alert [title]
(.alert (.-Alert ReactNative) title))
(defui AppRoot
static om/IQuery
(query [this]
'[:app/msg])
Object
(render [this]
(let [{:keys [app/msg]} (om/props this)]
(view {:style {:flexDirection "column" :margin 40 :alignItems "center"}}
(text {:style {:fontSize 30 :fontWeight "100" :marginBottom 20 :textAlign "center"}} msg)
(image {:source logo-img
:style {:width 80 :height 80 :marginBottom 30}})
(touchable-highlight {:style {:backgroundColor "#999" :padding 10 :borderRadius 5}
:onPress #(alert "HELLO!")}
(text {:style {:color "white" :textAlign "center" :fontWeight "bold"}} "press me"))))))
(defonce RootNode (sup/root-node! 1))
(defonce app-root (om/factory RootNode))
(defn init []
(om/add-root! state/reconciler AppRoot 1)
(ocall expo "registerRootComponent" app-root))
| null | https://raw.githubusercontent.com/seantempesta/expo-cljs-template/fb85abad30b000c24bb25f430b4f84ccae243cd4/resources/leiningen/new/expo/om/core.cljs | clojure | (ns {{name}}.core
(:require [om.next :as om :refer-macros [defui]]
[re-natal.support :as sup]
[oops.core :refer [ocall]]
[{{name}}.state :as state]))
(def logo-img (js/require "./assets/images/cljs.png"))
(set! js/window.React (js/require "react"))
(def ReactNative (js/require "react-native"))
(defn create-element [rn-comp opts & children]
(apply js/React.createElement rn-comp (clj->js opts) children))
(def expo (js/require "expo"))
(def app-registry (.-AppRegistry ReactNative))
(def view (partial create-element (.-View ReactNative)))
(def text (partial create-element (.-Text ReactNative)))
(def image (partial create-element (.-Image ReactNative)))
(def touchable-highlight (partial create-element (.-TouchableHighlight ReactNative)))
(defn alert [title]
(.alert (.-Alert ReactNative) title))
(defui AppRoot
static om/IQuery
(query [this]
'[:app/msg])
Object
(render [this]
(let [{:keys [app/msg]} (om/props this)]
(view {:style {:flexDirection "column" :margin 40 :alignItems "center"}}
(text {:style {:fontSize 30 :fontWeight "100" :marginBottom 20 :textAlign "center"}} msg)
(image {:source logo-img
:style {:width 80 :height 80 :marginBottom 30}})
(touchable-highlight {:style {:backgroundColor "#999" :padding 10 :borderRadius 5}
:onPress #(alert "HELLO!")}
(text {:style {:color "white" :textAlign "center" :fontWeight "bold"}} "press me"))))))
(defonce RootNode (sup/root-node! 1))
(defonce app-root (om/factory RootNode))
(defn init []
(om/add-root! state/reconciler AppRoot 1)
(ocall expo "registerRootComponent" app-root))
|
|
b26b125c60067e553db41af23b17691d0826a792eb3cba9bce11b5abfec1c092 | mzp/coq-ide-for-ios | segmenttree.ml | (** This module is a very simple implementation of "segment trees".
A segment tree of type ['a t] represents a mapping from a union of
disjoint segments to some values of type 'a.
*)
(** Misc. functions. *)
let list_iteri f l =
let rec loop i = function
| [] -> ()
| x :: xs -> f i x; loop (i + 1) xs
in
loop 0 l
let log2 x = log x /. log 2.
let log2n x = int_of_float (ceil (log2 (float_of_int x)))
(** We focus on integers but this module can be generalized. *)
type elt = int
(** A value of type [domain] is interpreted differently given its position
in the tree. On internal nodes, a domain represents the set of
integers which are _not_ in the set of keys handled by the tree. On
leaves, a domain represents the st of integers which are in the set of
keys. *)
type domain =
(** On internal nodes, a domain [Interval (a, b)] represents
the interval [a + 1; b - 1]. On leaves, it represents [a; b].
We always have [a] <= [b]. *)
| Interval of elt * elt
* On internal node or root , a domain [ Universe ] represents all
the integers . When the tree is not a trivial root ,
[ Universe ] has no interpretation on leaves . ( The lookup
function should never reach the leaves . )
the integers. When the tree is not a trivial root,
[Universe] has no interpretation on leaves. (The lookup
function should never reach the leaves.) *)
| Universe
* We use an array to store the almost complete tree . This array
contains at least one element .
contains at least one element. *)
type 'a t = (domain * 'a option) array
* The root is the first item of the array .
let is_root i = (i = 0)
(** Standard layout for left child. *)
let left_child i = 2 * i + 1
(** Standard layout for right child. *)
let right_child i = 2 * i + 2
(** Extract the annotation of a node, be it internal or a leaf. *)
let value_of i t = match t.(i) with (_, Some x) -> x | _ -> raise Not_found
(** Initialize the array to store [n] leaves. *)
let create n init =
Array.make (1 lsl (log2n n + 1) - 1) init
(** Make a complete interval tree from a list of disjoint segments.
Precondition : the segments must be sorted. *)
let make segments =
let nsegments = List.length segments in
let tree = create nsegments (Universe, None) in
let leaves_offset = (1 lsl (log2n nsegments)) - 1 in
* The algorithm proceeds in two steps using an intermediate tree
to store minimum and maximum of each subtree as annotation of
the node .
to store minimum and maximum of each subtree as annotation of
the node. *)
(** We start from leaves: the last level of the tree is initialized
with the given segments... *)
list_iteri
(fun i ((start, stop), value) ->
let k = leaves_offset + i in
let i = Interval (start, stop) in
tree.(k) <- (i, Some i))
segments;
(** ... the remaining leaves are initialized with neutral information. *)
for k = leaves_offset + nsegments to Array.length tree -1 do
tree.(k) <- (Universe, Some Universe)
done;
(** We traverse the tree bottom-up and compute the interval and
annotation associated to each node from the annotations of its
children. *)
for k = leaves_offset - 1 downto 0 do
let node, annotation =
match value_of (left_child k) tree, value_of (right_child k) tree with
| Interval (left_min, left_max), Interval (right_min, right_max) ->
(Interval (left_max, right_min), Interval (left_min, right_max))
| Interval (min, max), Universe ->
(Interval (max, max), Interval (min, max))
| Universe, Universe -> Universe, Universe
| Universe, _ -> assert false
in
tree.(k) <- (node, Some annotation)
done;
(** Finally, annotation are replaced with the image related to each leaf. *)
let final_tree =
Array.mapi (fun i (segment, value) -> (segment, None)) tree
in
list_iteri
(fun i ((start, stop), value) ->
final_tree.(leaves_offset + i)
<- (Interval (start, stop), Some value))
segments;
final_tree
(** [lookup k t] looks for an image for key [k] in the interval tree [t].
Raise [Not_found] if it fails. *)
let lookup k t =
let i = ref 0 in
while (snd t.(!i) = None) do
match fst t.(!i) with
| Interval (start, stop) ->
if k <= start then i := left_child !i
else if k >= stop then i:= right_child !i
else raise Not_found
| Universe -> raise Not_found
done;
match fst t.(!i) with
| Interval (start, stop) ->
if k >= start && k <= stop then
match snd t.(!i) with
| Some v -> v
| None -> assert false
else
raise Not_found
| Universe -> assert false
| null | https://raw.githubusercontent.com/mzp/coq-ide-for-ios/4cdb389bbecd7cdd114666a8450ecf5b5f0391d3/coqlib/lib/segmenttree.ml | ocaml | * This module is a very simple implementation of "segment trees".
A segment tree of type ['a t] represents a mapping from a union of
disjoint segments to some values of type 'a.
* Misc. functions.
* We focus on integers but this module can be generalized.
* A value of type [domain] is interpreted differently given its position
in the tree. On internal nodes, a domain represents the set of
integers which are _not_ in the set of keys handled by the tree. On
leaves, a domain represents the st of integers which are in the set of
keys.
* On internal nodes, a domain [Interval (a, b)] represents
the interval [a + 1; b - 1]. On leaves, it represents [a; b].
We always have [a] <= [b].
* Standard layout for left child.
* Standard layout for right child.
* Extract the annotation of a node, be it internal or a leaf.
* Initialize the array to store [n] leaves.
* Make a complete interval tree from a list of disjoint segments.
Precondition : the segments must be sorted.
* We start from leaves: the last level of the tree is initialized
with the given segments...
* ... the remaining leaves are initialized with neutral information.
* We traverse the tree bottom-up and compute the interval and
annotation associated to each node from the annotations of its
children.
* Finally, annotation are replaced with the image related to each leaf.
* [lookup k t] looks for an image for key [k] in the interval tree [t].
Raise [Not_found] if it fails. |
let list_iteri f l =
let rec loop i = function
| [] -> ()
| x :: xs -> f i x; loop (i + 1) xs
in
loop 0 l
let log2 x = log x /. log 2.
let log2n x = int_of_float (ceil (log2 (float_of_int x)))
type elt = int
type domain =
| Interval of elt * elt
* On internal node or root , a domain [ Universe ] represents all
the integers . When the tree is not a trivial root ,
[ Universe ] has no interpretation on leaves . ( The lookup
function should never reach the leaves . )
the integers. When the tree is not a trivial root,
[Universe] has no interpretation on leaves. (The lookup
function should never reach the leaves.) *)
| Universe
* We use an array to store the almost complete tree . This array
contains at least one element .
contains at least one element. *)
type 'a t = (domain * 'a option) array
* The root is the first item of the array .
let is_root i = (i = 0)
let left_child i = 2 * i + 1
let right_child i = 2 * i + 2
let value_of i t = match t.(i) with (_, Some x) -> x | _ -> raise Not_found
let create n init =
Array.make (1 lsl (log2n n + 1) - 1) init
let make segments =
let nsegments = List.length segments in
let tree = create nsegments (Universe, None) in
let leaves_offset = (1 lsl (log2n nsegments)) - 1 in
* The algorithm proceeds in two steps using an intermediate tree
to store minimum and maximum of each subtree as annotation of
the node .
to store minimum and maximum of each subtree as annotation of
the node. *)
list_iteri
(fun i ((start, stop), value) ->
let k = leaves_offset + i in
let i = Interval (start, stop) in
tree.(k) <- (i, Some i))
segments;
for k = leaves_offset + nsegments to Array.length tree -1 do
tree.(k) <- (Universe, Some Universe)
done;
for k = leaves_offset - 1 downto 0 do
let node, annotation =
match value_of (left_child k) tree, value_of (right_child k) tree with
| Interval (left_min, left_max), Interval (right_min, right_max) ->
(Interval (left_max, right_min), Interval (left_min, right_max))
| Interval (min, max), Universe ->
(Interval (max, max), Interval (min, max))
| Universe, Universe -> Universe, Universe
| Universe, _ -> assert false
in
tree.(k) <- (node, Some annotation)
done;
let final_tree =
Array.mapi (fun i (segment, value) -> (segment, None)) tree
in
list_iteri
(fun i ((start, stop), value) ->
final_tree.(leaves_offset + i)
<- (Interval (start, stop), Some value))
segments;
final_tree
let lookup k t =
let i = ref 0 in
while (snd t.(!i) = None) do
match fst t.(!i) with
| Interval (start, stop) ->
if k <= start then i := left_child !i
else if k >= stop then i:= right_child !i
else raise Not_found
| Universe -> raise Not_found
done;
match fst t.(!i) with
| Interval (start, stop) ->
if k >= start && k <= stop then
match snd t.(!i) with
| Some v -> v
| None -> assert false
else
raise Not_found
| Universe -> assert false
|
020ba5af09b4a317467009bf0c203617d78c976105c438a2c60651c8e11cb0f7 | taffybar/taffybar | Workspaces.hs | # OPTIONS_GHC -fno - warn - type - defaults #
# LANGUAGE ScopedTypeVariables , ExistentialQuantification , RankNTypes , OverloadedStrings #
-----------------------------------------------------------------------------
-- |
Module : System . . Widget . Workspaces
Copyright : ( c )
-- License : BSD3-style (see LICENSE)
--
Maintainer :
-- Stability : unstable
-- Portability : unportable
-----------------------------------------------------------------------------
module System.Taffybar.Widget.Workspaces where
import Control.Applicative
import Control.Arrow ((&&&))
import Control.Concurrent
import qualified Control.Concurrent.MVar as MV
import Control.Exception.Enclosed (catchAny)
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Trans.Class
import Control.Monad.Trans.Maybe
import Control.Monad.Trans.Reader
import Control.RateLimit
import Data.Default (Default(..))
import qualified Data.Foldable as F
import Data.GI.Base.ManagedPtr (unsafeCastTo)
import Data.Int
import Data.List (elemIndex, intersect, sortBy, (\\))
import qualified Data.Map as M
import Data.Maybe
import qualified Data.MultiMap as MM
import Data.Ord
import qualified Data.Set as Set
import qualified Data.Text as T
import Data.Time.Units
import Data.Tuple.Select
import Data.Tuple.Sequence
import qualified GI.Gdk.Enums as Gdk
import qualified GI.Gdk.Structs.EventScroll as Gdk
import qualified GI.GdkPixbuf.Objects.Pixbuf as Gdk
import qualified GI.Gtk as Gtk
import Prelude
import StatusNotifier.Tray (scalePixbufToSize)
import System.Log.Logger
import System.Taffybar.Context
import System.Taffybar.Information.EWMHDesktopInfo
import System.Taffybar.Information.SafeX11
import System.Taffybar.Information.X11DesktopInfo
import System.Taffybar.Util
import System.Taffybar.Widget.Generic.AutoSizeImage (autoSizeImage)
import System.Taffybar.Widget.Util
import System.Taffybar.WindowIcon
import Text.Printf
data WorkspaceState
= Active
| Visible
| Hidden
| Empty
| Urgent
deriving (Show, Eq)
getCSSClass :: (Show s) => s -> T.Text
getCSSClass = T.toLower . T.pack . show
cssWorkspaceStates :: [T.Text]
cssWorkspaceStates = map getCSSClass [Active, Visible, Hidden, Empty, Urgent]
data WindowData = WindowData
{ windowId :: X11Window
, windowTitle :: String
, windowClass :: String
, windowUrgent :: Bool
, windowActive :: Bool
, windowMinimized :: Bool
} deriving (Show, Eq)
data WidgetUpdate = WorkspaceUpdate Workspace | IconUpdate [X11Window]
data Workspace = Workspace
{ workspaceIdx :: WorkspaceId
, workspaceName :: String
, workspaceState :: WorkspaceState
, windows :: [WindowData]
} deriving (Show, Eq)
data WorkspacesContext = WorkspacesContext
{ controllersVar :: MV.MVar (M.Map WorkspaceId WWC)
, workspacesVar :: MV.MVar (M.Map WorkspaceId Workspace)
, workspacesWidget :: Gtk.Box
, workspacesConfig :: WorkspacesConfig
, taffyContext :: Context
}
type WorkspacesIO a = ReaderT WorkspacesContext IO a
liftContext :: TaffyIO a -> WorkspacesIO a
liftContext action = asks taffyContext >>= lift . runReaderT action
liftX11Def :: a -> X11Property a -> WorkspacesIO a
liftX11Def dflt prop = liftContext $ runX11Def dflt prop
setWorkspaceWidgetStatusClass ::
(MonadIO m, Gtk.IsWidget a) => Workspace -> a -> m ()
setWorkspaceWidgetStatusClass workspace widget =
updateWidgetClasses
widget
[getCSSClass $ workspaceState workspace]
cssWorkspaceStates
updateWidgetClasses ::
(Foldable t1, Foldable t, Gtk.IsWidget a, MonadIO m)
=> a
-> t1 T.Text
-> t T.Text
-> m ()
updateWidgetClasses widget toAdd toRemove = do
context <- Gtk.widgetGetStyleContext widget
let hasClass = Gtk.styleContextHasClass context
addIfMissing klass =
hasClass klass >>= (`when` Gtk.styleContextAddClass context klass) . not
removeIfPresent klass = unless (klass `elem` toAdd) $
hasClass klass >>= (`when` Gtk.styleContextRemoveClass context klass)
mapM_ removeIfPresent toRemove
mapM_ addIfMissing toAdd
class WorkspaceWidgetController wc where
getWidget :: wc -> WorkspacesIO Gtk.Widget
updateWidget :: wc -> WidgetUpdate -> WorkspacesIO wc
updateWidgetX11 :: wc -> WidgetUpdate -> WorkspacesIO wc
updateWidgetX11 cont _ = return cont
data WWC = forall a. WorkspaceWidgetController a => WWC a
instance WorkspaceWidgetController WWC where
getWidget (WWC wc) = getWidget wc
updateWidget (WWC wc) update = WWC <$> updateWidget wc update
updateWidgetX11 (WWC wc) update = WWC <$> updateWidgetX11 wc update
type ControllerConstructor = Workspace -> WorkspacesIO WWC
type ParentControllerConstructor =
ControllerConstructor -> ControllerConstructor
type WindowIconPixbufGetter =
Int32 -> WindowData -> TaffyIO (Maybe Gdk.Pixbuf)
data WorkspacesConfig =
WorkspacesConfig
{ widgetBuilder :: ControllerConstructor
, widgetGap :: Int
, maxIcons :: Maybe Int
, minIcons :: Int
, getWindowIconPixbuf :: WindowIconPixbufGetter
, labelSetter :: Workspace -> WorkspacesIO String
, showWorkspaceFn :: Workspace -> Bool
, borderWidth :: Int
, updateEvents :: [String]
, updateRateLimitMicroseconds :: Integer
, iconSort :: [WindowData] -> WorkspacesIO [WindowData]
, urgentWorkspaceState :: Bool
}
defaultWorkspacesConfig :: WorkspacesConfig
defaultWorkspacesConfig =
WorkspacesConfig
{ widgetBuilder = buildButtonController defaultBuildContentsController
, widgetGap = 0
, maxIcons = Nothing
, minIcons = 0
, getWindowIconPixbuf = defaultGetWindowIconPixbuf
, labelSetter = return . workspaceName
, showWorkspaceFn = const True
, borderWidth = 2
, iconSort = sortWindowsByPosition
, updateEvents = allEWMHProperties \\ [ewmhWMIcon]
, updateRateLimitMicroseconds = 100000
, urgentWorkspaceState = False
}
instance Default WorkspacesConfig where
def = defaultWorkspacesConfig
hideEmpty :: Workspace -> Bool
hideEmpty Workspace { workspaceState = Empty } = False
hideEmpty _ = True
wLog :: MonadIO m => Priority -> String -> m ()
wLog l s = liftIO $ logM "System.Taffybar.Widget.Workspaces" l s
updateVar :: MV.MVar a -> (a -> WorkspacesIO a) -> WorkspacesIO a
updateVar var modify = do
ctx <- ask
lift $ MV.modifyMVar var $ fmap (\a -> (a, a)) . flip runReaderT ctx . modify
updateWorkspacesVar :: WorkspacesIO (M.Map WorkspaceId Workspace)
updateWorkspacesVar = do
workspacesRef <- asks workspacesVar
updateVar workspacesRef buildWorkspaceData
getWorkspaceToWindows ::
[X11Window] -> X11Property (MM.MultiMap WorkspaceId X11Window)
getWorkspaceToWindows =
foldM
(\theMap window ->
MM.insert <$> getWorkspace window <*> pure window <*> pure theMap)
MM.empty
getWindowData :: Maybe X11Window
-> [X11Window]
-> X11Window
-> X11Property WindowData
getWindowData activeWindow urgentWindows window = do
wTitle <- getWindowTitle window
wClass <- getWindowClass window
wMinimized <- getWindowMinimized window
return
WindowData
{ windowId = window
, windowTitle = wTitle
, windowClass = wClass
, windowUrgent = window `elem` urgentWindows
, windowActive = Just window == activeWindow
, windowMinimized = wMinimized
}
buildWorkspaceData :: M.Map WorkspaceId Workspace
-> WorkspacesIO (M.Map WorkspaceId Workspace)
buildWorkspaceData _ = ask >>= \context -> liftX11Def M.empty $ do
names <- getWorkspaceNames
wins <- getWindows
workspaceToWindows <- getWorkspaceToWindows wins
urgentWindows <- filterM isWindowUrgent wins
activeWindow <- getActiveWindow
active:visible <- getVisibleWorkspaces
let getWorkspaceState idx ws
| idx == active = Active
| idx `elem` visible = Visible
| urgentWorkspaceState (workspacesConfig context) &&
not (null (ws `intersect` urgentWindows)) =
Urgent
| null ws = Empty
| otherwise = Hidden
foldM
(\theMap (idx, name) -> do
let ws = MM.lookup idx workspaceToWindows
windowInfos <- mapM (getWindowData activeWindow urgentWindows) ws
return $
M.insert
idx
Workspace
{ workspaceIdx = idx
, workspaceName = name
, workspaceState = getWorkspaceState idx ws
, windows = windowInfos
}
theMap)
M.empty
names
addWidgetsToTopLevel :: WorkspacesIO ()
addWidgetsToTopLevel = do
WorkspacesContext
{ controllersVar = controllersRef
, workspacesWidget = cont
} <- ask
controllersMap <- lift $ MV.readMVar controllersRef
Elems returns elements in ascending order of their keys so this will always
-- add the widgets in the correct order
mapM_ addWidget $ M.elems controllersMap
lift $ Gtk.widgetShowAll cont
addWidget :: WWC -> WorkspacesIO ()
addWidget controller = do
cont <- asks workspacesWidget
workspaceWidget <- getWidget controller
lift $ do
XXX : This hbox exists to ( hopefully ) prevent the issue where workspace
-- widgets appear out of order, in the switcher, by acting as an empty
-- place holder when the actual widget is hidden.
hbox <- Gtk.boxNew Gtk.OrientationHorizontal 0
void $ Gtk.widgetGetParent workspaceWidget >>=
traverse (unsafeCastTo Gtk.Box) >>=
traverse (flip Gtk.containerRemove workspaceWidget)
Gtk.containerAdd hbox workspaceWidget
Gtk.containerAdd cont hbox
workspacesNew :: WorkspacesConfig -> TaffyIO Gtk.Widget
workspacesNew cfg = ask >>= \tContext -> lift $ do
cont <- Gtk.boxNew Gtk.OrientationHorizontal $ fromIntegral (widgetGap cfg)
controllersRef <- MV.newMVar M.empty
workspacesRef <- MV.newMVar M.empty
let context =
WorkspacesContext
{ controllersVar = controllersRef
, workspacesVar = workspacesRef
, workspacesWidget = cont
, workspacesConfig = cfg
, taffyContext = tContext
}
-- This will actually create all the widgets
runReaderT updateAllWorkspaceWidgets context
updateHandler <- onWorkspaceUpdate context
iconHandler <- onIconsChanged context
let doUpdate = lift . updateHandler
handleConfigureEvents e@(ConfigureEvent {}) = doUpdate e
handleConfigureEvents _ = return ()
(workspaceSubscription, iconSubscription, geometrySubscription) <-
flip runReaderT tContext $ sequenceT
( subscribeToPropertyEvents (updateEvents cfg) $ doUpdate
, subscribeToPropertyEvents [ewmhWMIcon] (lift . onIconChanged iconHandler)
, subscribeToAll handleConfigureEvents
)
let doUnsubscribe = flip runReaderT tContext $
mapM_ unsubscribe
[ iconSubscription
, workspaceSubscription
, geometrySubscription
]
_ <- Gtk.onWidgetUnrealize cont doUnsubscribe
_ <- widgetSetClassGI cont "workspaces"
Gtk.toWidget cont
updateAllWorkspaceWidgets :: WorkspacesIO ()
updateAllWorkspaceWidgets = do
wLog DEBUG "Updating workspace widgets"
workspacesMap <- updateWorkspacesVar
wLog DEBUG $ printf "Workspaces: %s" $ show workspacesMap
wLog DEBUG "Adding and removing widgets"
updateWorkspaceControllers
let updateController' idx controller =
maybe (return controller)
(updateWidget controller . WorkspaceUpdate) $
M.lookup idx workspacesMap
logUpdateController i =
wLog DEBUG $ printf "Updating %s workspace widget" $ show i
updateController i cont = logUpdateController i >>
updateController' i cont
wLog DEBUG "Done updating individual widget"
doWidgetUpdate updateController
wLog DEBUG "Showing and hiding controllers"
setControllerWidgetVisibility
setControllerWidgetVisibility :: WorkspacesIO ()
setControllerWidgetVisibility = do
ctx@WorkspacesContext
{ workspacesVar = workspacesRef
, controllersVar = controllersRef
, workspacesConfig = cfg
} <- ask
lift $ do
workspacesMap <- MV.readMVar workspacesRef
controllersMap <- MV.readMVar controllersRef
forM_ (M.elems workspacesMap) $ \ws ->
let action = if showWorkspaceFn cfg ws
then Gtk.widgetShow
else Gtk.widgetHide
in
traverse (flip runReaderT ctx . getWidget)
(M.lookup (workspaceIdx ws) controllersMap) >>=
maybe (return ()) action
doWidgetUpdate :: (WorkspaceId -> WWC -> WorkspacesIO WWC) -> WorkspacesIO ()
doWidgetUpdate updateController = do
c@WorkspacesContext { controllersVar = controllersRef } <- ask
lift $ MV.modifyMVar_ controllersRef $ \controllers -> do
wLog DEBUG "Updating controllers ref"
controllersList <-
mapM
(\(idx, controller) -> do
newController <- runReaderT (updateController idx controller) c
return (idx, newController)) $
M.toList controllers
return $ M.fromList controllersList
updateWorkspaceControllers :: WorkspacesIO ()
updateWorkspaceControllers = do
WorkspacesContext
{ controllersVar = controllersRef
, workspacesVar = workspacesRef
, workspacesWidget = cont
, workspacesConfig = cfg
} <- ask
workspacesMap <- lift $ MV.readMVar workspacesRef
controllersMap <- lift $ MV.readMVar controllersRef
let newWorkspacesSet = M.keysSet workspacesMap
existingWorkspacesSet = M.keysSet controllersMap
when (existingWorkspacesSet /= newWorkspacesSet) $ do
let addWorkspaces = Set.difference newWorkspacesSet existingWorkspacesSet
removeWorkspaces = Set.difference existingWorkspacesSet newWorkspacesSet
builder = widgetBuilder cfg
_ <- updateVar controllersRef $ \controllers -> do
let oldRemoved = F.foldl (flip M.delete) controllers removeWorkspaces
buildController idx = builder <$> M.lookup idx workspacesMap
buildAndAddController theMap idx =
maybe (return theMap) (>>= return . flip (M.insert idx) theMap)
(buildController idx)
foldM buildAndAddController oldRemoved $ Set.toList addWorkspaces
-- Clear the container and repopulate it
lift $ Gtk.containerForeach cont (Gtk.containerRemove cont)
addWidgetsToTopLevel
rateLimitFn
:: forall req resp.
WorkspacesContext
-> (req -> IO resp)
-> ResultsCombiner req resp
-> IO (req -> IO resp)
rateLimitFn context =
let limit = (updateRateLimitMicroseconds $ workspacesConfig context)
rate = fromMicroseconds limit :: Microsecond in
generateRateLimitedFunction $ PerInvocation rate
onWorkspaceUpdate :: WorkspacesContext -> IO (Event -> IO ())
onWorkspaceUpdate context = do
rateLimited <- rateLimitFn context doUpdate combineRequests
let withLog event = do
case event of
PropertyEvent _ _ _ _ _ atom _ _ ->
wLog DEBUG $ printf "Event %s" $ show atom
_ -> return ()
void $ forkIO $ rateLimited event
return withLog
where
combineRequests _ b = Just (b, const ((), ()))
doUpdate _ = postGUIASync $ runReaderT updateAllWorkspaceWidgets context
onIconChanged :: (Set.Set X11Window -> IO ()) -> Event -> IO ()
onIconChanged handler event =
case event of
PropertyEvent { ev_window = wid } -> do
wLog DEBUG $ printf "Icon changed event %s" $ show wid
handler $ Set.singleton wid
_ -> return ()
onIconsChanged :: WorkspacesContext -> IO (Set.Set X11Window -> IO ())
onIconsChanged context = rateLimitFn context onIconsChanged' combineRequests
where
combineRequests windows1 windows2 =
Just (Set.union windows1 windows2, const ((), ()))
onIconsChanged' wids = do
wLog DEBUG $ printf "Icon update execute %s" $ show wids
postGUIASync $ flip runReaderT context $
doWidgetUpdate
(\idx c ->
wLog DEBUG (printf "Updating %s icons." $ show idx) >>
updateWidget c (IconUpdate $ Set.toList wids))
initializeWWC ::
WorkspaceWidgetController a => a -> Workspace -> ReaderT WorkspacesContext IO WWC
initializeWWC controller ws =
WWC <$> updateWidget controller (WorkspaceUpdate ws)
| A WrappingController can be used to wrap some child widget with another
-- abitrary widget.
data WrappingController = WrappingController
{ wrappedWidget :: Gtk.Widget
, wrappedController :: WWC
}
instance WorkspaceWidgetController WrappingController where
getWidget = lift . Gtk.toWidget . wrappedWidget
updateWidget wc update = do
updated <- updateWidget (wrappedController wc) update
return wc { wrappedController = updated }
data WorkspaceContentsController = WorkspaceContentsController
{ containerWidget :: Gtk.Widget
, contentsControllers :: [WWC]
}
buildContentsController :: [ControllerConstructor] -> ControllerConstructor
buildContentsController constructors ws = do
controllers <- mapM ($ ws) constructors
ctx <- ask
tempController <- lift $ do
cons <- Gtk.boxNew Gtk.OrientationHorizontal 0
mapM_ (flip runReaderT ctx . getWidget >=> Gtk.containerAdd cons) controllers
outerBox <- Gtk.toWidget cons >>= buildPadBox
_ <- widgetSetClassGI cons "contents"
widget <- Gtk.toWidget outerBox
return
WorkspaceContentsController
{ containerWidget = widget
, contentsControllers = controllers
}
initializeWWC tempController ws
defaultBuildContentsController :: ControllerConstructor
defaultBuildContentsController =
buildContentsController [buildLabelController, buildIconController]
bottomLeftAlignedBoxWrapper :: T.Text -> ControllerConstructor -> ControllerConstructor
bottomLeftAlignedBoxWrapper boxClass constructor ws = do
controller <- constructor ws
widget <- getWidget controller
ebox <- Gtk.eventBoxNew
_ <- widgetSetClassGI ebox boxClass
Gtk.widgetSetHalign ebox Gtk.AlignStart
Gtk.widgetSetValign ebox Gtk.AlignEnd
Gtk.containerAdd ebox widget
wrapped <- Gtk.toWidget ebox
let wrappingController = WrappingController
{ wrappedWidget = wrapped
, wrappedController = controller
}
initializeWWC wrappingController ws
buildLabelOverlayController :: ControllerConstructor
buildLabelOverlayController =
buildOverlayContentsController
[buildIconController]
[bottomLeftAlignedBoxWrapper "overlay-box" buildLabelController]
buildOverlayContentsController ::
[ControllerConstructor] -> [ControllerConstructor] -> ControllerConstructor
buildOverlayContentsController mainConstructors overlayConstructors ws = do
controllers <- mapM ($ ws) mainConstructors
overlayControllers <- mapM ($ ws) overlayConstructors
ctx <- ask
tempController <- lift $ do
mainContents <- Gtk.boxNew Gtk.OrientationHorizontal 0
mapM_ (flip runReaderT ctx . getWidget >=> Gtk.containerAdd mainContents)
controllers
outerBox <- Gtk.toWidget mainContents >>= buildPadBox
_ <- widgetSetClassGI mainContents "contents"
overlay <- Gtk.overlayNew
Gtk.containerAdd overlay outerBox
mapM_ (flip runReaderT ctx . getWidget >=>
Gtk.overlayAddOverlay overlay) overlayControllers
widget <- Gtk.toWidget overlay
return
WorkspaceContentsController
{ containerWidget = widget
, contentsControllers = controllers ++ overlayControllers
}
initializeWWC tempController ws
instance WorkspaceWidgetController WorkspaceContentsController where
getWidget = return . containerWidget
updateWidget cc update = do
WorkspacesContext {} <- ask
case update of
WorkspaceUpdate newWorkspace ->
lift $ setWorkspaceWidgetStatusClass newWorkspace $ containerWidget cc
_ -> return ()
newControllers <- mapM (`updateWidget` update) $ contentsControllers cc
return cc {contentsControllers = newControllers}
updateWidgetX11 cc update = do
newControllers <- mapM (`updateWidgetX11` update) $ contentsControllers cc
return cc {contentsControllers = newControllers}
newtype LabelController = LabelController { label :: Gtk.Label }
buildLabelController :: ControllerConstructor
buildLabelController ws = do
tempController <- lift $ do
lbl <- Gtk.labelNew Nothing
_ <- widgetSetClassGI lbl "workspace-label"
return LabelController { label = lbl }
initializeWWC tempController ws
instance WorkspaceWidgetController LabelController where
getWidget = lift . Gtk.toWidget . label
updateWidget lc (WorkspaceUpdate newWorkspace) = do
WorkspacesContext { workspacesConfig = cfg } <- ask
labelText <- labelSetter cfg newWorkspace
lift $ do
Gtk.labelSetMarkup (label lc) $ T.pack labelText
setWorkspaceWidgetStatusClass newWorkspace $ label lc
return lc
updateWidget lc _ = return lc
data IconWidget = IconWidget
{ iconContainer :: Gtk.EventBox
, iconImage :: Gtk.Image
, iconWindow :: MV.MVar (Maybe WindowData)
, iconForceUpdate :: IO ()
}
getPixbufForIconWidget :: Bool
-> MV.MVar (Maybe WindowData)
-> Int32
-> WorkspacesIO (Maybe Gdk.Pixbuf)
getPixbufForIconWidget transparentOnNone dataVar size = do
ctx <- ask
let tContext = taffyContext ctx
getPBFromData = getWindowIconPixbuf $ workspacesConfig ctx
getPB' = runMaybeT $
MaybeT (lift $ MV.readMVar dataVar) >>= MaybeT . getPBFromData size
getPB = if transparentOnNone
then maybeTCombine getPB' (Just <$> pixBufFromColor size 0)
else getPB'
lift $ runReaderT getPB tContext
buildIconWidget :: Bool -> Workspace -> WorkspacesIO IconWidget
buildIconWidget transparentOnNone ws = do
ctx <- ask
lift $ do
windowVar <- MV.newMVar Nothing
img <- Gtk.imageNew
refreshImage <-
autoSizeImage img
(flip runReaderT ctx . getPixbufForIconWidget transparentOnNone windowVar)
Gtk.OrientationHorizontal
ebox <- Gtk.eventBoxNew
_ <- widgetSetClassGI img "window-icon"
_ <- widgetSetClassGI ebox "window-icon-container"
Gtk.containerAdd ebox img
_ <-
Gtk.onWidgetButtonPressEvent ebox $
const $ liftIO $ do
info <- MV.readMVar windowVar
case info of
Just updatedInfo ->
flip runReaderT ctx $
liftX11Def () $ focusWindow $ windowId updatedInfo
_ -> liftIO $ void $ switch ctx (workspaceIdx ws)
return True
return
IconWidget
{ iconContainer = ebox
, iconImage = img
, iconWindow = windowVar
, iconForceUpdate = refreshImage
}
data IconController = IconController
{ iconsContainer :: Gtk.Box
, iconImages :: [IconWidget]
, iconWorkspace :: Workspace
}
buildIconController :: ControllerConstructor
buildIconController ws = do
tempController <-
lift $ do
hbox <- Gtk.boxNew Gtk.OrientationHorizontal 0
return
IconController
{iconsContainer = hbox, iconImages = [], iconWorkspace = ws}
initializeWWC tempController ws
instance WorkspaceWidgetController IconController where
getWidget = lift . Gtk.toWidget . iconsContainer
updateWidget ic (WorkspaceUpdate newWorkspace) = do
newImages <- updateImages ic newWorkspace
return ic { iconImages = newImages, iconWorkspace = newWorkspace }
updateWidget ic (IconUpdate updatedIcons) =
updateWindowIconsById ic updatedIcons >> return ic
updateWindowIconsById ::
IconController -> [X11Window] -> WorkspacesIO ()
updateWindowIconsById ic windowIds =
mapM_ maybeUpdateWindowIcon $ iconImages ic
where
maybeUpdateWindowIcon widget =
do
info <- lift $ MV.readMVar $ iconWindow widget
when (maybe False (flip elem windowIds . windowId) info) $
updateIconWidget ic widget info
scaledWindowIconPixbufGetter :: WindowIconPixbufGetter -> WindowIconPixbufGetter
scaledWindowIconPixbufGetter getter size =
getter size >=>
lift . traverse (scalePixbufToSize size Gtk.OrientationHorizontal)
constantScaleWindowIconPixbufGetter ::
Int32 -> WindowIconPixbufGetter -> WindowIconPixbufGetter
constantScaleWindowIconPixbufGetter constantSize getter =
const $ scaledWindowIconPixbufGetter getter constantSize
handleIconGetterException :: WindowIconPixbufGetter -> WindowIconPixbufGetter
handleIconGetterException getter =
\size windowData -> catchAny (getter size windowData) $ \e -> do
wLog WARNING $ printf "Failed to get window icon for %s: %s" (show windowData) (show e)
return Nothing
getWindowIconPixbufFromEWMH :: WindowIconPixbufGetter
getWindowIconPixbufFromEWMH = handleIconGetterException $ \size windowData ->
runX11Def Nothing (getIconPixBufFromEWMH size $ windowId windowData)
getWindowIconPixbufFromClass :: WindowIconPixbufGetter
getWindowIconPixbufFromClass = handleIconGetterException $ \size windowData ->
lift $ getWindowIconFromClasses size (windowClass windowData)
getWindowIconPixbufFromDesktopEntry :: WindowIconPixbufGetter
getWindowIconPixbufFromDesktopEntry = handleIconGetterException $ \size windowData ->
getWindowIconFromDesktopEntryByClasses size (windowClass windowData)
getWindowIconPixbufFromChrome :: WindowIconPixbufGetter
getWindowIconPixbufFromChrome _ windowData =
getPixBufFromChromeData $ windowId windowData
defaultGetWindowIconPixbuf :: WindowIconPixbufGetter
defaultGetWindowIconPixbuf =
scaledWindowIconPixbufGetter unscaledDefaultGetWindowIconPixbuf
unscaledDefaultGetWindowIconPixbuf :: WindowIconPixbufGetter
unscaledDefaultGetWindowIconPixbuf =
getWindowIconPixbufFromDesktopEntry <|||>
getWindowIconPixbufFromClass <|||>
getWindowIconPixbufFromEWMH
addCustomIconsToDefaultWithFallbackByPath
:: (WindowData -> Maybe FilePath)
-> FilePath
-> WindowIconPixbufGetter
addCustomIconsToDefaultWithFallbackByPath getCustomIconPath fallbackPath =
addCustomIconsAndFallback
getCustomIconPath
(const $ lift $ getPixbufFromFilePath fallbackPath)
unscaledDefaultGetWindowIconPixbuf
addCustomIconsAndFallback
:: (WindowData -> Maybe FilePath)
-> (Int32 -> TaffyIO (Maybe Gdk.Pixbuf))
-> WindowIconPixbufGetter
-> WindowIconPixbufGetter
addCustomIconsAndFallback getCustomIconPath fallback defaultGetter =
scaledWindowIconPixbufGetter $
getCustomIcon <|||> defaultGetter <|||> (\s _ -> fallback s)
where
getCustomIcon :: Int32 -> WindowData -> TaffyIO (Maybe Gdk.Pixbuf)
getCustomIcon _ wdata =
lift $
maybe (return Nothing) getPixbufFromFilePath $ getCustomIconPath wdata
-- | Sort windows by top-left corner position.
sortWindowsByPosition :: [WindowData] -> WorkspacesIO [WindowData]
sortWindowsByPosition wins = do
let getGeometryWorkspaces w = getDisplay >>= liftIO . (`safeGetGeometry` w)
getGeometries = mapM
(forkM return
((((sel2 &&& sel3) <$>) .) getGeometryWorkspaces) .
windowId)
wins
windowGeometries <- liftX11Def [] getGeometries
let getLeftPos wd =
fromMaybe (999999999, 99999999) $ lookup (windowId wd) windowGeometries
compareWindowData a b =
compare
(windowMinimized a, getLeftPos a)
(windowMinimized b, getLeftPos b)
return $ sortBy compareWindowData wins
| Sort windows in reverse _ NET_CLIENT_LIST_STACKING order .
Starting in xmonad - contrib 0.17.0 , this is effectively focus history , active first .
Previous versions erroneously stored focus - sort - order in _ .
sortWindowsByStackIndex :: [WindowData] -> WorkspacesIO [WindowData]
sortWindowsByStackIndex wins = do
stackingWindows <- liftX11Def [] getWindowsStacking
let getStackIdx wd = fromMaybe (-1) $ elemIndex (windowId wd) stackingWindows
compareWindowData a b = compare (getStackIdx b) (getStackIdx a)
return $ sortBy compareWindowData wins
updateImages :: IconController -> Workspace -> WorkspacesIO [IconWidget]
updateImages ic ws = do
WorkspacesContext {workspacesConfig = cfg} <- ask
sortedWindows <- iconSort cfg $ windows ws
wLog DEBUG $ printf "Updating images for %s" (show ws)
let updateIconWidget' getImageAction wdata = do
iconWidget <- getImageAction
_ <- updateIconWidget ic iconWidget wdata
return iconWidget
existingImages = map return $ iconImages ic
buildAndAddIconWidget transparentOnNone = do
iw <- buildIconWidget transparentOnNone ws
lift $ Gtk.containerAdd (iconsContainer ic) $ iconContainer iw
return iw
infiniteImages =
existingImages ++
replicate (minIcons cfg - length existingImages)
(buildAndAddIconWidget True) ++
repeat (buildAndAddIconWidget False)
windowCount = length $ windows ws
maxNeeded = maybe windowCount (min windowCount) $ maxIcons cfg
newImagesNeeded = length existingImages < max (minIcons cfg) maxNeeded
XXX : Only one of the two things being zipped can be an infinite list ,
-- which is why this newImagesNeeded contortion is needed.
imgSrcs =
if newImagesNeeded
then infiniteImages
else existingImages
getImgs = maybe imgSrcs (`take` imgSrcs) $ maxIcons cfg
justWindows = map Just sortedWindows
windowDatas =
if newImagesNeeded
then justWindows ++
replicate (minIcons cfg - length justWindows) Nothing
else justWindows ++ repeat Nothing
newImgs <-
zipWithM updateIconWidget' getImgs windowDatas
when newImagesNeeded $ lift $ Gtk.widgetShowAll $ iconsContainer ic
return newImgs
getWindowStatusString :: WindowData -> T.Text
getWindowStatusString windowData = T.toLower $ T.pack $
case windowData of
WindowData { windowMinimized = True } -> "minimized"
WindowData { windowActive = True } -> show Active
WindowData { windowUrgent = True } -> show Urgent
_ -> "normal"
possibleStatusStrings :: [T.Text]
possibleStatusStrings =
map
(T.toLower . T.pack)
[show Active, show Urgent, "minimized", "normal", "inactive"]
updateIconWidget
:: IconController
-> IconWidget
-> Maybe WindowData
-> WorkspacesIO ()
updateIconWidget _ IconWidget
{ iconContainer = iconButton
, iconWindow = windowRef
, iconForceUpdate = updateIcon
} windowData = do
let statusString = maybe "inactive" getWindowStatusString windowData :: T.Text
title = T.pack . windowTitle <$> windowData
setIconWidgetProperties =
updateWidgetClasses iconButton [statusString] possibleStatusStrings
void $ updateVar windowRef $ const $ return windowData
Gtk.widgetSetTooltipText iconButton title
lift $ updateIcon >> setIconWidgetProperties
data WorkspaceButtonController = WorkspaceButtonController
{ button :: Gtk.EventBox
, buttonWorkspace :: Workspace
, contentsController :: WWC
}
buildButtonController :: ParentControllerConstructor
buildButtonController contentsBuilder workspace = do
cc <- contentsBuilder workspace
workspacesRef <- asks workspacesVar
ctx <- ask
widget <- getWidget cc
lift $ do
ebox <- Gtk.eventBoxNew
Gtk.containerAdd ebox widget
Gtk.eventBoxSetVisibleWindow ebox False
_ <-
Gtk.onWidgetScrollEvent ebox $ \scrollEvent -> do
dir <- Gdk.getEventScrollDirection scrollEvent
workspaces <- liftIO $ MV.readMVar workspacesRef
let switchOne a =
liftIO $
flip runReaderT ctx $
liftX11Def
()
(switchOneWorkspace a (length (M.toList workspaces) - 1)) >>
return True
case dir of
Gdk.ScrollDirectionUp -> switchOne True
Gdk.ScrollDirectionLeft -> switchOne True
Gdk.ScrollDirectionDown -> switchOne False
Gdk.ScrollDirectionRight -> switchOne False
_ -> return False
_ <- Gtk.onWidgetButtonPressEvent ebox $ const $ switch ctx $ workspaceIdx workspace
return $
WWC
WorkspaceButtonController
{ button = ebox, buttonWorkspace = workspace, contentsController = cc }
switch :: (MonadIO m) => WorkspacesContext -> WorkspaceId -> m Bool
switch ctx idx = do
liftIO $ flip runReaderT ctx $ liftX11Def () $ switchToWorkspace idx
return True
instance WorkspaceWidgetController WorkspaceButtonController
where
getWidget wbc = lift $ Gtk.toWidget $ button wbc
updateWidget wbc update = do
newContents <- updateWidget (contentsController wbc) update
return wbc { contentsController = newContents }
| null | https://raw.githubusercontent.com/taffybar/taffybar/4129b2aed4349752dd9a1b47676d457883d95490/src/System/Taffybar/Widget/Workspaces.hs | haskell | ---------------------------------------------------------------------------
|
License : BSD3-style (see LICENSE)
Stability : unstable
Portability : unportable
---------------------------------------------------------------------------
add the widgets in the correct order
widgets appear out of order, in the switcher, by acting as an empty
place holder when the actual widget is hidden.
This will actually create all the widgets
Clear the container and repopulate it
abitrary widget.
| Sort windows by top-left corner position.
which is why this newImagesNeeded contortion is needed. | # OPTIONS_GHC -fno - warn - type - defaults #
# LANGUAGE ScopedTypeVariables , ExistentialQuantification , RankNTypes , OverloadedStrings #
Module : System . . Widget . Workspaces
Copyright : ( c )
Maintainer :
module System.Taffybar.Widget.Workspaces where
import Control.Applicative
import Control.Arrow ((&&&))
import Control.Concurrent
import qualified Control.Concurrent.MVar as MV
import Control.Exception.Enclosed (catchAny)
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Trans.Class
import Control.Monad.Trans.Maybe
import Control.Monad.Trans.Reader
import Control.RateLimit
import Data.Default (Default(..))
import qualified Data.Foldable as F
import Data.GI.Base.ManagedPtr (unsafeCastTo)
import Data.Int
import Data.List (elemIndex, intersect, sortBy, (\\))
import qualified Data.Map as M
import Data.Maybe
import qualified Data.MultiMap as MM
import Data.Ord
import qualified Data.Set as Set
import qualified Data.Text as T
import Data.Time.Units
import Data.Tuple.Select
import Data.Tuple.Sequence
import qualified GI.Gdk.Enums as Gdk
import qualified GI.Gdk.Structs.EventScroll as Gdk
import qualified GI.GdkPixbuf.Objects.Pixbuf as Gdk
import qualified GI.Gtk as Gtk
import Prelude
import StatusNotifier.Tray (scalePixbufToSize)
import System.Log.Logger
import System.Taffybar.Context
import System.Taffybar.Information.EWMHDesktopInfo
import System.Taffybar.Information.SafeX11
import System.Taffybar.Information.X11DesktopInfo
import System.Taffybar.Util
import System.Taffybar.Widget.Generic.AutoSizeImage (autoSizeImage)
import System.Taffybar.Widget.Util
import System.Taffybar.WindowIcon
import Text.Printf
data WorkspaceState
= Active
| Visible
| Hidden
| Empty
| Urgent
deriving (Show, Eq)
getCSSClass :: (Show s) => s -> T.Text
getCSSClass = T.toLower . T.pack . show
cssWorkspaceStates :: [T.Text]
cssWorkspaceStates = map getCSSClass [Active, Visible, Hidden, Empty, Urgent]
data WindowData = WindowData
{ windowId :: X11Window
, windowTitle :: String
, windowClass :: String
, windowUrgent :: Bool
, windowActive :: Bool
, windowMinimized :: Bool
} deriving (Show, Eq)
data WidgetUpdate = WorkspaceUpdate Workspace | IconUpdate [X11Window]
data Workspace = Workspace
{ workspaceIdx :: WorkspaceId
, workspaceName :: String
, workspaceState :: WorkspaceState
, windows :: [WindowData]
} deriving (Show, Eq)
data WorkspacesContext = WorkspacesContext
{ controllersVar :: MV.MVar (M.Map WorkspaceId WWC)
, workspacesVar :: MV.MVar (M.Map WorkspaceId Workspace)
, workspacesWidget :: Gtk.Box
, workspacesConfig :: WorkspacesConfig
, taffyContext :: Context
}
type WorkspacesIO a = ReaderT WorkspacesContext IO a
liftContext :: TaffyIO a -> WorkspacesIO a
liftContext action = asks taffyContext >>= lift . runReaderT action
liftX11Def :: a -> X11Property a -> WorkspacesIO a
liftX11Def dflt prop = liftContext $ runX11Def dflt prop
setWorkspaceWidgetStatusClass ::
(MonadIO m, Gtk.IsWidget a) => Workspace -> a -> m ()
setWorkspaceWidgetStatusClass workspace widget =
updateWidgetClasses
widget
[getCSSClass $ workspaceState workspace]
cssWorkspaceStates
updateWidgetClasses ::
(Foldable t1, Foldable t, Gtk.IsWidget a, MonadIO m)
=> a
-> t1 T.Text
-> t T.Text
-> m ()
updateWidgetClasses widget toAdd toRemove = do
context <- Gtk.widgetGetStyleContext widget
let hasClass = Gtk.styleContextHasClass context
addIfMissing klass =
hasClass klass >>= (`when` Gtk.styleContextAddClass context klass) . not
removeIfPresent klass = unless (klass `elem` toAdd) $
hasClass klass >>= (`when` Gtk.styleContextRemoveClass context klass)
mapM_ removeIfPresent toRemove
mapM_ addIfMissing toAdd
class WorkspaceWidgetController wc where
getWidget :: wc -> WorkspacesIO Gtk.Widget
updateWidget :: wc -> WidgetUpdate -> WorkspacesIO wc
updateWidgetX11 :: wc -> WidgetUpdate -> WorkspacesIO wc
updateWidgetX11 cont _ = return cont
data WWC = forall a. WorkspaceWidgetController a => WWC a
instance WorkspaceWidgetController WWC where
getWidget (WWC wc) = getWidget wc
updateWidget (WWC wc) update = WWC <$> updateWidget wc update
updateWidgetX11 (WWC wc) update = WWC <$> updateWidgetX11 wc update
type ControllerConstructor = Workspace -> WorkspacesIO WWC
type ParentControllerConstructor =
ControllerConstructor -> ControllerConstructor
type WindowIconPixbufGetter =
Int32 -> WindowData -> TaffyIO (Maybe Gdk.Pixbuf)
data WorkspacesConfig =
WorkspacesConfig
{ widgetBuilder :: ControllerConstructor
, widgetGap :: Int
, maxIcons :: Maybe Int
, minIcons :: Int
, getWindowIconPixbuf :: WindowIconPixbufGetter
, labelSetter :: Workspace -> WorkspacesIO String
, showWorkspaceFn :: Workspace -> Bool
, borderWidth :: Int
, updateEvents :: [String]
, updateRateLimitMicroseconds :: Integer
, iconSort :: [WindowData] -> WorkspacesIO [WindowData]
, urgentWorkspaceState :: Bool
}
defaultWorkspacesConfig :: WorkspacesConfig
defaultWorkspacesConfig =
WorkspacesConfig
{ widgetBuilder = buildButtonController defaultBuildContentsController
, widgetGap = 0
, maxIcons = Nothing
, minIcons = 0
, getWindowIconPixbuf = defaultGetWindowIconPixbuf
, labelSetter = return . workspaceName
, showWorkspaceFn = const True
, borderWidth = 2
, iconSort = sortWindowsByPosition
, updateEvents = allEWMHProperties \\ [ewmhWMIcon]
, updateRateLimitMicroseconds = 100000
, urgentWorkspaceState = False
}
instance Default WorkspacesConfig where
def = defaultWorkspacesConfig
hideEmpty :: Workspace -> Bool
hideEmpty Workspace { workspaceState = Empty } = False
hideEmpty _ = True
wLog :: MonadIO m => Priority -> String -> m ()
wLog l s = liftIO $ logM "System.Taffybar.Widget.Workspaces" l s
updateVar :: MV.MVar a -> (a -> WorkspacesIO a) -> WorkspacesIO a
updateVar var modify = do
ctx <- ask
lift $ MV.modifyMVar var $ fmap (\a -> (a, a)) . flip runReaderT ctx . modify
updateWorkspacesVar :: WorkspacesIO (M.Map WorkspaceId Workspace)
updateWorkspacesVar = do
workspacesRef <- asks workspacesVar
updateVar workspacesRef buildWorkspaceData
getWorkspaceToWindows ::
[X11Window] -> X11Property (MM.MultiMap WorkspaceId X11Window)
getWorkspaceToWindows =
foldM
(\theMap window ->
MM.insert <$> getWorkspace window <*> pure window <*> pure theMap)
MM.empty
getWindowData :: Maybe X11Window
-> [X11Window]
-> X11Window
-> X11Property WindowData
getWindowData activeWindow urgentWindows window = do
wTitle <- getWindowTitle window
wClass <- getWindowClass window
wMinimized <- getWindowMinimized window
return
WindowData
{ windowId = window
, windowTitle = wTitle
, windowClass = wClass
, windowUrgent = window `elem` urgentWindows
, windowActive = Just window == activeWindow
, windowMinimized = wMinimized
}
buildWorkspaceData :: M.Map WorkspaceId Workspace
-> WorkspacesIO (M.Map WorkspaceId Workspace)
buildWorkspaceData _ = ask >>= \context -> liftX11Def M.empty $ do
names <- getWorkspaceNames
wins <- getWindows
workspaceToWindows <- getWorkspaceToWindows wins
urgentWindows <- filterM isWindowUrgent wins
activeWindow <- getActiveWindow
active:visible <- getVisibleWorkspaces
let getWorkspaceState idx ws
| idx == active = Active
| idx `elem` visible = Visible
| urgentWorkspaceState (workspacesConfig context) &&
not (null (ws `intersect` urgentWindows)) =
Urgent
| null ws = Empty
| otherwise = Hidden
foldM
(\theMap (idx, name) -> do
let ws = MM.lookup idx workspaceToWindows
windowInfos <- mapM (getWindowData activeWindow urgentWindows) ws
return $
M.insert
idx
Workspace
{ workspaceIdx = idx
, workspaceName = name
, workspaceState = getWorkspaceState idx ws
, windows = windowInfos
}
theMap)
M.empty
names
addWidgetsToTopLevel :: WorkspacesIO ()
addWidgetsToTopLevel = do
WorkspacesContext
{ controllersVar = controllersRef
, workspacesWidget = cont
} <- ask
controllersMap <- lift $ MV.readMVar controllersRef
Elems returns elements in ascending order of their keys so this will always
mapM_ addWidget $ M.elems controllersMap
lift $ Gtk.widgetShowAll cont
addWidget :: WWC -> WorkspacesIO ()
addWidget controller = do
cont <- asks workspacesWidget
workspaceWidget <- getWidget controller
lift $ do
XXX : This hbox exists to ( hopefully ) prevent the issue where workspace
hbox <- Gtk.boxNew Gtk.OrientationHorizontal 0
void $ Gtk.widgetGetParent workspaceWidget >>=
traverse (unsafeCastTo Gtk.Box) >>=
traverse (flip Gtk.containerRemove workspaceWidget)
Gtk.containerAdd hbox workspaceWidget
Gtk.containerAdd cont hbox
workspacesNew :: WorkspacesConfig -> TaffyIO Gtk.Widget
workspacesNew cfg = ask >>= \tContext -> lift $ do
cont <- Gtk.boxNew Gtk.OrientationHorizontal $ fromIntegral (widgetGap cfg)
controllersRef <- MV.newMVar M.empty
workspacesRef <- MV.newMVar M.empty
let context =
WorkspacesContext
{ controllersVar = controllersRef
, workspacesVar = workspacesRef
, workspacesWidget = cont
, workspacesConfig = cfg
, taffyContext = tContext
}
runReaderT updateAllWorkspaceWidgets context
updateHandler <- onWorkspaceUpdate context
iconHandler <- onIconsChanged context
let doUpdate = lift . updateHandler
handleConfigureEvents e@(ConfigureEvent {}) = doUpdate e
handleConfigureEvents _ = return ()
(workspaceSubscription, iconSubscription, geometrySubscription) <-
flip runReaderT tContext $ sequenceT
( subscribeToPropertyEvents (updateEvents cfg) $ doUpdate
, subscribeToPropertyEvents [ewmhWMIcon] (lift . onIconChanged iconHandler)
, subscribeToAll handleConfigureEvents
)
let doUnsubscribe = flip runReaderT tContext $
mapM_ unsubscribe
[ iconSubscription
, workspaceSubscription
, geometrySubscription
]
_ <- Gtk.onWidgetUnrealize cont doUnsubscribe
_ <- widgetSetClassGI cont "workspaces"
Gtk.toWidget cont
updateAllWorkspaceWidgets :: WorkspacesIO ()
updateAllWorkspaceWidgets = do
wLog DEBUG "Updating workspace widgets"
workspacesMap <- updateWorkspacesVar
wLog DEBUG $ printf "Workspaces: %s" $ show workspacesMap
wLog DEBUG "Adding and removing widgets"
updateWorkspaceControllers
let updateController' idx controller =
maybe (return controller)
(updateWidget controller . WorkspaceUpdate) $
M.lookup idx workspacesMap
logUpdateController i =
wLog DEBUG $ printf "Updating %s workspace widget" $ show i
updateController i cont = logUpdateController i >>
updateController' i cont
wLog DEBUG "Done updating individual widget"
doWidgetUpdate updateController
wLog DEBUG "Showing and hiding controllers"
setControllerWidgetVisibility
setControllerWidgetVisibility :: WorkspacesIO ()
setControllerWidgetVisibility = do
ctx@WorkspacesContext
{ workspacesVar = workspacesRef
, controllersVar = controllersRef
, workspacesConfig = cfg
} <- ask
lift $ do
workspacesMap <- MV.readMVar workspacesRef
controllersMap <- MV.readMVar controllersRef
forM_ (M.elems workspacesMap) $ \ws ->
let action = if showWorkspaceFn cfg ws
then Gtk.widgetShow
else Gtk.widgetHide
in
traverse (flip runReaderT ctx . getWidget)
(M.lookup (workspaceIdx ws) controllersMap) >>=
maybe (return ()) action
doWidgetUpdate :: (WorkspaceId -> WWC -> WorkspacesIO WWC) -> WorkspacesIO ()
doWidgetUpdate updateController = do
c@WorkspacesContext { controllersVar = controllersRef } <- ask
lift $ MV.modifyMVar_ controllersRef $ \controllers -> do
wLog DEBUG "Updating controllers ref"
controllersList <-
mapM
(\(idx, controller) -> do
newController <- runReaderT (updateController idx controller) c
return (idx, newController)) $
M.toList controllers
return $ M.fromList controllersList
updateWorkspaceControllers :: WorkspacesIO ()
updateWorkspaceControllers = do
WorkspacesContext
{ controllersVar = controllersRef
, workspacesVar = workspacesRef
, workspacesWidget = cont
, workspacesConfig = cfg
} <- ask
workspacesMap <- lift $ MV.readMVar workspacesRef
controllersMap <- lift $ MV.readMVar controllersRef
let newWorkspacesSet = M.keysSet workspacesMap
existingWorkspacesSet = M.keysSet controllersMap
when (existingWorkspacesSet /= newWorkspacesSet) $ do
let addWorkspaces = Set.difference newWorkspacesSet existingWorkspacesSet
removeWorkspaces = Set.difference existingWorkspacesSet newWorkspacesSet
builder = widgetBuilder cfg
_ <- updateVar controllersRef $ \controllers -> do
let oldRemoved = F.foldl (flip M.delete) controllers removeWorkspaces
buildController idx = builder <$> M.lookup idx workspacesMap
buildAndAddController theMap idx =
maybe (return theMap) (>>= return . flip (M.insert idx) theMap)
(buildController idx)
foldM buildAndAddController oldRemoved $ Set.toList addWorkspaces
lift $ Gtk.containerForeach cont (Gtk.containerRemove cont)
addWidgetsToTopLevel
rateLimitFn
:: forall req resp.
WorkspacesContext
-> (req -> IO resp)
-> ResultsCombiner req resp
-> IO (req -> IO resp)
rateLimitFn context =
let limit = (updateRateLimitMicroseconds $ workspacesConfig context)
rate = fromMicroseconds limit :: Microsecond in
generateRateLimitedFunction $ PerInvocation rate
onWorkspaceUpdate :: WorkspacesContext -> IO (Event -> IO ())
onWorkspaceUpdate context = do
rateLimited <- rateLimitFn context doUpdate combineRequests
let withLog event = do
case event of
PropertyEvent _ _ _ _ _ atom _ _ ->
wLog DEBUG $ printf "Event %s" $ show atom
_ -> return ()
void $ forkIO $ rateLimited event
return withLog
where
combineRequests _ b = Just (b, const ((), ()))
doUpdate _ = postGUIASync $ runReaderT updateAllWorkspaceWidgets context
onIconChanged :: (Set.Set X11Window -> IO ()) -> Event -> IO ()
onIconChanged handler event =
case event of
PropertyEvent { ev_window = wid } -> do
wLog DEBUG $ printf "Icon changed event %s" $ show wid
handler $ Set.singleton wid
_ -> return ()
onIconsChanged :: WorkspacesContext -> IO (Set.Set X11Window -> IO ())
onIconsChanged context = rateLimitFn context onIconsChanged' combineRequests
where
combineRequests windows1 windows2 =
Just (Set.union windows1 windows2, const ((), ()))
onIconsChanged' wids = do
wLog DEBUG $ printf "Icon update execute %s" $ show wids
postGUIASync $ flip runReaderT context $
doWidgetUpdate
(\idx c ->
wLog DEBUG (printf "Updating %s icons." $ show idx) >>
updateWidget c (IconUpdate $ Set.toList wids))
initializeWWC ::
WorkspaceWidgetController a => a -> Workspace -> ReaderT WorkspacesContext IO WWC
initializeWWC controller ws =
WWC <$> updateWidget controller (WorkspaceUpdate ws)
| A WrappingController can be used to wrap some child widget with another
data WrappingController = WrappingController
{ wrappedWidget :: Gtk.Widget
, wrappedController :: WWC
}
instance WorkspaceWidgetController WrappingController where
getWidget = lift . Gtk.toWidget . wrappedWidget
updateWidget wc update = do
updated <- updateWidget (wrappedController wc) update
return wc { wrappedController = updated }
data WorkspaceContentsController = WorkspaceContentsController
{ containerWidget :: Gtk.Widget
, contentsControllers :: [WWC]
}
buildContentsController :: [ControllerConstructor] -> ControllerConstructor
buildContentsController constructors ws = do
controllers <- mapM ($ ws) constructors
ctx <- ask
tempController <- lift $ do
cons <- Gtk.boxNew Gtk.OrientationHorizontal 0
mapM_ (flip runReaderT ctx . getWidget >=> Gtk.containerAdd cons) controllers
outerBox <- Gtk.toWidget cons >>= buildPadBox
_ <- widgetSetClassGI cons "contents"
widget <- Gtk.toWidget outerBox
return
WorkspaceContentsController
{ containerWidget = widget
, contentsControllers = controllers
}
initializeWWC tempController ws
defaultBuildContentsController :: ControllerConstructor
defaultBuildContentsController =
buildContentsController [buildLabelController, buildIconController]
bottomLeftAlignedBoxWrapper :: T.Text -> ControllerConstructor -> ControllerConstructor
bottomLeftAlignedBoxWrapper boxClass constructor ws = do
controller <- constructor ws
widget <- getWidget controller
ebox <- Gtk.eventBoxNew
_ <- widgetSetClassGI ebox boxClass
Gtk.widgetSetHalign ebox Gtk.AlignStart
Gtk.widgetSetValign ebox Gtk.AlignEnd
Gtk.containerAdd ebox widget
wrapped <- Gtk.toWidget ebox
let wrappingController = WrappingController
{ wrappedWidget = wrapped
, wrappedController = controller
}
initializeWWC wrappingController ws
buildLabelOverlayController :: ControllerConstructor
buildLabelOverlayController =
buildOverlayContentsController
[buildIconController]
[bottomLeftAlignedBoxWrapper "overlay-box" buildLabelController]
buildOverlayContentsController ::
[ControllerConstructor] -> [ControllerConstructor] -> ControllerConstructor
buildOverlayContentsController mainConstructors overlayConstructors ws = do
controllers <- mapM ($ ws) mainConstructors
overlayControllers <- mapM ($ ws) overlayConstructors
ctx <- ask
tempController <- lift $ do
mainContents <- Gtk.boxNew Gtk.OrientationHorizontal 0
mapM_ (flip runReaderT ctx . getWidget >=> Gtk.containerAdd mainContents)
controllers
outerBox <- Gtk.toWidget mainContents >>= buildPadBox
_ <- widgetSetClassGI mainContents "contents"
overlay <- Gtk.overlayNew
Gtk.containerAdd overlay outerBox
mapM_ (flip runReaderT ctx . getWidget >=>
Gtk.overlayAddOverlay overlay) overlayControllers
widget <- Gtk.toWidget overlay
return
WorkspaceContentsController
{ containerWidget = widget
, contentsControllers = controllers ++ overlayControllers
}
initializeWWC tempController ws
instance WorkspaceWidgetController WorkspaceContentsController where
getWidget = return . containerWidget
updateWidget cc update = do
WorkspacesContext {} <- ask
case update of
WorkspaceUpdate newWorkspace ->
lift $ setWorkspaceWidgetStatusClass newWorkspace $ containerWidget cc
_ -> return ()
newControllers <- mapM (`updateWidget` update) $ contentsControllers cc
return cc {contentsControllers = newControllers}
updateWidgetX11 cc update = do
newControllers <- mapM (`updateWidgetX11` update) $ contentsControllers cc
return cc {contentsControllers = newControllers}
newtype LabelController = LabelController { label :: Gtk.Label }
buildLabelController :: ControllerConstructor
buildLabelController ws = do
tempController <- lift $ do
lbl <- Gtk.labelNew Nothing
_ <- widgetSetClassGI lbl "workspace-label"
return LabelController { label = lbl }
initializeWWC tempController ws
instance WorkspaceWidgetController LabelController where
getWidget = lift . Gtk.toWidget . label
updateWidget lc (WorkspaceUpdate newWorkspace) = do
WorkspacesContext { workspacesConfig = cfg } <- ask
labelText <- labelSetter cfg newWorkspace
lift $ do
Gtk.labelSetMarkup (label lc) $ T.pack labelText
setWorkspaceWidgetStatusClass newWorkspace $ label lc
return lc
updateWidget lc _ = return lc
data IconWidget = IconWidget
{ iconContainer :: Gtk.EventBox
, iconImage :: Gtk.Image
, iconWindow :: MV.MVar (Maybe WindowData)
, iconForceUpdate :: IO ()
}
getPixbufForIconWidget :: Bool
-> MV.MVar (Maybe WindowData)
-> Int32
-> WorkspacesIO (Maybe Gdk.Pixbuf)
getPixbufForIconWidget transparentOnNone dataVar size = do
ctx <- ask
let tContext = taffyContext ctx
getPBFromData = getWindowIconPixbuf $ workspacesConfig ctx
getPB' = runMaybeT $
MaybeT (lift $ MV.readMVar dataVar) >>= MaybeT . getPBFromData size
getPB = if transparentOnNone
then maybeTCombine getPB' (Just <$> pixBufFromColor size 0)
else getPB'
lift $ runReaderT getPB tContext
buildIconWidget :: Bool -> Workspace -> WorkspacesIO IconWidget
buildIconWidget transparentOnNone ws = do
ctx <- ask
lift $ do
windowVar <- MV.newMVar Nothing
img <- Gtk.imageNew
refreshImage <-
autoSizeImage img
(flip runReaderT ctx . getPixbufForIconWidget transparentOnNone windowVar)
Gtk.OrientationHorizontal
ebox <- Gtk.eventBoxNew
_ <- widgetSetClassGI img "window-icon"
_ <- widgetSetClassGI ebox "window-icon-container"
Gtk.containerAdd ebox img
_ <-
Gtk.onWidgetButtonPressEvent ebox $
const $ liftIO $ do
info <- MV.readMVar windowVar
case info of
Just updatedInfo ->
flip runReaderT ctx $
liftX11Def () $ focusWindow $ windowId updatedInfo
_ -> liftIO $ void $ switch ctx (workspaceIdx ws)
return True
return
IconWidget
{ iconContainer = ebox
, iconImage = img
, iconWindow = windowVar
, iconForceUpdate = refreshImage
}
data IconController = IconController
{ iconsContainer :: Gtk.Box
, iconImages :: [IconWidget]
, iconWorkspace :: Workspace
}
buildIconController :: ControllerConstructor
buildIconController ws = do
tempController <-
lift $ do
hbox <- Gtk.boxNew Gtk.OrientationHorizontal 0
return
IconController
{iconsContainer = hbox, iconImages = [], iconWorkspace = ws}
initializeWWC tempController ws
instance WorkspaceWidgetController IconController where
getWidget = lift . Gtk.toWidget . iconsContainer
updateWidget ic (WorkspaceUpdate newWorkspace) = do
newImages <- updateImages ic newWorkspace
return ic { iconImages = newImages, iconWorkspace = newWorkspace }
updateWidget ic (IconUpdate updatedIcons) =
updateWindowIconsById ic updatedIcons >> return ic
updateWindowIconsById ::
IconController -> [X11Window] -> WorkspacesIO ()
updateWindowIconsById ic windowIds =
mapM_ maybeUpdateWindowIcon $ iconImages ic
where
maybeUpdateWindowIcon widget =
do
info <- lift $ MV.readMVar $ iconWindow widget
when (maybe False (flip elem windowIds . windowId) info) $
updateIconWidget ic widget info
scaledWindowIconPixbufGetter :: WindowIconPixbufGetter -> WindowIconPixbufGetter
scaledWindowIconPixbufGetter getter size =
getter size >=>
lift . traverse (scalePixbufToSize size Gtk.OrientationHorizontal)
constantScaleWindowIconPixbufGetter ::
Int32 -> WindowIconPixbufGetter -> WindowIconPixbufGetter
constantScaleWindowIconPixbufGetter constantSize getter =
const $ scaledWindowIconPixbufGetter getter constantSize
handleIconGetterException :: WindowIconPixbufGetter -> WindowIconPixbufGetter
handleIconGetterException getter =
\size windowData -> catchAny (getter size windowData) $ \e -> do
wLog WARNING $ printf "Failed to get window icon for %s: %s" (show windowData) (show e)
return Nothing
getWindowIconPixbufFromEWMH :: WindowIconPixbufGetter
getWindowIconPixbufFromEWMH = handleIconGetterException $ \size windowData ->
runX11Def Nothing (getIconPixBufFromEWMH size $ windowId windowData)
getWindowIconPixbufFromClass :: WindowIconPixbufGetter
getWindowIconPixbufFromClass = handleIconGetterException $ \size windowData ->
lift $ getWindowIconFromClasses size (windowClass windowData)
getWindowIconPixbufFromDesktopEntry :: WindowIconPixbufGetter
getWindowIconPixbufFromDesktopEntry = handleIconGetterException $ \size windowData ->
getWindowIconFromDesktopEntryByClasses size (windowClass windowData)
getWindowIconPixbufFromChrome :: WindowIconPixbufGetter
getWindowIconPixbufFromChrome _ windowData =
getPixBufFromChromeData $ windowId windowData
defaultGetWindowIconPixbuf :: WindowIconPixbufGetter
defaultGetWindowIconPixbuf =
scaledWindowIconPixbufGetter unscaledDefaultGetWindowIconPixbuf
unscaledDefaultGetWindowIconPixbuf :: WindowIconPixbufGetter
unscaledDefaultGetWindowIconPixbuf =
getWindowIconPixbufFromDesktopEntry <|||>
getWindowIconPixbufFromClass <|||>
getWindowIconPixbufFromEWMH
addCustomIconsToDefaultWithFallbackByPath
:: (WindowData -> Maybe FilePath)
-> FilePath
-> WindowIconPixbufGetter
addCustomIconsToDefaultWithFallbackByPath getCustomIconPath fallbackPath =
addCustomIconsAndFallback
getCustomIconPath
(const $ lift $ getPixbufFromFilePath fallbackPath)
unscaledDefaultGetWindowIconPixbuf
addCustomIconsAndFallback
:: (WindowData -> Maybe FilePath)
-> (Int32 -> TaffyIO (Maybe Gdk.Pixbuf))
-> WindowIconPixbufGetter
-> WindowIconPixbufGetter
addCustomIconsAndFallback getCustomIconPath fallback defaultGetter =
scaledWindowIconPixbufGetter $
getCustomIcon <|||> defaultGetter <|||> (\s _ -> fallback s)
where
getCustomIcon :: Int32 -> WindowData -> TaffyIO (Maybe Gdk.Pixbuf)
getCustomIcon _ wdata =
lift $
maybe (return Nothing) getPixbufFromFilePath $ getCustomIconPath wdata
sortWindowsByPosition :: [WindowData] -> WorkspacesIO [WindowData]
sortWindowsByPosition wins = do
let getGeometryWorkspaces w = getDisplay >>= liftIO . (`safeGetGeometry` w)
getGeometries = mapM
(forkM return
((((sel2 &&& sel3) <$>) .) getGeometryWorkspaces) .
windowId)
wins
windowGeometries <- liftX11Def [] getGeometries
let getLeftPos wd =
fromMaybe (999999999, 99999999) $ lookup (windowId wd) windowGeometries
compareWindowData a b =
compare
(windowMinimized a, getLeftPos a)
(windowMinimized b, getLeftPos b)
return $ sortBy compareWindowData wins
| Sort windows in reverse _ NET_CLIENT_LIST_STACKING order .
Starting in xmonad - contrib 0.17.0 , this is effectively focus history , active first .
Previous versions erroneously stored focus - sort - order in _ .
sortWindowsByStackIndex :: [WindowData] -> WorkspacesIO [WindowData]
sortWindowsByStackIndex wins = do
stackingWindows <- liftX11Def [] getWindowsStacking
let getStackIdx wd = fromMaybe (-1) $ elemIndex (windowId wd) stackingWindows
compareWindowData a b = compare (getStackIdx b) (getStackIdx a)
return $ sortBy compareWindowData wins
updateImages :: IconController -> Workspace -> WorkspacesIO [IconWidget]
updateImages ic ws = do
WorkspacesContext {workspacesConfig = cfg} <- ask
sortedWindows <- iconSort cfg $ windows ws
wLog DEBUG $ printf "Updating images for %s" (show ws)
let updateIconWidget' getImageAction wdata = do
iconWidget <- getImageAction
_ <- updateIconWidget ic iconWidget wdata
return iconWidget
existingImages = map return $ iconImages ic
buildAndAddIconWidget transparentOnNone = do
iw <- buildIconWidget transparentOnNone ws
lift $ Gtk.containerAdd (iconsContainer ic) $ iconContainer iw
return iw
infiniteImages =
existingImages ++
replicate (minIcons cfg - length existingImages)
(buildAndAddIconWidget True) ++
repeat (buildAndAddIconWidget False)
windowCount = length $ windows ws
maxNeeded = maybe windowCount (min windowCount) $ maxIcons cfg
newImagesNeeded = length existingImages < max (minIcons cfg) maxNeeded
XXX : Only one of the two things being zipped can be an infinite list ,
imgSrcs =
if newImagesNeeded
then infiniteImages
else existingImages
getImgs = maybe imgSrcs (`take` imgSrcs) $ maxIcons cfg
justWindows = map Just sortedWindows
windowDatas =
if newImagesNeeded
then justWindows ++
replicate (minIcons cfg - length justWindows) Nothing
else justWindows ++ repeat Nothing
newImgs <-
zipWithM updateIconWidget' getImgs windowDatas
when newImagesNeeded $ lift $ Gtk.widgetShowAll $ iconsContainer ic
return newImgs
getWindowStatusString :: WindowData -> T.Text
getWindowStatusString windowData = T.toLower $ T.pack $
case windowData of
WindowData { windowMinimized = True } -> "minimized"
WindowData { windowActive = True } -> show Active
WindowData { windowUrgent = True } -> show Urgent
_ -> "normal"
possibleStatusStrings :: [T.Text]
possibleStatusStrings =
map
(T.toLower . T.pack)
[show Active, show Urgent, "minimized", "normal", "inactive"]
updateIconWidget
:: IconController
-> IconWidget
-> Maybe WindowData
-> WorkspacesIO ()
updateIconWidget _ IconWidget
{ iconContainer = iconButton
, iconWindow = windowRef
, iconForceUpdate = updateIcon
} windowData = do
let statusString = maybe "inactive" getWindowStatusString windowData :: T.Text
title = T.pack . windowTitle <$> windowData
setIconWidgetProperties =
updateWidgetClasses iconButton [statusString] possibleStatusStrings
void $ updateVar windowRef $ const $ return windowData
Gtk.widgetSetTooltipText iconButton title
lift $ updateIcon >> setIconWidgetProperties
data WorkspaceButtonController = WorkspaceButtonController
{ button :: Gtk.EventBox
, buttonWorkspace :: Workspace
, contentsController :: WWC
}
buildButtonController :: ParentControllerConstructor
buildButtonController contentsBuilder workspace = do
cc <- contentsBuilder workspace
workspacesRef <- asks workspacesVar
ctx <- ask
widget <- getWidget cc
lift $ do
ebox <- Gtk.eventBoxNew
Gtk.containerAdd ebox widget
Gtk.eventBoxSetVisibleWindow ebox False
_ <-
Gtk.onWidgetScrollEvent ebox $ \scrollEvent -> do
dir <- Gdk.getEventScrollDirection scrollEvent
workspaces <- liftIO $ MV.readMVar workspacesRef
let switchOne a =
liftIO $
flip runReaderT ctx $
liftX11Def
()
(switchOneWorkspace a (length (M.toList workspaces) - 1)) >>
return True
case dir of
Gdk.ScrollDirectionUp -> switchOne True
Gdk.ScrollDirectionLeft -> switchOne True
Gdk.ScrollDirectionDown -> switchOne False
Gdk.ScrollDirectionRight -> switchOne False
_ -> return False
_ <- Gtk.onWidgetButtonPressEvent ebox $ const $ switch ctx $ workspaceIdx workspace
return $
WWC
WorkspaceButtonController
{ button = ebox, buttonWorkspace = workspace, contentsController = cc }
switch :: (MonadIO m) => WorkspacesContext -> WorkspaceId -> m Bool
switch ctx idx = do
liftIO $ flip runReaderT ctx $ liftX11Def () $ switchToWorkspace idx
return True
instance WorkspaceWidgetController WorkspaceButtonController
where
getWidget wbc = lift $ Gtk.toWidget $ button wbc
updateWidget wbc update = do
newContents <- updateWidget (contentsController wbc) update
return wbc { contentsController = newContents }
|
9b54058724746c06a29d23d429bce88821cbefbbff8cfb4165ab466e116dcb70 | OCADml/OCADml | v.ml | * Two - dimensional vector
@canonical OCADml.v2
@canonical OCADml.v2 *)
type v2 = Gg.v2
* Three - dimensional vector
@canonical OCADml.v3
@canonical OCADml.v3 *)
type v3 = Gg.v3
* Four - dimensional vector
@canonical OCADml.v4
@canonical OCADml.v4 *)
type v4 = Gg.v4
let[@inline] v2 x y = Gg.V2.v x y
let[@inline] v3 x y z = Gg.V3.v x y z
let[@inline] v4 x y z w = Gg.V4.v x y z w
module type S = sig
type t
* Zero vector
val zero : t
* A line segment between two points .
type line =
{ a : t
; b : t
}
* { 1 Comparison }
(** [equal a b]
Float equality between the vectors [a] and [b]. *)
val equal : t -> t -> bool
(** [compare a b]
Compare the vectors [a] and [b]. *)
val compare : t -> t -> int
(** [approx ?eps a b]
Returns true if the distance between vectors [a] and [b] is less than or
equal to the epsilon [eps]. *)
val approx : ?eps:float -> t -> t -> bool
(** {1 Basic Arithmetic} *)
(** [horizontal_op f a b]
Hadamard (element-wise) operation between vectors [a] and [b] using the
function [f]. *)
val horizontal_op : (float -> float -> float) -> t -> t -> t
(** [add a b]
Hadamard (element-wise) addition of vectors [a] and [b]. *)
val add : t -> t -> t
(** [sub a b]
Hadamard (element-wise) subtraction of vector [b] from [a]. *)
val sub : t -> t -> t
(** [mul a b]
Hadamard (element-wise) product of vectors [a] and [b]. *)
val mul : t -> t -> t
(** [div a b]
Hadamard (element-wise) division of vector [a] by [b]. *)
val div : t -> t -> t
(** [neg t]
Negation of all elements of [t]. *)
val neg : t -> t
(** [add_scalar t s]
Element-wise addition of [s] to [t]. *)
val sadd : t -> float -> t
(** [sub_scalar t s]
Element-wise subtraction of [s] from [t]. *)
val ssub : t -> float -> t
* [ mul_scalar t s ]
Element - wise multiplication of [ t ] by [ s ] .
Element-wise multiplication of [t] by [s]. *)
val smul : t -> float -> t
(** [div_scalar t s]
Element-wise division of [t] by [s]. *)
val sdiv : t -> float -> t
(** [abs t]
Calculate the absolute value of the vector [t]. *)
val abs : t -> t
(** {1 Vector Math} *)
(** [norm t]
Calculate the vector norm (a.k.a. magnitude) of [t]. *)
val norm : t -> float
(** [distance a b]
Calculate the magnitude of the difference (Hadamard subtraction) between [a]
and [b]. *)
val distance : t -> t -> float
* [ normalize t ]
Normalize [ t ] to a vector for which the magnitude is equal to 1 .
e.g. [ norm ( normalize t ) = 1 . ]
Normalize [t] to a vector for which the magnitude is equal to 1.
e.g. [norm (normalize t) = 1.] *)
val normalize : t -> t
(** [dot a b]
Vector dot product of [a] and [b]. *)
val dot : t -> t -> float
(** [cross a b]
Vector cross product of [a] and [b]. In the case of 2d vectors, the cross
product is performed with an assumed z = 0. *)
val cross : t -> t -> v3
(** [mid a b]
Compute the midpoint between the vectors [a] and [b]. *)
val mid : t -> t -> t
(** [mean l]
Calculate the mean / average of all vectors in [l]. *)
val mean : t list -> t
(** [mean' a]
Calculate the mean / average of all vectors in the array [a]. *)
val mean' : t array -> t
(** [angle a b]
Calculate the angle between the vectors [a] and [b]. *)
val angle : t -> t -> float
(** [angle_points a b c]
Calculate the angle between the points [a], [b], and [c]. *)
val angle_points : t -> t -> t -> float
(** [ccw_theta t]
Calculate the angle in radians counter-clockwise [t] is from the positive
x-axis along the xy plane. *)
val ccw_theta : t -> float
(** [vector_axis a b]
Compute the vector perpendicular to the vectors [a] and [b]. *)
val vector_axis : t -> t -> v3
* [ clockwise_sign ? eps a b c ]
Returns the rotational ordering ( around the z - axis , from the perspective of
the origin , looking " up " the z - axis ) of the points [ a ] , [ b ] , and [ c ] as a
signed float , [ 1 . ] for clockwise , and [ -1 . ] for counter - clockwise . If the
points are collinear ( not forming a valid triangle , within the tolerance of
[ eps ] ) , [ 0 . ] is returned .
Returns the rotational ordering (around the z-axis, from the perspective of
the origin, looking "up" the z-axis) of the points [a], [b], and [c] as a
signed float, [1.] for clockwise, and [-1.] for counter-clockwise. If the
points are collinear (not forming a valid triangle, within the tolerance of
[eps]), [0.] is returned. *)
val clockwise_sign : ?eps:float -> t -> t -> t -> float
(** [collinear p1 p2 p3]
Returns [true] if [p2] lies on the line between [p1] and [p3]. *)
val collinear : t -> t -> t -> bool
* [ lerp a b u ]
Linearly interpolate between vectors [ a ] and [ b ] .
Linearly interpolate between vectors [a] and [b]. *)
val lerp : t -> t -> float -> t
(** [lerpn a b n]
Linearly interpolate [n] vectors between vectors [a] and [b]. If [endpoint]
is [true], the last vector will be equal to [b], otherwise, it will be about
[a + (b - a) * (1 - 1 / n)]. *)
val lerpn : ?endpoint:bool -> t -> t -> int -> t list
(** [distance_to_vector p v]
Distance from point [p] to the line passing through the origin with unit
direction [v]. *)
val distance_to_vector : t -> t -> float
(** [distance_to_line ?bounds ~line t]
Distance between the vector [t], and any point on [line]. [bounds]
indicates whether each end [{a; b}] of [line] is bounded, or a ray (default
= [(false, false)], indicating an infinite line in both directions.). *)
val distance_to_line : ?bounds:bool * bool -> line:line -> t -> float
(** [point_on_line ?eps ?bounds ~line t]
Return [true] if the point [t] falls within [eps] distance of the [line].
[bounds] indicates whether each end [{a; b}] of [line] is bounded, or a ray
(default = [(false, false)], indicating an infinite line in both
directions.) *)
val point_on_line : ?eps:float -> ?bounds:bool * bool -> line:line -> t -> bool
(** [line_closest_point ?bounds ~line t]
Find the closest point to [t] lying on the provided [line]. [bounds]
indicates whether each end [{a; b}] of [line] is bounded, or a ray (default =
[(false, false)], indicating an infinite line in both directions.) *)
val line_closest_point : ?bounds:bool * bool -> line:line -> t -> t
(** [lower_bounds a b]
Compute the lower bounds (minima of each dimension) of the vectors [a] and [b]. *)
val lower_bounds : t -> t -> t
(** [upper_bounds a b]
Compute the upper bounds (maxima of each dimension) of the vectors [a] and [b]. *)
val upper_bounds : t -> t -> t
(** {1 Utilities} *)
val map : (float -> float) -> t -> t
val x : t -> float
val y : t -> float
val z : t -> float
val to_v2 : t -> v2
val to_string : t -> string
(** [deg_of_rad t]
Element-wise conversion of [t] from radians to degrees. *)
val deg_of_rad : t -> t
(** [rad_to_deg t]
Element-wise conversion of [t] from degrees to radians. *)
val rad_of_deg : t -> t
* { 1 Infix operations }
(** [a +@ b]
Hadamard (element-wise) addition of [a] and [b]. *)
val ( +@ ) : t -> t -> t
(** [a -@ b]
Hadamard (element-wise) subtraction of [b] from [a]. *)
val ( -@ ) : t -> t -> t
(** [a *@ b]
Hadamard (element-wise) product of [a] and [b]. *)
val ( *@ ) : t -> t -> t
(** [a /@ b]
Hadamard (element-wise) division of [a] by [b]. *)
val ( /@ ) : t -> t -> t
(** [t +$ s]
Scalar addition of the vector [t] and scalar [s]. *)
val ( +$ ) : t -> float -> t
(** [t -$ s]
Scalar subtraction of the scalar [s] from the vector [t]. *)
val ( -$ ) : t -> float -> t
(** [t *$ s]
Scalar multiplication of the vector [t] by the scalar [s]. *)
val ( *$ ) : t -> float -> t
(** [t /$ s]
Scalar division of the vector [t] by the scalar [s]. *)
val ( /$ ) : t -> float -> t
end
| null | https://raw.githubusercontent.com/OCADml/OCADml/f8cd87da86cd5ea4c31ec169c796640ffdc6bdee/lib/v.ml | ocaml | * [equal a b]
Float equality between the vectors [a] and [b].
* [compare a b]
Compare the vectors [a] and [b].
* [approx ?eps a b]
Returns true if the distance between vectors [a] and [b] is less than or
equal to the epsilon [eps].
* {1 Basic Arithmetic}
* [horizontal_op f a b]
Hadamard (element-wise) operation between vectors [a] and [b] using the
function [f].
* [add a b]
Hadamard (element-wise) addition of vectors [a] and [b].
* [sub a b]
Hadamard (element-wise) subtraction of vector [b] from [a].
* [mul a b]
Hadamard (element-wise) product of vectors [a] and [b].
* [div a b]
Hadamard (element-wise) division of vector [a] by [b].
* [neg t]
Negation of all elements of [t].
* [add_scalar t s]
Element-wise addition of [s] to [t].
* [sub_scalar t s]
Element-wise subtraction of [s] from [t].
* [div_scalar t s]
Element-wise division of [t] by [s].
* [abs t]
Calculate the absolute value of the vector [t].
* {1 Vector Math}
* [norm t]
Calculate the vector norm (a.k.a. magnitude) of [t].
* [distance a b]
Calculate the magnitude of the difference (Hadamard subtraction) between [a]
and [b].
* [dot a b]
Vector dot product of [a] and [b].
* [cross a b]
Vector cross product of [a] and [b]. In the case of 2d vectors, the cross
product is performed with an assumed z = 0.
* [mid a b]
Compute the midpoint between the vectors [a] and [b].
* [mean l]
Calculate the mean / average of all vectors in [l].
* [mean' a]
Calculate the mean / average of all vectors in the array [a].
* [angle a b]
Calculate the angle between the vectors [a] and [b].
* [angle_points a b c]
Calculate the angle between the points [a], [b], and [c].
* [ccw_theta t]
Calculate the angle in radians counter-clockwise [t] is from the positive
x-axis along the xy plane.
* [vector_axis a b]
Compute the vector perpendicular to the vectors [a] and [b].
* [collinear p1 p2 p3]
Returns [true] if [p2] lies on the line between [p1] and [p3].
* [lerpn a b n]
Linearly interpolate [n] vectors between vectors [a] and [b]. If [endpoint]
is [true], the last vector will be equal to [b], otherwise, it will be about
[a + (b - a) * (1 - 1 / n)].
* [distance_to_vector p v]
Distance from point [p] to the line passing through the origin with unit
direction [v].
* [distance_to_line ?bounds ~line t]
Distance between the vector [t], and any point on [line]. [bounds]
indicates whether each end [{a; b}] of [line] is bounded, or a ray (default
= [(false, false)], indicating an infinite line in both directions.).
* [point_on_line ?eps ?bounds ~line t]
Return [true] if the point [t] falls within [eps] distance of the [line].
[bounds] indicates whether each end [{a; b}] of [line] is bounded, or a ray
(default = [(false, false)], indicating an infinite line in both
directions.)
* [line_closest_point ?bounds ~line t]
Find the closest point to [t] lying on the provided [line]. [bounds]
indicates whether each end [{a; b}] of [line] is bounded, or a ray (default =
[(false, false)], indicating an infinite line in both directions.)
* [lower_bounds a b]
Compute the lower bounds (minima of each dimension) of the vectors [a] and [b].
* [upper_bounds a b]
Compute the upper bounds (maxima of each dimension) of the vectors [a] and [b].
* {1 Utilities}
* [deg_of_rad t]
Element-wise conversion of [t] from radians to degrees.
* [rad_to_deg t]
Element-wise conversion of [t] from degrees to radians.
* [a +@ b]
Hadamard (element-wise) addition of [a] and [b].
* [a -@ b]
Hadamard (element-wise) subtraction of [b] from [a].
* [a *@ b]
Hadamard (element-wise) product of [a] and [b].
* [a /@ b]
Hadamard (element-wise) division of [a] by [b].
* [t +$ s]
Scalar addition of the vector [t] and scalar [s].
* [t -$ s]
Scalar subtraction of the scalar [s] from the vector [t].
* [t *$ s]
Scalar multiplication of the vector [t] by the scalar [s].
* [t /$ s]
Scalar division of the vector [t] by the scalar [s]. | * Two - dimensional vector
@canonical OCADml.v2
@canonical OCADml.v2 *)
type v2 = Gg.v2
* Three - dimensional vector
@canonical OCADml.v3
@canonical OCADml.v3 *)
type v3 = Gg.v3
* Four - dimensional vector
@canonical OCADml.v4
@canonical OCADml.v4 *)
type v4 = Gg.v4
let[@inline] v2 x y = Gg.V2.v x y
let[@inline] v3 x y z = Gg.V3.v x y z
let[@inline] v4 x y z w = Gg.V4.v x y z w
module type S = sig
type t
* Zero vector
val zero : t
* A line segment between two points .
type line =
{ a : t
; b : t
}
* { 1 Comparison }
val equal : t -> t -> bool
val compare : t -> t -> int
val approx : ?eps:float -> t -> t -> bool
val horizontal_op : (float -> float -> float) -> t -> t -> t
val add : t -> t -> t
val sub : t -> t -> t
val mul : t -> t -> t
val div : t -> t -> t
val neg : t -> t
val sadd : t -> float -> t
val ssub : t -> float -> t
* [ mul_scalar t s ]
Element - wise multiplication of [ t ] by [ s ] .
Element-wise multiplication of [t] by [s]. *)
val smul : t -> float -> t
val sdiv : t -> float -> t
val abs : t -> t
val norm : t -> float
val distance : t -> t -> float
* [ normalize t ]
Normalize [ t ] to a vector for which the magnitude is equal to 1 .
e.g. [ norm ( normalize t ) = 1 . ]
Normalize [t] to a vector for which the magnitude is equal to 1.
e.g. [norm (normalize t) = 1.] *)
val normalize : t -> t
val dot : t -> t -> float
val cross : t -> t -> v3
val mid : t -> t -> t
val mean : t list -> t
val mean' : t array -> t
val angle : t -> t -> float
val angle_points : t -> t -> t -> float
val ccw_theta : t -> float
val vector_axis : t -> t -> v3
* [ clockwise_sign ? eps a b c ]
Returns the rotational ordering ( around the z - axis , from the perspective of
the origin , looking " up " the z - axis ) of the points [ a ] , [ b ] , and [ c ] as a
signed float , [ 1 . ] for clockwise , and [ -1 . ] for counter - clockwise . If the
points are collinear ( not forming a valid triangle , within the tolerance of
[ eps ] ) , [ 0 . ] is returned .
Returns the rotational ordering (around the z-axis, from the perspective of
the origin, looking "up" the z-axis) of the points [a], [b], and [c] as a
signed float, [1.] for clockwise, and [-1.] for counter-clockwise. If the
points are collinear (not forming a valid triangle, within the tolerance of
[eps]), [0.] is returned. *)
val clockwise_sign : ?eps:float -> t -> t -> t -> float
val collinear : t -> t -> t -> bool
* [ lerp a b u ]
Linearly interpolate between vectors [ a ] and [ b ] .
Linearly interpolate between vectors [a] and [b]. *)
val lerp : t -> t -> float -> t
val lerpn : ?endpoint:bool -> t -> t -> int -> t list
val distance_to_vector : t -> t -> float
val distance_to_line : ?bounds:bool * bool -> line:line -> t -> float
val point_on_line : ?eps:float -> ?bounds:bool * bool -> line:line -> t -> bool
val line_closest_point : ?bounds:bool * bool -> line:line -> t -> t
val lower_bounds : t -> t -> t
val upper_bounds : t -> t -> t
val map : (float -> float) -> t -> t
val x : t -> float
val y : t -> float
val z : t -> float
val to_v2 : t -> v2
val to_string : t -> string
val deg_of_rad : t -> t
val rad_of_deg : t -> t
* { 1 Infix operations }
val ( +@ ) : t -> t -> t
val ( -@ ) : t -> t -> t
val ( *@ ) : t -> t -> t
val ( /@ ) : t -> t -> t
val ( +$ ) : t -> float -> t
val ( -$ ) : t -> float -> t
val ( *$ ) : t -> float -> t
val ( /$ ) : t -> float -> t
end
|
a50441ca6441bccff0f9ad1ce865bdf6183c9da1eebdfa569178b0bc74f7500f | lispgames/mathkit | package.lisp | (defpackage #:kit.math
(:use #:cl #:sb-cga)
(:export #:deg-to-rad
#:rad-to-deg
#:matrix*vec4
#:matrix*vec3
#:copy-matrix
#:perspective-matrix
#:ortho-matrix
#:look-at
#:frustum
#:unproject
#:vec2 #:vec3 #:vec4
#:dvec2 #:dvec3 #:dvec4
#:ivec2 #:ivec3 #:ivec4))
| null | https://raw.githubusercontent.com/lispgames/mathkit/fd884f94b36ef5e9bc19459ad0b3cda6303d2a2a/src/package.lisp | lisp | (defpackage #:kit.math
(:use #:cl #:sb-cga)
(:export #:deg-to-rad
#:rad-to-deg
#:matrix*vec4
#:matrix*vec3
#:copy-matrix
#:perspective-matrix
#:ortho-matrix
#:look-at
#:frustum
#:unproject
#:vec2 #:vec3 #:vec4
#:dvec2 #:dvec3 #:dvec4
#:ivec2 #:ivec3 #:ivec4))
|
|
31a684890933d4d82597e4c7ac161f2aee2be91859d3163ed109f85a020e5ec0 | eeng/mercurius | in_memory_ticker_repository_test.clj | (ns mercurius.trading.adapters.repositories.in-memory-ticker-repository-test
(:require [clojure.test :refer [deftest testing is]]
[matcher-combinators.test]
[mercurius.support.factory :refer [build-trade]]
[mercurius.trading.domain.repositories.ticker-repository :refer [update-ticker get-ticker]]
[mercurius.trading.adapters.repositories.in-memory-ticker-repository :refer [new-in-memory-ticker-repo]]))
(deftest update-ticker-test
(testing "should set the new last-price"
(let [repo (new-in-memory-ticker-repo)]
(update-ticker repo (build-trade {:ticker "BTCUSD" :price 10.0}))
(is (match? {:last-price 10.0} (get-ticker repo "BTCUSD")))
(update-ticker repo (build-trade {:ticker "BTCUSD" :price 10.1}))
(is (match? {:last-price 10.1} (get-ticker repo "BTCUSD")))
(update-ticker repo (build-trade {:ticker "ETHUSD" :price 20.0}))
(is (match? {:last-price 10.1} (get-ticker repo "BTCUSD")))
(is (match? {:last-price 20.0} (get-ticker repo "ETHUSD")))))
(testing "should increase the volume"
(let [repo (new-in-memory-ticker-repo)]
(is (match? {:volume 0M} (get-ticker repo "BTCUSD")))
(update-ticker repo (build-trade {:ticker "BTCUSD" :amount 10M}))
(is (match? {:volume 10M} (get-ticker repo "BTCUSD")))
(update-ticker repo (build-trade {:ticker "BTCUSD" :amount 9M}))
(is (match? {:volume 19M} (get-ticker repo "BTCUSD")))))
(testing "should return the updated data"
(let [repo (new-in-memory-ticker-repo)]
(is (match? {:volume 5M :ticker "BTCUSD"}
(update-ticker repo (build-trade {:ticker "BTCUSD" :amount 5M})))))))
| null | https://raw.githubusercontent.com/eeng/mercurius/f83778ddde99aa13692e4fe2e70b2e9dc2fd70e9/test/mercurius/trading/adapters/repositories/in_memory_ticker_repository_test.clj | clojure | (ns mercurius.trading.adapters.repositories.in-memory-ticker-repository-test
(:require [clojure.test :refer [deftest testing is]]
[matcher-combinators.test]
[mercurius.support.factory :refer [build-trade]]
[mercurius.trading.domain.repositories.ticker-repository :refer [update-ticker get-ticker]]
[mercurius.trading.adapters.repositories.in-memory-ticker-repository :refer [new-in-memory-ticker-repo]]))
(deftest update-ticker-test
(testing "should set the new last-price"
(let [repo (new-in-memory-ticker-repo)]
(update-ticker repo (build-trade {:ticker "BTCUSD" :price 10.0}))
(is (match? {:last-price 10.0} (get-ticker repo "BTCUSD")))
(update-ticker repo (build-trade {:ticker "BTCUSD" :price 10.1}))
(is (match? {:last-price 10.1} (get-ticker repo "BTCUSD")))
(update-ticker repo (build-trade {:ticker "ETHUSD" :price 20.0}))
(is (match? {:last-price 10.1} (get-ticker repo "BTCUSD")))
(is (match? {:last-price 20.0} (get-ticker repo "ETHUSD")))))
(testing "should increase the volume"
(let [repo (new-in-memory-ticker-repo)]
(is (match? {:volume 0M} (get-ticker repo "BTCUSD")))
(update-ticker repo (build-trade {:ticker "BTCUSD" :amount 10M}))
(is (match? {:volume 10M} (get-ticker repo "BTCUSD")))
(update-ticker repo (build-trade {:ticker "BTCUSD" :amount 9M}))
(is (match? {:volume 19M} (get-ticker repo "BTCUSD")))))
(testing "should return the updated data"
(let [repo (new-in-memory-ticker-repo)]
(is (match? {:volume 5M :ticker "BTCUSD"}
(update-ticker repo (build-trade {:ticker "BTCUSD" :amount 5M})))))))
|
|
f78df326f48bfc99fb5861b71955d57a8214a2283d0fc0dd885b1a804c2cf2e9 | maximedenes/native-coq | namegen.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
open Names
open Term
open Environ
(*********************************************************************
Generating "intuitive" names from their type *)
val lowercase_first_char : identifier -> string
val sort_hdchar : sorts -> string
val hdchar : env -> types -> string
val id_of_name_using_hdchar : env -> types -> name -> identifier
val named_hd : env -> types -> name -> name
val mkProd_name : env -> name * types * types -> types
val mkLambda_name : env -> name * types * constr -> constr
(** Deprecated synonyms of [mkProd_name] and [mkLambda_name] *)
val prod_name : env -> name * types * types -> types
val lambda_name : env -> name * types * constr -> constr
val prod_create : env -> types * types -> constr
val lambda_create : env -> types * constr -> constr
val name_assumption : env -> rel_declaration -> rel_declaration
val name_context : env -> rel_context -> rel_context
val mkProd_or_LetIn_name : env -> types -> rel_declaration -> types
val mkLambda_or_LetIn_name : env -> constr -> rel_declaration -> constr
val it_mkProd_or_LetIn_name : env -> types -> rel_context -> types
val it_mkLambda_or_LetIn_name : env -> constr -> rel_context -> constr
(*********************************************************************
Fresh names *)
(** Avoid clashing with a name satisfying some predicate *)
val next_ident_away_from : identifier -> (identifier -> bool) -> identifier
(** Avoid clashing with a name of the given list *)
val next_ident_away : identifier -> identifier list -> identifier
(** Avoid clashing with a name already used in current module *)
val next_ident_away_in_goal : identifier -> identifier list -> identifier
(** Avoid clashing with a name already used in current module
but tolerate overwriting section variables, as in goals *)
val next_global_ident_away : identifier -> identifier list -> identifier
(** Avoid clashing with a constructor name already used in current module *)
val next_name_away_in_cases_pattern : name -> identifier list -> identifier
val next_name_away : name -> identifier list -> identifier (** default is "H" *)
val next_name_away_with_default : string -> name -> identifier list ->
identifier
val next_name_away_with_default_using_types : string -> name ->
identifier list -> types -> identifier
val set_reserved_typed_name : (types -> name) -> unit
(*********************************************************************
Making name distinct for displaying *)
type renaming_flags =
| RenamingForCasesPattern (** avoid only global constructors *)
| RenamingForGoal (** avoid all globals (as in intro) *)
| RenamingElsewhereFor of (name list * constr)
val make_all_name_different : env -> env
val compute_displayed_name_in :
renaming_flags -> identifier list -> name -> constr -> name * identifier list
val compute_and_force_displayed_name_in :
renaming_flags -> identifier list -> name -> constr -> name * identifier list
val compute_displayed_let_name_in :
renaming_flags -> identifier list -> name -> constr -> name * identifier list
val rename_bound_vars_as_displayed :
identifier list -> name list -> types -> types
| null | https://raw.githubusercontent.com/maximedenes/native-coq/3623a4d9fe95c165f02f7119c0e6564a83a9f4c9/pretyping/namegen.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
********************************************************************
Generating "intuitive" names from their type
* Deprecated synonyms of [mkProd_name] and [mkLambda_name]
********************************************************************
Fresh names
* Avoid clashing with a name satisfying some predicate
* Avoid clashing with a name of the given list
* Avoid clashing with a name already used in current module
* Avoid clashing with a name already used in current module
but tolerate overwriting section variables, as in goals
* Avoid clashing with a constructor name already used in current module
* default is "H"
********************************************************************
Making name distinct for displaying
* avoid only global constructors
* avoid all globals (as in intro) | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Names
open Term
open Environ
val lowercase_first_char : identifier -> string
val sort_hdchar : sorts -> string
val hdchar : env -> types -> string
val id_of_name_using_hdchar : env -> types -> name -> identifier
val named_hd : env -> types -> name -> name
val mkProd_name : env -> name * types * types -> types
val mkLambda_name : env -> name * types * constr -> constr
val prod_name : env -> name * types * types -> types
val lambda_name : env -> name * types * constr -> constr
val prod_create : env -> types * types -> constr
val lambda_create : env -> types * constr -> constr
val name_assumption : env -> rel_declaration -> rel_declaration
val name_context : env -> rel_context -> rel_context
val mkProd_or_LetIn_name : env -> types -> rel_declaration -> types
val mkLambda_or_LetIn_name : env -> constr -> rel_declaration -> constr
val it_mkProd_or_LetIn_name : env -> types -> rel_context -> types
val it_mkLambda_or_LetIn_name : env -> constr -> rel_context -> constr
val next_ident_away_from : identifier -> (identifier -> bool) -> identifier
val next_ident_away : identifier -> identifier list -> identifier
val next_ident_away_in_goal : identifier -> identifier list -> identifier
val next_global_ident_away : identifier -> identifier list -> identifier
val next_name_away_in_cases_pattern : name -> identifier list -> identifier
val next_name_away_with_default : string -> name -> identifier list ->
identifier
val next_name_away_with_default_using_types : string -> name ->
identifier list -> types -> identifier
val set_reserved_typed_name : (types -> name) -> unit
type renaming_flags =
| RenamingElsewhereFor of (name list * constr)
val make_all_name_different : env -> env
val compute_displayed_name_in :
renaming_flags -> identifier list -> name -> constr -> name * identifier list
val compute_and_force_displayed_name_in :
renaming_flags -> identifier list -> name -> constr -> name * identifier list
val compute_displayed_let_name_in :
renaming_flags -> identifier list -> name -> constr -> name * identifier list
val rename_bound_vars_as_displayed :
identifier list -> name list -> types -> types
|
2cd3e8bf564cb1f0404ebc6b582b49ba8d7d2942bad2458729dde1082b052112 | kit-clj/kit | formats.clj | (ns <<ns-name>>.web.middleware.formats
(:require
[luminus-transit.time :as time]
[muuntaja.core :as m]))
(def instance
(m/create
(-> m/default-options
(update-in
[:formats "application/transit+json" :decoder-opts]
(partial merge time/time-deserialization-handlers))
(update-in
[:formats "application/transit+json" :encoder-opts]
(partial merge time/time-serialization-handlers)))))
| null | https://raw.githubusercontent.com/kit-clj/kit/9a38fbdfce072e056e6b0d79001f810e5deebe62/libs/deps-template/resources/io/github/kit_clj/kit/src/clj/web/middleware/formats.clj | clojure | (ns <<ns-name>>.web.middleware.formats
(:require
[luminus-transit.time :as time]
[muuntaja.core :as m]))
(def instance
(m/create
(-> m/default-options
(update-in
[:formats "application/transit+json" :decoder-opts]
(partial merge time/time-deserialization-handlers))
(update-in
[:formats "application/transit+json" :encoder-opts]
(partial merge time/time-serialization-handlers)))))
|
|
ad9eb8437886f29967cc652b1e3cfb54d9940ec1dfe2d849693d1eb457261b43 | unisonweb/unison | Internal.hs | | The private Unison . Name innards . Prefer importing Unison . Name instead , unless you need the data constructor of
-- Name.
module Unison.Name.Internal
( Name (..),
isAbsolute,
segments,
)
where
import Control.Lens as Lens
import Data.List.NonEmpty (pattern (:|))
import qualified Data.List.NonEmpty as List (NonEmpty)
import qualified Data.List.NonEmpty as List.NonEmpty
import Unison.NameSegment (NameSegment)
import Unison.Position (Position (..))
import Unison.Prelude
import Unison.Util.Alphabetical
-- | A name is an absolute-or-relative non-empty list of name segments.
data Name
= -- A few example names:
--
-- "foo.bar" --> Name Relative ["bar", "foo"]
-- ".foo.bar" --> Name Absolute ["bar", "foo"]
" |>.<| " -- > Name Relative [ " < | " , " | > " ]
-- "." --> Name Relative ["."]
-- ".." --> Name Absolute ["."]
--
Name
-- whether the name is positioned absolutely (to some arbitrary root namespace), or relatively
Position
-- the name segments in reverse order
(List.NonEmpty NameSegment)
deriving stock (Eq, Generic, Show)
-- | Compare names (kinda) alphabetically: absolute comes before relative, but otherwise compare the name segments
-- alphabetically, in order.
instance Alphabetical Name where
compareAlphabetical n1 n2 =
case (isAbsolute n1, isAbsolute n2) of
(True, False) -> LT
(False, True) -> GT
_ -> compareAlphabetical (segments n1) (segments n2)
instance Ord Name where
compare (Name p0 ss0) (Name p1 ss1) =
compare ss0 ss1 <> compare p0 p1
instance Lens.Snoc Name Name NameSegment NameSegment where
_Snoc =
Lens.prism snoc unsnoc
where
snoc :: (Name, NameSegment) -> Name
snoc (Name p (x :| xs), y) =
Name p (y :| x : xs)
unsnoc :: Name -> Either Name (Name, NameSegment)
unsnoc name =
case name of
Name _ (_ :| []) -> Left name
Name p (x :| y : ys) -> Right (Name p (y :| ys), x)
-- | Is this name absolute?
--
-- /O(1)/.
isAbsolute :: Name -> Bool
isAbsolute = \case
Name Absolute _ -> True
Name Relative _ -> False
-- | Return the name segments of a name.
--
-- >>> segments "a.b.c"
-- "a" :| ["b", "c"]
--
-- /O(n)/, where /n/ is the number of name segments.
segments :: Name -> List.NonEmpty NameSegment
segments (Name _ ss) =
List.NonEmpty.reverse ss
| null | https://raw.githubusercontent.com/unisonweb/unison/ef3e70dc3a07e08e7979fafa8c2a9ebc0411f090/unison-core/src/Unison/Name/Internal.hs | haskell | Name.
| A name is an absolute-or-relative non-empty list of name segments.
A few example names:
"foo.bar" --> Name Relative ["bar", "foo"]
".foo.bar" --> Name Absolute ["bar", "foo"]
> Name Relative [ " < | " , " | > " ]
"." --> Name Relative ["."]
".." --> Name Absolute ["."]
whether the name is positioned absolutely (to some arbitrary root namespace), or relatively
the name segments in reverse order
| Compare names (kinda) alphabetically: absolute comes before relative, but otherwise compare the name segments
alphabetically, in order.
| Is this name absolute?
/O(1)/.
| Return the name segments of a name.
>>> segments "a.b.c"
"a" :| ["b", "c"]
/O(n)/, where /n/ is the number of name segments. | | The private Unison . Name innards . Prefer importing Unison . Name instead , unless you need the data constructor of
module Unison.Name.Internal
( Name (..),
isAbsolute,
segments,
)
where
import Control.Lens as Lens
import Data.List.NonEmpty (pattern (:|))
import qualified Data.List.NonEmpty as List (NonEmpty)
import qualified Data.List.NonEmpty as List.NonEmpty
import Unison.NameSegment (NameSegment)
import Unison.Position (Position (..))
import Unison.Prelude
import Unison.Util.Alphabetical
data Name
Name
Position
(List.NonEmpty NameSegment)
deriving stock (Eq, Generic, Show)
instance Alphabetical Name where
compareAlphabetical n1 n2 =
case (isAbsolute n1, isAbsolute n2) of
(True, False) -> LT
(False, True) -> GT
_ -> compareAlphabetical (segments n1) (segments n2)
instance Ord Name where
compare (Name p0 ss0) (Name p1 ss1) =
compare ss0 ss1 <> compare p0 p1
instance Lens.Snoc Name Name NameSegment NameSegment where
_Snoc =
Lens.prism snoc unsnoc
where
snoc :: (Name, NameSegment) -> Name
snoc (Name p (x :| xs), y) =
Name p (y :| x : xs)
unsnoc :: Name -> Either Name (Name, NameSegment)
unsnoc name =
case name of
Name _ (_ :| []) -> Left name
Name p (x :| y : ys) -> Right (Name p (y :| ys), x)
isAbsolute :: Name -> Bool
isAbsolute = \case
Name Absolute _ -> True
Name Relative _ -> False
segments :: Name -> List.NonEmpty NameSegment
segments (Name _ ss) =
List.NonEmpty.reverse ss
|
85bc24ec0f6aa5b41dca62eea6aa3536dece2fa272abe314026b78bd0c9ae69c | hspec/hspec | Mock.hs | module Mock where
import Prelude ()
import Test.Hspec.Core.Compat
newtype Mock = Mock (IORef Int)
newMock :: IO Mock
newMock = Mock <$> newIORef 0
mockAction :: Mock -> IO ()
mockAction (Mock ref) = modifyIORef ref succ
mockCounter :: Mock -> IO Int
mockCounter (Mock ref) = readIORef ref
| null | https://raw.githubusercontent.com/hspec/hspec/b48eee41032450123044de82c4c02213813563b1/hspec-core/test/Mock.hs | haskell | module Mock where
import Prelude ()
import Test.Hspec.Core.Compat
newtype Mock = Mock (IORef Int)
newMock :: IO Mock
newMock = Mock <$> newIORef 0
mockAction :: Mock -> IO ()
mockAction (Mock ref) = modifyIORef ref succ
mockCounter :: Mock -> IO Int
mockCounter (Mock ref) = readIORef ref
|
|
37b7f22ab707d32a5bf62d5c3fa8aa0494e91d21794f6c67acaf04db3dda60f0 | qiao/sicp-solutions | 2.38.scm | (define nil '())
3/2
1/6
( 1 ( 2 ( 3 ( ) ) ) )
( ( ( ( ) 1 ) 2 ) 3 )
| null | https://raw.githubusercontent.com/qiao/sicp-solutions/a2fe069ba6909710a0867bdb705b2e58b2a281af/chapter2/2.38.scm | scheme | (define nil '())
3/2
1/6
( 1 ( 2 ( 3 ( ) ) ) )
( ( ( ( ) 1 ) 2 ) 3 )
|
|
12e6ef37f33d40fdea6013316fd6460319abc423e041463737e44af3614eb9d9 | sergv/hkanren | InterleavingLogic.hs | ----------------------------------------------------------------------------
-- |
-- Module : Control.Monad.InterleavingLogic
Copyright : ( c ) 2015
-- License : BSD3-style (see LICENSE)
--
-- Maintainer :
-- Stability :
-- Portability :
--
--
----------------------------------------------------------------------------
# LANGUAGE InstanceSigs #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE ScopedTypeVariables #
module Control.Monad.InterleavingLogic
( Logic
, logic
, observe
, observeAll
, observeMany
, runLogic
)
where
import Control.Applicative
import Control.Monad
import Control.Monad.Logic.Class
import qualified Data.Foldable as F
import qualified Data.Traversable as T
msplit ' ssk fk m = lift $ unLogicT m ( \x ma - > ssk x ( lift ma ) ) fk
-------------------------------------------------------------------------
| The basic Logic monad , for performing backtracking computations
-- returning values of type 'a'
newtype Logic a = Logic { unLogic :: forall r. (a -> r -> r) -> r -> r }
-------------------------------------------------------------------------
-- | A smart constructor for Logic computations.
logic :: (forall r. (a -> r -> r) -> r -> r) -> Logic a
logic = Logic
-------------------------------------------------------------------------
| Extracts the first result from a Logic computation .
observe :: Logic a -> a
observe l = unLogic l const (error "No answer.")
-------------------------------------------------------------------------
-- | Extracts all results from a Logic computation.
observeAll :: Logic a -> [a]
observeAll l = unLogic l (:) []
-------------------------------------------------------------------------
-- | Extracts up to a given number of results from a Logic computation.
observeMany :: forall a. Int -> Logic a -> [a]
observeMany n m
| n <= 0 = []
| n == 1 = unLogic m (\a _ -> [a]) []
| otherwise = unLogic (msplit m) sk []
where
sk :: Maybe (a, Logic a) -> [a] -> [a]
sk Nothing _ = []
sk (Just (a, m')) _ = n' `seq` (a : observeMany n' m')
where
n' = n - 1
-------------------------------------------------------------------------
-- | Runs a Logic computation with the specified initial success and
-- failure continuations.
runLogic :: Logic a -> (a -> r -> r) -> r -> r
runLogic = unLogic
instance Functor Logic where
# INLINABLE fmap #
fmap f lt = Logic $ \sk fk -> unLogic lt (sk . f) fk
instance Applicative Logic where
# INLINABLE pure #
pure a = Logic $ \sk fk -> sk a fk
# INLINABLE ( < * > ) #
f <*> a = Logic $ \sk fk -> unLogic f (\g fk' -> unLogic a (sk . g) fk') fk
instance Alternative Logic where
# INLINABLE empty #
empty = Logic $ \_ fk -> fk
# INLINABLE ( < | > ) #
f1 <|> f2 = Logic $ \sk fk -> unLogic f1 sk (unLogic f2 sk fk)
instance Monad Logic where
# INLINABLE return #
return a = Logic $ \sk fk -> sk a fk
# INLINABLE ( > > =) #
m >>= f = Logic $ \sk fk -> unLogic m (\a fk' -> unLogic (f a) sk fk') fk
fail _ = Logic $ \_ fk -> fk
instance MonadPlus Logic where
# INLINABLE mzero #
mzero = Logic $ \_ fk -> fk
# INLINABLE mplus #
m1 `mplus` m2 = Logic $ \sk fk -> unLogic m1 sk (unLogic m2 sk fk)
instance MonadLogic Logic where
# INLINABLE msplit #
msplit :: forall a. Logic a -> Logic (Maybe (a, Logic a))
msplit m = unLogic m ssk (return Nothing)
where
ssk :: a -> Logic (Maybe (a, Logic a)) -> Logic (Maybe (a, Logic a))
ssk a fk = return $ Just (a, (fk >>= reflect))
-- msplit' :: forall a b. (a -> Logic a -> Logic b) -> Logic b -> Logic a -> Logic b
msplit ' f g m = unLogic m
-- where
-- ssk :: a -> Logic b -> Logic b
-- ssk a fk = undefined
instance F.Foldable Logic where
foldMap f m = unLogic m (mappend . f) mempty
instance T.Traversable Logic where
traverse g l = unLogic l (\a ft -> cons <$> g a <*> ft) (pure mzero)
where
cons a l' = return a `mplus` l'
| null | https://raw.githubusercontent.com/sergv/hkanren/94a9038f5885471c9f4d3b17a8e52af4e7747af3/src/Control/Monad/InterleavingLogic.hs | haskell | --------------------------------------------------------------------------
|
Module : Control.Monad.InterleavingLogic
License : BSD3-style (see LICENSE)
Maintainer :
Stability :
Portability :
--------------------------------------------------------------------------
# LANGUAGE RankNTypes #
-----------------------------------------------------------------------
returning values of type 'a'
-----------------------------------------------------------------------
| A smart constructor for Logic computations.
-----------------------------------------------------------------------
-----------------------------------------------------------------------
| Extracts all results from a Logic computation.
-----------------------------------------------------------------------
| Extracts up to a given number of results from a Logic computation.
-----------------------------------------------------------------------
| Runs a Logic computation with the specified initial success and
failure continuations.
msplit' :: forall a b. (a -> Logic a -> Logic b) -> Logic b -> Logic a -> Logic b
where
ssk :: a -> Logic b -> Logic b
ssk a fk = undefined | Copyright : ( c ) 2015
# LANGUAGE InstanceSigs #
# LANGUAGE ScopedTypeVariables #
module Control.Monad.InterleavingLogic
( Logic
, logic
, observe
, observeAll
, observeMany
, runLogic
)
where
import Control.Applicative
import Control.Monad
import Control.Monad.Logic.Class
import qualified Data.Foldable as F
import qualified Data.Traversable as T
msplit ' ssk fk m = lift $ unLogicT m ( \x ma - > ssk x ( lift ma ) ) fk
| The basic Logic monad , for performing backtracking computations
newtype Logic a = Logic { unLogic :: forall r. (a -> r -> r) -> r -> r }
logic :: (forall r. (a -> r -> r) -> r -> r) -> Logic a
logic = Logic
| Extracts the first result from a Logic computation .
observe :: Logic a -> a
observe l = unLogic l const (error "No answer.")
observeAll :: Logic a -> [a]
observeAll l = unLogic l (:) []
observeMany :: forall a. Int -> Logic a -> [a]
observeMany n m
| n <= 0 = []
| n == 1 = unLogic m (\a _ -> [a]) []
| otherwise = unLogic (msplit m) sk []
where
sk :: Maybe (a, Logic a) -> [a] -> [a]
sk Nothing _ = []
sk (Just (a, m')) _ = n' `seq` (a : observeMany n' m')
where
n' = n - 1
runLogic :: Logic a -> (a -> r -> r) -> r -> r
runLogic = unLogic
instance Functor Logic where
# INLINABLE fmap #
fmap f lt = Logic $ \sk fk -> unLogic lt (sk . f) fk
instance Applicative Logic where
# INLINABLE pure #
pure a = Logic $ \sk fk -> sk a fk
# INLINABLE ( < * > ) #
f <*> a = Logic $ \sk fk -> unLogic f (\g fk' -> unLogic a (sk . g) fk') fk
instance Alternative Logic where
# INLINABLE empty #
empty = Logic $ \_ fk -> fk
# INLINABLE ( < | > ) #
f1 <|> f2 = Logic $ \sk fk -> unLogic f1 sk (unLogic f2 sk fk)
instance Monad Logic where
# INLINABLE return #
return a = Logic $ \sk fk -> sk a fk
# INLINABLE ( > > =) #
m >>= f = Logic $ \sk fk -> unLogic m (\a fk' -> unLogic (f a) sk fk') fk
fail _ = Logic $ \_ fk -> fk
instance MonadPlus Logic where
# INLINABLE mzero #
mzero = Logic $ \_ fk -> fk
# INLINABLE mplus #
m1 `mplus` m2 = Logic $ \sk fk -> unLogic m1 sk (unLogic m2 sk fk)
instance MonadLogic Logic where
# INLINABLE msplit #
msplit :: forall a. Logic a -> Logic (Maybe (a, Logic a))
msplit m = unLogic m ssk (return Nothing)
where
ssk :: a -> Logic (Maybe (a, Logic a)) -> Logic (Maybe (a, Logic a))
ssk a fk = return $ Just (a, (fk >>= reflect))
msplit ' f g m = unLogic m
instance F.Foldable Logic where
foldMap f m = unLogic m (mappend . f) mempty
instance T.Traversable Logic where
traverse g l = unLogic l (\a ft -> cons <$> g a <*> ft) (pure mzero)
where
cons a l' = return a `mplus` l'
|
1eee368544fa6670f36022212b897eb13bf6de5a6b1d204e8ac4e14b80285594 | pfdietz/ansi-test | tagbody.lsp | (in-package :cl-test)
;;; Utility to make a random tagbody
(defun make-random-digraph (n m)
"Create a random digraph with n nodes and m edges. Error if m is out of range of possible values."
(assert (typep n '(integer 0)))
(assert (typep m '(integer 0)))
(let ((m-max (* n (1- n)))
(adj-vec (make-array (list n) :initial-element nil)))
(assert (<= m m-max))
(if (> m (/ m-max 2))
;; Generate all and select randomly
(let ((m-vec (make-array (list m-max)))
(k 0))
(loop for i from 0 below n do
(loop for j from 0 below n do
(unless (= i j)
(setf (aref m-vec k) (list i j))
(incf k))))
(assert (= k m-max))
(select-m-random-edges m-vec m adj-vec))
;; Few edges; generate with iteration when collision
;; is detected
(generate-random-edges n adj-vec m #'/=))
(adj-vec-to-lists n adj-vec)))
(defun select-m-random-edges (m-vec m adj-vec)
(let ((k (length m-vec)))
(loop repeat m
do (let ((r (random k)))
(destructuring-bind (i j) (aref m-vec r)
(push j (aref adj-vec i)))
(setf (aref m-vec r) (aref m-vec (decf k)))))))
(defun adj-vec-to-lists (n adj-vec)
(assert (= (length adj-vec) n))
(loop for i from 0 below n
collect (cons i (sort (aref adj-vec i) #'<))))
(defun generate-random-edges (n adj-vec m pred)
(let ((e-table (make-hash-table :test #'equal)))
(loop for i from 0 below n do
(loop for j in (aref adj-vec i) do
(setf (gethash (list i j) e-table) t)))
(loop repeat m
do (loop (let* ((i (random n))
(j (random n)))
(when (funcall pred i j)
(let ((e (list i j)))
(unless (gethash e e-table)
(setf (gethash e e-table) t)
(push j (aref adj-vec i))
(return)))))))))
(defun make-random-mostly-dag (n m b)
"Create a random DAG in which m edges go forward and b edges go backwards"
(assert (typep n '(integer 0)))
(assert (typep m '(integer 0)))
(assert (typep b '(integer 0)))
(let ((m-max (/ (* n (1- n)) 2))
(adj-vec (make-array (list n) :initial-element nil)))
(assert (<= m m-max))
(assert (<= b m-max))
(if (> m (/ m-max 2))
;; Generate all and select randomly
(let* ((m-vec (coerce
(loop for i from 0 below n nconc
(loop for j from (1+ i) below n do
collect (list i j)))
'vector)))
(select-m-random-edges m-vec m adj-vec))
;; Generate randomly
(generate-random-edges n adj-vec m #'<))
;; Now generate back edges
(generate-random-edges n adj-vec b #'>)
(adj-vec-to-lists n adj-vec)))
| null | https://raw.githubusercontent.com/pfdietz/ansi-test/3f4b9d31c3408114f0467eaeca4fd13b28e2ce31/random/tagbody.lsp | lisp | Utility to make a random tagbody
Generate all and select randomly
Few edges; generate with iteration when collision
is detected
Generate all and select randomly
Generate randomly
Now generate back edges | (in-package :cl-test)
(defun make-random-digraph (n m)
"Create a random digraph with n nodes and m edges. Error if m is out of range of possible values."
(assert (typep n '(integer 0)))
(assert (typep m '(integer 0)))
(let ((m-max (* n (1- n)))
(adj-vec (make-array (list n) :initial-element nil)))
(assert (<= m m-max))
(if (> m (/ m-max 2))
(let ((m-vec (make-array (list m-max)))
(k 0))
(loop for i from 0 below n do
(loop for j from 0 below n do
(unless (= i j)
(setf (aref m-vec k) (list i j))
(incf k))))
(assert (= k m-max))
(select-m-random-edges m-vec m adj-vec))
(generate-random-edges n adj-vec m #'/=))
(adj-vec-to-lists n adj-vec)))
(defun select-m-random-edges (m-vec m adj-vec)
(let ((k (length m-vec)))
(loop repeat m
do (let ((r (random k)))
(destructuring-bind (i j) (aref m-vec r)
(push j (aref adj-vec i)))
(setf (aref m-vec r) (aref m-vec (decf k)))))))
(defun adj-vec-to-lists (n adj-vec)
(assert (= (length adj-vec) n))
(loop for i from 0 below n
collect (cons i (sort (aref adj-vec i) #'<))))
(defun generate-random-edges (n adj-vec m pred)
(let ((e-table (make-hash-table :test #'equal)))
(loop for i from 0 below n do
(loop for j in (aref adj-vec i) do
(setf (gethash (list i j) e-table) t)))
(loop repeat m
do (loop (let* ((i (random n))
(j (random n)))
(when (funcall pred i j)
(let ((e (list i j)))
(unless (gethash e e-table)
(setf (gethash e e-table) t)
(push j (aref adj-vec i))
(return)))))))))
(defun make-random-mostly-dag (n m b)
"Create a random DAG in which m edges go forward and b edges go backwards"
(assert (typep n '(integer 0)))
(assert (typep m '(integer 0)))
(assert (typep b '(integer 0)))
(let ((m-max (/ (* n (1- n)) 2))
(adj-vec (make-array (list n) :initial-element nil)))
(assert (<= m m-max))
(assert (<= b m-max))
(if (> m (/ m-max 2))
(let* ((m-vec (coerce
(loop for i from 0 below n nconc
(loop for j from (1+ i) below n do
collect (list i j)))
'vector)))
(select-m-random-edges m-vec m adj-vec))
(generate-random-edges n adj-vec m #'<))
(generate-random-edges n adj-vec b #'>)
(adj-vec-to-lists n adj-vec)))
|
99330e29be1b38c6eca9bf66432b70e5c997872200cfb6f8db1ff999c6d47280 | rtoy/cmucl | ctor.lisp | Copyright ( C ) 2002 < >
;;; 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.
3 . The name of the author may not be used to endorse or promote
;;; products derived from this software without specific prior written
;;; permission.
;;;
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` 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 AUTHOR OR
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.
#+cmu
(ext:file-comment "$Header: src/pcl/rt/ctor.lisp $")
(in-package "PCL-TESTS")
(deftest plist-keys.0
(pcl::plist-keys '())
nil)
(deftest plist-keys.1
(pcl::plist-keys '(:a 1 :b 2))
(:a :b))
(deftest plist-keys.2
(multiple-value-bind (result condition)
(ignore-errors (pcl::plist-keys '(:a)))
(values result (typep condition 'condition)))
nil
t)
(deftest make-instance->constructor-call.0
(pcl::make-instance->constructor-call '(make-instance 'foo a x))
nil)
(deftest make-instance->constructor-call.1
(pcl::make-instance->constructor-call '(make-instance foo :a x))
nil)
(deftest make-instance->constructor-call.2
(pcl::make-instance->constructor-call '(make-instance 'foo x))
nil)
(deftest make-instance->constructor-call.4
(pcl::make-instance->constructor-call '(make-instance 1))
nil)
(deftest make-instance->constructor-call.5
(let* ((form (pcl::make-instance->constructor-call
'(make-instance 'foo)))
(call (car (last form))))
(values (eq (first call) 'funcall)
(cddr call)))
t ())
(deftest make-instance->constructor-call.6
(let* ((form (pcl::make-instance->constructor-call
'(make-instance 'foo :x 1 :y 2)))
(call (car (last form))))
(values (eq (first call) 'funcall)
(cddr call)))
t ())
(deftest make-instance->constructor-call.7
(let* ((form (pcl::make-instance->constructor-call
'(make-instance 'foo :x x :y 2)))
(call (car (last form))))
(values (eq (first call) 'funcall)
(cddr call)))
t (x))
(deftest make-instance->constructor-call.8
(let* ((form (pcl::make-instance->constructor-call
'(make-instance 'foo :x x :y y)))
(call (car (last form))))
(values (eq (first call) 'funcall)
(cddr call)))
t (x y))
(deftest make-instance->constructor-call.9
(let* ((form (pcl::make-instance->constructor-call
'(make-instance 'foo :x x :y 1)))
(call (car (last form))))
(values (eq (first call) 'funcall)
(cddr call)))
t (x))
(deftest make-instance->constructor-call.10
(let* ((form (pcl::make-instance->constructor-call
'(make-instance 'foo :x x :y 1 :z z)))
(call (car (last form))))
(values (eq (first call) 'funcall)
(cddr call)))
t (x z))
(deftest make-ctor.0
(let ((ctor (pcl::make-ctor '(pcl::ctor bar) 'bar '(:x 1 :y 2))))
(values (pcl::ctor-function-name ctor)
(pcl::ctor-class-name ctor)
(pcl::ctor-initargs ctor)))
(pcl::ctor bar)
bar
(:x 1 :y 2))
(defclass foo ()
((a :initarg :a :initform 1)
(b :initarg :b :initform 2)))
(defun call-generator (generator function-name class-name args)
(declare (ignore function-name))
(let* ((ctor
(pcl::make-ctor (list 'pcl::ctor class-name) class-name args))
(class (find-class class-name))
(proto (pcl::class-prototype class))
(ii (pcl::compute-applicable-methods
#'initialize-instance (list proto)))
(si (pcl::compute-applicable-methods
#'shared-initialize (list proto t))))
(setf (pcl::ctor-class ctor) class)
(if (eq generator #'pcl::fallback-generator)
(funcall generator ctor)
(funcall generator ctor ii si))))
(deftest fallback-generator.0
(let ((fn (call-generator #'pcl::fallback-generator
'make-foo 'foo '(:a 0 :b 1))))
(values (second fn)
(type-of (second (third fn)))
(nthcdr 2 (third fn))))
()
pcl::standard-class
(:a 0 :b 1))
(deftest fallback-generator.1
(let ((fn (call-generator #'pcl::fallback-generator
'make-foo 'foo '(:a 0))))
(values (second fn)
(first (third fn))
(type-of (second (third fn)))
(nthcdr 2 (third fn))))
()
make-instance
pcl::standard-class
(:a 0))
(deftest fallback-generator.2
(let ((fn (call-generator #'pcl::fallback-generator
'make-foo 'foo '())))
(values (second fn)
(type-of (second (third fn)))
(nthcdr 2 (third fn))))
()
pcl::standard-class
())
(deftest fallback-generator.3
(let ((fn (call-generator #'pcl::fallback-generator
'make-foo 'foo '(:a .p0.))))
(values (second fn)
(type-of (second (third fn)))
(nthcdr 2 (third fn))))
(.p0.)
pcl::standard-class
(:a .p0.))
(deftest fallback-generator.4
(let ((fn (call-generator #'pcl::fallback-generator
'make-foo 'foo '(:a a :b b))))
(values (second fn)
(type-of (second (third fn)))
(nthcdr 2 (third fn))))
(a b)
pcl::standard-class
(:a a :b b))
;;; These depend on the actual slot definition location computation,
which may be different in my PCL than in the CVS PCL .
(deftest compute-initarg-locations.0
(let ((class (find-class 'foo)))
(pcl::compute-initarg-locations class '(:a :b)))
((:a (0 . t)) (:b (1 . t))))
(defclass foo2 (foo)
((c :initarg :a)))
(deftest compute-initarg-locations.1
(let ((class (find-class 'foo2)))
(pcl::compute-initarg-locations class '(:a :b)))
((:a (0 . t) (2 . t)) (:b (1 . t))))
(defclass foo3 (foo)
((c :initarg :a :allocation :class)))
;;;
This test must be compiled for the case that PCL::+SLOT - UNBOUND+
;;; is a symbol macro calling PCL::MAKE-UNBOUND-MARKER, otherwise
;;; we'll get a complaint that C::%%PRIMITIVE is not defined.
;;;
(define-compiled-test compute-initarg-locations.2
(let ((class (find-class 'foo3)))
(subst 'unbound pcl::+slot-unbound+
(pcl::compute-initarg-locations class '(:a :b))))
((:a (0 . t) ((c . unbound) . t)) (:b (1 . t))))
(defclass foo4 ()
((a :initarg :a :initarg :both)
(b :initarg :b :initarg :both)))
(deftest compute-initarg-locations.3
(let ((class (find-class 'foo4)))
(pcl::compute-initarg-locations class '(:both :a :b)))
((:both (0 . t) (1 . t)) (:a) (:b)))
(deftest compute-initarg-locations.4
(let ((class (find-class 'foo4)))
(pcl::compute-initarg-locations class '(:a :both)))
((:a (0 . t)) (:both (1 . t))))
(deftest slot-init-forms.0
(let ((ctor (pcl::make-ctor
(list 'pcl::ctor 'make-foo)
'foo '(:a a :b b))))
(setf (pcl::ctor-class ctor) (find-class 'foo))
(pcl::slot-init-forms ctor nil))
(let ()
(declare (ignorable) (optimize (safety 3)))
(setf (svref pcl::.slots. 0) (the t a))
(setf (svref pcl::.slots. 1) (the t b)))
nil)
(deftest slot-init-forms.1
(let ((ctor (pcl::make-ctor
(list 'pcl::ctor 'make-foo)
'foo '(:a a))))
(setf (pcl::ctor-class ctor) (find-class 'foo))
(pcl::slot-init-forms ctor nil))
(let ()
(declare (ignorable) (optimize (safety 3)))
(setf (svref pcl::.slots. 0) (the t a))
(setf (svref pcl::.slots. 1) (the t '2)))
nil)
(defclass foo5 ()
((a :initarg :a :initform 0)
(b :initarg :b)))
(deftest slot-init-forms.2
(let ((ctor (pcl::make-ctor
(list 'pcl::ctor 'make-foo)
'foo5 '(:a a))))
(setf (pcl::ctor-class ctor) (find-class 'foo5))
(pcl::slot-init-forms ctor nil))
(let ()
(declare (ignorable) (optimize (safety 3)))
(setf (svref pcl::.slots. 0) (the t a))
(setf (svref pcl::.slots. 1) pcl::+slot-unbound+))
nil)
(defclass foo5a ()
((a :initarg :a :initform 0)
(b :initarg :b :initform 0)))
(deftest slot-init-forms.2a
(let ((ctor (pcl::make-ctor
(list 'pcl::ctor 'make-foo)
'foo5a '())))
(setf (pcl::ctor-class ctor) (find-class 'foo5a))
(pcl::slot-init-forms ctor nil))
(let ()
(declare (ignorable) (optimize (safety 3)))
(setf (svref pcl::.slots. 0) (the t '0))
(setf (svref pcl::.slots. 1) (the t '0)))
nil)
(defclass foo6 ()
((a :initarg :a :initform 0 :allocation :class)
(b :initarg :b)))
(deftest slot-init-forms.3
(let ((ctor (pcl::make-ctor
(list 'pcl::ctor 'make-foo)
'foo6 '(:a a))))
(setf (pcl::ctor-class ctor) (find-class 'foo6))
(pcl::slot-init-forms ctor nil))
(let ()
(declare (ignorable) (optimize (safety 3)))
(setf (svref pcl::.slots. 0) pcl::+slot-unbound+)
(setf (cdr '(a . 0)) (the t a)))
nil)
(defun foo ()
(error "should never be called"))
(defclass foo7 ()
((a :initarg :a :initform (foo))
(b :initarg :b)))
(deftest slot-init-forms.4
(let* ((ctor (pcl::make-ctor
(list 'pcl::ctor 'make-foo)
'foo7 '())))
(setf (pcl::ctor-class ctor) (find-class 'foo7))
(let ((form (pcl::slot-init-forms ctor nil)))
(destructuring-bind (let vars declare setf1 setf2) form
(declare (ignore let vars declare))
(values setf2 (second setf1) (first (third (third setf1)))
(functionp (second (third (third setf1))))))))
(setf (svref pcl::.slots. 1) pcl::+slot-unbound+)
(svref pcl::.slots. 0)
funcall
t)
(deftest slot-init-forms.5
(let ((ctor (pcl::make-ctor
(list 'pcl::ctor 'make-foo)
'foo '(:a '(foo)))))
(setf (pcl::ctor-class ctor) (find-class 'foo))
(pcl::slot-init-forms ctor nil))
(let ()
(declare (ignorable) (optimize (safety 3)))
(setf (svref pcl::.slots. 0) (the t '(foo)))
(setf (svref pcl::.slots. 1) (the t '2)))
nil)
(deftest slot-init-forms.6
(let ((ctor (pcl::make-ctor
(list 'pcl::ctor 'make-foo)
'foo '(:a 'x))))
(setf (pcl::ctor-class ctor) (find-class 'foo))
(pcl::slot-init-forms ctor nil))
(let ()
(declare (ignorable) (optimize (safety 3)))
(setf (svref pcl::.slots. 0) (the t 'x))
(setf (svref pcl::.slots. 1) (the t '2)))
nil)
(defmethod bar1 ((x integer))
(* x 2))
(defmethod bar2 ((x integer)) x)
(defmethod bar2 :around ((x integer)) x)
(deftest around-or-nonstandard-primary-method-p.0
(pcl::around-or-nonstandard-primary-method-p
(pcl::compute-applicable-methods #'bar2 (list 1)))
t)
(defmethod bar3 ((x integer)) x)
(defmethod bar3 :after ((x integer)) x)
(deftest around-or-nonstandard-primary-method-p.1
(pcl::around-or-nonstandard-primary-method-p
(pcl::compute-applicable-methods #'bar3 (list 1)))
nil)
(deftest optimizing-generator.0
(let ((fn (call-generator #'pcl::optimizing-generator
'make-foo 'foo '(:a 0 :b 1))))
(second fn))
())
(defun construct (class-name initargs &rest args)
(let* ((form (call-generator #'pcl::optimizing-generator
'some-function-name
class-name
initargs))
(fn (pcl::compile-lambda form)))
(apply fn args)))
(deftest optimizing-generator.1
(with-slots (a b) (construct 'foo '(:a 0 :b 1))
(values a b))
0 1)
(deftest optimizing-generator.2
(with-slots (a b) (construct 'foo '())
(values a b))
1 2)
(defclass g1 ()
((a :initform 0)
(b)))
(deftest optimizing-generator.3
(let ((instance (construct 'g1 '())))
(values (slot-value instance 'a)
(slot-boundp instance 'b)))
0 nil)
;; Test for default-initargs bug.
(defclass g2 ()
((a :initarg :aa)))
(defmethod initialize-instance :after ((f g2) &key aa)
(princ aa))
(defclass g3 (g2)
((b :initarg :b))
(:default-initargs :aa 5))
(deftest defaulting-initargs.1
(with-output-to-string (*standard-output*)
(make-instance 'g3))
"5")
| null | https://raw.githubusercontent.com/rtoy/cmucl/9b1abca53598f03a5b39ded4185471a5b8777dea/tests/pcl/ctor.lisp | lisp | All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
notice, this list of conditions and the following disclaimer.
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
products derived from this software without specific prior written
permission.
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
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
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
These depend on the actual slot definition location computation,
is a symbol macro calling PCL::MAKE-UNBOUND-MARKER, otherwise
we'll get a complaint that C::%%PRIMITIVE is not defined.
Test for default-initargs bug. | Copyright ( C ) 2002 < >
1 . Redistributions of source code must retain the above copyright
2 . Redistributions in binary form must reproduce the above copyright
3 . The name of the author may not be used to endorse or promote
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` AS IS '' AND ANY EXPRESS
ARE DISCLAIMED . IN NO EVENT SHALL THE AUTHOR OR
LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
#+cmu
(ext:file-comment "$Header: src/pcl/rt/ctor.lisp $")
(in-package "PCL-TESTS")
(deftest plist-keys.0
(pcl::plist-keys '())
nil)
(deftest plist-keys.1
(pcl::plist-keys '(:a 1 :b 2))
(:a :b))
(deftest plist-keys.2
(multiple-value-bind (result condition)
(ignore-errors (pcl::plist-keys '(:a)))
(values result (typep condition 'condition)))
nil
t)
(deftest make-instance->constructor-call.0
(pcl::make-instance->constructor-call '(make-instance 'foo a x))
nil)
(deftest make-instance->constructor-call.1
(pcl::make-instance->constructor-call '(make-instance foo :a x))
nil)
(deftest make-instance->constructor-call.2
(pcl::make-instance->constructor-call '(make-instance 'foo x))
nil)
(deftest make-instance->constructor-call.4
(pcl::make-instance->constructor-call '(make-instance 1))
nil)
(deftest make-instance->constructor-call.5
(let* ((form (pcl::make-instance->constructor-call
'(make-instance 'foo)))
(call (car (last form))))
(values (eq (first call) 'funcall)
(cddr call)))
t ())
(deftest make-instance->constructor-call.6
(let* ((form (pcl::make-instance->constructor-call
'(make-instance 'foo :x 1 :y 2)))
(call (car (last form))))
(values (eq (first call) 'funcall)
(cddr call)))
t ())
(deftest make-instance->constructor-call.7
(let* ((form (pcl::make-instance->constructor-call
'(make-instance 'foo :x x :y 2)))
(call (car (last form))))
(values (eq (first call) 'funcall)
(cddr call)))
t (x))
(deftest make-instance->constructor-call.8
(let* ((form (pcl::make-instance->constructor-call
'(make-instance 'foo :x x :y y)))
(call (car (last form))))
(values (eq (first call) 'funcall)
(cddr call)))
t (x y))
(deftest make-instance->constructor-call.9
(let* ((form (pcl::make-instance->constructor-call
'(make-instance 'foo :x x :y 1)))
(call (car (last form))))
(values (eq (first call) 'funcall)
(cddr call)))
t (x))
(deftest make-instance->constructor-call.10
(let* ((form (pcl::make-instance->constructor-call
'(make-instance 'foo :x x :y 1 :z z)))
(call (car (last form))))
(values (eq (first call) 'funcall)
(cddr call)))
t (x z))
(deftest make-ctor.0
(let ((ctor (pcl::make-ctor '(pcl::ctor bar) 'bar '(:x 1 :y 2))))
(values (pcl::ctor-function-name ctor)
(pcl::ctor-class-name ctor)
(pcl::ctor-initargs ctor)))
(pcl::ctor bar)
bar
(:x 1 :y 2))
(defclass foo ()
((a :initarg :a :initform 1)
(b :initarg :b :initform 2)))
(defun call-generator (generator function-name class-name args)
(declare (ignore function-name))
(let* ((ctor
(pcl::make-ctor (list 'pcl::ctor class-name) class-name args))
(class (find-class class-name))
(proto (pcl::class-prototype class))
(ii (pcl::compute-applicable-methods
#'initialize-instance (list proto)))
(si (pcl::compute-applicable-methods
#'shared-initialize (list proto t))))
(setf (pcl::ctor-class ctor) class)
(if (eq generator #'pcl::fallback-generator)
(funcall generator ctor)
(funcall generator ctor ii si))))
(deftest fallback-generator.0
(let ((fn (call-generator #'pcl::fallback-generator
'make-foo 'foo '(:a 0 :b 1))))
(values (second fn)
(type-of (second (third fn)))
(nthcdr 2 (third fn))))
()
pcl::standard-class
(:a 0 :b 1))
(deftest fallback-generator.1
(let ((fn (call-generator #'pcl::fallback-generator
'make-foo 'foo '(:a 0))))
(values (second fn)
(first (third fn))
(type-of (second (third fn)))
(nthcdr 2 (third fn))))
()
make-instance
pcl::standard-class
(:a 0))
(deftest fallback-generator.2
(let ((fn (call-generator #'pcl::fallback-generator
'make-foo 'foo '())))
(values (second fn)
(type-of (second (third fn)))
(nthcdr 2 (third fn))))
()
pcl::standard-class
())
(deftest fallback-generator.3
(let ((fn (call-generator #'pcl::fallback-generator
'make-foo 'foo '(:a .p0.))))
(values (second fn)
(type-of (second (third fn)))
(nthcdr 2 (third fn))))
(.p0.)
pcl::standard-class
(:a .p0.))
(deftest fallback-generator.4
(let ((fn (call-generator #'pcl::fallback-generator
'make-foo 'foo '(:a a :b b))))
(values (second fn)
(type-of (second (third fn)))
(nthcdr 2 (third fn))))
(a b)
pcl::standard-class
(:a a :b b))
which may be different in my PCL than in the CVS PCL .
(deftest compute-initarg-locations.0
(let ((class (find-class 'foo)))
(pcl::compute-initarg-locations class '(:a :b)))
((:a (0 . t)) (:b (1 . t))))
(defclass foo2 (foo)
((c :initarg :a)))
(deftest compute-initarg-locations.1
(let ((class (find-class 'foo2)))
(pcl::compute-initarg-locations class '(:a :b)))
((:a (0 . t) (2 . t)) (:b (1 . t))))
(defclass foo3 (foo)
((c :initarg :a :allocation :class)))
This test must be compiled for the case that PCL::+SLOT - UNBOUND+
(define-compiled-test compute-initarg-locations.2
(let ((class (find-class 'foo3)))
(subst 'unbound pcl::+slot-unbound+
(pcl::compute-initarg-locations class '(:a :b))))
((:a (0 . t) ((c . unbound) . t)) (:b (1 . t))))
(defclass foo4 ()
((a :initarg :a :initarg :both)
(b :initarg :b :initarg :both)))
(deftest compute-initarg-locations.3
(let ((class (find-class 'foo4)))
(pcl::compute-initarg-locations class '(:both :a :b)))
((:both (0 . t) (1 . t)) (:a) (:b)))
(deftest compute-initarg-locations.4
(let ((class (find-class 'foo4)))
(pcl::compute-initarg-locations class '(:a :both)))
((:a (0 . t)) (:both (1 . t))))
(deftest slot-init-forms.0
(let ((ctor (pcl::make-ctor
(list 'pcl::ctor 'make-foo)
'foo '(:a a :b b))))
(setf (pcl::ctor-class ctor) (find-class 'foo))
(pcl::slot-init-forms ctor nil))
(let ()
(declare (ignorable) (optimize (safety 3)))
(setf (svref pcl::.slots. 0) (the t a))
(setf (svref pcl::.slots. 1) (the t b)))
nil)
(deftest slot-init-forms.1
(let ((ctor (pcl::make-ctor
(list 'pcl::ctor 'make-foo)
'foo '(:a a))))
(setf (pcl::ctor-class ctor) (find-class 'foo))
(pcl::slot-init-forms ctor nil))
(let ()
(declare (ignorable) (optimize (safety 3)))
(setf (svref pcl::.slots. 0) (the t a))
(setf (svref pcl::.slots. 1) (the t '2)))
nil)
(defclass foo5 ()
((a :initarg :a :initform 0)
(b :initarg :b)))
(deftest slot-init-forms.2
(let ((ctor (pcl::make-ctor
(list 'pcl::ctor 'make-foo)
'foo5 '(:a a))))
(setf (pcl::ctor-class ctor) (find-class 'foo5))
(pcl::slot-init-forms ctor nil))
(let ()
(declare (ignorable) (optimize (safety 3)))
(setf (svref pcl::.slots. 0) (the t a))
(setf (svref pcl::.slots. 1) pcl::+slot-unbound+))
nil)
(defclass foo5a ()
((a :initarg :a :initform 0)
(b :initarg :b :initform 0)))
(deftest slot-init-forms.2a
(let ((ctor (pcl::make-ctor
(list 'pcl::ctor 'make-foo)
'foo5a '())))
(setf (pcl::ctor-class ctor) (find-class 'foo5a))
(pcl::slot-init-forms ctor nil))
(let ()
(declare (ignorable) (optimize (safety 3)))
(setf (svref pcl::.slots. 0) (the t '0))
(setf (svref pcl::.slots. 1) (the t '0)))
nil)
(defclass foo6 ()
((a :initarg :a :initform 0 :allocation :class)
(b :initarg :b)))
(deftest slot-init-forms.3
(let ((ctor (pcl::make-ctor
(list 'pcl::ctor 'make-foo)
'foo6 '(:a a))))
(setf (pcl::ctor-class ctor) (find-class 'foo6))
(pcl::slot-init-forms ctor nil))
(let ()
(declare (ignorable) (optimize (safety 3)))
(setf (svref pcl::.slots. 0) pcl::+slot-unbound+)
(setf (cdr '(a . 0)) (the t a)))
nil)
(defun foo ()
(error "should never be called"))
(defclass foo7 ()
((a :initarg :a :initform (foo))
(b :initarg :b)))
(deftest slot-init-forms.4
(let* ((ctor (pcl::make-ctor
(list 'pcl::ctor 'make-foo)
'foo7 '())))
(setf (pcl::ctor-class ctor) (find-class 'foo7))
(let ((form (pcl::slot-init-forms ctor nil)))
(destructuring-bind (let vars declare setf1 setf2) form
(declare (ignore let vars declare))
(values setf2 (second setf1) (first (third (third setf1)))
(functionp (second (third (third setf1))))))))
(setf (svref pcl::.slots. 1) pcl::+slot-unbound+)
(svref pcl::.slots. 0)
funcall
t)
(deftest slot-init-forms.5
(let ((ctor (pcl::make-ctor
(list 'pcl::ctor 'make-foo)
'foo '(:a '(foo)))))
(setf (pcl::ctor-class ctor) (find-class 'foo))
(pcl::slot-init-forms ctor nil))
(let ()
(declare (ignorable) (optimize (safety 3)))
(setf (svref pcl::.slots. 0) (the t '(foo)))
(setf (svref pcl::.slots. 1) (the t '2)))
nil)
(deftest slot-init-forms.6
(let ((ctor (pcl::make-ctor
(list 'pcl::ctor 'make-foo)
'foo '(:a 'x))))
(setf (pcl::ctor-class ctor) (find-class 'foo))
(pcl::slot-init-forms ctor nil))
(let ()
(declare (ignorable) (optimize (safety 3)))
(setf (svref pcl::.slots. 0) (the t 'x))
(setf (svref pcl::.slots. 1) (the t '2)))
nil)
(defmethod bar1 ((x integer))
(* x 2))
(defmethod bar2 ((x integer)) x)
(defmethod bar2 :around ((x integer)) x)
(deftest around-or-nonstandard-primary-method-p.0
(pcl::around-or-nonstandard-primary-method-p
(pcl::compute-applicable-methods #'bar2 (list 1)))
t)
(defmethod bar3 ((x integer)) x)
(defmethod bar3 :after ((x integer)) x)
(deftest around-or-nonstandard-primary-method-p.1
(pcl::around-or-nonstandard-primary-method-p
(pcl::compute-applicable-methods #'bar3 (list 1)))
nil)
(deftest optimizing-generator.0
(let ((fn (call-generator #'pcl::optimizing-generator
'make-foo 'foo '(:a 0 :b 1))))
(second fn))
())
(defun construct (class-name initargs &rest args)
(let* ((form (call-generator #'pcl::optimizing-generator
'some-function-name
class-name
initargs))
(fn (pcl::compile-lambda form)))
(apply fn args)))
(deftest optimizing-generator.1
(with-slots (a b) (construct 'foo '(:a 0 :b 1))
(values a b))
0 1)
(deftest optimizing-generator.2
(with-slots (a b) (construct 'foo '())
(values a b))
1 2)
(defclass g1 ()
((a :initform 0)
(b)))
(deftest optimizing-generator.3
(let ((instance (construct 'g1 '())))
(values (slot-value instance 'a)
(slot-boundp instance 'b)))
0 nil)
(defclass g2 ()
((a :initarg :aa)))
(defmethod initialize-instance :after ((f g2) &key aa)
(princ aa))
(defclass g3 (g2)
((b :initarg :b))
(:default-initargs :aa 5))
(deftest defaulting-initargs.1
(with-output-to-string (*standard-output*)
(make-instance 'g3))
"5")
|
77bb8e1386c640d06576bf40093510204453058362341ce9a82138294cd26679 | bit-ranger/scheme-bootstrap | core.scm | (load "eval/types.scm")
(load "eval/keywords.scm")
(define (interp exp env)
(cond ((self-evaluating? exp) exp) ; 字面量
(else (interp-generic (wrap exp) env))))
;封装语法类型
(define (wrap exp)
(if (pair? exp)
(attach-tag (car exp) exp)
(attach-tag exp exp)))
动态转发解释过程
(define (interp-generic tagged-exp env)
(let ((type (type-tag tagged-exp))
(exp (contents tagged-exp)))
(let ((proc (get eval-proc-key type)))
(if proc
(proc exp env)
(if (or (eq? type variable-keyword)
(eq? type application-keyword))
(error "Unknown expression type -- INTERP" exp)
(cond ((variable? exp)
(interp-generic (attach-tag variable-keyword exp) env))
((application? exp)
(interp-generic (attach-tag application-keyword exp) env))
(else (error "Unknown expression type -- INTERP" exp))))))))
处理表达式序列
(define (interp-sequence exps env)
(cond ((last-exp? exps) (interp (first-exp exps) env))
(else (interp (first-exp exps) env)
(interp-sequence (rest-exps exps) env))))
;是否字面量?
(define (self-evaluating? exp)
(cond ((number? exp) true)
((string? exp) true)
(else false)))
是否变量 ?
(define (variable? exp)
(symbol? exp))
;是否过程应用?
(define (application? exp)
(pair? exp))
?
(define (last-exp? seq)
(null? (cdr seq)))
;取序列第一个
(define (first-exp seq)
(car seq))
;剩余的序列
(define (rest-exps seq)
(cdr seq))
| null | https://raw.githubusercontent.com/bit-ranger/scheme-bootstrap/a9155ebd29efe1196854b2dcd76941357dab151e/eval/core.scm | scheme | 字面量
封装语法类型
是否字面量?
是否过程应用?
取序列第一个
剩余的序列 | (load "eval/types.scm")
(load "eval/keywords.scm")
(define (interp exp env)
(else (interp-generic (wrap exp) env))))
(define (wrap exp)
(if (pair? exp)
(attach-tag (car exp) exp)
(attach-tag exp exp)))
动态转发解释过程
(define (interp-generic tagged-exp env)
(let ((type (type-tag tagged-exp))
(exp (contents tagged-exp)))
(let ((proc (get eval-proc-key type)))
(if proc
(proc exp env)
(if (or (eq? type variable-keyword)
(eq? type application-keyword))
(error "Unknown expression type -- INTERP" exp)
(cond ((variable? exp)
(interp-generic (attach-tag variable-keyword exp) env))
((application? exp)
(interp-generic (attach-tag application-keyword exp) env))
(else (error "Unknown expression type -- INTERP" exp))))))))
处理表达式序列
(define (interp-sequence exps env)
(cond ((last-exp? exps) (interp (first-exp exps) env))
(else (interp (first-exp exps) env)
(interp-sequence (rest-exps exps) env))))
(define (self-evaluating? exp)
(cond ((number? exp) true)
((string? exp) true)
(else false)))
是否变量 ?
(define (variable? exp)
(symbol? exp))
(define (application? exp)
(pair? exp))
?
(define (last-exp? seq)
(null? (cdr seq)))
(define (first-exp seq)
(car seq))
(define (rest-exps seq)
(cdr seq))
|
976f6093a09a2d120f1d38f66e5b29b89cb0f7b6ab65c82fdd588203aa64b2e6 | electric-sql/vaxine | log_dump.erl | #!/usr/bin/env escript
%% -*- erlang -*-
%%! -sname log_dump -I ../../
-include("../include/antidote.hrl").
main([LogFile]) ->
try
read_log(LogFile)
catch
_:_ ->
usage()
end;
main(_) ->
usage().
usage() ->
io:format("usage: log_dump LOG_FILE_NAME\n"),
halt(1).
read_log(LogFile) ->
case
disk_log:open([{name, log}, {file, LogFile}, {mode, read_only}])
of
{ok, Log} ->
io:format("FILE: ~p~nINFO: ~p~n", [LogFile, disk_log:info(Log)]),
read_log_records(Log);
{repaired, Log, _, _} ->
io:format("Repaired log~n", []),
read_log_records(Log);
{error, _Error} = E ->
io:format("Error: ~p~n", [E]),
E
end.
read_log_records(Log) ->
try print_log_records(Log)
catch T:E:S ->
io:format("~p:~p ~n~p~n", [T, E, S])
after
disk_log:close(Log)
end.
print_log_records(Log) ->
print_log_records(Log, start, #{}).
print_log_records(Log, Continuation, Cache) ->
case disk_log:chunk(Log, Continuation) of
eof ->
io:format("EOF~n", []),
{eof, []};
{error, Reason} ->
{error, Reason};
{NewContinuation, NewTerms} ->
Cache1 = iterate_terms(NewTerms, Cache),
print_log_records(Log, NewContinuation, Cache1);
{NewContinuation, NewTerms, BadBytes} ->
Cache1 = iterate_terms(NewTerms, Cache),
case BadBytes > 0 of
true ->
io:format("Badbytes: ~p:~p~n", [BadBytes, NewTerms]),
{error, bad_bytes};
false ->
print_log_records(Log, NewContinuation, Cache1)
end
end.
iterate_terms([{LogId, Op} | Rest], Cache) ->
Cache1 = maybe_print_log_id(LogId, Cache),
Cache2 = iterate_term(Op, Cache1),
iterate_terms(Rest, Cache2);
iterate_terms([], Cache) ->
Cache.
iterate_term(#log_record{version = _V, op_number = OpNumber,
bucket_op_number = _BNumber, log_operation = Op}, Cache) ->
Cache1 = maybe_print_node(OpNumber, Cache),
io:format("|~s|", [printable(OpNumber)]),
print_operation(Op, Cache1),
Cache1.
print_operation(#log_operation{tx_id = TxId, op_type = OpType,
log_payload = Payload
}, _Cache) ->
io:format("TX:~s|OP:~p|~n", [printable_tx(TxId), OpType]),
print_payload(Payload).
print_payload(#prepare_log_payload{prepare_time = TM}) ->
io:format(" prepare_time: ~p~n", [TM]);
print_payload(#commit_log_payload{commit_time = {_DC, CT}, snapshot_time = ST}) ->
io:format(" commit_time: ~p~n snapshot_time: ~p~n", [CT, ST]);
print_payload(#update_log_payload{} = R) ->
Fields = record_info(fields, update_log_payload),
[_| Values] = tuple_to_list(R),
Zip = lists:zip(Fields, Values),
lists:foreach(fun({_K, undefined}) ->
ok;
({K, V}) ->
io:format(" ~p = ~p~n", [K, V])
end, Zip);
print_payload(R) ->
io:format(" ~p~n", [R]).
printable_tx(#tx_id{local_start_time = TM, server_pid = Pid}) ->
io_lib:format("~p-~p", [TM, Pid]).
printable(#op_number{global = G, local = L}) ->
io_lib:format("G:~p|L:~p", [G, L]);
printable(Op) ->
Op.
%%------------------------------------------------------------------------------
maybe_print_log_id(LogId, #{log_id := LogId} = Cache) ->
Cache;
maybe_print_log_id(LogId, Cache) ->
io:format("LogId: ~p~n", [LogId]),
Cache#{log_id => LogId}.
maybe_print_node(#op_number{node = N}, #{node := N} = Cache) ->
Cache;
maybe_print_node(#op_number{node = {N, DC} = Node}, Cache) ->
io:format("-------------------------------------------------------~n",[]),
io:format("NODE: ~p DC: ~p~n~n", [N, DC]),
Cache#{node => Node}.
| null | https://raw.githubusercontent.com/electric-sql/vaxine/d726a7a3aeead9b9362e8b657f0929cb4fca9b5c/apps/antidote/priv/log_dump.erl | erlang | -*- erlang -*-
! -sname log_dump -I ../../
------------------------------------------------------------------------------ | #!/usr/bin/env escript
-include("../include/antidote.hrl").
main([LogFile]) ->
try
read_log(LogFile)
catch
_:_ ->
usage()
end;
main(_) ->
usage().
usage() ->
io:format("usage: log_dump LOG_FILE_NAME\n"),
halt(1).
read_log(LogFile) ->
case
disk_log:open([{name, log}, {file, LogFile}, {mode, read_only}])
of
{ok, Log} ->
io:format("FILE: ~p~nINFO: ~p~n", [LogFile, disk_log:info(Log)]),
read_log_records(Log);
{repaired, Log, _, _} ->
io:format("Repaired log~n", []),
read_log_records(Log);
{error, _Error} = E ->
io:format("Error: ~p~n", [E]),
E
end.
read_log_records(Log) ->
try print_log_records(Log)
catch T:E:S ->
io:format("~p:~p ~n~p~n", [T, E, S])
after
disk_log:close(Log)
end.
print_log_records(Log) ->
print_log_records(Log, start, #{}).
print_log_records(Log, Continuation, Cache) ->
case disk_log:chunk(Log, Continuation) of
eof ->
io:format("EOF~n", []),
{eof, []};
{error, Reason} ->
{error, Reason};
{NewContinuation, NewTerms} ->
Cache1 = iterate_terms(NewTerms, Cache),
print_log_records(Log, NewContinuation, Cache1);
{NewContinuation, NewTerms, BadBytes} ->
Cache1 = iterate_terms(NewTerms, Cache),
case BadBytes > 0 of
true ->
io:format("Badbytes: ~p:~p~n", [BadBytes, NewTerms]),
{error, bad_bytes};
false ->
print_log_records(Log, NewContinuation, Cache1)
end
end.
iterate_terms([{LogId, Op} | Rest], Cache) ->
Cache1 = maybe_print_log_id(LogId, Cache),
Cache2 = iterate_term(Op, Cache1),
iterate_terms(Rest, Cache2);
iterate_terms([], Cache) ->
Cache.
iterate_term(#log_record{version = _V, op_number = OpNumber,
bucket_op_number = _BNumber, log_operation = Op}, Cache) ->
Cache1 = maybe_print_node(OpNumber, Cache),
io:format("|~s|", [printable(OpNumber)]),
print_operation(Op, Cache1),
Cache1.
print_operation(#log_operation{tx_id = TxId, op_type = OpType,
log_payload = Payload
}, _Cache) ->
io:format("TX:~s|OP:~p|~n", [printable_tx(TxId), OpType]),
print_payload(Payload).
print_payload(#prepare_log_payload{prepare_time = TM}) ->
io:format(" prepare_time: ~p~n", [TM]);
print_payload(#commit_log_payload{commit_time = {_DC, CT}, snapshot_time = ST}) ->
io:format(" commit_time: ~p~n snapshot_time: ~p~n", [CT, ST]);
print_payload(#update_log_payload{} = R) ->
Fields = record_info(fields, update_log_payload),
[_| Values] = tuple_to_list(R),
Zip = lists:zip(Fields, Values),
lists:foreach(fun({_K, undefined}) ->
ok;
({K, V}) ->
io:format(" ~p = ~p~n", [K, V])
end, Zip);
print_payload(R) ->
io:format(" ~p~n", [R]).
printable_tx(#tx_id{local_start_time = TM, server_pid = Pid}) ->
io_lib:format("~p-~p", [TM, Pid]).
printable(#op_number{global = G, local = L}) ->
io_lib:format("G:~p|L:~p", [G, L]);
printable(Op) ->
Op.
maybe_print_log_id(LogId, #{log_id := LogId} = Cache) ->
Cache;
maybe_print_log_id(LogId, Cache) ->
io:format("LogId: ~p~n", [LogId]),
Cache#{log_id => LogId}.
maybe_print_node(#op_number{node = N}, #{node := N} = Cache) ->
Cache;
maybe_print_node(#op_number{node = {N, DC} = Node}, Cache) ->
io:format("-------------------------------------------------------~n",[]),
io:format("NODE: ~p DC: ~p~n~n", [N, DC]),
Cache#{node => Node}.
|
32205e91e79fbd54ac244b6619a69b58209b8ba474f35395f744b67351cd2ca7 | joearms/music_experiments | midi_event_listener.erl | -module(midi_event_listener).
-compile(export_all).
start() ->
register(?MODULE,
spawn(fun() ->
process_flag(trap_exit, true),
Port = open_port({spawn, "./midi_event_listener"},
[{packet, 2}]),
io:format("Port=~p~n",[Port]),
loop(Port)
end)).
sleep(T) ->
receive
after T ->
true
end.
stop() ->
?MODULE ! stop.
send(M) -> call_port([1|M]).
call_port(Msg) ->
?MODULE ! {call, self(), Msg},
receive
{?MODULE, Result} ->
Result
end.
loop(Port) ->
receive
{call, Caller, Msg} ->
Port ! {self(), {command, Msg}},
receive
{Port, {data, Data}} ->
Caller ! {?MODULE, Data}
end,
loop(Port);
stop ->
Port ! {self(), close},
receive
{Port, closed} ->
exit(normal)
end;
{'EXIT', Port, Reason} ->
exit({port_terminated, Reason});
{Port,{data,Data}} ->
io:format("~n~p bytes~n",[length(Data)]),
Data1 = cvt(list_to_binary(Data)),
io:format("event:~p~n",[Data1]),
loop(Port);
Any ->
io:format("Received:~p~n",[Any]),
loop(Port)
end.
cvt(<<1,T:64/unsigned-little-integer,B/binary>>) ->
{T, B}.
| null | https://raw.githubusercontent.com/joearms/music_experiments/3c0db01d03571599a3506fcb1a001d0b8dd205d9/midi_mac_driver/midi_event_listener.erl | erlang | -module(midi_event_listener).
-compile(export_all).
start() ->
register(?MODULE,
spawn(fun() ->
process_flag(trap_exit, true),
Port = open_port({spawn, "./midi_event_listener"},
[{packet, 2}]),
io:format("Port=~p~n",[Port]),
loop(Port)
end)).
sleep(T) ->
receive
after T ->
true
end.
stop() ->
?MODULE ! stop.
send(M) -> call_port([1|M]).
call_port(Msg) ->
?MODULE ! {call, self(), Msg},
receive
{?MODULE, Result} ->
Result
end.
loop(Port) ->
receive
{call, Caller, Msg} ->
Port ! {self(), {command, Msg}},
receive
{Port, {data, Data}} ->
Caller ! {?MODULE, Data}
end,
loop(Port);
stop ->
Port ! {self(), close},
receive
{Port, closed} ->
exit(normal)
end;
{'EXIT', Port, Reason} ->
exit({port_terminated, Reason});
{Port,{data,Data}} ->
io:format("~n~p bytes~n",[length(Data)]),
Data1 = cvt(list_to_binary(Data)),
io:format("event:~p~n",[Data1]),
loop(Port);
Any ->
io:format("Received:~p~n",[Any]),
loop(Port)
end.
cvt(<<1,T:64/unsigned-little-integer,B/binary>>) ->
{T, B}.
|
|
8d12c107241857b8e34e822e09d68436ac478de26096a7007cb9c9929fe078c7 | ku-fpg/blank-canvas | Rounded_Corners.hs | {-# LANGUAGE OverloadedStrings #-}
module Rounded_Corners where
import Graphics.Blank
( 578,200 )
main :: IO ()
main = blankCanvas 3000 $ \ context -> do
send context $ do
lineWidth 25;
let rectWidth = 200;
let rectHeight = 100;
let rectX = 189;
let rectY = 50;
let cornerRadius = 50;
beginPath();
moveTo(rectX, rectY);
lineTo(rectX + rectWidth - cornerRadius, rectY);
arcTo(rectX + rectWidth, rectY, rectX + rectWidth, rectY + cornerRadius, cornerRadius);
lineTo(rectX + rectWidth, rectY + rectHeight);
lineWidth 5;
stroke();
wiki $ snapShot context "images/Rounded_Corners.png"
wiki $ close context
| null | https://raw.githubusercontent.com/ku-fpg/blank-canvas/39915c17561106ce06e1e3dcef85cc2e956626e6/wiki-suite/Rounded_Corners.hs | haskell | # LANGUAGE OverloadedStrings # | module Rounded_Corners where
import Graphics.Blank
( 578,200 )
main :: IO ()
main = blankCanvas 3000 $ \ context -> do
send context $ do
lineWidth 25;
let rectWidth = 200;
let rectHeight = 100;
let rectX = 189;
let rectY = 50;
let cornerRadius = 50;
beginPath();
moveTo(rectX, rectY);
lineTo(rectX + rectWidth - cornerRadius, rectY);
arcTo(rectX + rectWidth, rectY, rectX + rectWidth, rectY + cornerRadius, cornerRadius);
lineTo(rectX + rectWidth, rectY + rectHeight);
lineWidth 5;
stroke();
wiki $ snapShot context "images/Rounded_Corners.png"
wiki $ close context
|
b01bf8f832230e9eb5618534718e0b61eb8110bc422fac007b883d29a357f6f2 | arcadia-unity/catcon | junit.clj | Copyright ( c ) . All rights reserved .
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
;; test/junit.clj: Extension to clojure.test for JUnit-compatible XML output
by
June 2009
;; DOCUMENTATION
;;
(ns ^{:doc "clojure.test extension for JUnit-compatible XML output.
JUnit (/) is the most popular unit-testing library
for Java. As such, tool support for JUnit output formats is
common. By producing compatible output from tests, this tool
support can be exploited.
To use, wrap any calls to clojure.test/run-tests in the
with-junit-output macro, like this:
(use 'clojure.test)
(use 'clojure.test.junit)
(with-junit-output
(run-tests 'my.cool.library))
To write the output to a file, rebind clojure.test/*test-out* to
your own PrintWriter (perhaps opened using
clojure.java.io/writer)."
:author "Jason Sankey"}
clojure.test.junit
(:require [clojure.stacktrace :as stack]
[clojure.test :as t]))
;; copied from clojure.contrib.lazy-xml
(def ^{:private true}
escape-xml-map
(zipmap "'<>\"&" (map #(str \& % \;) '[apos lt gt quot amp])))
(defn- escape-xml [text]
(apply str (map #(escape-xml-map % %) text)))
(def ^:dynamic *var-context*)
(def ^:dynamic *depth*)
(defn indent
[]
(dotimes [n (* *depth* 4)] (print " ")))
(defn start-element
[tag pretty & [attrs]]
(if pretty (indent))
(print (str "<" tag))
(if (seq attrs)
(doseq [[key value] attrs]
(print (str " " (name key) "=\"" (escape-xml value) "\""))))
(print ">")
(if pretty (println))
(set! *depth* (inc *depth*)))
(defn element-content
[content]
(print (escape-xml content)))
(defn finish-element
[tag pretty]
(set! *depth* (dec *depth*))
(if pretty (indent))
(print (str "</" tag ">"))
(if pretty (println)))
(defn test-name
[vars]
(apply str (interpose "."
(reverse (map #(:name (meta %)) vars)))))
(defn package-class
[name]
(let [i (.LastIndexOf name ".")] ;;; lastIndexOf
(if (< i 0)
[nil name]
[(.Substring name 0 i) (.Substring name (+ i 1))]))) ;;; .substring
(defn start-case
[name classname]
(start-element 'testcase true {:name name :classname classname}))
(defn finish-case
[]
(finish-element 'testcase true))
(defn suite-attrs
[package classname]
(let [attrs {:name classname}]
(if package
(assoc attrs :package package)
attrs)))
(defn start-suite
[name]
(let [[package classname] (package-class name)]
(start-element 'testsuite true (suite-attrs package classname))))
(defn finish-suite
[]
(finish-element 'testsuite true))
(defn message-el
[tag message expected-str actual-str]
(indent)
(start-element tag false (if message {:message message} {}))
(element-content
(let [[file line] (t/file-position 5)
detail (apply str (interpose
"\n"
[(str "expected: " expected-str)
(str " actual: " actual-str)
(str " at: " file ":" line)]))]
(if message (str message "\n" detail) detail)))
(finish-element tag false)
(println))
(defn failure-el
[message expected actual]
(message-el 'failure message (pr-str expected) (pr-str actual)))
(defn error-el
[message expected actual]
(message-el 'error
message
(pr-str expected)
(if (instance? Exception actual) ;;; Throwable
(with-out-str (stack/print-cause-trace actual t/*stack-trace-depth*))
(prn actual))))
;; This multimethod will override test-is/report
(defmulti ^:dynamic junit-report :type)
(defmethod junit-report :begin-test-ns [m]
(t/with-test-out
(start-suite (name (ns-name (:ns m))))))
(defmethod junit-report :end-test-ns [_]
(t/with-test-out
(finish-suite)))
(defmethod junit-report :begin-test-var [m]
(t/with-test-out
(let [var (:var m)]
(binding [*var-context* (conj *var-context* var)]
(start-case (test-name *var-context*) (name (ns-name (:ns (meta var)))))))))
(defmethod junit-report :end-test-var [m]
(t/with-test-out
(finish-case)))
(defmethod junit-report :pass [m]
(t/with-test-out
(t/inc-report-counter :pass)))
(defmethod junit-report :fail [m]
(t/with-test-out
(t/inc-report-counter :fail)
(failure-el (:message m)
(:expected m)
(:actual m))))
(defmethod junit-report :error [m]
(t/with-test-out
(t/inc-report-counter :error)
(error-el (:message m)
(:expected m)
(:actual m))))
(defmethod junit-report :default [_])
(defmacro with-junit-output
"Execute body with modified test-is reporting functions that write
JUnit-compatible XML output."
{:added "1.1"}
[& body]
`(binding [t/report junit-report
*var-context* (list)
*depth* 1]
(t/with-test-out
(println "<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
(println "<testsuites>"))
(let [result# ~@body]
(t/with-test-out (println "</testsuites>"))
result#)))
| null | https://raw.githubusercontent.com/arcadia-unity/catcon/6c69f424d3c14639ff11a3ea7d9da6aa81328f8a/Arcadia/Internal/clojure/test/junit.clj | clojure | The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software.
test/junit.clj: Extension to clojure.test for JUnit-compatible XML output
DOCUMENTATION
copied from clojure.contrib.lazy-xml
) '[apos lt gt quot amp])))
lastIndexOf
.substring
Throwable
This multimethod will override test-is/report
| Copyright ( c ) . All rights reserved .
by
June 2009
(ns ^{:doc "clojure.test extension for JUnit-compatible XML output.
JUnit (/) is the most popular unit-testing library
for Java. As such, tool support for JUnit output formats is
common. By producing compatible output from tests, this tool
support can be exploited.
To use, wrap any calls to clojure.test/run-tests in the
with-junit-output macro, like this:
(use 'clojure.test)
(use 'clojure.test.junit)
(with-junit-output
(run-tests 'my.cool.library))
To write the output to a file, rebind clojure.test/*test-out* to
your own PrintWriter (perhaps opened using
clojure.java.io/writer)."
:author "Jason Sankey"}
clojure.test.junit
(:require [clojure.stacktrace :as stack]
[clojure.test :as t]))
(def ^{:private true}
escape-xml-map
(defn- escape-xml [text]
(apply str (map #(escape-xml-map % %) text)))
(def ^:dynamic *var-context*)
(def ^:dynamic *depth*)
(defn indent
[]
(dotimes [n (* *depth* 4)] (print " ")))
(defn start-element
[tag pretty & [attrs]]
(if pretty (indent))
(print (str "<" tag))
(if (seq attrs)
(doseq [[key value] attrs]
(print (str " " (name key) "=\"" (escape-xml value) "\""))))
(print ">")
(if pretty (println))
(set! *depth* (inc *depth*)))
(defn element-content
[content]
(print (escape-xml content)))
(defn finish-element
[tag pretty]
(set! *depth* (dec *depth*))
(if pretty (indent))
(print (str "</" tag ">"))
(if pretty (println)))
(defn test-name
[vars]
(apply str (interpose "."
(reverse (map #(:name (meta %)) vars)))))
(defn package-class
[name]
(if (< i 0)
[nil name]
(defn start-case
[name classname]
(start-element 'testcase true {:name name :classname classname}))
(defn finish-case
[]
(finish-element 'testcase true))
(defn suite-attrs
[package classname]
(let [attrs {:name classname}]
(if package
(assoc attrs :package package)
attrs)))
(defn start-suite
[name]
(let [[package classname] (package-class name)]
(start-element 'testsuite true (suite-attrs package classname))))
(defn finish-suite
[]
(finish-element 'testsuite true))
(defn message-el
[tag message expected-str actual-str]
(indent)
(start-element tag false (if message {:message message} {}))
(element-content
(let [[file line] (t/file-position 5)
detail (apply str (interpose
"\n"
[(str "expected: " expected-str)
(str " actual: " actual-str)
(str " at: " file ":" line)]))]
(if message (str message "\n" detail) detail)))
(finish-element tag false)
(println))
(defn failure-el
[message expected actual]
(message-el 'failure message (pr-str expected) (pr-str actual)))
(defn error-el
[message expected actual]
(message-el 'error
message
(pr-str expected)
(with-out-str (stack/print-cause-trace actual t/*stack-trace-depth*))
(prn actual))))
(defmulti ^:dynamic junit-report :type)
(defmethod junit-report :begin-test-ns [m]
(t/with-test-out
(start-suite (name (ns-name (:ns m))))))
(defmethod junit-report :end-test-ns [_]
(t/with-test-out
(finish-suite)))
(defmethod junit-report :begin-test-var [m]
(t/with-test-out
(let [var (:var m)]
(binding [*var-context* (conj *var-context* var)]
(start-case (test-name *var-context*) (name (ns-name (:ns (meta var)))))))))
(defmethod junit-report :end-test-var [m]
(t/with-test-out
(finish-case)))
(defmethod junit-report :pass [m]
(t/with-test-out
(t/inc-report-counter :pass)))
(defmethod junit-report :fail [m]
(t/with-test-out
(t/inc-report-counter :fail)
(failure-el (:message m)
(:expected m)
(:actual m))))
(defmethod junit-report :error [m]
(t/with-test-out
(t/inc-report-counter :error)
(error-el (:message m)
(:expected m)
(:actual m))))
(defmethod junit-report :default [_])
(defmacro with-junit-output
"Execute body with modified test-is reporting functions that write
JUnit-compatible XML output."
{:added "1.1"}
[& body]
`(binding [t/report junit-report
*var-context* (list)
*depth* 1]
(t/with-test-out
(println "<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
(println "<testsuites>"))
(let [result# ~@body]
(t/with-test-out (println "</testsuites>"))
result#)))
|
aec93e32c265a2962b325478e2c3d68d45909b11ab1a629347931c5f24702032 | AshleyYakeley/Truth | Main.hs | {-# OPTIONS -fno-warn-orphans #-}
module Main
( main
) where
import Changes.Core
import Lens
import Resource
import Shapes
import Shapes.Test
import Subscribe
import Test.SimpleString
instance Arbitrary SequencePoint where
arbitrary = MkSequencePoint <$> (getSmall . getNonNegative <$> arbitrary)
shrink 0 = []
shrink 1 = [0]
shrink n = [0, pred n]
instance Arbitrary SequenceRun where
arbitrary = MkSequenceRun <$> arbitrary <*> arbitrary
shrink (MkSequenceRun s l) = [MkSequenceRun s' l' | (s', l') <- shrink (s, l)]
instance Arbitrary seq => Arbitrary (StringEdit seq) where
arbitrary = oneof [StringReplaceWhole <$> arbitrary, StringReplaceSection <$> arbitrary <*> arbitrary]
shrink (StringReplaceWhole s) = StringReplaceWhole <$> shrink s
shrink (StringReplaceSection r s) =
(StringReplaceWhole s) : [StringReplaceSection r' s' | (r', s') <- shrink (r, s)]
instance {-# OVERLAPPING #-} Arbitrary (StringEdit String) where
arbitrary =
oneof
[ StringReplaceWhole <$> (getSimpleString <$> arbitrary)
, StringReplaceSection <$> arbitrary <*> (getSimpleString <$> arbitrary)
]
shrink (StringReplaceWhole s) = StringReplaceWhole <$> (getSimpleString <$> shrink (MkSimpleString s))
shrink (StringReplaceSection r s) =
(StringReplaceWhole s) : [StringReplaceSection r' s' | (r', MkSimpleString s') <- shrink (r, MkSimpleString s)]
testApplyEditsPar :: TestTree
testApplyEditsPar =
testTree "apply edits parallel" $ let
start = (False, False)
edits :: [PairUpdateEdit (WholeUpdate Bool) (WholeUpdate Bool)]
edits =
[ MkTupleUpdateEdit SelectFirst $ MkWholeReaderEdit True
, MkTupleUpdateEdit SelectSecond $ MkWholeReaderEdit True
]
expected = (True, True)
rf :: ReadFunction (TupleUpdateReader (PairSelector (WholeUpdate Bool) (WholeUpdate Bool))) (TupleUpdateReader (PairSelector (WholeUpdate Bool) (WholeUpdate Bool)))
rf = applyEdits edits
in do
found <- readableToSubject $ rf $ subjectToReadable start
assertEqual "" expected found
testApplyEditsSeq :: TestTree
testApplyEditsSeq =
testTree "apply edits sequence" $ let
start = 0
edits :: [WholeEdit Int]
edits = [MkWholeReaderEdit 1, MkWholeReaderEdit 2]
expected = 2
rf :: ReadFunction (WholeReader Int) (WholeReader Int)
rf = applyEdits edits
in do
found <- readableToSubject $ rf $ subjectToReadable start
assertEqual "" expected found
applyEditSubject ::
(ApplicableEdit edit, FullSubjectReader (EditReader edit)) => edit -> EditSubject edit -> IO (EditSubject edit)
applyEditSubject edit subj = readableToSubject $ applyEdit edit $ subjectToReadable subj
testEdit ::
forall edit.
( ApplicableEdit edit
, FullSubjectReader (EditReader edit)
, Eq (EditSubject edit)
, Show edit
, Show (EditSubject edit)
)
=> edit
-> EditSubject edit
-> EditSubject edit
-> TestTree
testEdit edit original expected = let
name = show edit ++ " " ++ show original
in testTree name $ do
found <- applyEditSubject edit original
assertEqual "" expected found
testEditRead ::
forall edit t.
( SubjectReader (EditReader edit)
, ApplicableEdit edit
, Eq t
, Show t
, Show edit
, Show (EditSubject edit)
, Show (EditReader edit t)
)
=> edit
-> EditSubject edit
-> EditReader edit t
-> t
-> TestTree
testEditRead edit original rt expected = let
name = show edit ++ " " ++ show original ++ " " ++ show rt
in testTree name $ do
found <- applyEdit edit (subjectToReadable original) rt
assertEqual "" expected found
seqRun :: Int64 -> Int64 -> SequenceRun
seqRun start len = MkSequenceRun (MkSequencePoint start) (MkSequencePoint len)
testStringEdit :: TestTree
testStringEdit =
testTree
"string edit"
[ testEdit (StringReplaceSection @String (seqRun 2 0) "XY") "ABCDE" "ABXYCDE"
, testEdit (StringReplaceSection @String (seqRun 2 1) "XY") "ABCDE" "ABXYDE"
, testEdit (StringReplaceSection @String (seqRun 2 2) "XY") "ABCDE" "ABXYE"
, testEdit (StringReplaceSection @String (seqRun 2 3) "XY") "ABCDE" "ABXY"
, testEdit (StringReplaceSection @String (seqRun 1 3) "XY") "ABCDE" "AXYE"
, testEditRead (StringReplaceSection @String (seqRun 2 0) "XY") "ABCDE" StringReadLength (MkSequencePoint 7)
, testEditRead
(StringReplaceSection @String (seqRun 2 0) "XY")
"ABCDE"
(StringReadSection $ seqRun 0 7)
"ABXYCDE"
, testEditRead (StringReplaceSection @String (seqRun 2 0) "XY") "ABCDE" (StringReadSection $ seqRun 0 3) "ABX"
, testEditRead (StringReplaceSection @String (seqRun 2 0) "XY") "ABCDE" (StringReadSection $ seqRun 1 3) "BXY"
, testEditRead (StringReplaceSection @String (seqRun 2 0) "XY") "ABCDE" (StringReadSection $ seqRun 1 4) "BXYC"
, testEditRead (StringReplaceSection @String (seqRun 2 0) "XY") "ABCDE" (StringReadSection $ seqRun 2 4) "XYCD"
, testEditRead (StringReplaceSection @String (seqRun 2 0) "XY") "ABCDE" (StringReadSection $ seqRun 3 3) "YCD"
]
testLensGet :: TestTree
testLensGet =
testTree "get" $ \srun (base :: String) ->
ioProperty $
runLifecycle $ do
MkFloatingChangeLens {..} <- return $ stringSectionLens srun
r <- runFloatInit fclInit $ subjectToReadable base
let
expected :: String
expected = subjectToRead base $ StringReadSection srun
found <- readableToSubject $ clRead (fclLens r) $ subjectToReadable base
return $ found === expected
showVar :: Show a => String -> a -> String
showVar name val = name ++ " = " ++ show val
counterexamples :: [String] -> Property -> Property
counterexamples [] = id
counterexamples (s:ss) = counterexample s . counterexamples ss
lensUpdateGetProperty ::
forall state updateA updateB.
( IsUpdate updateA
, Show (UpdateEdit updateA)
, ApplicableEdit (UpdateEdit updateA)
, FullSubjectReader (UpdateReader updateA)
, Show (UpdateSubject updateA)
, IsEditUpdate updateB
, Show updateB
, ApplicableEdit (UpdateEdit updateB)
, FullSubjectReader (UpdateReader updateB)
, Eq (UpdateSubject updateB)
, Show (UpdateSubject updateB)
, Show state
)
=> FloatingChangeLens updateA updateB
-> UpdateSubject updateA
-> UpdateEdit updateA
-> Property
lensUpdateGetProperty lens oldA editA =
ioProperty @Property $
runLifecycle $ do
MkFloatingChangeLens {..} <- return lens
--oldState <- get
r <- runFloatInit fclInit $ subjectToReadable oldA
newA <- readableToSubject $ applyEdit editA $ subjectToReadable oldA
oldB <- readableToSubject $ clRead (fclLens r) $ subjectToReadable oldA
updateBs <- clUpdate (fclLens r) (editUpdate editA) $ subjectToReadable newA
--newState <- get
newB1 <- readableToSubject $ applyEdits (fmap updateEdit updateBs) $ subjectToReadable oldB
newB2 <- readableToSubject $ clRead (fclLens r) $ subjectToReadable newA
let
vars =
[ showVar "oldA" oldA
, " oldState " oldState
, showVar "oldB" oldB
, showVar "editA" editA
, showVar "updateBs" updateBs
, showVar "newA" newA
, " newState " newState
, showVar "newB (edits)" newB1
, showVar "newB (lens )" newB2
]
return $ counterexamples vars $ newB1 === newB2
testLensUpdate :: TestTree
testLensUpdate =
testTree "update" $ \run (MkSimpleString base) edit ->
lensUpdateGetProperty @SequenceRun (stringSectionLens run) base edit
testStringSectionLens :: TestTree
testStringSectionLens =
testTree
"string section lens"
[ testLensGet
, localOption (QuickCheckTests 10000) testLensUpdate
, localOption (QuickCheckTests 1) $
testTree "update special" $
[ testTree "1 0" $
lensUpdateGetProperty
@SequenceRun
(stringSectionLens $ seqRun 0 1)
("A" :: String)
(StringReplaceSection (seqRun 1 0) "x")
, testTree "4 1" $
lensUpdateGetProperty
@SequenceRun
(stringSectionLens $ seqRun 0 5)
("ABCDE" :: String)
(StringReplaceSection (seqRun 4 1) "pqrstu")
, testTree "4 2" $
lensUpdateGetProperty
@SequenceRun
(stringSectionLens $ seqRun 0 5)
("ABCDE" :: String)
(StringReplaceSection (seqRun 4 2) "pqrstu")
, testTree "SharedString5" $
lensUpdateGetProperty
@SequenceRun
(stringSectionLens $ startEndRun 1 3)
("ABCD" :: String)
(StringReplaceSection (startEndRun 2 4) "")
]
]
testSequence :: TestTree
testSequence =
testTree
"sequence"
[ testTree "intersectInside" $
assertEqual "" (Just $ startEndRun 2 3) $ seqIntersectInside (startEndRun 1 3) (startEndRun 2 4)
]
tests :: TestTree
tests =
testTree
"changes-core"
[ testResource
, testApplyEditsPar
, testApplyEditsSeq
, testSequence
, testStringEdit
, testStringSectionLens
, testSubscribe
, testLens
]
main :: IO ()
main = testMain tests
| null | https://raw.githubusercontent.com/AshleyYakeley/Truth/2817d5e36bd1dc5de932d808026098b6c35e7185/Changes/changes-core/test/Main.hs | haskell | # OPTIONS -fno-warn-orphans #
# OVERLAPPING #
oldState <- get
newState <- get |
module Main
( main
) where
import Changes.Core
import Lens
import Resource
import Shapes
import Shapes.Test
import Subscribe
import Test.SimpleString
instance Arbitrary SequencePoint where
arbitrary = MkSequencePoint <$> (getSmall . getNonNegative <$> arbitrary)
shrink 0 = []
shrink 1 = [0]
shrink n = [0, pred n]
instance Arbitrary SequenceRun where
arbitrary = MkSequenceRun <$> arbitrary <*> arbitrary
shrink (MkSequenceRun s l) = [MkSequenceRun s' l' | (s', l') <- shrink (s, l)]
instance Arbitrary seq => Arbitrary (StringEdit seq) where
arbitrary = oneof [StringReplaceWhole <$> arbitrary, StringReplaceSection <$> arbitrary <*> arbitrary]
shrink (StringReplaceWhole s) = StringReplaceWhole <$> shrink s
shrink (StringReplaceSection r s) =
(StringReplaceWhole s) : [StringReplaceSection r' s' | (r', s') <- shrink (r, s)]
arbitrary =
oneof
[ StringReplaceWhole <$> (getSimpleString <$> arbitrary)
, StringReplaceSection <$> arbitrary <*> (getSimpleString <$> arbitrary)
]
shrink (StringReplaceWhole s) = StringReplaceWhole <$> (getSimpleString <$> shrink (MkSimpleString s))
shrink (StringReplaceSection r s) =
(StringReplaceWhole s) : [StringReplaceSection r' s' | (r', MkSimpleString s') <- shrink (r, MkSimpleString s)]
testApplyEditsPar :: TestTree
testApplyEditsPar =
testTree "apply edits parallel" $ let
start = (False, False)
edits :: [PairUpdateEdit (WholeUpdate Bool) (WholeUpdate Bool)]
edits =
[ MkTupleUpdateEdit SelectFirst $ MkWholeReaderEdit True
, MkTupleUpdateEdit SelectSecond $ MkWholeReaderEdit True
]
expected = (True, True)
rf :: ReadFunction (TupleUpdateReader (PairSelector (WholeUpdate Bool) (WholeUpdate Bool))) (TupleUpdateReader (PairSelector (WholeUpdate Bool) (WholeUpdate Bool)))
rf = applyEdits edits
in do
found <- readableToSubject $ rf $ subjectToReadable start
assertEqual "" expected found
testApplyEditsSeq :: TestTree
testApplyEditsSeq =
testTree "apply edits sequence" $ let
start = 0
edits :: [WholeEdit Int]
edits = [MkWholeReaderEdit 1, MkWholeReaderEdit 2]
expected = 2
rf :: ReadFunction (WholeReader Int) (WholeReader Int)
rf = applyEdits edits
in do
found <- readableToSubject $ rf $ subjectToReadable start
assertEqual "" expected found
applyEditSubject ::
(ApplicableEdit edit, FullSubjectReader (EditReader edit)) => edit -> EditSubject edit -> IO (EditSubject edit)
applyEditSubject edit subj = readableToSubject $ applyEdit edit $ subjectToReadable subj
testEdit ::
forall edit.
( ApplicableEdit edit
, FullSubjectReader (EditReader edit)
, Eq (EditSubject edit)
, Show edit
, Show (EditSubject edit)
)
=> edit
-> EditSubject edit
-> EditSubject edit
-> TestTree
testEdit edit original expected = let
name = show edit ++ " " ++ show original
in testTree name $ do
found <- applyEditSubject edit original
assertEqual "" expected found
testEditRead ::
forall edit t.
( SubjectReader (EditReader edit)
, ApplicableEdit edit
, Eq t
, Show t
, Show edit
, Show (EditSubject edit)
, Show (EditReader edit t)
)
=> edit
-> EditSubject edit
-> EditReader edit t
-> t
-> TestTree
testEditRead edit original rt expected = let
name = show edit ++ " " ++ show original ++ " " ++ show rt
in testTree name $ do
found <- applyEdit edit (subjectToReadable original) rt
assertEqual "" expected found
seqRun :: Int64 -> Int64 -> SequenceRun
seqRun start len = MkSequenceRun (MkSequencePoint start) (MkSequencePoint len)
testStringEdit :: TestTree
testStringEdit =
testTree
"string edit"
[ testEdit (StringReplaceSection @String (seqRun 2 0) "XY") "ABCDE" "ABXYCDE"
, testEdit (StringReplaceSection @String (seqRun 2 1) "XY") "ABCDE" "ABXYDE"
, testEdit (StringReplaceSection @String (seqRun 2 2) "XY") "ABCDE" "ABXYE"
, testEdit (StringReplaceSection @String (seqRun 2 3) "XY") "ABCDE" "ABXY"
, testEdit (StringReplaceSection @String (seqRun 1 3) "XY") "ABCDE" "AXYE"
, testEditRead (StringReplaceSection @String (seqRun 2 0) "XY") "ABCDE" StringReadLength (MkSequencePoint 7)
, testEditRead
(StringReplaceSection @String (seqRun 2 0) "XY")
"ABCDE"
(StringReadSection $ seqRun 0 7)
"ABXYCDE"
, testEditRead (StringReplaceSection @String (seqRun 2 0) "XY") "ABCDE" (StringReadSection $ seqRun 0 3) "ABX"
, testEditRead (StringReplaceSection @String (seqRun 2 0) "XY") "ABCDE" (StringReadSection $ seqRun 1 3) "BXY"
, testEditRead (StringReplaceSection @String (seqRun 2 0) "XY") "ABCDE" (StringReadSection $ seqRun 1 4) "BXYC"
, testEditRead (StringReplaceSection @String (seqRun 2 0) "XY") "ABCDE" (StringReadSection $ seqRun 2 4) "XYCD"
, testEditRead (StringReplaceSection @String (seqRun 2 0) "XY") "ABCDE" (StringReadSection $ seqRun 3 3) "YCD"
]
testLensGet :: TestTree
testLensGet =
testTree "get" $ \srun (base :: String) ->
ioProperty $
runLifecycle $ do
MkFloatingChangeLens {..} <- return $ stringSectionLens srun
r <- runFloatInit fclInit $ subjectToReadable base
let
expected :: String
expected = subjectToRead base $ StringReadSection srun
found <- readableToSubject $ clRead (fclLens r) $ subjectToReadable base
return $ found === expected
showVar :: Show a => String -> a -> String
showVar name val = name ++ " = " ++ show val
counterexamples :: [String] -> Property -> Property
counterexamples [] = id
counterexamples (s:ss) = counterexample s . counterexamples ss
lensUpdateGetProperty ::
forall state updateA updateB.
( IsUpdate updateA
, Show (UpdateEdit updateA)
, ApplicableEdit (UpdateEdit updateA)
, FullSubjectReader (UpdateReader updateA)
, Show (UpdateSubject updateA)
, IsEditUpdate updateB
, Show updateB
, ApplicableEdit (UpdateEdit updateB)
, FullSubjectReader (UpdateReader updateB)
, Eq (UpdateSubject updateB)
, Show (UpdateSubject updateB)
, Show state
)
=> FloatingChangeLens updateA updateB
-> UpdateSubject updateA
-> UpdateEdit updateA
-> Property
lensUpdateGetProperty lens oldA editA =
ioProperty @Property $
runLifecycle $ do
MkFloatingChangeLens {..} <- return lens
r <- runFloatInit fclInit $ subjectToReadable oldA
newA <- readableToSubject $ applyEdit editA $ subjectToReadable oldA
oldB <- readableToSubject $ clRead (fclLens r) $ subjectToReadable oldA
updateBs <- clUpdate (fclLens r) (editUpdate editA) $ subjectToReadable newA
newB1 <- readableToSubject $ applyEdits (fmap updateEdit updateBs) $ subjectToReadable oldB
newB2 <- readableToSubject $ clRead (fclLens r) $ subjectToReadable newA
let
vars =
[ showVar "oldA" oldA
, " oldState " oldState
, showVar "oldB" oldB
, showVar "editA" editA
, showVar "updateBs" updateBs
, showVar "newA" newA
, " newState " newState
, showVar "newB (edits)" newB1
, showVar "newB (lens )" newB2
]
return $ counterexamples vars $ newB1 === newB2
testLensUpdate :: TestTree
testLensUpdate =
testTree "update" $ \run (MkSimpleString base) edit ->
lensUpdateGetProperty @SequenceRun (stringSectionLens run) base edit
testStringSectionLens :: TestTree
testStringSectionLens =
testTree
"string section lens"
[ testLensGet
, localOption (QuickCheckTests 10000) testLensUpdate
, localOption (QuickCheckTests 1) $
testTree "update special" $
[ testTree "1 0" $
lensUpdateGetProperty
@SequenceRun
(stringSectionLens $ seqRun 0 1)
("A" :: String)
(StringReplaceSection (seqRun 1 0) "x")
, testTree "4 1" $
lensUpdateGetProperty
@SequenceRun
(stringSectionLens $ seqRun 0 5)
("ABCDE" :: String)
(StringReplaceSection (seqRun 4 1) "pqrstu")
, testTree "4 2" $
lensUpdateGetProperty
@SequenceRun
(stringSectionLens $ seqRun 0 5)
("ABCDE" :: String)
(StringReplaceSection (seqRun 4 2) "pqrstu")
, testTree "SharedString5" $
lensUpdateGetProperty
@SequenceRun
(stringSectionLens $ startEndRun 1 3)
("ABCD" :: String)
(StringReplaceSection (startEndRun 2 4) "")
]
]
testSequence :: TestTree
testSequence =
testTree
"sequence"
[ testTree "intersectInside" $
assertEqual "" (Just $ startEndRun 2 3) $ seqIntersectInside (startEndRun 1 3) (startEndRun 2 4)
]
tests :: TestTree
tests =
testTree
"changes-core"
[ testResource
, testApplyEditsPar
, testApplyEditsSeq
, testSequence
, testStringEdit
, testStringSectionLens
, testSubscribe
, testLens
]
main :: IO ()
main = testMain tests
|
2359caa9eb2ec5885a87df79eb9adc9b3f9674e3b5e0cdcaa75572238a7a8582 | tomjaguarpaw/haskell-opaleye | Column.hs | # OPTIONS_GHC -fno - warn - duplicate - exports #
| Do not use . Will be deprecated in version 0.10 . Use
-- "Opaleye.Field" instead.
--
-- Functions for working directly with 'Column's.
--
Please note that numeric ' Column ' types are instances of ' ' , so
-- you can use '*', '/', '+', '-' on them.
module Opaleye.Column (-- * 'Column'
Column,
-- * Working with @NULL@
Nullable,
null,
isNull,
-- * Unsafe operations
unsafeCast,
unsafeCoerceColumn,
unsafeCompositeField,
-- * Entire module
module Opaleye.Column) where
import Opaleye.Internal.Column (Column, Nullable, unsafeCoerceColumn,
unsafeCast, unsafeCompositeField)
import qualified Opaleye.Field as F
import qualified Opaleye.Internal.Column as C
import qualified Opaleye.Internal.HaskellDB.PrimQuery as HPQ
import qualified Opaleye.Internal.PGTypesExternal as T
import Prelude hiding (null)
-- | A NULL of any type
null :: Column (Nullable a)
null = F.null
-- | @TRUE@ if the value of the column is @NULL@, @FALSE@ otherwise.
isNull :: Column (Nullable a) -> Column T.PGBool
isNull = C.unOp HPQ.OpIsNull
joinNullable :: Column (Nullable (Nullable a)) -> Column (Nullable a)
joinNullable = unsafeCoerceColumn
| null | https://raw.githubusercontent.com/tomjaguarpaw/haskell-opaleye/2b264ecd62659f568c838a2bbdd796a4f6c3dd1f/src/Opaleye/Column.hs | haskell | "Opaleye.Field" instead.
Functions for working directly with 'Column's.
you can use '*', '/', '+', '-' on them.
* 'Column'
* Working with @NULL@
* Unsafe operations
* Entire module
| A NULL of any type
| @TRUE@ if the value of the column is @NULL@, @FALSE@ otherwise. | # OPTIONS_GHC -fno - warn - duplicate - exports #
| Do not use . Will be deprecated in version 0.10 . Use
Please note that numeric ' Column ' types are instances of ' ' , so
Column,
Nullable,
null,
isNull,
unsafeCast,
unsafeCoerceColumn,
unsafeCompositeField,
module Opaleye.Column) where
import Opaleye.Internal.Column (Column, Nullable, unsafeCoerceColumn,
unsafeCast, unsafeCompositeField)
import qualified Opaleye.Field as F
import qualified Opaleye.Internal.Column as C
import qualified Opaleye.Internal.HaskellDB.PrimQuery as HPQ
import qualified Opaleye.Internal.PGTypesExternal as T
import Prelude hiding (null)
null :: Column (Nullable a)
null = F.null
isNull :: Column (Nullable a) -> Column T.PGBool
isNull = C.unOp HPQ.OpIsNull
joinNullable :: Column (Nullable (Nullable a)) -> Column (Nullable a)
joinNullable = unsafeCoerceColumn
|
f07ddd4c856c1baaddfd257457665690eb731bda4885052fef9802dc6f4f4709 | Flexiana/xiana-template | core.cljs | (ns {{sanitized-name}}.core
(:require
[reagent.dom :as rdom]
[re-frame.core :as re-frame]
[{{sanitized-name}}.events :as events]
[{{sanitized-name}}.views :as views]
[{{sanitized-name}}.config :as config]))
(defn dev-setup []
(when config/debug?
(println "dev mode")))
(defn ^:dev/after-load mount-root []
(re-frame/clear-subscription-cache!)
(let [root-el (.getElementById js/document "app")]
(rdom/unmount-component-at-node root-el)
(rdom/render [views/main-panel] root-el)))
(defn init []
(re-frame/dispatch-sync [::events/initialize-db])
(dev-setup)
(mount-root))
| null | https://raw.githubusercontent.com/Flexiana/xiana-template/238738a29db3c948bd6d3281b4c0c241c5bdb59e/resources/leiningen/new/xiana/src/frontend/app_name/core.cljs | clojure | (ns {{sanitized-name}}.core
(:require
[reagent.dom :as rdom]
[re-frame.core :as re-frame]
[{{sanitized-name}}.events :as events]
[{{sanitized-name}}.views :as views]
[{{sanitized-name}}.config :as config]))
(defn dev-setup []
(when config/debug?
(println "dev mode")))
(defn ^:dev/after-load mount-root []
(re-frame/clear-subscription-cache!)
(let [root-el (.getElementById js/document "app")]
(rdom/unmount-component-at-node root-el)
(rdom/render [views/main-panel] root-el)))
(defn init []
(re-frame/dispatch-sync [::events/initialize-db])
(dev-setup)
(mount-root))
|
|
9b10cb1a7aaf720aa8a6023aa693f5147b4726c75d01141fe8b865e171af01e0 | yesodweb/yesod | streaming.hs | # LANGUAGE OverloadedStrings , TemplateHaskell , QuasiQuotes , TypeFamilies #
import Yesod.Core
import Data.Conduit
import qualified Data.Conduit.Binary as CB
import Control.Concurrent.Lifted (threadDelay)
import Data.Monoid ((<>))
import qualified Data.Text as T
import Control.Monad (forM_)
data App = App
mkYesod "App" [parseRoutes|
/ HomeR GET
|]
instance Yesod App
fibs :: [Int]
fibs = 1 : 1 : zipWith (+) fibs (tail fibs)
getHomeR :: Handler TypedContent
getHomeR = do
value <- lookupGetParam "x"
case value of
Just "file" -> respondSource typePlain $ do
sendChunkText "Going to read a file\n\n"
CB.sourceFile "streaming.hs" $= awaitForever sendChunkBS
sendChunkText "Finished reading the file\n"
Just "fibs" -> respondSource typePlain $ do
forM_ fibs $ \fib -> do
$logError $ "Got fib: " <> T.pack (show fib)
sendChunkText $ "Next fib is: " <> T.pack (show fib) <> "\n"
yield Flush
sendFlush
threadDelay 1000000
_ -> fmap toTypedContent $ defaultLayout $ do
setTitle "Streaming"
[whamlet|
<p>Notice how in the code above we perform selection before starting the stream.
<p>Anyway, choose one of the options below.
<ul>
<li>
<a href=?x=file>Read a file
<li>
<a href=?x=fibs>See the fibs
|]
main = warp 3000 App
| null | https://raw.githubusercontent.com/yesodweb/yesod/c59993ff287b880abbf768f1e3f56ae9b19df51e/demo/streaming/streaming.hs | haskell | # LANGUAGE OverloadedStrings , TemplateHaskell , QuasiQuotes , TypeFamilies #
import Yesod.Core
import Data.Conduit
import qualified Data.Conduit.Binary as CB
import Control.Concurrent.Lifted (threadDelay)
import Data.Monoid ((<>))
import qualified Data.Text as T
import Control.Monad (forM_)
data App = App
mkYesod "App" [parseRoutes|
/ HomeR GET
|]
instance Yesod App
fibs :: [Int]
fibs = 1 : 1 : zipWith (+) fibs (tail fibs)
getHomeR :: Handler TypedContent
getHomeR = do
value <- lookupGetParam "x"
case value of
Just "file" -> respondSource typePlain $ do
sendChunkText "Going to read a file\n\n"
CB.sourceFile "streaming.hs" $= awaitForever sendChunkBS
sendChunkText "Finished reading the file\n"
Just "fibs" -> respondSource typePlain $ do
forM_ fibs $ \fib -> do
$logError $ "Got fib: " <> T.pack (show fib)
sendChunkText $ "Next fib is: " <> T.pack (show fib) <> "\n"
yield Flush
sendFlush
threadDelay 1000000
_ -> fmap toTypedContent $ defaultLayout $ do
setTitle "Streaming"
[whamlet|
<p>Notice how in the code above we perform selection before starting the stream.
<p>Anyway, choose one of the options below.
<ul>
<li>
<a href=?x=file>Read a file
<li>
<a href=?x=fibs>See the fibs
|]
main = warp 3000 App
|
|
6ee6379b350608c488f07e629542056743cad966f05af4b0ba3051701bfbbd71 | bbusching/libgit2 | revert.rkt | #lang racket
(require ffi/unsafe
"define.rkt"
"types.rkt"
"merge.rkt"
"checkout.rkt"
"index.rkt"
"utils.rkt")
(provide (all-defined-out))
; Types
(define-cstruct _git_revert_opts
([version _uint]
[mainline _uint]
[merge_opts _git_merge_opts]
[checkout_opts _git_checkout_opts]))
(define GIT_REVERT_OPTS_VERSION 1)
; Functions
(define-libgit2/check git_revert
(_fun _repository _commit _git_revert_opts-pointer -> _int))
(define-libgit2/alloc git_revert_commit
(_fun _index _repository _commit _commit _uint _git_merge_opts-pointer -> _int)
git_index_free)
(define-libgit2/check git_revert_init_options
(_fun _git_revert_opts-pointer _uint -> _int))
| null | https://raw.githubusercontent.com/bbusching/libgit2/6d6a007543900eb7a6fbbeba55850288665bdde5/libgit2/include/revert.rkt | racket | Types
Functions | #lang racket
(require ffi/unsafe
"define.rkt"
"types.rkt"
"merge.rkt"
"checkout.rkt"
"index.rkt"
"utils.rkt")
(provide (all-defined-out))
(define-cstruct _git_revert_opts
([version _uint]
[mainline _uint]
[merge_opts _git_merge_opts]
[checkout_opts _git_checkout_opts]))
(define GIT_REVERT_OPTS_VERSION 1)
(define-libgit2/check git_revert
(_fun _repository _commit _git_revert_opts-pointer -> _int))
(define-libgit2/alloc git_revert_commit
(_fun _index _repository _commit _commit _uint _git_merge_opts-pointer -> _int)
git_index_free)
(define-libgit2/check git_revert_init_options
(_fun _git_revert_opts-pointer _uint -> _int))
|
d3e82f1ebd14d2fc61f8cff19e2345ef6ff330b7745e657fb5cf6ae223f48c56 | cirodrig/triolet | Kind.hs | | The first pass of Core code generation , which computes kinds for
all type - level definitions in the module .
all type-level definitions in the module.
-}
module CParser2.GenCode.Kind(genKind, kindTranslation)
where
import Control.Applicative
import Control.Monad
import qualified Data.Map as Map
import Data.Monoid
import Common.Identifier
import Common.SourcePos
import Common.Supply
import CParser2.AST
import CParser2.GenCode.Util
import Type.Environment
import qualified Type.Type as Type
import Type.Var
-- | Translate an AST kind to a core kind
genKind :: RLType -> TransT Type.Kind
genKind (L pos rtype) =
case rtype
of VarT v -> do
-- Look up this type, if it's a @let type@ synonym
mtype <- lookupLetTypeSynonym v
case mtype of
Just t -> return t
Nothing -> return $ Type.VarT (toVar v)
k1 `FunT` k2 ->
Type.FunT <$> genKind k1 <*> genKind k2
_ -> error $ show pos ++ ": Unexpected kind expression"
-- | Translate a global type-related declaration.
declKind :: LDecl Resolved -> TransT UpdateTypeEnv
declKind (L loc (Decl ident ent)) = do
let make_update kind =
return $ UpdateTypeEnv $ \env -> insertGlobalType env (toVar ident) kind
case ent of
TypeEnt k _ -> genKind k >>= make_update
DataEnt binders k _ _ -> genKind (fun_kind binders k) >>= make_update
_ -> return mempty
where
fun_kind bs k = foldr fun_t k bs
where
fun_t (Domain _ (Just dom)) rng = L loc (dom `FunT` rng)
-- | Create a kind environment from the declarations in the module
moduleKindEnvironment :: RModule -> TransT UpdateTypeEnv
moduleKindEnvironment (Module decls) =
liftM mconcat $ mapM declKind decls
-- | Compute the kinds of all type-level entities in the module.
-- These kinds are not part of the module that's finally generated.
-- They are needed while translating type-level entities into core.
kindTranslation :: IdentSupply Var
-> [(Var, Type.Type)]
-> Map.Map String BuiltinTypeFunction
-> RModule
-> IO TypeEnv
kindTranslation var_ids type_synonyms type_functions mod = do
-- Create a type environment with built-in types to use
-- while examining kinds
tenv <- mkWiredInTypeEnv
kind_env_updates <-
runTypeTranslation var_ids tenv type_synonyms type_functions $
moduleKindEnvironment mod
-- Add bindings to the type environment
applyUpdates kind_env_updates tenv
return tenv | null | https://raw.githubusercontent.com/cirodrig/triolet/e515a1dc0d6b3e546320eac7b71fb36cea5b53d0/src/program/CParser2/GenCode/Kind.hs | haskell | | Translate an AST kind to a core kind
Look up this type, if it's a @let type@ synonym
| Translate a global type-related declaration.
| Create a kind environment from the declarations in the module
| Compute the kinds of all type-level entities in the module.
These kinds are not part of the module that's finally generated.
They are needed while translating type-level entities into core.
Create a type environment with built-in types to use
while examining kinds
Add bindings to the type environment | | The first pass of Core code generation , which computes kinds for
all type - level definitions in the module .
all type-level definitions in the module.
-}
module CParser2.GenCode.Kind(genKind, kindTranslation)
where
import Control.Applicative
import Control.Monad
import qualified Data.Map as Map
import Data.Monoid
import Common.Identifier
import Common.SourcePos
import Common.Supply
import CParser2.AST
import CParser2.GenCode.Util
import Type.Environment
import qualified Type.Type as Type
import Type.Var
genKind :: RLType -> TransT Type.Kind
genKind (L pos rtype) =
case rtype
of VarT v -> do
mtype <- lookupLetTypeSynonym v
case mtype of
Just t -> return t
Nothing -> return $ Type.VarT (toVar v)
k1 `FunT` k2 ->
Type.FunT <$> genKind k1 <*> genKind k2
_ -> error $ show pos ++ ": Unexpected kind expression"
declKind :: LDecl Resolved -> TransT UpdateTypeEnv
declKind (L loc (Decl ident ent)) = do
let make_update kind =
return $ UpdateTypeEnv $ \env -> insertGlobalType env (toVar ident) kind
case ent of
TypeEnt k _ -> genKind k >>= make_update
DataEnt binders k _ _ -> genKind (fun_kind binders k) >>= make_update
_ -> return mempty
where
fun_kind bs k = foldr fun_t k bs
where
fun_t (Domain _ (Just dom)) rng = L loc (dom `FunT` rng)
moduleKindEnvironment :: RModule -> TransT UpdateTypeEnv
moduleKindEnvironment (Module decls) =
liftM mconcat $ mapM declKind decls
kindTranslation :: IdentSupply Var
-> [(Var, Type.Type)]
-> Map.Map String BuiltinTypeFunction
-> RModule
-> IO TypeEnv
kindTranslation var_ids type_synonyms type_functions mod = do
tenv <- mkWiredInTypeEnv
kind_env_updates <-
runTypeTranslation var_ids tenv type_synonyms type_functions $
moduleKindEnvironment mod
applyUpdates kind_env_updates tenv
return tenv |
c98c13652bec11736b104d75791f4e95c62d970aa7e8361aaa3855fe2e6bbb85 | typelead/eta | tc036.hs | module ShouldSucceed where
class (Eq a) => A a where
op1 :: a -> a
| null | https://raw.githubusercontent.com/typelead/eta/97ee2251bbc52294efbf60fa4342ce6f52c0d25c/tests/suite/typecheck/compile/tc036.hs | haskell | module ShouldSucceed where
class (Eq a) => A a where
op1 :: a -> a
|
|
1613a5ebf5434ad082ee35c207946b21e61c5cfe82ffb2478f99c1992e413523 | degree9/enterprise | service.cljs | (ns degree9.service
"A service endpoint via websockets."
(:require [degree9.socket-io :as io]
["@feathersjs/feathers" :as feathers]
["@feathersjs/socketio-client" :as socketio]
[goog.object :as obj]
[meta.server :as server]
[degree9.debug :as dbg]))
(dbg/defdebug debug "degree9:enterprise:service")
(def io io/io)
(defn with-websockets
"Configure feathers app for websockets."
[client socket]
(debug "Configure feathers socket.io client")
(doto client
(.configure (socketio socket))))
(defn client [socket]
(with-websockets (feathers) socket))
(defn µservice [client service]
(reify
Object
(setup [this app path]
(debug "Setup proxy to remote service %s" service)
(obj/set this :io (.service client service)))
(find [this params]
(debug "Proxy find to remote service %s with %s" service params)
(.find (obj/get this :io) params))
(get [this id params]
(debug "Proxy get to remote service %s/%s with %s" service id params)
(.get (obj/get this :io) id params))
(create [this data params]
(debug "Proxy create to remote service %s with %s" service params)
(.create (obj/get this :io) data params))
(update [this id data params]
(debug "Proxy update to remote service %s with %s" service params)
(.update (obj/get this :io) id data params))
(patch [this id data params]
(debug "Proxy patch to remote service %s with %s" service params)
(.patch (obj/get this :io) id data params))
(remove [this id params]
(debug "Proxy remove to remote service %s with %s" service params)
(.remove (obj/get this :io) id params))))
(defn api
"Mount a remote Microservice to a local endpoint."
([app path client service hooks]
(debug "Mount remote microservice at %s" path)
(server/api app path (µservice client service) hooks)))
Multi - Service ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;
(defn- api-service [app [prefix client services] hooks]
(reduce (fn [app service] (api app (str prefix service) client service hooks)) app services))
(defn- reduce-apis [app services hooks]
(reduce (fn [app service] (api-service app service hooks)) app services))
(defn multi-service
"Mount multiple remote services from different servers."
[app specs & [hooks]]
(reduce-apis app specs hooks))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
| null | https://raw.githubusercontent.com/degree9/enterprise/65737c347e513d0a0bf94f2d4374935c7270185d/src/degree9/service.cljs | clojure | ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;
| (ns degree9.service
"A service endpoint via websockets."
(:require [degree9.socket-io :as io]
["@feathersjs/feathers" :as feathers]
["@feathersjs/socketio-client" :as socketio]
[goog.object :as obj]
[meta.server :as server]
[degree9.debug :as dbg]))
(dbg/defdebug debug "degree9:enterprise:service")
(def io io/io)
(defn with-websockets
"Configure feathers app for websockets."
[client socket]
(debug "Configure feathers socket.io client")
(doto client
(.configure (socketio socket))))
(defn client [socket]
(with-websockets (feathers) socket))
(defn µservice [client service]
(reify
Object
(setup [this app path]
(debug "Setup proxy to remote service %s" service)
(obj/set this :io (.service client service)))
(find [this params]
(debug "Proxy find to remote service %s with %s" service params)
(.find (obj/get this :io) params))
(get [this id params]
(debug "Proxy get to remote service %s/%s with %s" service id params)
(.get (obj/get this :io) id params))
(create [this data params]
(debug "Proxy create to remote service %s with %s" service params)
(.create (obj/get this :io) data params))
(update [this id data params]
(debug "Proxy update to remote service %s with %s" service params)
(.update (obj/get this :io) id data params))
(patch [this id data params]
(debug "Proxy patch to remote service %s with %s" service params)
(.patch (obj/get this :io) id data params))
(remove [this id params]
(debug "Proxy remove to remote service %s with %s" service params)
(.remove (obj/get this :io) id params))))
(defn api
"Mount a remote Microservice to a local endpoint."
([app path client service hooks]
(debug "Mount remote microservice at %s" path)
(server/api app path (µservice client service) hooks)))
(defn- api-service [app [prefix client services] hooks]
(reduce (fn [app service] (api app (str prefix service) client service hooks)) app services))
(defn- reduce-apis [app services hooks]
(reduce (fn [app service] (api-service app service hooks)) app services))
(defn multi-service
"Mount multiple remote services from different servers."
[app specs & [hooks]]
(reduce-apis app specs hooks))
|
d0631a68705a099f3c345fb6925f7871f846a81158a468db8a50f22fe316e354 | haskell-trasa/trasa | Doctest.hs | module Main (main) where
import Test.DocTest (doctest)
main :: IO ()
main = do
putStrLn "\nRUNNING DOCTESTS"
doctest
[ "src"
]
| null | https://raw.githubusercontent.com/haskell-trasa/trasa/bfc23d4fd5b895493ba650a7f607b5fa034179d7/trasa/test/Doctest.hs | haskell | module Main (main) where
import Test.DocTest (doctest)
main :: IO ()
main = do
putStrLn "\nRUNNING DOCTESTS"
doctest
[ "src"
]
|
|
6378866f61493176ad076768d3d0125418c8fc3d6294aa10c6d420d4f4759d28 | couchbase/couchdb | mochiweb_acceptor.erl | @author < >
@copyright 2010 Mochi Media , Inc.
%%
%% Permission is hereby granted, free of charge, to any person obtaining a
%% copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction , including without limitation
%% the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software , and to permit persons to whom the
%% Software is furnished to do so, subject to the following conditions:
%%
%% The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software .
%%
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
%% THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
%% FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
%% DEALINGS IN THE SOFTWARE.
@doc MochiWeb acceptor .
-module(mochiweb_acceptor).
-author('').
-include_lib("kernel/include/logger.hrl").
-include("internal.hrl").
-export([init/4, start_link/3, start_link/4]).
-define(EMFILE_SLEEP_MSEC, 100).
start_link(Server, Listen, Loop) ->
start_link(Server, Listen, Loop, []).
start_link(Server, Listen, Loop, Opts) ->
proc_lib:spawn_link(?MODULE, init,
[Server, Listen, Loop, Opts]).
do_accept(Server, Listen) ->
T1 = os:timestamp(),
case mochiweb_socket:transport_accept(Listen) of
{ok, Socket} ->
gen_server:cast(Server,
{accepted, self(),
timer:now_diff(os:timestamp(), T1)}),
mochiweb_socket:finish_accept(Socket);
Other -> Other
end.
init(Server, Listen, Loop, Opts) ->
case catch do_accept(Server, Listen) of
{ok, Socket} -> call_loop(Loop, Socket, Opts);
{error, Err}
when Err =:= closed orelse
Err =:= esslaccept orelse Err =:= timeout ->
exit(normal);
Other ->
%% Mitigate out of file descriptor scenario by sleeping for a
%% short time to slow error rate
case Other of
{error, emfile} ->
receive after ?EMFILE_SLEEP_MSEC -> ok end;
_ -> ok
end,
?LOG_ERROR(
#{label => {mochiweb_acceptor, accept_error},
report => [{application, mochiweb},
{accept_error, lists:flatten(
io_lib:format("~p", [Other]))}]},
#{domain => [mochiweb],
report_cb => fun logger:format_otp_report/1,
logger_formatter => #{title => "ERROR REPORT"}}),
exit({error, accept_failed})
end.
call_loop({M, F}, Socket, Opts) when is_atom(M) ->
M:F(Socket, Opts);
call_loop({M, F, [A1]}, Socket, Opts) when is_atom(M) ->
M:F(Socket, Opts, A1);
call_loop({M, F, A}, Socket, Opts) when is_atom(M) ->
erlang:apply(M, F, [Socket, Opts | A]);
call_loop(Loop, Socket, Opts) -> Loop(Socket, Opts).
| null | https://raw.githubusercontent.com/couchbase/couchdb/8a75fd2faa89f95158de1776354ceccf3e762753/src/mochiweb/mochiweb_acceptor.erl | erlang |
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
Mitigate out of file descriptor scenario by sleeping for a
short time to slow error rate | @author < >
@copyright 2010 Mochi Media , Inc.
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
@doc MochiWeb acceptor .
-module(mochiweb_acceptor).
-author('').
-include_lib("kernel/include/logger.hrl").
-include("internal.hrl").
-export([init/4, start_link/3, start_link/4]).
-define(EMFILE_SLEEP_MSEC, 100).
start_link(Server, Listen, Loop) ->
start_link(Server, Listen, Loop, []).
start_link(Server, Listen, Loop, Opts) ->
proc_lib:spawn_link(?MODULE, init,
[Server, Listen, Loop, Opts]).
do_accept(Server, Listen) ->
T1 = os:timestamp(),
case mochiweb_socket:transport_accept(Listen) of
{ok, Socket} ->
gen_server:cast(Server,
{accepted, self(),
timer:now_diff(os:timestamp(), T1)}),
mochiweb_socket:finish_accept(Socket);
Other -> Other
end.
init(Server, Listen, Loop, Opts) ->
case catch do_accept(Server, Listen) of
{ok, Socket} -> call_loop(Loop, Socket, Opts);
{error, Err}
when Err =:= closed orelse
Err =:= esslaccept orelse Err =:= timeout ->
exit(normal);
Other ->
case Other of
{error, emfile} ->
receive after ?EMFILE_SLEEP_MSEC -> ok end;
_ -> ok
end,
?LOG_ERROR(
#{label => {mochiweb_acceptor, accept_error},
report => [{application, mochiweb},
{accept_error, lists:flatten(
io_lib:format("~p", [Other]))}]},
#{domain => [mochiweb],
report_cb => fun logger:format_otp_report/1,
logger_formatter => #{title => "ERROR REPORT"}}),
exit({error, accept_failed})
end.
call_loop({M, F}, Socket, Opts) when is_atom(M) ->
M:F(Socket, Opts);
call_loop({M, F, [A1]}, Socket, Opts) when is_atom(M) ->
M:F(Socket, Opts, A1);
call_loop({M, F, A}, Socket, Opts) when is_atom(M) ->
erlang:apply(M, F, [Socket, Opts | A]);
call_loop(Loop, Socket, Opts) -> Loop(Socket, Opts).
|
f09ae1be1b7bc98cc0046e9fd6e3bd7b8c8208fd6a80a9d01949403fa8f7c175 | Zetawar/zetawar | spec.cljs | (ns zetawar.system.spec
(:require
[cljs.core.async :as async]
[cljs.core.async.impl.protocols :as async.protocols]
[clojure.spec :as s]
[clojure.spec.impl.gen :as gen]
[clojure.test.check]
[datascript.core :as d]))
;; Logger
(s/def :zetawar.system/logger nil?)
DataScript
(s/def :zetawar.system.datascript/schema
(s/with-gen map?
#(gen/return {})))
(s/def :zetawar.system.datascript/conn
(s/with-gen d/conn?
#(gen/return (d/create-conn {}))))
(s/def :zetawar.system/datascript
(s/keys :req-un [:zetawar.system.datascript/schema
:zetawar.system.datascript/conn]))
;; Players
(s/def :zetawar.system/players
(s/with-gen (s/and #(satisfies? IDeref %)
#(map? (deref %)))
#(gen/fmap (fn [m] (atom m))
(gen/map (gen/keyword) (gen/any-printable)))))
;; Router
(s/def :zetawar.system.router/ev-chan
(s/with-gen
(s/and #(satisfies? async.protocols/ReadPort %)
#(satisfies? async.protocols/WritePort %))
#(gen/return (async/chan))))
(s/def :zetawar.system.router/notify-chan
(s/with-gen
#(satisfies? async.protocols/WritePort %)
#(gen/return (async/chan))))
(s/def :zetawar.system.router/notify-pub
(s/with-gen
#(satisfies? async/Pub %)
#(gen/return (let [notify-chan (async/chan)]
(async/pub notify-chan (fn [x] (nth x 1)))))))
(s/def :zetawar.system/router
(s/keys :req-un [:zetawar.system.datascript/conn
:zetawar.system/players
:zetawar.system.router/ev-chan
:zetawar.system.router/notify-chan
:zetawar.system.router/notify-pub]))
;; Views
(s/def :zetawar.system.views/dispatch fn?)
(s/def :zetawar.system.views/translate fn?)
(s/def :zetawar.system/views
(s/keys :req-un [:zetawar.system.datascript/conn
:zetawar.system.views/dispatch
:zetawar.system.views/translate]))
System
(s/def :zetawar/system
(s/keys :req-un [:zetawar.system/logger
:zetawar.system/datascript
:zetawar.system/players
:zetawar.system/router
:zetawar.system/views]))
| null | https://raw.githubusercontent.com/Zetawar/zetawar/dc1ee8d27afcac1cd98904859289012c2806e58c/src/cljs/zetawar/system/spec.cljs | clojure | Logger
Players
Router
Views | (ns zetawar.system.spec
(:require
[cljs.core.async :as async]
[cljs.core.async.impl.protocols :as async.protocols]
[clojure.spec :as s]
[clojure.spec.impl.gen :as gen]
[clojure.test.check]
[datascript.core :as d]))
(s/def :zetawar.system/logger nil?)
DataScript
(s/def :zetawar.system.datascript/schema
(s/with-gen map?
#(gen/return {})))
(s/def :zetawar.system.datascript/conn
(s/with-gen d/conn?
#(gen/return (d/create-conn {}))))
(s/def :zetawar.system/datascript
(s/keys :req-un [:zetawar.system.datascript/schema
:zetawar.system.datascript/conn]))
(s/def :zetawar.system/players
(s/with-gen (s/and #(satisfies? IDeref %)
#(map? (deref %)))
#(gen/fmap (fn [m] (atom m))
(gen/map (gen/keyword) (gen/any-printable)))))
(s/def :zetawar.system.router/ev-chan
(s/with-gen
(s/and #(satisfies? async.protocols/ReadPort %)
#(satisfies? async.protocols/WritePort %))
#(gen/return (async/chan))))
(s/def :zetawar.system.router/notify-chan
(s/with-gen
#(satisfies? async.protocols/WritePort %)
#(gen/return (async/chan))))
(s/def :zetawar.system.router/notify-pub
(s/with-gen
#(satisfies? async/Pub %)
#(gen/return (let [notify-chan (async/chan)]
(async/pub notify-chan (fn [x] (nth x 1)))))))
(s/def :zetawar.system/router
(s/keys :req-un [:zetawar.system.datascript/conn
:zetawar.system/players
:zetawar.system.router/ev-chan
:zetawar.system.router/notify-chan
:zetawar.system.router/notify-pub]))
(s/def :zetawar.system.views/dispatch fn?)
(s/def :zetawar.system.views/translate fn?)
(s/def :zetawar.system/views
(s/keys :req-un [:zetawar.system.datascript/conn
:zetawar.system.views/dispatch
:zetawar.system.views/translate]))
System
(s/def :zetawar/system
(s/keys :req-un [:zetawar.system/logger
:zetawar.system/datascript
:zetawar.system/players
:zetawar.system/router
:zetawar.system/views]))
|
8a2f6dcdd3f6d9d76f9f02edb29c88e744189c3a707388b96be97af083dc7db5 | OCamlPro/typerex-lint | lexer_iter.mli | (**************************************************************************)
(* *)
(* OCamlPro Typerex *)
(* *)
Copyright OCamlPro 2011 - 2016 . All rights reserved .
(* This file is distributed under the terms of the GPL v3.0 *)
( GNU General Public Licence version 3.0 ) .
(* *)
(* Contact: <> (/) *)
(* *)
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
(* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES *)
(* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND *)
NONINFRINGEMENT . IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN
(* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN *)
(* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE *)
(* SOFTWARE. *)
(**************************************************************************)
val iter_tokens : (Parser.token -> Location.t -> unit) -> string -> unit
val get_tokens : string -> (Parser.token * Location.t) array
| null | https://raw.githubusercontent.com/OCamlPro/typerex-lint/6d9e994c8278fb65e1f7de91d74876531691120c/libs/ocplib-compiler/lexer_iter.mli | ocaml | ************************************************************************
OCamlPro Typerex
This file is distributed under the terms of the GPL v3.0
Contact: <> (/)
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
************************************************************************ | Copyright OCamlPro 2011 - 2016 . All rights reserved .
( GNU General Public Licence version 3.0 ) .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
NONINFRINGEMENT . IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN
val iter_tokens : (Parser.token -> Location.t -> unit) -> string -> unit
val get_tokens : string -> (Parser.token * Location.t) array
|
71956dace56acc0c6adacfd5aad19bbded74517c420781801134565724f34c03 | weavejester/clout | project.clj | (defproject clout "2.2.1"
:description "A HTTP route matching library"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.7.0"]
[org.clojure/clojurescript "1.7.228" :scope "provided"]
[instaparse "1.4.8" :exclusions [org.clojure/clojure]]]
:plugins [[lein-doo "0.1.7"]
[lein-cljsbuild "1.1.4"]]
:cljsbuild {:builds
{:test
{:source-paths ["src" "test"]
:compiler {:main clout.test-runner
:output-dir "target/out"
:output-to "target/test/advanced.js"
:target :nodejs
:optimizations :advanced}}}}
:doo {:build "test"}
:profiles
{:dev {:jvm-opts ^:replace []
:dependencies [[ring/ring-mock "0.2.0"]
[criterium "0.4.2"]]}
:1.7 {:dependencies [[org.clojure/clojure "1.7.0"]
[org.clojure/clojurescript "1.7.228"]]}
:1.8 {:dependencies [[org.clojure/clojure "1.8.0"]
[org.clojure/clojurescript "1.8.51"]]}
:1.9 {:dependencies [[org.clojure/clojure "1.9.0"]
[org.clojure/clojurescript "1.9.946"]]}})
| null | https://raw.githubusercontent.com/weavejester/clout/122b6a6ea31fb29904de4ca9964819557ac982ac/project.clj | clojure | (defproject clout "2.2.1"
:description "A HTTP route matching library"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.7.0"]
[org.clojure/clojurescript "1.7.228" :scope "provided"]
[instaparse "1.4.8" :exclusions [org.clojure/clojure]]]
:plugins [[lein-doo "0.1.7"]
[lein-cljsbuild "1.1.4"]]
:cljsbuild {:builds
{:test
{:source-paths ["src" "test"]
:compiler {:main clout.test-runner
:output-dir "target/out"
:output-to "target/test/advanced.js"
:target :nodejs
:optimizations :advanced}}}}
:doo {:build "test"}
:profiles
{:dev {:jvm-opts ^:replace []
:dependencies [[ring/ring-mock "0.2.0"]
[criterium "0.4.2"]]}
:1.7 {:dependencies [[org.clojure/clojure "1.7.0"]
[org.clojure/clojurescript "1.7.228"]]}
:1.8 {:dependencies [[org.clojure/clojure "1.8.0"]
[org.clojure/clojurescript "1.8.51"]]}
:1.9 {:dependencies [[org.clojure/clojure "1.9.0"]
[org.clojure/clojurescript "1.9.946"]]}})
|
|
081869f7bf5ebb4419687a3ec98c5a225f6c3e9eac58c3bbd1b06feb3ffa3da6 | xapi-project/xenopsd | fence.ml |
* Copyright ( C ) 2006 - 2009 Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
* Copyright (C) 2006-2009 Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*)
(* The world's simplest program which attempts to reboot domain 0 *)
let _ =
if Array.length Sys.argv <> 2 || Sys.argv.(1) <> "yesreally" then (
Printf.fprintf stderr
"Immediately fence this host - use with extreme caution\n" ;
Printf.fprintf stderr "Usage: %s yesreally\n" Sys.argv.(0) ;
exit 1
) ;
let xc = Xenctrl.interface_open () in
(* Clear both watchdog slots *)
(try ignore (Xenctrl.watchdog xc 1 0l) with _ -> ()) ;
(try ignore (Xenctrl.watchdog xc 2 0l) with _ -> ()) ;
(* set a very short timeout *)
Xenctrl.watchdog xc 0 0l
(* boom? *)
| null | https://raw.githubusercontent.com/xapi-project/xenopsd/f4da21a4ead7c6a7082af5ec32f778faf368cf1c/xc/fence/fence.ml | ocaml | The world's simplest program which attempts to reboot domain 0
Clear both watchdog slots
set a very short timeout
boom? |
* Copyright ( C ) 2006 - 2009 Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
* Copyright (C) 2006-2009 Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*)
let _ =
if Array.length Sys.argv <> 2 || Sys.argv.(1) <> "yesreally" then (
Printf.fprintf stderr
"Immediately fence this host - use with extreme caution\n" ;
Printf.fprintf stderr "Usage: %s yesreally\n" Sys.argv.(0) ;
exit 1
) ;
let xc = Xenctrl.interface_open () in
(try ignore (Xenctrl.watchdog xc 1 0l) with _ -> ()) ;
(try ignore (Xenctrl.watchdog xc 2 0l) with _ -> ()) ;
Xenctrl.watchdog xc 0 0l
|
7b71b53077d8b068c3b85fa1a58bb52be6205a3e07f22a824ce407d1af1fdf3d | Disco-Dave/message-db | Properties.hs | module Properties
( jsonRoundtrip
)
where
import qualified Data.Aeson as Aeson
import Hedgehog (Gen, PropertyT, forAll, (===))
jsonRoundtrip :: (Aeson.ToJSON a, Aeson.FromJSON a, Eq a, Show a) => Gen a -> PropertyT IO ()
jsonRoundtrip gen = do
thing <- forAll gen
Aeson.eitherDecode (Aeson.encode thing) === Right thing
| null | https://raw.githubusercontent.com/Disco-Dave/message-db/b272c1648587046657e778685518a79f27c9f793/message-db/test/Properties.hs | haskell | module Properties
( jsonRoundtrip
)
where
import qualified Data.Aeson as Aeson
import Hedgehog (Gen, PropertyT, forAll, (===))
jsonRoundtrip :: (Aeson.ToJSON a, Aeson.FromJSON a, Eq a, Show a) => Gen a -> PropertyT IO ()
jsonRoundtrip gen = do
thing <- forAll gen
Aeson.eitherDecode (Aeson.encode thing) === Right thing
|
|
143fd6f3c2a51f9a6a5004559479a1aac833bca53452bdfcbe5f24df6b313b62 | racket/racket-lang-org | plot.rkt | #lang racket/base
(require pict
racket/list
racket/format
"color.rkt")
(provide plot
single-plot
get-times
r5rs-color
r5rs?)
(define (get-times f)
(define all-times
(call-with-input-file*
f
(lambda (i)
(for/fold ([ht '#hasheq()]) ([i (in-port read i)])
(define k (rename (cadr i)))
(define t (caaddr i))
(define e (hash-ref ht k null))
(if t
(hash-set ht k (cons t e))
ht)))))
(define (median l)
(list-ref (sort l <) (quotient (length l) 2)))
(for/hasheq ([(k e) (in-hash all-times)]
#:unless (or (eq? k 'nothing)
(eq? k 'hello)))
(values k (median e))))
(define (rename k)
(hash-ref #hasheq((mandelbrot-generic . mandelbrot-g)
(reversecomplement . reversecomp)
(spectralnorm-generic . spectralnorm-g)
(nbody-vec-generic . nbody-vec-g)
(cheapconcurrency . cheapconcur))
k
k))
(define r5rs-color "forestgreen")
(define r5rs-keys
'(conform destruct dynamic lattice maze peval psyntax scheme-c scheme-i scheme sort1))
(define (r5rs? key) (memq key r5rs-keys))
(define (plot names colors timess
#:t t #:tt tt #:gap-size gap-size
#:bar-t [bar-t t]
#:columns [columns 2]
#:width [W 200]
#:bar-sep [bar-sep 0]
#:bar-text-scale [bar-text-scale 0.5]
#:normalize-max? [normalize-max? #f]
#:pin-max? [pin-max? #f]
#:max [starting-max 0]
#:sort-ratio [sort-ratio #f]
#:key->pict [key->pict (lambda (k) #f)]
#:reverse? [reverse? #f]
#:ghost-label [ghost-label #f]
#:details [details (map (lambda (v) #hasheq()) timess)]
#:detail-spec [detail-spec #f]
#:display-scale [display-scale 1]
#:decimal-places [decimal-places 0]
#:vertical-bars? [vertical-bars? #f]
#:fill-vertical? [fill-vertical? #f]
#:widen? [widen? vertical-bars?]
#:pad-left [pad-left 0]
#:prefix [prefix ""]
#:suffix [suffix ""]
#:notes [notes #f])
(define H (* 2 bar-text-scale (if vertical-bars? 70 30)))
(define keys ((if reverse? reverse values)
(sort (hash-keys (car timess))
(lambda (a b)
(cond
[(and (r5rs? a) (not (r5rs? b))) #f]
[(and (r5rs? b) (not (r5rs? a))) #t]
[sort-ratio
(define (ratio a)
(/ (hash-ref (list-ref timess (car sort-ratio)) a)
(hash-ref (list-ref timess (cdr sort-ratio)) a)))
(< (ratio a) (ratio b))]
[else (symbol<? a b)])))))
(define base-max (if normalize-max?
(for*/fold ([mx starting-max]) ([times (in-list timess)]
[t (in-hash-values times)])
(max mx t))
starting-max))
(define (overlay-detail bar total detail key)
(cond
[(not detail-spec) bar]
[else
(let loop ([bar bar] [delta 0] [spec detail-spec])
(cond
[(null? spec) bar]
[else
(define t (hash-ref (hash-ref detail key) (caar spec) 0))
(define dbar (colorize (if vertical-bars?
(filled-rectangle H
(* (pict-height bar) (/ t total)))
(filled-rectangle (* (pict-width bar) (/ t total))
H))
(cdar spec)))
(loop (if vertical-bars?
(lb-superimpose bar
(inset dbar 0 0 0 delta))
(rb-superimpose bar
(inset dbar 0 0 delta 0)))
(+ delta (if vertical-bars? (pict-height dbar) (pict-width dbar)))
(cdr spec))]))]))
(define (widen p) (if widen?
(let ([a (* 2/3 (pict-width p))])
(inset p (+ a pad-left) 0 a 0))
(if pad-left
(inset p pad-left 0 0 0)
p)))
(define plots (for/list ([key (in-list keys)])
(define max-time (if pin-max?
base-max
(for/fold ([mx base-max]) ([times (in-list timess)])
(max mx (hash-ref times key)))))
(vl-append
2
(or (key->pict key)
(let ([p (tt (symbol->string key))])
(if (r5rs? key)
(colorize p r5rs-color)
p)))
(widen
(apply
(if vertical-bars? hb-append vr-append)
bar-sep
(for/list ([name (in-list names)]
[color (in-list colors)]
[times (in-list timess)]
[detail (in-list details)]
[note (in-list (or notes (map (lambda (n) #f) names)))])
(define time (hash-ref times key))
((if vertical-bars? (lambda (sep a b) (vc-append sep b a)) hc-append)
5
(let ([l (colorize name color)])
(let ([p (if ghost-label
(if vertical-bars?
(ctl-superimpose l (ghost ghost-label))
(rtl-superimpose l (ghost ghost-label)))
l)])
(if vertical-bars?
(let ([p2 (scale p (min 1 (/ H (pict-width p))))])
(cc-superimpose p2 (blank 0 (pict-height p))))
p)))
(let ([lbl (scale (let ([tp (t (format "~a~a~a"
prefix
(~r (* time display-scale) #:precision decimal-places)
suffix))])
tp)
0.5)]
[bar (let ([bar (overlay-detail
(colorize (if vertical-bars?
(filled-rectangle H (* W (/ time (max 1 max-time))))
(filled-rectangle (* W (/ time (max 1 max-time))) H))
color)
time detail key)])
(if (and pin-max? (time . > . max-time))
(if vertical-bars?
(inset bar 0 (- W (pict-height bar)) 0 0)
(inset bar 0 0 (- W (pict-width bar)) 0))
bar))])
(define (add-note bar note)
(if note
(refocus (hc-append 5
(lt-superimpose bar (blank W H))
(colorize (t note) color))
bar)
bar))
(define labelled-bar
((if vertical-bars? cb-superimpose lb-superimpose)
bar
(inset (colorize lbl "white")
4)))
((if vertical-bars? cb-superimpose lt-superimpose)
(pin-under (add-note (clip (refocus labelled-bar bar)) note)
lbl lt-find
(colorize lbl color))
(if vertical-bars?
(blank H (if fill-vertical? W 0))
(blank W H)))))))))))
(define (pad plots)
(append plots
(let ([n (remainder (length plots) columns)])
(if (zero? n)
null
(make-list (- columns n) (blank))))))
start R5RS on new row
(if (ormap r5rs? keys)
(let loop ([keys keys] [plots plots] [rev-plots '()])
(cond
[(r5rs? (car keys))
(append (pad (reverse rev-plots)) plots)]
[else (loop (cdr keys) (cdr plots) (cons (car plots) rev-plots))]))
plots))
(table columns
(pad spaced-plots)
cc-superimpose cc-superimpose
(* 2 gap-size) gap-size))
(define (single-plot label-str
#:t t #:tt tt #:it [it #f] #:gap-size gap-size
#:cs cs
#:r r
#:r-cify [r-cify #f]
#:r6 [r6 #f]
#:r-all [r-all #f]
#:r-jit [r-jit #f]
#:max max
#:display-scale [display-scale 1]
#:suffix [suffix ""]
#:vertical-bars? [vertical-bars? #f]
#:fill-vertical? [fill-vertical? #t]
#:widen? [widen? vertical-bars?]
#:width [width 200]
#:pad-left [pad-left 0]
#:label [label #f]
#:desc [desc ""]
#:desc-indest [desc-inset 0]
#:decimal-places [decimal-places 0])
(define key (string->symbol label-str))
(define (mk n) (if n (list (hash key n)) null))
(define (add-desc desc p)
(rt-superimpose
(hbl-append (scale ((or it t) desc) 0.75) (t ""))
(inset p desc-inset 0)))
(define bar-sep (* (/ 5 24) gap-size))
(add-desc
desc
(plot #:t t #:tt tt #:gap-size gap-size #:bar-sep bar-sep
#:normalize-max? #t
#:max max
#:columns 1
#:width width
#:display-scale display-scale
#:suffix suffix
#:vertical-bars? vertical-bars?
#:fill-vertical? fill-vertical?
#:widen? widen?
#:pad-left pad-left
#:key->pict (lambda (k) label)
#:decimal-places decimal-places
(append
(list (t "R/CS") (t "R"))
(if r-cify (list (t "R/cify")) null)
(if r6 (list (t "Rv6")) null)
(if r-all (list (t "R -d")) null)
(if r-jit (list (t "R/JIT!")) null))
(append
(list racket-color c-color)
(if r-cify (list plain-c-color) null)
(if r6 (list r6-color) null)
(if r-all (list r-jit-color) null)
(if r-jit (list r-jit-color) null))
(append
(list (hash key cs)
(hash key r))
(mk r-cify)
(mk r6)
(mk r-all)
(mk r-jit)))))
| null | https://raw.githubusercontent.com/racket/racket-lang-org/88dada2ee769ada9afaf1e3ec1fb28b8ddf216db/blog/_src/posts/racket-status-jan2021/plot.rkt | racket | #lang racket/base
(require pict
racket/list
racket/format
"color.rkt")
(provide plot
single-plot
get-times
r5rs-color
r5rs?)
(define (get-times f)
(define all-times
(call-with-input-file*
f
(lambda (i)
(for/fold ([ht '#hasheq()]) ([i (in-port read i)])
(define k (rename (cadr i)))
(define t (caaddr i))
(define e (hash-ref ht k null))
(if t
(hash-set ht k (cons t e))
ht)))))
(define (median l)
(list-ref (sort l <) (quotient (length l) 2)))
(for/hasheq ([(k e) (in-hash all-times)]
#:unless (or (eq? k 'nothing)
(eq? k 'hello)))
(values k (median e))))
(define (rename k)
(hash-ref #hasheq((mandelbrot-generic . mandelbrot-g)
(reversecomplement . reversecomp)
(spectralnorm-generic . spectralnorm-g)
(nbody-vec-generic . nbody-vec-g)
(cheapconcurrency . cheapconcur))
k
k))
(define r5rs-color "forestgreen")
(define r5rs-keys
'(conform destruct dynamic lattice maze peval psyntax scheme-c scheme-i scheme sort1))
(define (r5rs? key) (memq key r5rs-keys))
(define (plot names colors timess
#:t t #:tt tt #:gap-size gap-size
#:bar-t [bar-t t]
#:columns [columns 2]
#:width [W 200]
#:bar-sep [bar-sep 0]
#:bar-text-scale [bar-text-scale 0.5]
#:normalize-max? [normalize-max? #f]
#:pin-max? [pin-max? #f]
#:max [starting-max 0]
#:sort-ratio [sort-ratio #f]
#:key->pict [key->pict (lambda (k) #f)]
#:reverse? [reverse? #f]
#:ghost-label [ghost-label #f]
#:details [details (map (lambda (v) #hasheq()) timess)]
#:detail-spec [detail-spec #f]
#:display-scale [display-scale 1]
#:decimal-places [decimal-places 0]
#:vertical-bars? [vertical-bars? #f]
#:fill-vertical? [fill-vertical? #f]
#:widen? [widen? vertical-bars?]
#:pad-left [pad-left 0]
#:prefix [prefix ""]
#:suffix [suffix ""]
#:notes [notes #f])
(define H (* 2 bar-text-scale (if vertical-bars? 70 30)))
(define keys ((if reverse? reverse values)
(sort (hash-keys (car timess))
(lambda (a b)
(cond
[(and (r5rs? a) (not (r5rs? b))) #f]
[(and (r5rs? b) (not (r5rs? a))) #t]
[sort-ratio
(define (ratio a)
(/ (hash-ref (list-ref timess (car sort-ratio)) a)
(hash-ref (list-ref timess (cdr sort-ratio)) a)))
(< (ratio a) (ratio b))]
[else (symbol<? a b)])))))
(define base-max (if normalize-max?
(for*/fold ([mx starting-max]) ([times (in-list timess)]
[t (in-hash-values times)])
(max mx t))
starting-max))
(define (overlay-detail bar total detail key)
(cond
[(not detail-spec) bar]
[else
(let loop ([bar bar] [delta 0] [spec detail-spec])
(cond
[(null? spec) bar]
[else
(define t (hash-ref (hash-ref detail key) (caar spec) 0))
(define dbar (colorize (if vertical-bars?
(filled-rectangle H
(* (pict-height bar) (/ t total)))
(filled-rectangle (* (pict-width bar) (/ t total))
H))
(cdar spec)))
(loop (if vertical-bars?
(lb-superimpose bar
(inset dbar 0 0 0 delta))
(rb-superimpose bar
(inset dbar 0 0 delta 0)))
(+ delta (if vertical-bars? (pict-height dbar) (pict-width dbar)))
(cdr spec))]))]))
(define (widen p) (if widen?
(let ([a (* 2/3 (pict-width p))])
(inset p (+ a pad-left) 0 a 0))
(if pad-left
(inset p pad-left 0 0 0)
p)))
(define plots (for/list ([key (in-list keys)])
(define max-time (if pin-max?
base-max
(for/fold ([mx base-max]) ([times (in-list timess)])
(max mx (hash-ref times key)))))
(vl-append
2
(or (key->pict key)
(let ([p (tt (symbol->string key))])
(if (r5rs? key)
(colorize p r5rs-color)
p)))
(widen
(apply
(if vertical-bars? hb-append vr-append)
bar-sep
(for/list ([name (in-list names)]
[color (in-list colors)]
[times (in-list timess)]
[detail (in-list details)]
[note (in-list (or notes (map (lambda (n) #f) names)))])
(define time (hash-ref times key))
((if vertical-bars? (lambda (sep a b) (vc-append sep b a)) hc-append)
5
(let ([l (colorize name color)])
(let ([p (if ghost-label
(if vertical-bars?
(ctl-superimpose l (ghost ghost-label))
(rtl-superimpose l (ghost ghost-label)))
l)])
(if vertical-bars?
(let ([p2 (scale p (min 1 (/ H (pict-width p))))])
(cc-superimpose p2 (blank 0 (pict-height p))))
p)))
(let ([lbl (scale (let ([tp (t (format "~a~a~a"
prefix
(~r (* time display-scale) #:precision decimal-places)
suffix))])
tp)
0.5)]
[bar (let ([bar (overlay-detail
(colorize (if vertical-bars?
(filled-rectangle H (* W (/ time (max 1 max-time))))
(filled-rectangle (* W (/ time (max 1 max-time))) H))
color)
time detail key)])
(if (and pin-max? (time . > . max-time))
(if vertical-bars?
(inset bar 0 (- W (pict-height bar)) 0 0)
(inset bar 0 0 (- W (pict-width bar)) 0))
bar))])
(define (add-note bar note)
(if note
(refocus (hc-append 5
(lt-superimpose bar (blank W H))
(colorize (t note) color))
bar)
bar))
(define labelled-bar
((if vertical-bars? cb-superimpose lb-superimpose)
bar
(inset (colorize lbl "white")
4)))
((if vertical-bars? cb-superimpose lt-superimpose)
(pin-under (add-note (clip (refocus labelled-bar bar)) note)
lbl lt-find
(colorize lbl color))
(if vertical-bars?
(blank H (if fill-vertical? W 0))
(blank W H)))))))))))
(define (pad plots)
(append plots
(let ([n (remainder (length plots) columns)])
(if (zero? n)
null
(make-list (- columns n) (blank))))))
start R5RS on new row
(if (ormap r5rs? keys)
(let loop ([keys keys] [plots plots] [rev-plots '()])
(cond
[(r5rs? (car keys))
(append (pad (reverse rev-plots)) plots)]
[else (loop (cdr keys) (cdr plots) (cons (car plots) rev-plots))]))
plots))
(table columns
(pad spaced-plots)
cc-superimpose cc-superimpose
(* 2 gap-size) gap-size))
(define (single-plot label-str
#:t t #:tt tt #:it [it #f] #:gap-size gap-size
#:cs cs
#:r r
#:r-cify [r-cify #f]
#:r6 [r6 #f]
#:r-all [r-all #f]
#:r-jit [r-jit #f]
#:max max
#:display-scale [display-scale 1]
#:suffix [suffix ""]
#:vertical-bars? [vertical-bars? #f]
#:fill-vertical? [fill-vertical? #t]
#:widen? [widen? vertical-bars?]
#:width [width 200]
#:pad-left [pad-left 0]
#:label [label #f]
#:desc [desc ""]
#:desc-indest [desc-inset 0]
#:decimal-places [decimal-places 0])
(define key (string->symbol label-str))
(define (mk n) (if n (list (hash key n)) null))
(define (add-desc desc p)
(rt-superimpose
(hbl-append (scale ((or it t) desc) 0.75) (t ""))
(inset p desc-inset 0)))
(define bar-sep (* (/ 5 24) gap-size))
(add-desc
desc
(plot #:t t #:tt tt #:gap-size gap-size #:bar-sep bar-sep
#:normalize-max? #t
#:max max
#:columns 1
#:width width
#:display-scale display-scale
#:suffix suffix
#:vertical-bars? vertical-bars?
#:fill-vertical? fill-vertical?
#:widen? widen?
#:pad-left pad-left
#:key->pict (lambda (k) label)
#:decimal-places decimal-places
(append
(list (t "R/CS") (t "R"))
(if r-cify (list (t "R/cify")) null)
(if r6 (list (t "Rv6")) null)
(if r-all (list (t "R -d")) null)
(if r-jit (list (t "R/JIT!")) null))
(append
(list racket-color c-color)
(if r-cify (list plain-c-color) null)
(if r6 (list r6-color) null)
(if r-all (list r-jit-color) null)
(if r-jit (list r-jit-color) null))
(append
(list (hash key cs)
(hash key r))
(mk r-cify)
(mk r6)
(mk r-all)
(mk r-jit)))))
|
|
3998145ed41d6745b03c8306a77c9d411b1fcc97eb901cb69278818188d80cdd | jwiegley/linearscan-hoopl | BranchAlloc.hs | module Programs.BranchAlloc where
import Assembly
import LinearScan.Hoopl.DSL
branchAlloc :: Program (Node IRVar)
branchAlloc = do
label "entry" $ do
branch v55 "L39" "L111"
label "L111" $ do
jump "L19"
label "L19" $ do
lc v0
branch v6 "L49" "L32"
label "L32" $ do
branch v68 "L10" "L93"
label "L93" $ do
copy v33 v14
call 33
branch v36 "L11" "L9"
label "L9" $ do
lc v88
branch v80 "L98" "L110"
label "L110" $ do
jump "L19"
label "L10" $ do
lc v79
offp v56 v26 v99
offlpi v45
move v40 v75
nop
copy v73 v60
copy v87 v6
call 35
nop
offlpi v35
lc v59
move v32 v58
move v18 v25
move v53 v53
add v30 v80 v64
move v36 v62
move v72 v16
call 81
alloc (Just v5) v91
branch v45 "L40" "L21"
label "L40" $ do
branch v78 "L109" "L99"
label "L109" $ do
jump "L100"
label "L100" $ do
call 54
move v54 v72
add v90 v90 v81
branch v73 "L77" "L88"
label "L88" $ do
call 9
branch v35 "L108" "L37"
label "L37" $ do
lc v5
call 48
copy v6 v18
add v11 v93 v99
lc v10
branch v7 "L44" "L80"
label "L44" $ do
copy v35 v24
branch v91 "L67" "L58"
label "L58" $ do
add v26 v97 v25
copy v7 v32
branch v85 "L106" "L45"
label "L45" $ do
move v94 v55
add v25 v26 v68
nop
move v1 v54
move v70 v78
lc v98
call 90
lc v22
move v5 v43
branch v39 "L57" "L16"
label "L16" $ do
move v52 v99
jump "L50"
label "L50" $ do
move v81 v100
branch v31 "L54" "L105"
label "L105" $ do
jump "L38"
label "L38" $ do
add v49 v12 v31
branch v52 "L104" "L103"
label "L103" $ do
jump "L53"
label "L104" $ do
jump "L38"
label "L106" $ do
jump "L100"
label "L39" $ do
branch v92 "L4" "L101"
label "L101" $ do
jump "L53"
label "L53" $ do
jump "L53"
label "L4" $ do
copy v58 v16
move v45 v96
return_
label "L54" $ do
copy v88 v65
add v40 v71 v58
copy v39 v59
offp v69 v46 v51
offp v1 v12 v46
call 82
return_
label "L57" $ do
move v15 v32
offp v21 v43 v57
lc v5
branch v83 "L102" "L46"
label "L46" $ do
add v23 v44 v84
move v88 v37
move v74 v96
copy v29 v31
alloc Nothing v60
add v87 v20 v34
move v98 v68
move v52 v82
copy v70 pr11
copy v22 v95
move v67 v22
lc v71
add v50 v77 v43
nop
move v28 v58
move v24 v44
nop
nop
lc v33
offlpi v80
copy v92 v1
copy v72 v16
lc v33
lc v5
lc v6
return_
label "L102" $ do
jump "L62"
label "L67" $ do
move v17 v19
add v96 v67 v48
add v72 v58 v21
call 75
move v67 v82
move v0 v43
lc v10
move v37 v10
move v41 v39
offp v20 v58 v17
copy v100 v74
move v36 v93
return_
label "L80" $ do
call 38
lc v54
lc v97
call 29
call 20
move v62 v9
call 100
lc v79
nop
add v53 v1 v75
move v43 v56
offlpi v67
add v33 v62 v19
copy v12 v26
move v9 v36
offp v100 v82 v99
jump "L82"
label "L82" $ do
move v41 v100
add v34 pr19 v37
branch v84 "L85" "L107"
label "L107" $ do
jump "L60"
label "L85" $ do
move v87 v7
offlpi v8
jump "L62"
label "L62" $ do
move v2 v100
offp v79 v71 v54
call 34
jump "L78"
label "L78" $ do
copy v96 v46
return_
label "L108" $ do
jump "L60"
label "L77" $ do
add v39 v82 v37
move v60 v80
return_
label "L99" $ do
add v87 v36 v77
lc v97
lc v89
copy v16 v37
add v4 v73 v8
add v83 v48 v59
copy v24 v63
return_
label "L21" $ do
alloc (Just v61) v42
move v82 v58
copy v62 v16
nop
move v0 v39
move v92 v82
move v54 v0
move v58 v37
add v68 v40 v20
add v72 v26 v76
lc v98
lc v18
call 48
move v38 v35
jump "L60"
label "L60" $ do
lc v92
move v1 v64
copy pr31 v15
return_
label "L98" $ do
move pr21 v90
return_
label "L11" $ do
jump "L86"
label "L86" $ do
add v51 v51 v28
lc v9
return_
label "L49" $ do
copy v56 v81
move v19 v57
call 46
offlpi v19
branch v15 "L71" "L31"
label "L31" $ do
lc v19
call 38
branch v87 "L59" "L30"
label "L30" $ do
move v1 v28
return_
label "L59" $ do
move v14 v63
move v33 v23
alloc Nothing v19
copy v81 v28
return_
label "L71" $ do
lc v38
call 76
return_
| null | https://raw.githubusercontent.com/jwiegley/linearscan-hoopl/f654adf64cba4b3af1f42f06112c9225b1369c74/test/Programs/BranchAlloc.hs | haskell | module Programs.BranchAlloc where
import Assembly
import LinearScan.Hoopl.DSL
branchAlloc :: Program (Node IRVar)
branchAlloc = do
label "entry" $ do
branch v55 "L39" "L111"
label "L111" $ do
jump "L19"
label "L19" $ do
lc v0
branch v6 "L49" "L32"
label "L32" $ do
branch v68 "L10" "L93"
label "L93" $ do
copy v33 v14
call 33
branch v36 "L11" "L9"
label "L9" $ do
lc v88
branch v80 "L98" "L110"
label "L110" $ do
jump "L19"
label "L10" $ do
lc v79
offp v56 v26 v99
offlpi v45
move v40 v75
nop
copy v73 v60
copy v87 v6
call 35
nop
offlpi v35
lc v59
move v32 v58
move v18 v25
move v53 v53
add v30 v80 v64
move v36 v62
move v72 v16
call 81
alloc (Just v5) v91
branch v45 "L40" "L21"
label "L40" $ do
branch v78 "L109" "L99"
label "L109" $ do
jump "L100"
label "L100" $ do
call 54
move v54 v72
add v90 v90 v81
branch v73 "L77" "L88"
label "L88" $ do
call 9
branch v35 "L108" "L37"
label "L37" $ do
lc v5
call 48
copy v6 v18
add v11 v93 v99
lc v10
branch v7 "L44" "L80"
label "L44" $ do
copy v35 v24
branch v91 "L67" "L58"
label "L58" $ do
add v26 v97 v25
copy v7 v32
branch v85 "L106" "L45"
label "L45" $ do
move v94 v55
add v25 v26 v68
nop
move v1 v54
move v70 v78
lc v98
call 90
lc v22
move v5 v43
branch v39 "L57" "L16"
label "L16" $ do
move v52 v99
jump "L50"
label "L50" $ do
move v81 v100
branch v31 "L54" "L105"
label "L105" $ do
jump "L38"
label "L38" $ do
add v49 v12 v31
branch v52 "L104" "L103"
label "L103" $ do
jump "L53"
label "L104" $ do
jump "L38"
label "L106" $ do
jump "L100"
label "L39" $ do
branch v92 "L4" "L101"
label "L101" $ do
jump "L53"
label "L53" $ do
jump "L53"
label "L4" $ do
copy v58 v16
move v45 v96
return_
label "L54" $ do
copy v88 v65
add v40 v71 v58
copy v39 v59
offp v69 v46 v51
offp v1 v12 v46
call 82
return_
label "L57" $ do
move v15 v32
offp v21 v43 v57
lc v5
branch v83 "L102" "L46"
label "L46" $ do
add v23 v44 v84
move v88 v37
move v74 v96
copy v29 v31
alloc Nothing v60
add v87 v20 v34
move v98 v68
move v52 v82
copy v70 pr11
copy v22 v95
move v67 v22
lc v71
add v50 v77 v43
nop
move v28 v58
move v24 v44
nop
nop
lc v33
offlpi v80
copy v92 v1
copy v72 v16
lc v33
lc v5
lc v6
return_
label "L102" $ do
jump "L62"
label "L67" $ do
move v17 v19
add v96 v67 v48
add v72 v58 v21
call 75
move v67 v82
move v0 v43
lc v10
move v37 v10
move v41 v39
offp v20 v58 v17
copy v100 v74
move v36 v93
return_
label "L80" $ do
call 38
lc v54
lc v97
call 29
call 20
move v62 v9
call 100
lc v79
nop
add v53 v1 v75
move v43 v56
offlpi v67
add v33 v62 v19
copy v12 v26
move v9 v36
offp v100 v82 v99
jump "L82"
label "L82" $ do
move v41 v100
add v34 pr19 v37
branch v84 "L85" "L107"
label "L107" $ do
jump "L60"
label "L85" $ do
move v87 v7
offlpi v8
jump "L62"
label "L62" $ do
move v2 v100
offp v79 v71 v54
call 34
jump "L78"
label "L78" $ do
copy v96 v46
return_
label "L108" $ do
jump "L60"
label "L77" $ do
add v39 v82 v37
move v60 v80
return_
label "L99" $ do
add v87 v36 v77
lc v97
lc v89
copy v16 v37
add v4 v73 v8
add v83 v48 v59
copy v24 v63
return_
label "L21" $ do
alloc (Just v61) v42
move v82 v58
copy v62 v16
nop
move v0 v39
move v92 v82
move v54 v0
move v58 v37
add v68 v40 v20
add v72 v26 v76
lc v98
lc v18
call 48
move v38 v35
jump "L60"
label "L60" $ do
lc v92
move v1 v64
copy pr31 v15
return_
label "L98" $ do
move pr21 v90
return_
label "L11" $ do
jump "L86"
label "L86" $ do
add v51 v51 v28
lc v9
return_
label "L49" $ do
copy v56 v81
move v19 v57
call 46
offlpi v19
branch v15 "L71" "L31"
label "L31" $ do
lc v19
call 38
branch v87 "L59" "L30"
label "L30" $ do
move v1 v28
return_
label "L59" $ do
move v14 v63
move v33 v23
alloc Nothing v19
copy v81 v28
return_
label "L71" $ do
lc v38
call 76
return_
|