_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 |
|---|---|---|---|---|---|---|---|---|
65961d59c2d6daabdb3a4ed1a4011fd966426a67b32ea22fbd81e158949ba972 | CloudI/cloudi_core | cloudi_core_i_services_internal_init.erl | -*-Mode : erlang;coding : utf-8;tab - width:4;c - basic - offset:4;indent - tabs - mode:()-*-
ex : set utf-8 sts=4 ts=4 sw=4 et nomod :
%%%
%%%------------------------------------------------------------------------
%%% @doc
= = CloudI Internal Service Init Process==
A separate Erlang process that exists as a Dispatcher proxy . Using this
Erlang process as a type of bootstrap process prevents a deadlock on the
%%% Dispatcher process while still allowing the internal service init function
call to occur within the Dispatcher process .
%%% @end
%%%
MIT License
%%%
Copyright ( c ) 2013 - 2020 < mjtruog at protonmail dot com >
%%%
%%% 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.
%%%
@author < mjtruog at protonmail dot com >
2013 - 2020
%%% @version 2.0.1 {@date} {@time}
%%%------------------------------------------------------------------------
-module(cloudi_core_i_services_internal_init).
-author('mjtruog at protonmail dot com').
-behaviour(gen_server).
%% external interface
-export([start_link/4,
stop_link/1,
process_dictionary_get/0,
process_dictionary_set/1]).
%% gen_server callbacks
-export([init/1,
handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-record(state,
{
service_state :: any(),
init_timeout :: undefined | reference()
}).
-include("cloudi_logger.hrl").
-include("cloudi_core_i_constants.hrl").
-include("cloudi_core_i_services_common_init.hrl").
%%%------------------------------------------------------------------------
%%% External interface functions
%%%------------------------------------------------------------------------
start_link(Timeout, PidOptions, ProcessDictionary, InternalState) ->
gen_server:start_link(?MODULE,
[Timeout, PidOptions,
ProcessDictionary, InternalState],
[{timeout, Timeout},
{spawn_opt,
spawn_opt_options_before(PidOptions)}]).
stop_link(Pid) ->
gen_server:call(Pid, stop, infinity).
process_dictionary_get() ->
erlang:get().
process_dictionary_set(ProcessDictionary) ->
_ = erlang:erase(),
lists:foreach(fun({K, V}) ->
erlang:put(K, V)
end, ProcessDictionary),
ok.
%%%------------------------------------------------------------------------
%%% Callback functions from gen_server
%%%------------------------------------------------------------------------
init([Timeout, PidOptions, ProcessDictionary, InternalState]) ->
ok = spawn_opt_options_after(PidOptions),
InitTimeout = erlang:send_after(Timeout, self(),
'cloudi_service_init_timeout'),
lists:foreach(fun({K, V}) ->
erlang:put(K, V)
end, ProcessDictionary),
{ok, #state{service_state = InternalState,
init_timeout = InitTimeout}}.
handle_call(stop, {Pid, _}, #state{service_state = InternalState,
init_timeout = InitTimeout} = State) ->
ok = cancel_timer_async(InitTimeout),
Result = {erlang:get(), InternalState},
NewState = State#state{service_state = undefined,
init_timeout = undefined},
erlang:unlink(Pid),
{stop, normal, Result, NewState};
handle_call(Request, _, State)
when is_tuple(Request),
(element(1, Request) =:= 'send_sync' orelse
element(1, Request) =:= 'recv_async' orelse
element(1, Request) =:= 'recv_asyncs') ->
% service request responses are always handled after initialization
% is successful though it is possible for the
% service request response to be received before initialization
% is complete (the response remains queued)
{stop, {error, invalid_state}, State};
handle_call(Request, From, #state{service_state = InternalState} = State) ->
case cloudi_core_i_services_internal:
handle_call(Request, From, InternalState) of
{reply, Reply, NewInternalState} ->
{reply, Reply,
State#state{service_state = NewInternalState}};
{reply, Reply, NewInternalState, Timeout} ->
{reply, Reply,
State#state{service_state = NewInternalState}, Timeout};
{noreply, NewInternalState} ->
{noreply,
State#state{service_state = NewInternalState}};
{noreply, NewInternalState, Timeout} ->
{noreply,
State#state{service_state = NewInternalState}, Timeout};
{stop, Reason, Reply, NewInternalState} ->
{stop, Reason, Reply,
State#state{service_state = NewInternalState}}%;
{ stop , , NewInternalState } - >
{ stop , ,
% State#state{service_state = NewInternalState}}
end.
handle_cast(Request, #state{service_state = InternalState} = State) ->
case cloudi_core_i_services_internal:
handle_cast(Request, InternalState) of
{ noreply , NewInternalState } - >
{ noreply ,
% State#state{service_state = NewInternalState}};
{ noreply , NewInternalState , Timeout } - >
{ noreply ,
% State#state{service_state = NewInternalState}, Timeout};
{stop, Reason, NewInternalState} ->
{stop, Reason,
State#state{service_state = NewInternalState}}
end.
handle_info('cloudi_service_init_timeout', State) ->
{stop, timeout, State#state{init_timeout = undefined}};
handle_info(Request, #state{service_state = InternalState} = State) ->
case cloudi_core_i_services_internal:
handle_info(Request, InternalState) of
{noreply, NewInternalState} ->
{noreply,
State#state{service_state = NewInternalState}};
{noreply, NewInternalState, Timeout} ->
{noreply,
State#state{service_state = NewInternalState}, Timeout};
{stop, Reason, NewInternalState} ->
{stop, Reason,
State#state{service_state = NewInternalState}}
end.
terminate(_, _) ->
ok.
code_change(_, State, _) ->
{ok, State}.
%%%------------------------------------------------------------------------
%%% Private functions
%%%------------------------------------------------------------------------
| null | https://raw.githubusercontent.com/CloudI/cloudi_core/1b6c6d2aeb3565a7fd2265185a892b20b8aeccec/src/cloudi_core_i_services_internal_init.erl | erlang |
------------------------------------------------------------------------
@doc
Dispatcher process while still allowing the internal service init function
@end
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.
@version 2.0.1 {@date} {@time}
------------------------------------------------------------------------
external interface
gen_server callbacks
------------------------------------------------------------------------
External interface functions
------------------------------------------------------------------------
------------------------------------------------------------------------
Callback functions from gen_server
------------------------------------------------------------------------
service request responses are always handled after initialization
is successful though it is possible for the
service request response to be received before initialization
is complete (the response remains queued)
;
State#state{service_state = NewInternalState}}
State#state{service_state = NewInternalState}};
State#state{service_state = NewInternalState}, Timeout};
------------------------------------------------------------------------
Private functions
------------------------------------------------------------------------ | -*-Mode : erlang;coding : utf-8;tab - width:4;c - basic - offset:4;indent - tabs - mode:()-*-
ex : set utf-8 sts=4 ts=4 sw=4 et nomod :
= = CloudI Internal Service Init Process==
A separate Erlang process that exists as a Dispatcher proxy . Using this
Erlang process as a type of bootstrap process prevents a deadlock on the
call to occur within the Dispatcher process .
MIT License
Copyright ( c ) 2013 - 2020 < mjtruog at protonmail dot com >
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
@author < mjtruog at protonmail dot com >
2013 - 2020
-module(cloudi_core_i_services_internal_init).
-author('mjtruog at protonmail dot com').
-behaviour(gen_server).
-export([start_link/4,
stop_link/1,
process_dictionary_get/0,
process_dictionary_set/1]).
-export([init/1,
handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-record(state,
{
service_state :: any(),
init_timeout :: undefined | reference()
}).
-include("cloudi_logger.hrl").
-include("cloudi_core_i_constants.hrl").
-include("cloudi_core_i_services_common_init.hrl").
start_link(Timeout, PidOptions, ProcessDictionary, InternalState) ->
gen_server:start_link(?MODULE,
[Timeout, PidOptions,
ProcessDictionary, InternalState],
[{timeout, Timeout},
{spawn_opt,
spawn_opt_options_before(PidOptions)}]).
stop_link(Pid) ->
gen_server:call(Pid, stop, infinity).
process_dictionary_get() ->
erlang:get().
process_dictionary_set(ProcessDictionary) ->
_ = erlang:erase(),
lists:foreach(fun({K, V}) ->
erlang:put(K, V)
end, ProcessDictionary),
ok.
init([Timeout, PidOptions, ProcessDictionary, InternalState]) ->
ok = spawn_opt_options_after(PidOptions),
InitTimeout = erlang:send_after(Timeout, self(),
'cloudi_service_init_timeout'),
lists:foreach(fun({K, V}) ->
erlang:put(K, V)
end, ProcessDictionary),
{ok, #state{service_state = InternalState,
init_timeout = InitTimeout}}.
handle_call(stop, {Pid, _}, #state{service_state = InternalState,
init_timeout = InitTimeout} = State) ->
ok = cancel_timer_async(InitTimeout),
Result = {erlang:get(), InternalState},
NewState = State#state{service_state = undefined,
init_timeout = undefined},
erlang:unlink(Pid),
{stop, normal, Result, NewState};
handle_call(Request, _, State)
when is_tuple(Request),
(element(1, Request) =:= 'send_sync' orelse
element(1, Request) =:= 'recv_async' orelse
element(1, Request) =:= 'recv_asyncs') ->
{stop, {error, invalid_state}, State};
handle_call(Request, From, #state{service_state = InternalState} = State) ->
case cloudi_core_i_services_internal:
handle_call(Request, From, InternalState) of
{reply, Reply, NewInternalState} ->
{reply, Reply,
State#state{service_state = NewInternalState}};
{reply, Reply, NewInternalState, Timeout} ->
{reply, Reply,
State#state{service_state = NewInternalState}, Timeout};
{noreply, NewInternalState} ->
{noreply,
State#state{service_state = NewInternalState}};
{noreply, NewInternalState, Timeout} ->
{noreply,
State#state{service_state = NewInternalState}, Timeout};
{stop, Reason, Reply, NewInternalState} ->
{stop, Reason, Reply,
{ stop , , NewInternalState } - >
{ stop , ,
end.
handle_cast(Request, #state{service_state = InternalState} = State) ->
case cloudi_core_i_services_internal:
handle_cast(Request, InternalState) of
{ noreply , NewInternalState } - >
{ noreply ,
{ noreply , NewInternalState , Timeout } - >
{ noreply ,
{stop, Reason, NewInternalState} ->
{stop, Reason,
State#state{service_state = NewInternalState}}
end.
handle_info('cloudi_service_init_timeout', State) ->
{stop, timeout, State#state{init_timeout = undefined}};
handle_info(Request, #state{service_state = InternalState} = State) ->
case cloudi_core_i_services_internal:
handle_info(Request, InternalState) of
{noreply, NewInternalState} ->
{noreply,
State#state{service_state = NewInternalState}};
{noreply, NewInternalState, Timeout} ->
{noreply,
State#state{service_state = NewInternalState}, Timeout};
{stop, Reason, NewInternalState} ->
{stop, Reason,
State#state{service_state = NewInternalState}}
end.
terminate(_, _) ->
ok.
code_change(_, State, _) ->
{ok, State}.
|
11bf93c2e2a9d260e8728e6d48fc10af01486aa0c3ab2faeb44e3db8eab26855 | haroldcarr/learn-haskell-coq-ml-etc | Part4.hs | module Part4 where
-to-singletons-4.html
Introduction to Singletons ( Part 4 )
Monday October 22 , 2018
functional programming at the type level .
GHC 8.6.1
nightly-2018 - 09 - 29 ( singletons-2.5 )
Review
View full source
$ ( singletons [ d|
data DoorState = Opened | Closed | Locked
deriving ( Show , Eq , Ord )
| ] )
data Door : : DoorState - > Type where
UnsafeMkDoor : : { doorMaterial : : String } - > Door s
mkDoor : : Sing s - > String - > Door s
mkDoor _ = UnsafeMkDoor
And we talked about using Sing s , or SDoorState s , to represent the state of the door ( in its type ) as a run - time value . We ’ve been using a wrapper to existentially hide the door state type , but also stuffing in a singleton to let us recover the type information once we want it again :
data SomeDoor : : Type where
MkSomeDoor : : Sing s - > Door s - > SomeDoor
mkSomeDoor : : DoorState - > String - > SomeDoor
mkSomeDoor ds mat = withSomeSing ds $ \dsSing - >
MkSomeDoor dsSing ( mkDoor dsSing mat )
In Part 3 we talked about a Pass data type that we used to talk about whether or not we can walk through or knock on a door :
$ ( singletons [ d|
data Pass = Obstruct | Allow
deriving ( Show , Eq , Ord )
| ] )
And we defined type - level functions on it using singletons :
$ ( singletons [ d|
statePass : : DoorState - > Pass
statePass Opened = Allow
statePass Closed = Obstruct
statePass Locked = Obstruct
| ] )
This essentially generates these three things :
statePass : : DoorState - > Pass
statePass Opened = Allow
statePass Closed = Obstruct
statePass Locked = Obstruct
type family StatePass ( s : : DoorState ) : : Pass where
StatePass ' Opened = ' Allow
StatePass ' Closed = ' Obstruct
StatePass ' Locked = ' Obstruct
sStatePass : : Sing s - > Sing ( StatePass s )
sStatePass = \case
SOpened - > SAllow
SClosed - > SObstruct
SLocked - > SObstruct
And we can use StatePass as a type - level function while using sStatePass to manipulate the singletons representing s and StatePass s.
We used this as a constraint to restrict how we can call our functions :
View full source
knockP : : ( StatePass s ~ ' Obstruct ) = > Door s - > IO ( )
knockP d = " Knock knock on " + + doorMaterial d + + " door ! "
But then we wondered … is there a way to not only restrict our functions , but to describe how the inputs and outputs are related to each other ?
Inputs and Outputstop
In the past we have settled with very simple relationships , like :
closeDoor : : Door ' Opened - > Door ' Closed
This means that the relationship between the input and output is that the input is opened … and is then closed .
However , armed with promotion of type - level functions , writing more complex relationships becomes fairly straightforward !
We can write a function mergeDoor that “ merges ” two doors together , in sequence :
mergeDoor : : Door s - > Door t - > Door ? ? ? ?
mergeDoor d e = UnsafeMkDoor $ doorMaterial d + + " and " + + doorMaterial e
A merged door will have a material that is composite of the original materials . But , what will the new DoorState be ? What goes in the ? ? ? above ?
Well , if we can write the function as a normal function in values … singletons lets us use it as a function on types . Let ’s write that relationship . Let ’s say merging takes on the higher “ security ” option — merging opened with locked is locked , merging closed with opened is closed , merging locked with closed is locked .
$ ( singletons [ d|
mergeState : : DoorState - > DoorState - > DoorState
mergeState Opened d = d
mergeState Closed Opened = Closed
mergeState Closed Closed = Closed
mergeState Closed Locked = Locked
mergeState Locked _ = Locked
| ] )
-- Alternatively , taking advantage of the derived instance :
$ ( singletons [ d|
mergeState : : DoorState - > DoorState - > DoorState
mergeState = ] )
This makes writing mergeDoor ’s type clean to read :
View full source
mergeDoor
: : Door s
- > Door t
- > Door ( MergeState s t )
mergeDoor d e = UnsafeMkDoor $ doorMaterial d + + " and " + + doorMaterial e
And , with the help of singletons , we can also write this for our doors where we do n’t know the types until runtime :
View full source
mergeSomeDoor : : SomeDoor - > SomeDoor - > SomeDoor
mergeSomeDoor ( MkSomeDoor s d ) ( MkSomeDoor t e ) =
MkSomeDoor ( sMergeState s t ) ( mergeDoor d e )
To see why this typechecks properly , compare the types of sMergeState and mergeDoor :
sMergeState : : Sing s - > Sing t - > Sing ( MergeState s t )
mergeDoor : : Door s - > Door t - > Door ( MergeState s t )
MkSomeDoor : : Sing ( MergeState s t ) - > Door ( MergeState s t ) - > SomeDoor
Because the results both create types MergeState s t , MkSomeDoor is happy to apply them to each other , and everything typechecks . However , if , say , we directly stuffed s or t into MkSomeDoor , things would fall apart and not .
And so now we have full expressiveness in determining input and output relationships ! Once we unlock the power of type - level functions with singletons , writing type - level relationships become as simple as writing value - level ones . If you can write a value - level function , you can write a type - level function .
Kicking it up a notchtop
How far we can really take this ?
Let ’s make a data type that represents a series of hallways , each linked by a door . A hallway is either an empty stretch with no door , or two hallways linked by a door . We ’ll structure it like a linked list , and store the list of all door states as a type - level list as a type parameter :
View full source
data Hallway : : [ DoorState ] - > Type where
HEnd : : Hallway ' [ ] -- ^ end of the hallway , a stretch with no
-- doors
(: < # ) : : Door s
- > Hallway ss
- > Hallway ( s ' : ss ) -- ^ A door connected to a hallway is a new
-- hallway , and we track the door 's state
-- in the list of hallway door states
infixr 5 : < #
( If you need a refresher on type - level lists , check out the quick introduction in Part 1 and Exercise 4 in Part 2 )
So we might have :
ghci > let door1 = mkDoor SClosed " Oak "
ghci > let door2 = mkDoor SOpened " Spruce "
ghci > let = mkDoor SLocked " Acacia "
ghci > : t door1 : < # door2 : < # : < # HEnd
Hallway ' [ ' Closed , ' Opened , ' Locked ]
That is , a Hallway ' [ s , t , u ] is a hallway consisting of a Door s , a Door t , and a Door u , constructed like a linked list in Haskell .
Now , let ’s write a function to collapse all doors in a hallway down to a single door :
collapseHallway : : Hallway ss - > Door ? ? ? ? ?
Basically , we want to merge all of the doors one after the other , collapsing it until we have a single door state . Luckily , MergeState is both commutative and associative and has an identity , so this can be defined sensibly .
First , let ’s think about the type we want . What will the result of merging ss be ?
We can pattern match and collapse an entire list down item - by - item :
$ ( singletons [ d|
mergeStateList : : [ DoorState ] - > DoorState
mergeStateList [ ] = Opened -- ^ the identity of mergeState
mergeStateList ( s : ss ) = s ` mergeState ` mergeStateList ss
| ] )
Again , remember that this also defines the type family MergeStateList and the singleton function sMergeStateList : : Sing ss - > Sing ( MergeStateList ss ) .
With this , we can write collapseHallway :
View full source
collapseHallway : : Hallway ss - > Door ( MergeStateList ss )
collapseHallway HEnd = mkDoor SOpened " End of Hallway "
collapseHallway ( d : < # ds ) = d ` mergeDoor ` collapseHallway ds
Now , because the structure of collapseHallway perfectly mirrors the structure of mergeStateList , this all typechecks , and we ’re done !
ghci > collapseHallway ( door1 : < # door2 : < # : < # HEnd )
UnsafeMkDoor " Oak and Spruce and Acacia and End of Hallway "
: : Door ' Locked
Note one nice benefit – the door state of collapseHallway ( door1 : < # door2 : < # : < # HEnd ) is known at compile - time to be Door ' Locked , if the types of all of the component doors are also known !
Functional
We went over that all a bit fast , but some of you might have noticed that the definition of mergeStateList bears a really strong resemblance to a very common list processing pattern :
mergeStateList : : [ DoorState ] - > DoorState
mergeStateList [ ] = Opened -- ^ the identity of mergeState
mergeStateList ( s : ss ) = s ` mergeState ` mergeStateList ss
The algorithm is to basically [ ] with Opened , and all ( :) with mergeState . If this sounds familiar , that ’s because this is exactly a right fold ! ( In fact , hlint actually made this suggestion to me while I was writing this )
mergeStateList : : [ DoorState ] - > DoorState
mergeStateList = foldr mergeState Opened
In Haskell , we are always encouraged to use higher - order functions whenever possible instead of explicit recursion , both because explicit recursion opens you up to a lot of potential bugs , and also because using established higher - order functions make your code more readable .
So , as Haskellers , let us hold ourselves to a higher standard and not be satisfied with a MergeState written using explicit recursion . Let us instead go full fold — ONWARD HO !
The Problemtop
Initial attempts to write a higher - order type - level function as a type family , however , serve to temper our enthusiasm .
type family ( f : : j - > k - > k ) ( z : : k ) ( xs : : [ j ] ) : : k where
Foldr f z ' [ ] = z
Foldr f z ( x ' : xs ) = f x ( Foldr f z xs )
So far so good right ? So we should expect to be able to write MergeStateList using , MergeState , and ' Opened
type MergeStateList ss = Foldr MergeState ' Opened ss
Ah , but the compiler is here to tell you this is n’t allowed in :
• The type family ‘ MergeState ’ should have 2 arguments , but has been given none
• In the equations for closed type family ‘ MergeStateList ’
In the type family declaration for ‘ MergeStateList ’
What happened ? To figure out , we have to remember that pesky restriction on type synonyms and type families : they can not be used partially applied ( “ unsaturated ” ) , and must always be fully applied ( “ saturated ” ) . For the most part , only type constructors ( like Maybe , Either , IO ) and lifted DataKinds data constructors ( like ' Just , ' ( :) ) in Haskell can ever be partially applied at the type level . We therefore ca n’t use MergeState as an argument to , because MergeState must always be fully applied .
Unfortunately for us , this makes our effectively useless . That ’s because we ’re always going to want to pass in type families ( like MergeState ) , so there ’s pretty much literally no way to ever actually call except with type constructors or lifted DataKinds data constructors .
So … back to the drawing board ?
I like to mentally think of the singletons library as having two parts : the first is linking lifted DataKinds types with run - time values to allow us to manipulate types at runtime as first - class values . The second is a system for effective functional programming at the type level .
To make a working , we ’re going to have to jump into that second half : defunctionalization .
Defunctionalization is a technique invented in the early 70 ’s as a way of compiling higher - order functions into first - order functions in target languages . The main idea is :
Instead of working with functions , work with symbols representing functions .
Build your final functions and values by composing and combining these symbols .
At the end of it all , have a single Apply function interpret all of your symbols and produce the value you want .
In singletons these symbols are implemented as “ dummy ” empty data constructors , and Apply is a type family .
To help us understand ’s defunctionalization system better , let ’s build our own defunctionalization system from scratch .
First , a little trick to make things easier to read :
View full source
data TyFun a b
type a ~ > b = TyFun a b - > Type
infixr 0 ~ >
Our First Symbolstop
Now we can define a dummy data type like I d , which represents the identity function i d :
View full source
data I d : : a ~ > a
The “ actual ” kind of I d is I d : : TyFun a a - > Type ; you can imagine TyFun a a as a phantom parameter that signifies that I d represents a function from a to a. It ’s essentially a nice trick to allow you to write I d : : a ~ > a as a kind signature .
Now , I d is not a function … it ’s a dummy type constructor that represents a function a - > a. A type constructor of kind a ~ > a represents a defunctionalization symbol – a type constructor that represents a function from a to a.
To interpret it , we need to write our global interpreter function :
View full source
type family Apply ( f : : a ~ > b ) ( x : : a ) : : b
That ’s the syntax for the definition of an open type family in : users are free to add their own instances , just like how type classes are normally open in Haskell .
Let ’s tell Apply how to interpret I d :
View full source
type instance Apply I d x = x
The above is the actual function definition , like writing i d x = x. We can now call I d to get an actual type in return :
ghci > : kind ! Apply I d ' True
' True
( Remember , : kind ! is the ghci command to evaluate a type family )
Let ’s define another one ! We ’ll implement Not :
View full source
data Not : : Bool ~ > Bool
type instance Apply Not ' False = ' True
type instance Apply Not ' True = ' False
We can try it out :
ghci > : kind ! Apply Not ' True
' False
ghci > : kind ! Apply Not ' False
' True
It can be convenient to define an infix synonym for Apply :
View full source
type f @@ a = Apply f a
infixl 9 @@
Then we can write :
ghci > : kind ! Not @@ ' False
' True
ghci > : kind ! I d @@ ' True
' True
Remember , I d and Not are not actual functions — they ’re just dummy data types ( “ defunctionalization symbols ” ) , and we define the functions they represent through the global Apply type function .
A Bit of Principletop
So we ’ve got the basics of defunctionalization — instead of using functions directly , use dummy symbols that encode your functions that are interpreted using Apply . Let ’s add a bit of principle to make this all a bit more scalable .
The singletons library adopts a few conventions for linking all of these together . Using the Not function as an example , if we wanted to lift the function :
not : : Bool - > Bool
not False = True
not True = Flse
We already know about the type family and singleton function this would produce :
type family Not ( x : : ) : : where
Not ' False = ' True
Not ' True = ' False
sNot : : Sing x - > Sing ( Not x )
sNot SFalse = STrue
= SFalse
But the singletons library also produces the following defunctionalization symbols , according to a naming convention :
data NotSym0 : : Bool ~ > Bool
type instance Apply NotSym0 x = Not x
-- also generated for consistency
type x = Not x
NotSym0 is the defunctionalization symbol associated with the Not type family , defined so that NotSym0 = Not x. Its purpose is to allow us to pass in Not as an un - applied function . The Sym0 suffix is a naming convention , and the 0 stands for “ expects 0 arguments ” . Similarly for – the 1 stands for “ expects 1 argument ” .
Two - Argument Functionstop
Let ’s look at a slightly more complicated example – a two - argument function . Let ’s define the boolean “ and ” :
$ ( singletons [ d|
and : : Bool - > ( Bool - > Bool )
and False _ = False
and True x = x
] )
this will generate :
type family And ( x : : ) ( y : : ) : : where
And ' False x = ' False
And ' True x = x
: : Sing x - > Sing y - > Sing ( And x y )
= SFalse
= x
And the defunctionalization symbols :
data AndSym0 : : Bool ~ > ( Bool ~ > Bool )
type instance Apply AndSym0 x = AndSym1 x
data AndSym1 ( x : : ) : : ( Bool ~ > Bool )
-- or
data AndSym1 : : Bool - > ( Bool ~ > Bool )
type instance Apply ( AndSym1 x ) y = And x y
type AndSym2 x y = And x y
AndSym0 is a defunctionalization symbol representing a “ fully unapplied ” ( “ completely unsaturated ” ) version of And . AndSym1 x is a defunctionalization symbol representing a “ partially applied ” version of And — partially applied to x ( its kind is AndSym1 : : Bool - > ( Bool ~ > ) ) .
The application of AndSym0 to x gives you AndSym1 x :
ghci > : kind ! AndSym0 @@ ' False
AndSym1 ' False
Remember its kind AndSym0 : : Bool ~ > ( Bool ~ > ) ( or just AndSym0 : : Bool ~ > Bool ~ > ): it takes a Bool , and returns a Bool ~ > Bool defunctionalization symbol .
The application of AndSym1 x to y gives you And x y :
ghci > : kind ! AndSym1 ' False @@ ' True
' False -- or FalseSym0 , which is a synonym for ' False
ghci > : kind ! AndSym1 ' True @@ ' True
' True
A note to remember : AndSym1 ' True is the defunctionalization symbol , and not AndSym1 itself . AndSym1 has kind Bool - > ( Bool ~ > ) , but AndSym1 ' True has kind Bool ~ > — the kind of a defunctionalization symbol . AndSym1 is a sort of “ defunctionalization symbol constructor ” .
Also note here that we encounter the fact that singletons also provides “ defunctionalization symbols ” for “ nullary ” type functions like False and True , where :
type FalseSym0 = ' False
type TrueSym0 = ' True
Just like how it defines AndSym0 for consistency , as well .
Symbols for type constructorstop
One extra interesting defunctionalization symbol we can write : we turn lift any type constructor into a “ free ” defunctionalization symbol :
View full source
data
: : ( j - > k ) -- ^ take a type constructor
- > ( j ~ > k ) -- ^ return a defunctionalization symbol
-- alternatively
-- data ( t : : j - > k ) : : j ~ > k
type instance Apply ( t ) a = t a
Basically the Apply instance just applies the type constructor t to its input a.
ghci > : kind ! Maybe @@ Int
Maybe Int
ghci > : kind ! ' Right @@ ' False
' Right ' False
We can use this to give a normal j - > k type constructor to a function that expects a j ~ > k defunctionalization symbol .
Bring Me a Higher Ordertop
Okay , so now we have these tokens that represent “ unapplied ” versions of functions . So what ?
Well , remember the problem with our implementation of ? We could n’t pass in a type family , since type families must be passed fully applied . So , instead of having expect a type family … we can make it expect a defunctionalization symbol instead . Remember , defunctionalization symbols represent the “ unapplied ” versions of type families , so they are exactly the tools we need !
View full source
type family ( f : : j ~ > k ~ > k ) ( z : : k ) ( xs : : [ j ] ) : : k where
Foldr f z ' [ ] = z
Foldr f z ( x ' : xs ) = ( f @@ x ) z xs
The difference is that instead of taking a type family or type constructor f : : j - > k - > k , we have it take the defunctionalization symbol f : : j ~ > ( k ~ > k ) .
Instead of taking a type family or type constructor , we take that dummy type constructor .
Now we just need to have our defunctionalization symbols for MergeStateList :
View full source
data MergeStateSym0 : : DoorState ~ > DoorState ~ > DoorState
type instance Apply MergeStateSym0 s = MergeStateSym1 s
data MergeStateSym1 : : DoorState - > DoorState ~ > DoorState
type instance Apply ( MergeStateSym1 s ) t = MergeState s t
type MergeStateSym2 s t = MergeState s t
And now we can write MergeStateList :
View full source
type MergeStateList ss = Foldr MergeStateSym0 ' Opened ss
( If you “ see ” MergeStateSym0 , you should read it was MergeState , but partially applied )
This compiles !
ghci > : kind ! MergeStateList ' [ ' Closed , ' Opened , ' Locked ]
' Locked
ghci > : kind ! MergeStateList ' [ ' Closed , ' Opened ]
' Closed
View full source
collapseHallway : : Hallway ss - > Door ( MergeStateList ss )
collapseHallway HEnd = UnsafeMkDoor " End of Hallway "
collapseHallway ( d : < # ds ) = d ` mergeDoor ` collapseHallway ds
( Note : Unfortunately , we do have to use our our own here , that we just defined , instead of using the one that comes with singletons , because of some outstanding issues with how the singletons TH processes alternative implementations of foldr from Prelude . In general , the issue is that we should only expect type families to work with singletons if the definition of the type family perfectly matches the structure of how we implement our value - level functions like collapseHallway )
Singletons to make things nicertop
Admittedly this is all a huge mess of boilerplate . The code we had to write more than tripled , and we also have an unsightly number of defunctionalization symbols and Apply instance boilerplate for every function .
Luckily , the singletons library is here to help . You can just write :
$ ( singletons [ d|
data DoorState = Opened | Closed | Locked
deriving ( Show , Eq , Ord )
mergeState : : DoorState - > DoorState - > DoorState
mergeState = : : ( a - > b - > b ) - > b - > [ a ] - > b
foldr _ z [ ] = z
foldr f z ( x : xs ) = f x ( foldr f z xs )
mergeStateList : : [ DoorState ] - > DoorState
mergeStateList = foldr mergeState Opened
| ] )
And all of these defunctionalization symbols are generated for you ; singletons is also able to recognize that foldr is a higher - order function and translate its lifted version to take a defunctionalization symbol a ~ > b ~ > b.
That the template haskell also generates SingI instances for all of your defunctionalization symbols , too ( more on that in a bit ) .
It ’s okay to stay “ in the world of singletons ” for the most part , and let singletons handle the composition of functions for you . However , it ’s still important to know what the singletons library generates , because sometimes it ’s still useful to manually create defunctionalization symbols and work with them .
The naming convention for non - symbolic names ( non - operators ) like myFunction are just to call them MyFunctionSym0 for the completely unapplied defunctionalization symbol , for the type constructor that expects one argument before returning a defunctionalization symbol , MyFunctionSym2 for the type constructor that expects two arguments before returning a defunctionalization symbol , etc .
For operator names like + + , the naming convention is to have + + @#@$ be the completely unapplied defunctionalization symbol , + + @#@$$ be the type constructor that expects one argument before returning a defunctionalization symbol , + + @#@$$$ be the type constructor that takes two arguments before returning a defunctionalization symbol , etc .
Another helpful thing that singletons does is that it also generates defunctionalization symbols for type families and type synonyms you define in the Template Haskell , as well — so if you write
$ ( singletons [ d|
type MyTypeFamily ( b : : ) : : Type where
MyTypeFamily ' False = Int
MyTypeFamily ' True = String
| ] )
and
$ ( singletons [ d|
type MyTypeSynonym a = ( a , [ a ] )
| ] )
singletons will generate :
data MyTypeFamilySym0 : : Bool ~ > Type
type instance Apply MyTypeFamilySym0 b = MyTypeFamily b
type b = MyTypeFamily b
and
data MyTypeSynonymSym0 : : Type ~ > Type
type instance Apply MyTypeSynonym b = MyTypeSynonym a
type MyTypeSynonymSym1 a = MyTypeSynonym a
Bringing it All Togethertop
Just to show off the library , remember that singletons also promotes typeclasses ?
Because DoorState is a monoid with respect to merging , we can actually write and promote a Monoid instance : ( requires singletons-2.5 or higher )
$ ( singletons [ d|
instance Semigroup DoorState where
( < > ) = mergeState
instance where
= Opened
mappend = ( < > )
| ] )
We can promote fold :
$ ( singletons [ d|
fold : : Monoid b = > [ b ] - > b
fold [ ] = fold ( x : xs ) = x < > fold xs
| ] )
And we can write collapseHallway in terms of those instead :)
View full source
collapseHallway '
: : Hallway ss
- > Door ( Fold ss )
collapseHallway ' HEnd = UnsafeMkDoor " End of Hallway "
collapseHallway ' ( d : < # ds ) = d ` mergeDoor ` collapseHallway ' ds
collapseSomeHallway ' : : SomeHallway - > SomeDoor
collapseSomeHallway ' ( ss : & : d ) =
sFold ss
: & : collapseHallway ' d
( Note again unfortunately that we have to define our own fold instead of using the one from singletons and the SFoldable typeclass , because of issue # 339 )
Thoughts on symbols may feel like a bit of a mess , and the naming convention is arguably less than aesthetically satisfying . But , as you work with them more and more , you start to appreciate them on a deeper level .
At the end of the day , you can compare defunctionalization as turning “ functions ” into just constructors you can match on , just like any other data or type constructor . That ’s because they are just type constructors !
In a sense , defining defunctionalization symbols is a lot like working with pattern synonyms of your functions , instead of directly passing the functions themselves . At the type family and type class level , you can “ pattern match ” on these functions .
For a comparison at the value level – you ca n’t pattern match on ( + ) , ( - ) , ( * ) , and ( / ):
-- Does n't work like you think it does
invertOperation : : ( Double - > Dobule - > Double ) - > ( Double - > Double - > Double )
invertOperation ( + ) = ( - )
invertOperation ( - ) = ( + )
invertOperation ( * ) = ( / )
invertOperation ( / ) = ( * )
You ca n’t quite match on the equality of functions to some list of patterns . But , what you can do is create constructors representing your functions , and match on those .
This essentially fixes the “ type lambda problem ” of type inference and typeclass resolution . You ca n’t match on arbitrary lambdas , but you can match on dummy constructors representing type functions .
And a bit of the magic here , also , is the fact that you do n’t always need to make our own defunctionalization symbols from scratch — you can create them based on other ones in a compositional way . This is the basis of libraries like decidable .
For example , suppose we wanted to build defunctionalization symbols for MergeStateList . We can actually build them directly from defunctionalization symbols for .
Check out the defunctionalization symbols for :
View full source
data FoldrSym0 : : ( j ~ > k ~ > k ) ~ > k ~ > [ j ] ~ > k
type instance Apply FoldrSym0 f = FoldrSym1 f
data FoldrSym1 : : ( j ~ > k ~ > k ) - > k ~ > [ j ] ~ > k
type instance Apply ( FoldrSym1 f ) z = FoldrSym2 f z
data FoldrSym2 : : ( j ~ > k ~ > k ) - > k - > [ j ] ~ > k
type instance Apply ( FoldrSym2 f z ) xs = Foldr f z xs
type FoldrSym3 f z xs = Foldr f z xs
We can actually use these to define our MergeStateList defunctionalization symbols , since defunctionalization symbols are first - class :
View full source
type MergeStateListSym0 = FoldrSym2 MergeStateSym0 ' Opened
And you can just write collapseHallway as :
collapseHallway : : Hallway ss - > Door ( MergeStateListSym0 @@ ss )
-- or
collapseHallway : : Hallway ss - > Door ( FoldrSym2 MergeStateSym0 ' Opened @@ ss )
You never have to actually define MergeStateList as a function or type family !
The whole time , we ’re just building defunctionalization symbols in terms of other defunctionalization symbols . And , at the end , when we finally want to interpret the complex function we construct , we use Apply , or @@.
You can think of FoldrSym1 and FoldrSym2 as defunctionalization symbol constructors – they ’re combinators that take in defunctionalization symbols ( like MergeStateSym0 ) and return new ones .
Sigmatop
Let ’s look at a nice tool that is made possible using defunctionalization symbols : dependent pairs . I talk a bit about dependent pairs ( or dependent sums ) in part 2 of this series , and also in my dependent types in Haskell series .
Essentially , a dependent pair is a tuple where the type of the second field depends on the value of the first one . This is basically what SomeDoor was :
data SomeDoor : : Type where
MkSomeDoor : : Sing x - > Door x - > SomeDoor
The type of the Door x depends on the value of the Sing x , which you can read as essentially storing the x.
We made SomeDoor pretty ad - hoc . But what if we wanted to make some other predicate ? Well , we can make a generic dependent pair by parameterizing it on the dependence between the first and second field . Singletons provides the Sigma type , in the Data . Singletons . Sigma module :
data Sigma k : : ( k ~ > Type ) - > Type where
(: & :) : : Sing x - > ( f @@ x ) - > Sigma k f
-- also available through fancy type synonym
type Σ k = Sigma k
If you squint carefully , you can see that Sigma k is just SomeDoor , but parameterized over Door . Instead of always holding Door x , we can have it parameterized on an arbitrary function f and have it hold an f @@ x.
We can actually define SomeDoor in terms of Sigma :
View full source
type SomeDoor = Sigma DoorState ( TyCon1 Door )
mkSomeDoor : : DoorState - > String - > SomeDoor
mkSomeDoor ds mat = withSomeSing ds $ \dsSing - >
dsSing : & : mkDoor dsSing mat
( Remember is the defunctionalization symbol constructor that turns any normal type constructor j - > k into a defunctionalization symbol j ~ > k )
That ’s because a Sigma DoorState ( TyCon1 Door ) contains a Sing ( x : : DoorState ) and a TyCon1 Door @@ x , or a Door x.
This is a simple relationship , but one can imagine a Sigma parameterized on an even more complex type - level function . We ’ll explore more of these in the exercises .
For some context , Sigma is an interesting data type ( the “ dependent sum ” ) that is ubiquitous in dependently typed programming .
Singletons of
One last thing to tie it all together – let ’s write collapseHallway in a way that we do n’t know the types of the doors .
Luckily , we now have a SomeHallway type for free :
View full source
type SomeHallway = Sigma [ DoorState ] ( )
The easy way would be to just use sMergeStateList that we defined :
View full source
collapseSomeHallway : : SomeHallway - > SomeDoor
collapseSomeHallway ( ss : & : d ) =
But what if we did n’t write sMergeStateList , and we constructed our defunctionalization symbols from scratch ?
View full source
collapseHallway ''
: : Hallway ss
- > Door ( FoldrSym2 MergeStateSym0 ' Opened @@ ss )
collapseHallway '' HEnd = UnsafeMkDoor " End of Hallway "
collapseHallway '' ( d : < # ds ) = d ` mergeDoor ` collapseHallway '' ds
collapseSomeHallway '' : : SomeHallway - > SomeDoor
collapseSomeHallway '' ( ss : & : d ) = ? ? ? -- what goes here ?
: & : collapseHallway '' d
This will be our final defunctionalization lesson . How do we turn a singleton of ss into a singleton of FoldrSym2 MergeStateSym0 ' Opened @@ s ?
First – we have at the value level , as . We glossed over this earlier , but singletons generates the following function for us :
type family ( f : : j ~ > k ~ > k ) ( z : : k ) ( xs : : [ j ] ) : : k where
Foldr f z ' [ ] = z
Foldr f z ( x ' : xs ) = ( f @@ x ) z xs
sFoldr
: : Sing ( f : : j ~ > k ~ > k )
- > Sing ( z : : k )
- > Sing ( xs : : [ j ] )
- > Sing ( Foldr f z xs : : k )
sFoldr f z SNil = z
sFoldr f z ( x ` SCons ` xs ) = ( f @@ x ) z xs
Where ( @@ ) : : Sing f - > Sing x - > Sing ( f @@ x ) ( or applySing ) is the singleton / value - level counterpart of Apply or ( @@).1
So we can write :
collapseSomeHallway '' : : SomeHallway - > SomeDoor
collapseSomeHallway '' ( ss : & : d ) = sFoldr ? ? ? ? SOpened ss
: & : collapseHallwa''y d
But how do we get a Sing MergeStateSym0 ?
We can use the singFun family of functions :
singFun2 @MergeStateSym0 sMergeState
: : Sing MergeStateSym0
But , also , conveniently , the singletons library generates a SingI instance for MergeStateSym0 , if you defined mergeState using the singletons template haskell :
sing : : Sing MergeStateSym0
-- or
sing @ _ -- singletons 2.4
sing -- singletons 2.5
And finally , we get our answer :
View full source
collapseSomeHallway '' : : SomeHallway - > SomeDoor
collapseSomeHallway '' ( ss : & : d ) =
sFoldr ( singFun2 @MergeStateSym0 sMergeState ) SOpened ss
-- or
-- sFoldr ( sing ) SOpened ss
: & : collapseHallway '' d
Closing Uptop
Woo ! Congratulations , you ’ve made it to the end of the this Introduction to Singletons tetralogy ! This last and final part understandably ramps things up pretty quickly , so do n’t be afraid to re - read it a few times until it all sinks in before jumping into the exercises .
I hope you enjoyed this journey deep into the motivation , philosophy , mechanics , and usage of this great library . Hopefully these toy examples have been able to show you a lot of ways that type - level programming can help your programs today , both in type safety and in writing more expressive programs . And also , I hope that you can also see now how to leverage the full power of the singletons library to make those gains a reality .
There are a few corners of the library we have n’t gone over ( like the TypeLits- and TypeRep - based singletons – if you ’re interested , check out this post where I talk a lot about them ) , but I ’d like to hope as well that this series has equipped you to be able to dive into the library documentation and decipher what it holds , armed with the knowledge you now have . ( We also look at TypeLits briefly in the exercises )
You can download the source code here — Door4Final.hs contains the final versions of all our definitions , and Defunctionalization.hs contains all of our defunctionalization - from - scratch work . These are designed as stack scripts that you can load into ghci . Just execute the scripts :
$ ./Door4Final.hs
ghci >
And you ’ll be dropped into a ghci session with all of the definitions in scope .
As always , please try out the exercises , which are designed to help solidify the concepts we went over here ! And if you ever have any future questions , feel free to leave a comment or find me on twitter or in freenode # haskell , where I idle as jle ` .
Looking
Some final things to note before truly embracing singletons : remember that , as a library , singletons was always meant to become obsolete . It ’s a library that only exists because does n’t have real dependent types yet .
Dependent is coming some day ! It ’s mostly driven by one solo man , , but every year buzz does get bigger . In a recent progress report , we do know that we realistically wo n’t have dependent types before 2020 . That means that this tutorial will still remain relevant for at least another two years :)
How will things be different in a world of Haskell with real dependent types ? Well , for a good guess , take a look at Dissertation !
One day , hopefully , we wo n’t need singletons to work with types at the value - level ; we would just be able to directly pattern match and manipulate the types within the language and use them as first - class values , with a nice story for dependent sums . And some day , I hope we wo n’t need any more dances with defunctionalization symbols to write higher - order functions at the type level — maybe we ’ll have a nicer way to work with partially applied type - level functions ( maybe they ’ll just be normal functions ? ) , and we do n’t need to think any different about higher - order or first - order functions .
So , as a final word — , everyone ! May you leverage the great singletons library to its full potential , and may we also all dream of a day where singletons becomes obsolete . But may we all enjoy the wonderful journey along the way .
Until next time !
Here are your final exercises for this series ! Start from this sample source code , which has all of the definitions that the exercises and their solutions require . Just make sure to delete all of the parts after the -- Exercises comment if you do n’t want to be spoiled . Remember again to enable -Werror = incomplete - patterns or -Wall to ensure that all of your functions are total .
Let ’s try combining type families with proofs ! In doing so , hopefully we can also see the value of using dependent proofs to show how we can manipulate proofs as first - class values that the compiler can verify .
Remember from Part 3 ?
View full source
data : : DoorState - > Type where
KnockClosed : : ' Closed
KnockLocked : : ' Locked
Closed and Locked doors are knockable . But , if you merge two knockable doors … is the result also always knockable ?
I say yes , but do n’t take my word for it . Prove it using Knockable !
View full source
mergedIsKnockable
: : s
- > Knockable t
- > Knockable ( MergeState s t )
mergedIsKnockable is only implementable if the merging of two DoorStates that are knockable is also knockable . See if you can write the implementation !
Solution here !
Write a function to append two hallways together .
appendHallways
: : Hallway ss
- > Hallway ts
- > Hallway ? ? ? ?
from singletons — implement any type families you might need from scratch !
Remember the important principle that your type family must mirror the implementation of the functions that use it .
Next , for fun , use appendHallways to implement appendSomeHallways :
View full source
type SomeHallway = Sigma [ DoorState ] ( )
appendSomeHallways
: : SomeHallway
- > SomeHallway
- > SomeHallway
Solution here !
Can you use Sigma to define a door that must be knockable ?
To do this , try directly defining the defunctionalization symbol KnockableDoor : : DoorState ~ > Type ( or use singletons to generate it for you — remember that singletons can also promote type families ) so that :
type SomeKnockableDoor = Sigma DoorState KnockableDoor
will contain a Door that must be knockable .
Try doing it for both ( a ) the “ dependent proof ” version ( with the data type ) and for ( b ) the type family version ( with the StatePass type family ) .
Solutions here ! I gave four different ways of doing it , for a full range of manual vs. auto - promoted defunctionalization symbols and vs. Pass - based methods .
Hint : Look at the definition of SomeDoor in terms of Sigma :
type SomeDoor = Sigma DoorState ( TyCon1 Door )
Hint : Try having KnockableDoor return a tuple .
Take a look at the API of the Data . Singletons . TypeLits module , based on the API exposed in GHC.TypeNats module from base .
Using this , you can use Sigma to create a predicate that a given number is even :
data IsHalfOf : : > Type
type instance Apply ( IsHalfOf n ) m = n : ~ : ( m * 2 )
type IsEven n = ( IsHalfOf n )
( * ) is multiplication from the Data . Singletons . Prelude . Num module . ( You must have the -XNoStarIsType extension on for this to work in GHC 8.6 + ) , and : ~ : is the predicate of equality from Part 3 :
data (: ~ :) : : k - > k - > Type where
Refl : : a : ~ : a
( It ’s only possible to make a value of type a : ~ : b using : : a : ~ : a , so it ’s only possible to make a value of that type when a and b are equal . I like to use with type application syntax , like , so it ’s clear what we are saying is the same on both sides ; : : a : ~ : a )
The only way to construct an IsEven n is to provide a number m where m * 2 is n. We can do this by using SNat @m , which is the singleton constructor for the kind ( just like how STrue and SFalse are the singleton constructors for the kind ):
tenIsEven : : IsEven 10
tenIsEven = SNat @5 : & : Refl @10
is the constructor of type n : ~ : ( m * 2 )
-- here , we use it as Refl @10 : : 10 : ~ : 10
-- wo n't compile
sevenIsEven : : IsEven 10
sevenIsEven = SNat @4 : & : -- wo n't compile , because we need something of type ` ( 4 * 2 ) : ~ : 7 ` ,
-- but must have type ` a : ~ : a ` ; ` 8 : ~ : 7 ` is not constructable
-- using ` Refl ` . Neither ` Refl @8 ` nor ` Refl @7 ` will work .
Write a similar type IsOdd n that can only be constructed if n is odd .
type IsOdd n = ( ? ? ? ? n )
And construct a proof that 7 is odd :
View full source
sevenIsOdd : : IsOdd 7
Solution here !
On a sad note , one exercise I ’d like to be able to add is to ask you to write decision functions and proofs for and IsOdd . Unfortunately , is not rich enough to support this out of the box without a lot of extra tooling !
A common beginner Haskeller exercise is to implement map in terms of foldr :
map : : ( a - > b ) - > [ a ] _ > [ b ]
map f = foldr ( (: ) . f ) [ ]
Let ’s do the same thing at the type level , manually .
Directly implement a type - level Map , with kind ( j ~ > k ) - > [ j ] - > [ k ] , in terms of :
type Map f xs = Foldr ? ? ? ? ? ? ? ? xs
Try to mirror the value - level definition , passing in ( :) . f , and use the promoted version of ( . ) from the singletons library , in Data . Singletons . Prelude . You might find helpful !
Solution here !
Make a SomeHallway from a list of SomeDoor :
View full source
type SomeDoor = Sigma DoorState ( TyCon1 Door )
type SomeHallway = Sigma [ DoorState ] ( )
mkSomeHallway : : [ SomeDoor ] - > SomeHallway
Remember that the singleton constructors for list are SNil ( for [ ] ) and SCons ( for ( :)) !
Solution here !
-to-singletons-4.html
Justin Le
Introduction to Singletons (Part 4)
Monday October 22, 2018
functional programming at the type level.
GHC 8.6.1
nightly-2018-09-29 (singletons-2.5)
Review
View full source
$(singletons [d|
data DoorState = Opened | Closed | Locked
deriving (Show, Eq, Ord)
|])
data Door :: DoorState -> Type where
UnsafeMkDoor :: { doorMaterial :: String } -> Door s
mkDoor :: Sing s -> String -> Door s
mkDoor _ = UnsafeMkDoor
And we talked about using Sing s, or SDoorState s, to represent the state of the door (in its type) as a run-time value. We’ve been using a wrapper to existentially hide the door state type, but also stuffing in a singleton to let us recover the type information once we want it again:
data SomeDoor :: Type where
MkSomeDoor :: Sing s -> Door s -> SomeDoor
mkSomeDoor :: DoorState -> String -> SomeDoor
mkSomeDoor ds mat = withSomeSing ds $ \dsSing ->
MkSomeDoor dsSing (mkDoor dsSing mat)
In Part 3 we talked about a Pass data type that we used to talk about whether or not we can walk through or knock on a door:
$(singletons [d|
data Pass = Obstruct | Allow
deriving (Show, Eq, Ord)
|])
And we defined type-level functions on it using singletons Template Haskell:
$(singletons [d|
statePass :: DoorState -> Pass
statePass Opened = Allow
statePass Closed = Obstruct
statePass Locked = Obstruct
|])
This essentially generates these three things:
statePass :: DoorState -> Pass
statePass Opened = Allow
statePass Closed = Obstruct
statePass Locked = Obstruct
type family StatePass (s :: DoorState) :: Pass where
StatePass 'Opened = 'Allow
StatePass 'Closed = 'Obstruct
StatePass 'Locked = 'Obstruct
sStatePass :: Sing s -> Sing (StatePass s)
sStatePass = \case
SOpened -> SAllow
SClosed -> SObstruct
SLocked -> SObstruct
And we can use StatePass as a type-level function while using sStatePass to manipulate the singletons representing s and StatePass s.
We used this as a constraint to restrict how we can call our functions:
View full source
knockP :: (StatePass s ~ 'Obstruct) => Door s -> IO ()
knockP d = putStrLn $ "Knock knock on " ++ doorMaterial d ++ " door!"
But then we wondered…is there a way to not only restrict our functions, but to describe how the inputs and outputs are related to each other?
Inputs and Outputstop
In the past we have settled with very simple relationships, like:
closeDoor :: Door 'Opened -> Door 'Closed
This means that the relationship between the input and output is that the input is opened…and is then closed.
However, armed with promotion of type-level functions, writing more complex relationships becomes fairly straightforward!
We can write a function mergeDoor that “merges” two doors together, in sequence:
mergeDoor :: Door s -> Door t -> Door ????
mergeDoor d e = UnsafeMkDoor $ doorMaterial d ++ " and " ++ doorMaterial e
A merged door will have a material that is composite of the original materials. But, what will the new DoorState be? What goes in the ??? above?
Well, if we can write the function as a normal function in values…singletons lets us use it as a function on types. Let’s write that relationship. Let’s say merging takes on the higher “security” option — merging opened with locked is locked, merging closed with opened is closed, merging locked with closed is locked.
$(singletons [d|
mergeState :: DoorState -> DoorState -> DoorState
mergeState Opened d = d
mergeState Closed Opened = Closed
mergeState Closed Closed = Closed
mergeState Closed Locked = Locked
mergeState Locked _ = Locked
|])
-- Alternatively, taking advantage of the derived Ord instance:
$(singletons [d|
mergeState :: DoorState -> DoorState -> DoorState
mergeState = max
|])
This makes writing mergeDoor’s type clean to read:
View full source
mergeDoor
:: Door s
-> Door t
-> Door (MergeState s t)
mergeDoor d e = UnsafeMkDoor $ doorMaterial d ++ " and " ++ doorMaterial e
And, with the help of singletons, we can also write this for our doors where we don’t know the types until runtime:
View full source
mergeSomeDoor :: SomeDoor -> SomeDoor -> SomeDoor
mergeSomeDoor (MkSomeDoor s d) (MkSomeDoor t e) =
MkSomeDoor (sMergeState s t) (mergeDoor d e)
To see why this typechecks properly, compare the types of sMergeState and mergeDoor:
sMergeState :: Sing s -> Sing t -> Sing (MergeState s t)
mergeDoor :: Door s -> Door t -> Door (MergeState s t)
MkSomeDoor :: Sing (MergeState s t) -> Door (MergeState s t) -> SomeDoor
Because the results both create types MergeState s t, MkSomeDoor is happy to apply them to each other, and everything typechecks. However, if, say, we directly stuffed s or t into MkSomeDoor, things would fall apart and not typecheck.
And so now we have full expressiveness in determining input and output relationships! Once we unlock the power of type-level functions with singletons, writing type-level relationships become as simple as writing value-level ones. If you can write a value-level function, you can write a type-level function.
Kicking it up a notchtop
How far we can really take this?
Let’s make a data type that represents a series of hallways, each linked by a door. A hallway is either an empty stretch with no door, or two hallways linked by a door. We’ll structure it like a linked list, and store the list of all door states as a type-level list as a type parameter:
View full source
data Hallway :: [DoorState] -> Type where
HEnd :: Hallway '[] -- ^ end of the hallway, a stretch with no
-- doors
(:<#) :: Door s
-> Hallway ss
-> Hallway (s ': ss) -- ^ A door connected to a hallway is a new
-- hallway, and we track the door's state
-- in the list of hallway door states
infixr 5 :<#
(If you need a refresher on type-level lists, check out the quick introduction in Part 1 and Exercise 4 in Part 2)
So we might have:
ghci> let door1 = mkDoor SClosed "Oak"
ghci> let door2 = mkDoor SOpened "Spruce"
ghci> let door3 = mkDoor SLocked "Acacia"
ghci> :t door1 :<# door2 :<# door3 :<# HEnd
Hallway '[ 'Closed, 'Opened, 'Locked ]
That is, a Hallway '[ s, t, u ] is a hallway consisting of a Door s, a Door t, and a Door u, constructed like a linked list in Haskell.
Now, let’s write a function to collapse all doors in a hallway down to a single door:
collapseHallway :: Hallway ss -> Door ?????
Basically, we want to merge all of the doors one after the other, collapsing it until we have a single door state. Luckily, MergeState is both commutative and associative and has an identity, so this can be defined sensibly.
First, let’s think about the type we want. What will the result of merging ss be?
We can pattern match and collapse an entire list down item-by-item:
$(singletons [d|
mergeStateList :: [DoorState] -> DoorState
mergeStateList [] = Opened -- ^ the identity of mergeState
mergeStateList (s:ss) = s `mergeState` mergeStateList ss
|])
Again, remember that this also defines the type family MergeStateList and the singleton function sMergeStateList :: Sing ss -> Sing (MergeStateList ss).
With this, we can write collapseHallway:
View full source
collapseHallway :: Hallway ss -> Door (MergeStateList ss)
collapseHallway HEnd = mkDoor SOpened "End of Hallway"
collapseHallway (d :<# ds) = d `mergeDoor` collapseHallway ds
Now, because the structure of collapseHallway perfectly mirrors the structure of mergeStateList, this all typechecks, and we’re done!
ghci> collapseHallway (door1 :<# door2 :<# door3 :<# HEnd)
UnsafeMkDoor "Oak and Spruce and Acacia and End of Hallway"
:: Door 'Locked
Note one nice benefit – the door state of collapseHallway (door1 :<# door2 :<# door3 :<# HEnd) is known at compile-time to be Door 'Locked, if the types of all of the component doors are also known!
Functional Programmingtop
We went over that all a bit fast, but some of you might have noticed that the definition of mergeStateList bears a really strong resemblance to a very common Haskell list processing pattern:
mergeStateList :: [DoorState] -> DoorState
mergeStateList [] = Opened -- ^ the identity of mergeState
mergeStateList (s:ss) = s `mergeState` mergeStateList ss
The algorithm is to basically [] with Opened, and all (:) with mergeState. If this sounds familiar, that’s because this is exactly a right fold! (In fact, hlint actually made this suggestion to me while I was writing this)
mergeStateList :: [DoorState] -> DoorState
mergeStateList = foldr mergeState Opened
In Haskell, we are always encouraged to use higher-order functions whenever possible instead of explicit recursion, both because explicit recursion opens you up to a lot of potential bugs, and also because using established higher-order functions make your code more readable.
So, as Haskellers, let us hold ourselves to a higher standard and not be satisfied with a MergeState written using explicit recursion. Let us instead go full fold — ONWARD HO!
The Problemtop
Initial attempts to write a higher-order type-level function as a type family, however, serve to temper our enthusiasm.
type family Foldr (f :: j -> k -> k) (z :: k) (xs :: [j]) :: k where
Foldr f z '[] = z
Foldr f z (x ': xs) = f x (Foldr f z xs)
So far so good right? So we should expect to be able to write MergeStateList using Foldr, MergeState, and 'Opened
type MergeStateList ss = Foldr MergeState 'Opened ss
Ah, but the compiler is here to tell you this isn’t allowed in Haskell:
• The type family ‘MergeState’ should have 2 arguments, but has been given none
• In the equations for closed type family ‘MergeStateList’
In the type family declaration for ‘MergeStateList’
What happened? To figure out, we have to remember that pesky restriction on type synonyms and type families: they can not be used partially applied (“unsaturated”), and must always be fully applied (“saturated”). For the most part, only type constructors (like Maybe, Either, IO) and lifted DataKinds data constructors (like 'Just, '(:)) in Haskell can ever be partially applied at the type level. We therefore can’t use MergeState as an argument to Foldr, because MergeState must always be fully applied.
Unfortunately for us, this makes our Foldr effectively useless. That’s because we’re always going to want to pass in type families (like MergeState), so there’s pretty much literally no way to ever actually call Foldr except with type constructors or lifted DataKinds data constructors.
So…back to the drawing board?
Defunctionalizationtop
I like to mentally think of the singletons library as having two parts: the first is linking lifted DataKinds types with run-time values to allow us to manipulate types at runtime as first-class values. The second is a system for effective functional programming at the type level.
To make a working Foldr, we’re going to have to jump into that second half: defunctionalization.
Defunctionalization is a technique invented in the early 70’s as a way of compiling higher-order functions into first-order functions in target languages. The main idea is:
Instead of working with functions, work with symbols representing functions.
Build your final functions and values by composing and combining these symbols.
At the end of it all, have a single Apply function interpret all of your symbols and produce the value you want.
In singletons these symbols are implemented as “dummy” empty data constructors, and Apply is a type family.
To help us understand singleton’s defunctionalization system better, let’s build our own defunctionalization system from scratch.
First, a little trick to make things easier to read:
View full source
data TyFun a b
type a ~> b = TyFun a b -> Type
infixr 0 ~>
Our First Symbolstop
Now we can define a dummy data type like Id, which represents the identity function id:
View full source
data Id :: a ~> a
The “actual” kind of Id is Id :: TyFun a a -> Type; you can imagine TyFun a a as a phantom parameter that signifies that Id represents a function from a to a. It’s essentially a nice trick to allow you to write Id :: a ~> a as a kind signature.
Now, Id is not a function…it’s a dummy type constructor that represents a function a -> a. A type constructor of kind a ~> a represents a defunctionalization symbol – a type constructor that represents a function from a to a.
To interpret it, we need to write our global interpreter function:
View full source
type family Apply (f :: a ~> b) (x :: a) :: b
That’s the syntax for the definition of an open type family in Haskell: users are free to add their own instances, just like how type classes are normally open in Haskell.
Let’s tell Apply how to interpret Id:
View full source
type instance Apply Id x = x
The above is the actual function definition, like writing id x = x. We can now call Id to get an actual type in return:
ghci> :kind! Apply Id 'True
'True
(Remember, :kind! is the ghci command to evaluate a type family)
Let’s define another one! We’ll implement Not:
View full source
data Not :: Bool ~> Bool
type instance Apply Not 'False = 'True
type instance Apply Not 'True = 'False
We can try it out:
ghci> :kind! Apply Not 'True
'False
ghci> :kind! Apply Not 'False
'True
It can be convenient to define an infix synonym for Apply:
View full source
type f @@ a = Apply f a
infixl 9 @@
Then we can write:
ghci> :kind! Not @@ 'False
'True
ghci> :kind! Id @@ 'True
'True
Remember, Id and Not are not actual functions — they’re just dummy data types (“defunctionalization symbols”), and we define the functions they represent through the global Apply type function.
A Bit of Principletop
So we’ve got the basics of defunctionalization — instead of using functions directly, use dummy symbols that encode your functions that are interpreted using Apply. Let’s add a bit of principle to make this all a bit more scalable.
The singletons library adopts a few conventions for linking all of these together. Using the Not function as an example, if we wanted to lift the function:
not :: Bool -> Bool
not False = True
not True = Flse
We already know about the type family and singleton function this would produce:
type family Not (x :: Bool) :: Bool where
Not 'False = 'True
Not 'True = 'False
sNot :: Sing x -> Sing (Not x)
sNot SFalse = STrue
sNot STrue = SFalse
But the singletons library also produces the following defunctionalization symbols, according to a naming convention:
data NotSym0 :: Bool ~> Bool
type instance Apply NotSym0 x = Not x
-- also generated for consistency
type NotSym1 x = Not x
NotSym0 is the defunctionalization symbol associated with the Not type family, defined so that NotSym0 @@ x = Not x. Its purpose is to allow us to pass in Not as an un-applied function. The Sym0 suffix is a naming convention, and the 0 stands for “expects 0 arguments”. Similarly for NotSym1 – the 1 stands for “expects 1 argument”.
Two-Argument Functionstop
Let’s look at a slightly more complicated example – a two-argument function. Let’s define the boolean “and”:
$(singletons [d|
and :: Bool -> (Bool -> Bool)
and False _ = False
and True x = x
])
this will generate:
type family And (x :: Bool) (y :: Bool) :: Bool where
And 'False x = 'False
And 'True x = x
sAnd :: Sing x -> Sing y -> Sing (And x y)
sAnd SFalse x = SFalse
sAnd STrue x = x
And the defunctionalization symbols:
data AndSym0 :: Bool ~> (Bool ~> Bool)
type instance Apply AndSym0 x = AndSym1 x
data AndSym1 (x :: Bool) :: (Bool ~> Bool)
-- or
data AndSym1 :: Bool -> (Bool ~> Bool)
type instance Apply (AndSym1 x) y = And x y
type AndSym2 x y = And x y
AndSym0 is a defunctionalization symbol representing a “fully unapplied” (“completely unsaturated”) version of And. AndSym1 x is a defunctionalization symbol representing a “partially applied” version of And — partially applied to x (its kind is AndSym1 :: Bool -> (Bool ~> Bool)).
The application of AndSym0 to x gives you AndSym1 x:
ghci> :kind! AndSym0 @@ 'False
AndSym1 'False
Remember its kind AndSym0 :: Bool ~> (Bool ~> Bool) (or just AndSym0 :: Bool ~> Bool ~> Bool): it takes a Bool, and returns a Bool ~> Bool defunctionalization symbol.
The application of AndSym1 x to y gives you And x y:
ghci> :kind! AndSym1 'False @@ 'True
'False -- or FalseSym0, which is a synonym for 'False
ghci> :kind! AndSym1 'True @@ 'True
'True
A note to remember: AndSym1 'True is the defunctionalization symbol, and not AndSym1 itself. AndSym1 has kind Bool -> (Bool ~> Bool), but AndSym1 'True has kind Bool ~> Bool — the kind of a defunctionalization symbol. AndSym1 is a sort of “defunctionalization symbol constructor”.
Also note here that we encounter the fact that singletons also provides “defunctionalization symbols” for “nullary” type functions like False and True, where:
type FalseSym0 = 'False
type TrueSym0 = 'True
Just like how it defines AndSym0 for consistency, as well.
Symbols for type constructorstop
One extra interesting defunctionalization symbol we can write: we turn lift any type constructor into a “free” defunctionalization symbol:
View full source
data TyCon1
:: (j -> k) -- ^ take a type constructor
-> (j ~> k) -- ^ return a defunctionalization symbol
-- alternatively
-- data TyCon1 (t :: j -> k) :: j ~> k
type instance Apply (TyCon1 t) a = t a
Basically the Apply instance just applies the type constructor t to its input a.
ghci> :kind! TyCon1 Maybe @@ Int
Maybe Int
ghci> :kind! TyCon1 'Right @@ 'False
'Right 'False
We can use this to give a normal j -> k type constructor to a function that expects a j ~> k defunctionalization symbol.
Bring Me a Higher Ordertop
Okay, so now we have these tokens that represent “unapplied” versions of functions. So what?
Well, remember the problem with our implementation of Foldr? We couldn’t pass in a type family, since type families must be passed fully applied. So, instead of having Foldr expect a type family…we can make it expect a defunctionalization symbol instead. Remember, defunctionalization symbols represent the “unapplied” versions of type families, so they are exactly the tools we need!
View full source
type family Foldr (f :: j ~> k ~> k) (z :: k) (xs :: [j]) :: k where
Foldr f z '[] = z
Foldr f z (x ': xs) = (f @@ x) @@ Foldr f z xs
The difference is that instead of taking a type family or type constructor f :: j -> k -> k, we have it take the defunctionalization symbol f :: j ~> (k ~> k).
Instead of taking a type family or type constructor, we take that dummy type constructor.
Now we just need to have our defunctionalization symbols for MergeStateList:
View full source
data MergeStateSym0 :: DoorState ~> DoorState ~> DoorState
type instance Apply MergeStateSym0 s = MergeStateSym1 s
data MergeStateSym1 :: DoorState -> DoorState ~> DoorState
type instance Apply (MergeStateSym1 s) t = MergeState s t
type MergeStateSym2 s t = MergeState s t
And now we can write MergeStateList:
View full source
type MergeStateList ss = Foldr MergeStateSym0 'Opened ss
(If you “see” MergeStateSym0, you should read it was MergeState, but partially applied)
This compiles!
ghci> :kind! MergeStateList '[ 'Closed, 'Opened, 'Locked ]
'Locked
ghci> :kind! MergeStateList '[ 'Closed, 'Opened ]
'Closed
View full source
collapseHallway :: Hallway ss -> Door (MergeStateList ss)
collapseHallway HEnd = UnsafeMkDoor "End of Hallway"
collapseHallway (d :<# ds) = d `mergeDoor` collapseHallway ds
(Note: Unfortunately, we do have to use our our own Foldr here, that we just defined, instead of using the one that comes with singletons, because of some outstanding issues with how the singletons TH processes alternative implementations of foldr from Prelude. In general, the issue is that we should only expect type families to work with singletons if the definition of the type family perfectly matches the structure of how we implement our value-level functions like collapseHallway)
Singletons to make things nicertop
Admittedly this is all a huge mess of boilerplate. The code we had to write more than tripled, and we also have an unsightly number of defunctionalization symbols and Apply instance boilerplate for every function.
Luckily, the singletons library is here to help. You can just write:
$(singletons [d|
data DoorState = Opened | Closed | Locked
deriving (Show, Eq, Ord)
mergeState :: DoorState -> DoorState -> DoorState
mergeState = max
foldr :: (a -> b -> b) -> b -> [a] -> b
foldr _ z [] = z
foldr f z (x:xs) = f x (foldr f z xs)
mergeStateList :: [DoorState] -> DoorState
mergeStateList = foldr mergeState Opened
|])
And all of these defunctionalization symbols are generated for you; singletons is also able to recognize that foldr is a higher-order function and translate its lifted version to take a defunctionalization symbol a ~> b ~> b.
That the template haskell also generates SingI instances for all of your defunctionalization symbols, too (more on that in a bit).
It’s okay to stay “in the world of singletons” for the most part, and let singletons handle the composition of functions for you. However, it’s still important to know what the singletons library generates, because sometimes it’s still useful to manually create defunctionalization symbols and work with them.
The naming convention for non-symbolic names (non-operators) like myFunction are just to call them MyFunctionSym0 for the completely unapplied defunctionalization symbol, MyFunctionSym1 for the type constructor that expects one argument before returning a defunctionalization symbol, MyFunctionSym2 for the type constructor that expects two arguments before returning a defunctionalization symbol, etc.
For operator names like ++, the naming convention is to have ++@#@$ be the completely unapplied defunctionalization symbol, ++@#@$$ be the type constructor that expects one argument before returning a defunctionalization symbol, ++@#@$$$ be the type constructor that takes two arguments before returning a defunctionalization symbol, etc.
Another helpful thing that singletons does is that it also generates defunctionalization symbols for type families and type synonyms you define in the Template Haskell, as well — so if you write
$(singletons [d|
type MyTypeFamily (b :: Bool) :: Type where
MyTypeFamily 'False = Int
MyTypeFamily 'True = String
|])
and
$(singletons [d|
type MyTypeSynonym a = (a, [a])
|])
singletons will generate:
data MyTypeFamilySym0 :: Bool ~> Type
type instance Apply MyTypeFamilySym0 b = MyTypeFamily b
type MyTypeFamilySym1 b = MyTypeFamily b
and
data MyTypeSynonymSym0 :: Type ~> Type
type instance Apply MyTypeSynonym b = MyTypeSynonym a
type MyTypeSynonymSym1 a = MyTypeSynonym a
Bringing it All Togethertop
Just to show off the library, remember that singletons also promotes typeclasses?
Because DoorState is a monoid with respect to merging, we can actually write and promote a Monoid instance: (requires singletons-2.5 or higher)
$(singletons [d|
instance Semigroup DoorState where
(<>) = mergeState
instance Monoid DoorState where
mempty = Opened
mappend = (<>)
|])
We can promote fold:
$(singletons [d|
fold :: Monoid b => [b] -> b
fold [] = mempty
fold (x:xs) = x <> fold xs
|])
And we can write collapseHallway in terms of those instead :)
View full source
collapseHallway'
:: Hallway ss
-> Door (Fold ss)
collapseHallway' HEnd = UnsafeMkDoor "End of Hallway"
collapseHallway' (d :<# ds) = d `mergeDoor` collapseHallway' ds
collapseSomeHallway' :: SomeHallway -> SomeDoor
collapseSomeHallway' (ss :&: d) =
sFold ss
:&: collapseHallway' d
(Note again unfortunately that we have to define our own fold instead of using the one from singletons and the SFoldable typeclass, because of issue #339)
Thoughts on Symbolstop
Defunctionalization symbols may feel like a bit of a mess, and the naming convention is arguably less than aesthetically satisfying. But, as you work with them more and more, you start to appreciate them on a deeper level.
At the end of the day, you can compare defunctionalization as turning “functions” into just constructors you can match on, just like any other data or type constructor. That’s because they are just type constructors!
In a sense, defining defunctionalization symbols is a lot like working with pattern synonyms of your functions, instead of directly passing the functions themselves. At the type family and type class level, you can “pattern match” on these functions.
For a comparison at the value level – you can’t pattern match on (+), (-), (*), and (/):
-- Doesn't work like you think it does
invertOperation :: (Double -> Dobule -> Double) -> (Double -> Double -> Double)
invertOperation (+) = (-)
invertOperation (-) = (+)
invertOperation (*) = (/)
invertOperation (/) = (*)
You can’t quite match on the equality of functions to some list of patterns. But, what you can do is create constructors representing your functions, and match on those.
This essentially fixes the “type lambda problem” of type inference and typeclass resolution. You can’t match on arbitrary lambdas, but you can match on dummy constructors representing type functions.
And a bit of the magic here, also, is the fact that you don’t always need to make our own defunctionalization symbols from scratch — you can create them based on other ones in a compositional way. This is the basis of libraries like decidable.
For example, suppose we wanted to build defunctionalization symbols for MergeStateList. We can actually build them directly from defunctionalization symbols for Foldr.
Check out the defunctionalization symbols for Foldr:
View full source
data FoldrSym0 :: (j ~> k ~> k) ~> k ~> [j] ~> k
type instance Apply FoldrSym0 f = FoldrSym1 f
data FoldrSym1 :: (j ~> k ~> k) -> k ~> [j] ~> k
type instance Apply (FoldrSym1 f) z = FoldrSym2 f z
data FoldrSym2 :: (j ~> k ~> k) -> k -> [j] ~> k
type instance Apply (FoldrSym2 f z) xs = Foldr f z xs
type FoldrSym3 f z xs = Foldr f z xs
We can actually use these to define our MergeStateList defunctionalization symbols, since defunctionalization symbols are first-class:
View full source
type MergeStateListSym0 = FoldrSym2 MergeStateSym0 'Opened
And you can just write collapseHallway as:
collapseHallway :: Hallway ss -> Door (MergeStateListSym0 @@ ss)
-- or
collapseHallway :: Hallway ss -> Door (FoldrSym2 MergeStateSym0 'Opened @@ ss)
You never have to actually define MergeStateList as a function or type family!
The whole time, we’re just building defunctionalization symbols in terms of other defunctionalization symbols. And, at the end, when we finally want to interpret the complex function we construct, we use Apply, or @@.
You can think of FoldrSym1 and FoldrSym2 as defunctionalization symbol constructors – they’re combinators that take in defunctionalization symbols (like MergeStateSym0) and return new ones.
Sigmatop
Let’s look at a nice tool that is made possible using defunctionalization symbols: dependent pairs. I talk a bit about dependent pairs (or dependent sums) in part 2 of this series, and also in my dependent types in Haskell series.
Essentially, a dependent pair is a tuple where the type of the second field depends on the value of the first one. This is basically what SomeDoor was:
data SomeDoor :: Type where
MkSomeDoor :: Sing x -> Door x -> SomeDoor
The type of the Door x depends on the value of the Sing x, which you can read as essentially storing the x.
We made SomeDoor pretty ad-hoc. But what if we wanted to make some other predicate? Well, we can make a generic dependent pair by parameterizing it on the dependence between the first and second field. Singletons provides the Sigma type, in the Data.Singletons.Sigma module:
data Sigma k :: (k ~> Type) -> Type where
(:&:) :: Sing x -> (f @@ x) -> Sigma k f
-- also available through fancy type synonym
type Σ k = Sigma k
If you squint carefully, you can see that Sigma k is just SomeDoor, but parameterized over Door. Instead of always holding Door x, we can have it parameterized on an arbitrary function f and have it hold an f @@ x.
We can actually define SomeDoor in terms of Sigma:
View full source
type SomeDoor = Sigma DoorState (TyCon1 Door)
mkSomeDoor :: DoorState -> String -> SomeDoor
mkSomeDoor ds mat = withSomeSing ds $ \dsSing ->
dsSing :&: mkDoor dsSing mat
(Remember TyCon1 is the defunctionalization symbol constructor that turns any normal type constructor j -> k into a defunctionalization symbol j ~> k)
That’s because a Sigma DoorState (TyCon1 Door) contains a Sing (x :: DoorState) and a TyCon1 Door @@ x, or a Door x.
This is a simple relationship, but one can imagine a Sigma parameterized on an even more complex type-level function. We’ll explore more of these in the exercises.
For some context, Sigma is an interesting data type (the “dependent sum”) that is ubiquitous in dependently typed programming.
Singletons of Defunctionalization Symbolstop
One last thing to tie it all together – let’s write collapseHallway in a way that we don’t know the types of the doors.
Luckily, we now have a SomeHallway type for free:
View full source
type SomeHallway = Sigma [DoorState] (TyCon1 Hallway)
The easy way would be to just use sMergeStateList that we defined:
View full source
collapseSomeHallway :: SomeHallway -> SomeDoor
collapseSomeHallway (ss :&: d) = sMergeStateList ss
:&: collapseHallway d
But what if we didn’t write sMergeStateList, and we constructed our defunctionalization symbols from scratch?
View full source
collapseHallway''
:: Hallway ss
-> Door (FoldrSym2 MergeStateSym0 'Opened @@ ss)
collapseHallway'' HEnd = UnsafeMkDoor "End of Hallway"
collapseHallway'' (d :<# ds) = d `mergeDoor` collapseHallway'' ds
collapseSomeHallway'' :: SomeHallway -> SomeDoor
collapseSomeHallway'' (ss :&: d) = ??? -- what goes here?
:&: collapseHallway'' d
This will be our final defunctionalization lesson. How do we turn a singleton of ss into a singleton of FoldrSym2 MergeStateSym0 'Opened @@ s ?
First – we have Foldr at the value level, as sFoldr. We glossed over this earlier, but singletons generates the following function for us:
type family Foldr (f :: j ~> k ~> k) (z :: k) (xs :: [j]) :: k where
Foldr f z '[] = z
Foldr f z (x ': xs) = (f @@ x) @@ Foldr f z xs
sFoldr
:: Sing (f :: j ~> k ~> k)
-> Sing (z :: k)
-> Sing (xs :: [j])
-> Sing (Foldr f z xs :: k)
sFoldr f z SNil = z
sFoldr f z (x `SCons` xs) = (f @@ x) @@ sFoldr f z xs
Where (@@) :: Sing f -> Sing x -> Sing (f @@ x) (or applySing) is the singleton/value-level counterpart of Apply or (@@).1
So we can write:
collapseSomeHallway'' :: SomeHallway -> SomeDoor
collapseSomeHallway'' (ss :&: d) = sFoldr ???? SOpened ss
:&: collapseHallwa''y d
But how do we get a Sing MergeStateSym0?
We can use the singFun family of functions:
singFun2 @MergeStateSym0 sMergeState
:: Sing MergeStateSym0
But, also, conveniently, the singletons library generates a SingI instance for MergeStateSym0, if you defined mergeState using the singletons template haskell:
sing :: Sing MergeStateSym0
-- or
sing @_ @MergeStateSym0 -- singletons 2.4
sing @MergeStateSym0 -- singletons 2.5
And finally, we get our answer:
View full source
collapseSomeHallway'' :: SomeHallway -> SomeDoor
collapseSomeHallway'' (ss :&: d) =
sFoldr (singFun2 @MergeStateSym0 sMergeState) SOpened ss
-- or
-- sFoldr (sing @MergeStateSym0) SOpened ss
:&: collapseHallway'' d
Closing Uptop
Woo! Congratulations, you’ve made it to the end of the this Introduction to Singletons tetralogy! This last and final part understandably ramps things up pretty quickly, so don’t be afraid to re-read it a few times until it all sinks in before jumping into the exercises.
I hope you enjoyed this journey deep into the motivation, philosophy, mechanics, and usage of this great library. Hopefully these toy examples have been able to show you a lot of ways that type-level programming can help your programs today, both in type safety and in writing more expressive programs. And also, I hope that you can also see now how to leverage the full power of the singletons library to make those gains a reality.
There are a few corners of the library we haven’t gone over (like the TypeLits- and TypeRep-based singletons – if you’re interested, check out this post where I talk a lot about them), but I’d like to hope as well that this series has equipped you to be able to dive into the library documentation and decipher what it holds, armed with the knowledge you now have. (We also look at TypeLits briefly in the exercises)
You can download the source code here — Door4Final.hs contains the final versions of all our definitions, and Defunctionalization.hs contains all of our defunctionalization-from-scratch work. These are designed as stack scripts that you can load into ghci. Just execute the scripts:
$ ./Door4Final.hs
ghci>
And you’ll be dropped into a ghci session with all of the definitions in scope.
As always, please try out the exercises, which are designed to help solidify the concepts we went over here! And if you ever have any future questions, feel free to leave a comment or find me on twitter or in freenode #haskell, where I idle as jle`.
Looking Forwardtop
Some final things to note before truly embracing singletons: remember that, as a library, singletons was always meant to become obsolete. It’s a library that only exists because Haskell doesn’t have real dependent types yet.
Dependent Haskell is coming some day! It’s mostly driven by one solo man, Richard Eisenberg, but every year buzz does get bigger. In a recent progress report, we do know that we realistically won’t have dependent types before 2020. That means that this tutorial will still remain relevant for at least another two years :)
How will things be different in a world of Haskell with real dependent types? Well, for a good guess, take a look at Richard Eisenberg’s Dissertation!
One day, hopefully, we won’t need singletons to work with types at the value-level; we would just be able to directly pattern match and manipulate the types within the language and use them as first-class values, with a nice story for dependent sums. And some day, I hope we won’t need any more dances with defunctionalization symbols to write higher-order functions at the type level — maybe we’ll have a nicer way to work with partially applied type-level functions (maybe they’ll just be normal functions?), and we don’t need to think any different about higher-order or first-order functions.
So, as a final word — Happy Haskelling, everyone! May you leverage the great singletons library to its full potential, and may we also all dream of a day where singletons becomes obsolete. But may we all enjoy the wonderful journey along the way.
Until next time!
Exercisestop
Here are your final exercises for this series! Start from this sample source code, which has all of the definitions that the exercises and their solutions require. Just make sure to delete all of the parts after the -- Exercises comment if you don’t want to be spoiled. Remember again to enable -Werror=incomplete-patterns or -Wall to ensure that all of your functions are total.
Let’s try combining type families with proofs! In doing so, hopefully we can also see the value of using dependent proofs to show how we can manipulate proofs as first-class values that the compiler can verify.
Remember Knockable from Part 3?
View full source
data Knockable :: DoorState -> Type where
KnockClosed :: Knockable 'Closed
KnockLocked :: Knockable 'Locked
Closed and Locked doors are knockable. But, if you merge two knockable doors…is the result also always knockable?
I say yes, but don’t take my word for it. Prove it using Knockable!
View full source
mergedIsKnockable
:: Knockable s
-> Knockable t
-> Knockable (MergeState s t)
mergedIsKnockable is only implementable if the merging of two DoorStates that are knockable is also knockable. See if you can write the implementation!
Solution here!
Write a function to append two hallways together.
appendHallways
:: Hallway ss
-> Hallway ts
-> Hallway ????
from singletons — implement any type families you might need from scratch!
Remember the important principle that your type family must mirror the implementation of the functions that use it.
Next, for fun, use appendHallways to implement appendSomeHallways:
View full source
type SomeHallway = Sigma [DoorState] (TyCon1 Hallway)
appendSomeHallways
:: SomeHallway
-> SomeHallway
-> SomeHallway
Solution here!
Can you use Sigma to define a door that must be knockable?
To do this, try directly defining the defunctionalization symbol KnockableDoor :: DoorState ~> Type (or use singletons to generate it for you — remember that singletons can also promote type families) so that:
type SomeKnockableDoor = Sigma DoorState KnockableDoor
will contain a Door that must be knockable.
Try doing it for both (a) the “dependent proof” version (with the Knockable data type) and for (b) the type family version (with the StatePass type family).
Solutions here! I gave four different ways of doing it, for a full range of manual vs. auto-promoted defunctionalization symbols and Knockable vs. Pass-based methods.
Hint: Look at the definition of SomeDoor in terms of Sigma:
type SomeDoor = Sigma DoorState (TyCon1 Door)
Hint: Try having KnockableDoor return a tuple.
Take a look at the API of the Data.Singletons.TypeLits module, based on the API exposed in GHC.TypeNats module from base.
Using this, you can use Sigma to create a predicate that a given Nat number is even:
data IsHalfOf :: Nat -> Nat ~> Type
type instance Apply (IsHalfOf n) m = n :~: (m * 2)
type IsEven n = Sigma Nat (IsHalfOf n)
(*) is multiplication from the Data.Singletons.Prelude.Num module. (You must have the -XNoStarIsType extension on for this to work in GHC 8.6+), and :~: is the predicate of equality from Part 3:
data (:~:) :: k -> k -> Type where
Refl :: a :~: a
(It’s only possible to make a value of type a :~: b using Refl :: a :~: a, so it’s only possible to make a value of that type when a and b are equal. I like to use Refl with type application syntax, like Refl @a, so it’s clear what we are saying is the same on both sides; Refl @a :: a :~: a)
The only way to construct an IsEven n is to provide a number m where m * 2 is n. We can do this by using SNat @m, which is the singleton constructor for the Nat kind (just like how STrue and SFalse are the singleton constructors for the Bool kind):
tenIsEven :: IsEven 10
tenIsEven = SNat @5 :&: Refl @10
-- Refl is the constructor of type n :~: (m * 2)
-- here, we use it as Refl @10 :: 10 :~: 10
-- won't compile
sevenIsEven :: IsEven 10
sevenIsEven = SNat @4 :&: Refl
-- won't compile, because we need something of type `(4 * 2) :~: 7`,
-- but Refl must have type `a :~: a`; `8 :~: 7` is not constructable
-- using `Refl`. Neither `Refl @8` nor `Refl @7` will work.
Write a similar type IsOdd n that can only be constructed if n is odd.
type IsOdd n = Sigma Nat (???? n)
And construct a proof that 7 is odd:
View full source
sevenIsOdd :: IsOdd 7
Solution here!
On a sad note, one exercise I’d like to be able to add is to ask you to write decision functions and proofs for IsEven and IsOdd. Unfortunately, Nat is not rich enough to support this out of the box without a lot of extra tooling!
A common beginner Haskeller exercise is to implement map in terms of foldr:
map :: (a -> b) -> [a] _> [b]
map f = foldr ((:) . f) []
Let’s do the same thing at the type level, manually.
Directly implement a type-level Map, with kind (j ~> k) -> [j] -> [k], in terms of Foldr:
type Map f xs = Foldr ???? ???? xs
Try to mirror the value-level definition, passing in (:) . f, and use the promoted version of (.) from the singletons library, in Data.Singletons.Prelude. You might find TyCon2 helpful!
Solution here!
Make a SomeHallway from a list of SomeDoor:
View full source
type SomeDoor = Sigma DoorState (TyCon1 Door)
type SomeHallway = Sigma [DoorState] (TyCon1 Hallway)
mkSomeHallway :: [SomeDoor] -> SomeHallway
Remember that the singleton constructors for list are SNil (for []) and SCons (for (:))!
Solution here!
-}
| null | https://raw.githubusercontent.com/haroldcarr/learn-haskell-coq-ml-etc/344eedbe0e9625bd6a43619ab9c60b3aaa817443/haskell/topic/type-level/2017-12-2018-10-justin-le-intro-to-singletons-parts-1-4/src/Part4.hs | haskell | Alternatively , taking advantage of the derived instance :
^ end of the hallway , a stretch with no
doors
^ A door connected to a hallway is a new
hallway , and we track the door 's state
in the list of hallway door states
^ the identity of mergeState
^ the identity of mergeState
also generated for consistency
or
or FalseSym0 , which is a synonym for ' False
^ take a type constructor
^ return a defunctionalization symbol
alternatively
data ( t : : j - > k ) : : j ~ > k
Does n't work like you think it does
or
also available through fancy type synonym
what goes here ?
or
singletons 2.4
singletons 2.5
or
sFoldr ( sing ) SOpened ss
Exercises comment if you do n’t want to be spoiled . Remember again to enable -Werror = incomplete - patterns or -Wall to ensure that all of your functions are total .
here , we use it as Refl @10 : : 10 : ~ : 10
wo n't compile
wo n't compile , because we need something of type ` ( 4 * 2 ) : ~ : 7 ` ,
but must have type ` a : ~ : a ` ; ` 8 : ~ : 7 ` is not constructable
using ` Refl ` . Neither ` Refl @8 ` nor ` Refl @7 ` will work .
Alternatively, taking advantage of the derived Ord instance:
^ end of the hallway, a stretch with no
doors
^ A door connected to a hallway is a new
hallway, and we track the door's state
in the list of hallway door states
^ the identity of mergeState
^ the identity of mergeState
also generated for consistency
or
or FalseSym0, which is a synonym for 'False
^ take a type constructor
^ return a defunctionalization symbol
alternatively
data TyCon1 (t :: j -> k) :: j ~> k
Doesn't work like you think it does
or
also available through fancy type synonym
what goes here?
or
singletons 2.4
singletons 2.5
or
sFoldr (sing @MergeStateSym0) SOpened ss
Exercises comment if you don’t want to be spoiled. Remember again to enable -Werror=incomplete-patterns or -Wall to ensure that all of your functions are total.
Refl is the constructor of type n :~: (m * 2)
here, we use it as Refl @10 :: 10 :~: 10
won't compile
won't compile, because we need something of type `(4 * 2) :~: 7`,
but Refl must have type `a :~: a`; `8 :~: 7` is not constructable
using `Refl`. Neither `Refl @8` nor `Refl @7` will work. | module Part4 where
-to-singletons-4.html
Introduction to Singletons ( Part 4 )
Monday October 22 , 2018
functional programming at the type level .
GHC 8.6.1
nightly-2018 - 09 - 29 ( singletons-2.5 )
Review
View full source
$ ( singletons [ d|
data DoorState = Opened | Closed | Locked
deriving ( Show , Eq , Ord )
| ] )
data Door : : DoorState - > Type where
UnsafeMkDoor : : { doorMaterial : : String } - > Door s
mkDoor : : Sing s - > String - > Door s
mkDoor _ = UnsafeMkDoor
And we talked about using Sing s , or SDoorState s , to represent the state of the door ( in its type ) as a run - time value . We ’ve been using a wrapper to existentially hide the door state type , but also stuffing in a singleton to let us recover the type information once we want it again :
data SomeDoor : : Type where
MkSomeDoor : : Sing s - > Door s - > SomeDoor
mkSomeDoor : : DoorState - > String - > SomeDoor
mkSomeDoor ds mat = withSomeSing ds $ \dsSing - >
MkSomeDoor dsSing ( mkDoor dsSing mat )
In Part 3 we talked about a Pass data type that we used to talk about whether or not we can walk through or knock on a door :
$ ( singletons [ d|
data Pass = Obstruct | Allow
deriving ( Show , Eq , Ord )
| ] )
And we defined type - level functions on it using singletons :
$ ( singletons [ d|
statePass : : DoorState - > Pass
statePass Opened = Allow
statePass Closed = Obstruct
statePass Locked = Obstruct
| ] )
This essentially generates these three things :
statePass : : DoorState - > Pass
statePass Opened = Allow
statePass Closed = Obstruct
statePass Locked = Obstruct
type family StatePass ( s : : DoorState ) : : Pass where
StatePass ' Opened = ' Allow
StatePass ' Closed = ' Obstruct
StatePass ' Locked = ' Obstruct
sStatePass : : Sing s - > Sing ( StatePass s )
sStatePass = \case
SOpened - > SAllow
SClosed - > SObstruct
SLocked - > SObstruct
And we can use StatePass as a type - level function while using sStatePass to manipulate the singletons representing s and StatePass s.
We used this as a constraint to restrict how we can call our functions :
View full source
knockP : : ( StatePass s ~ ' Obstruct ) = > Door s - > IO ( )
knockP d = " Knock knock on " + + doorMaterial d + + " door ! "
But then we wondered … is there a way to not only restrict our functions , but to describe how the inputs and outputs are related to each other ?
Inputs and Outputstop
In the past we have settled with very simple relationships , like :
closeDoor : : Door ' Opened - > Door ' Closed
This means that the relationship between the input and output is that the input is opened … and is then closed .
However , armed with promotion of type - level functions , writing more complex relationships becomes fairly straightforward !
We can write a function mergeDoor that “ merges ” two doors together , in sequence :
mergeDoor : : Door s - > Door t - > Door ? ? ? ?
mergeDoor d e = UnsafeMkDoor $ doorMaterial d + + " and " + + doorMaterial e
A merged door will have a material that is composite of the original materials . But , what will the new DoorState be ? What goes in the ? ? ? above ?
Well , if we can write the function as a normal function in values … singletons lets us use it as a function on types . Let ’s write that relationship . Let ’s say merging takes on the higher “ security ” option — merging opened with locked is locked , merging closed with opened is closed , merging locked with closed is locked .
$ ( singletons [ d|
mergeState : : DoorState - > DoorState - > DoorState
mergeState Opened d = d
mergeState Closed Opened = Closed
mergeState Closed Closed = Closed
mergeState Closed Locked = Locked
mergeState Locked _ = Locked
| ] )
$ ( singletons [ d|
mergeState : : DoorState - > DoorState - > DoorState
mergeState = ] )
This makes writing mergeDoor ’s type clean to read :
View full source
mergeDoor
: : Door s
- > Door t
- > Door ( MergeState s t )
mergeDoor d e = UnsafeMkDoor $ doorMaterial d + + " and " + + doorMaterial e
And , with the help of singletons , we can also write this for our doors where we do n’t know the types until runtime :
View full source
mergeSomeDoor : : SomeDoor - > SomeDoor - > SomeDoor
mergeSomeDoor ( MkSomeDoor s d ) ( MkSomeDoor t e ) =
MkSomeDoor ( sMergeState s t ) ( mergeDoor d e )
To see why this typechecks properly , compare the types of sMergeState and mergeDoor :
sMergeState : : Sing s - > Sing t - > Sing ( MergeState s t )
mergeDoor : : Door s - > Door t - > Door ( MergeState s t )
MkSomeDoor : : Sing ( MergeState s t ) - > Door ( MergeState s t ) - > SomeDoor
Because the results both create types MergeState s t , MkSomeDoor is happy to apply them to each other , and everything typechecks . However , if , say , we directly stuffed s or t into MkSomeDoor , things would fall apart and not .
And so now we have full expressiveness in determining input and output relationships ! Once we unlock the power of type - level functions with singletons , writing type - level relationships become as simple as writing value - level ones . If you can write a value - level function , you can write a type - level function .
Kicking it up a notchtop
How far we can really take this ?
Let ’s make a data type that represents a series of hallways , each linked by a door . A hallway is either an empty stretch with no door , or two hallways linked by a door . We ’ll structure it like a linked list , and store the list of all door states as a type - level list as a type parameter :
View full source
data Hallway : : [ DoorState ] - > Type where
(: < # ) : : Door s
- > Hallway ss
infixr 5 : < #
( If you need a refresher on type - level lists , check out the quick introduction in Part 1 and Exercise 4 in Part 2 )
So we might have :
ghci > let door1 = mkDoor SClosed " Oak "
ghci > let door2 = mkDoor SOpened " Spruce "
ghci > let = mkDoor SLocked " Acacia "
ghci > : t door1 : < # door2 : < # : < # HEnd
Hallway ' [ ' Closed , ' Opened , ' Locked ]
That is , a Hallway ' [ s , t , u ] is a hallway consisting of a Door s , a Door t , and a Door u , constructed like a linked list in Haskell .
Now , let ’s write a function to collapse all doors in a hallway down to a single door :
collapseHallway : : Hallway ss - > Door ? ? ? ? ?
Basically , we want to merge all of the doors one after the other , collapsing it until we have a single door state . Luckily , MergeState is both commutative and associative and has an identity , so this can be defined sensibly .
First , let ’s think about the type we want . What will the result of merging ss be ?
We can pattern match and collapse an entire list down item - by - item :
$ ( singletons [ d|
mergeStateList : : [ DoorState ] - > DoorState
mergeStateList ( s : ss ) = s ` mergeState ` mergeStateList ss
| ] )
Again , remember that this also defines the type family MergeStateList and the singleton function sMergeStateList : : Sing ss - > Sing ( MergeStateList ss ) .
With this , we can write collapseHallway :
View full source
collapseHallway : : Hallway ss - > Door ( MergeStateList ss )
collapseHallway HEnd = mkDoor SOpened " End of Hallway "
collapseHallway ( d : < # ds ) = d ` mergeDoor ` collapseHallway ds
Now , because the structure of collapseHallway perfectly mirrors the structure of mergeStateList , this all typechecks , and we ’re done !
ghci > collapseHallway ( door1 : < # door2 : < # : < # HEnd )
UnsafeMkDoor " Oak and Spruce and Acacia and End of Hallway "
: : Door ' Locked
Note one nice benefit – the door state of collapseHallway ( door1 : < # door2 : < # : < # HEnd ) is known at compile - time to be Door ' Locked , if the types of all of the component doors are also known !
Functional
We went over that all a bit fast , but some of you might have noticed that the definition of mergeStateList bears a really strong resemblance to a very common list processing pattern :
mergeStateList : : [ DoorState ] - > DoorState
mergeStateList ( s : ss ) = s ` mergeState ` mergeStateList ss
The algorithm is to basically [ ] with Opened , and all ( :) with mergeState . If this sounds familiar , that ’s because this is exactly a right fold ! ( In fact , hlint actually made this suggestion to me while I was writing this )
mergeStateList : : [ DoorState ] - > DoorState
mergeStateList = foldr mergeState Opened
In Haskell , we are always encouraged to use higher - order functions whenever possible instead of explicit recursion , both because explicit recursion opens you up to a lot of potential bugs , and also because using established higher - order functions make your code more readable .
So , as Haskellers , let us hold ourselves to a higher standard and not be satisfied with a MergeState written using explicit recursion . Let us instead go full fold — ONWARD HO !
The Problemtop
Initial attempts to write a higher - order type - level function as a type family , however , serve to temper our enthusiasm .
type family ( f : : j - > k - > k ) ( z : : k ) ( xs : : [ j ] ) : : k where
Foldr f z ' [ ] = z
Foldr f z ( x ' : xs ) = f x ( Foldr f z xs )
So far so good right ? So we should expect to be able to write MergeStateList using , MergeState , and ' Opened
type MergeStateList ss = Foldr MergeState ' Opened ss
Ah , but the compiler is here to tell you this is n’t allowed in :
• The type family ‘ MergeState ’ should have 2 arguments , but has been given none
• In the equations for closed type family ‘ MergeStateList ’
In the type family declaration for ‘ MergeStateList ’
What happened ? To figure out , we have to remember that pesky restriction on type synonyms and type families : they can not be used partially applied ( “ unsaturated ” ) , and must always be fully applied ( “ saturated ” ) . For the most part , only type constructors ( like Maybe , Either , IO ) and lifted DataKinds data constructors ( like ' Just , ' ( :) ) in Haskell can ever be partially applied at the type level . We therefore ca n’t use MergeState as an argument to , because MergeState must always be fully applied .
Unfortunately for us , this makes our effectively useless . That ’s because we ’re always going to want to pass in type families ( like MergeState ) , so there ’s pretty much literally no way to ever actually call except with type constructors or lifted DataKinds data constructors .
So … back to the drawing board ?
I like to mentally think of the singletons library as having two parts : the first is linking lifted DataKinds types with run - time values to allow us to manipulate types at runtime as first - class values . The second is a system for effective functional programming at the type level .
To make a working , we ’re going to have to jump into that second half : defunctionalization .
Defunctionalization is a technique invented in the early 70 ’s as a way of compiling higher - order functions into first - order functions in target languages . The main idea is :
Instead of working with functions , work with symbols representing functions .
Build your final functions and values by composing and combining these symbols .
At the end of it all , have a single Apply function interpret all of your symbols and produce the value you want .
In singletons these symbols are implemented as “ dummy ” empty data constructors , and Apply is a type family .
To help us understand ’s defunctionalization system better , let ’s build our own defunctionalization system from scratch .
First , a little trick to make things easier to read :
View full source
data TyFun a b
type a ~ > b = TyFun a b - > Type
infixr 0 ~ >
Our First Symbolstop
Now we can define a dummy data type like I d , which represents the identity function i d :
View full source
data I d : : a ~ > a
The “ actual ” kind of I d is I d : : TyFun a a - > Type ; you can imagine TyFun a a as a phantom parameter that signifies that I d represents a function from a to a. It ’s essentially a nice trick to allow you to write I d : : a ~ > a as a kind signature .
Now , I d is not a function … it ’s a dummy type constructor that represents a function a - > a. A type constructor of kind a ~ > a represents a defunctionalization symbol – a type constructor that represents a function from a to a.
To interpret it , we need to write our global interpreter function :
View full source
type family Apply ( f : : a ~ > b ) ( x : : a ) : : b
That ’s the syntax for the definition of an open type family in : users are free to add their own instances , just like how type classes are normally open in Haskell .
Let ’s tell Apply how to interpret I d :
View full source
type instance Apply I d x = x
The above is the actual function definition , like writing i d x = x. We can now call I d to get an actual type in return :
ghci > : kind ! Apply I d ' True
' True
( Remember , : kind ! is the ghci command to evaluate a type family )
Let ’s define another one ! We ’ll implement Not :
View full source
data Not : : Bool ~ > Bool
type instance Apply Not ' False = ' True
type instance Apply Not ' True = ' False
We can try it out :
ghci > : kind ! Apply Not ' True
' False
ghci > : kind ! Apply Not ' False
' True
It can be convenient to define an infix synonym for Apply :
View full source
type f @@ a = Apply f a
infixl 9 @@
Then we can write :
ghci > : kind ! Not @@ ' False
' True
ghci > : kind ! I d @@ ' True
' True
Remember , I d and Not are not actual functions — they ’re just dummy data types ( “ defunctionalization symbols ” ) , and we define the functions they represent through the global Apply type function .
A Bit of Principletop
So we ’ve got the basics of defunctionalization — instead of using functions directly , use dummy symbols that encode your functions that are interpreted using Apply . Let ’s add a bit of principle to make this all a bit more scalable .
The singletons library adopts a few conventions for linking all of these together . Using the Not function as an example , if we wanted to lift the function :
not : : Bool - > Bool
not False = True
not True = Flse
We already know about the type family and singleton function this would produce :
type family Not ( x : : ) : : where
Not ' False = ' True
Not ' True = ' False
sNot : : Sing x - > Sing ( Not x )
sNot SFalse = STrue
= SFalse
But the singletons library also produces the following defunctionalization symbols , according to a naming convention :
data NotSym0 : : Bool ~ > Bool
type instance Apply NotSym0 x = Not x
type x = Not x
NotSym0 is the defunctionalization symbol associated with the Not type family , defined so that NotSym0 = Not x. Its purpose is to allow us to pass in Not as an un - applied function . The Sym0 suffix is a naming convention , and the 0 stands for “ expects 0 arguments ” . Similarly for – the 1 stands for “ expects 1 argument ” .
Two - Argument Functionstop
Let ’s look at a slightly more complicated example – a two - argument function . Let ’s define the boolean “ and ” :
$ ( singletons [ d|
and : : Bool - > ( Bool - > Bool )
and False _ = False
and True x = x
] )
this will generate :
type family And ( x : : ) ( y : : ) : : where
And ' False x = ' False
And ' True x = x
: : Sing x - > Sing y - > Sing ( And x y )
= SFalse
= x
And the defunctionalization symbols :
data AndSym0 : : Bool ~ > ( Bool ~ > Bool )
type instance Apply AndSym0 x = AndSym1 x
data AndSym1 ( x : : ) : : ( Bool ~ > Bool )
data AndSym1 : : Bool - > ( Bool ~ > Bool )
type instance Apply ( AndSym1 x ) y = And x y
type AndSym2 x y = And x y
AndSym0 is a defunctionalization symbol representing a “ fully unapplied ” ( “ completely unsaturated ” ) version of And . AndSym1 x is a defunctionalization symbol representing a “ partially applied ” version of And — partially applied to x ( its kind is AndSym1 : : Bool - > ( Bool ~ > ) ) .
The application of AndSym0 to x gives you AndSym1 x :
ghci > : kind ! AndSym0 @@ ' False
AndSym1 ' False
Remember its kind AndSym0 : : Bool ~ > ( Bool ~ > ) ( or just AndSym0 : : Bool ~ > Bool ~ > ): it takes a Bool , and returns a Bool ~ > Bool defunctionalization symbol .
The application of AndSym1 x to y gives you And x y :
ghci > : kind ! AndSym1 ' False @@ ' True
ghci > : kind ! AndSym1 ' True @@ ' True
' True
A note to remember : AndSym1 ' True is the defunctionalization symbol , and not AndSym1 itself . AndSym1 has kind Bool - > ( Bool ~ > ) , but AndSym1 ' True has kind Bool ~ > — the kind of a defunctionalization symbol . AndSym1 is a sort of “ defunctionalization symbol constructor ” .
Also note here that we encounter the fact that singletons also provides “ defunctionalization symbols ” for “ nullary ” type functions like False and True , where :
type FalseSym0 = ' False
type TrueSym0 = ' True
Just like how it defines AndSym0 for consistency , as well .
Symbols for type constructorstop
One extra interesting defunctionalization symbol we can write : we turn lift any type constructor into a “ free ” defunctionalization symbol :
View full source
data
type instance Apply ( t ) a = t a
Basically the Apply instance just applies the type constructor t to its input a.
ghci > : kind ! Maybe @@ Int
Maybe Int
ghci > : kind ! ' Right @@ ' False
' Right ' False
We can use this to give a normal j - > k type constructor to a function that expects a j ~ > k defunctionalization symbol .
Bring Me a Higher Ordertop
Okay , so now we have these tokens that represent “ unapplied ” versions of functions . So what ?
Well , remember the problem with our implementation of ? We could n’t pass in a type family , since type families must be passed fully applied . So , instead of having expect a type family … we can make it expect a defunctionalization symbol instead . Remember , defunctionalization symbols represent the “ unapplied ” versions of type families , so they are exactly the tools we need !
View full source
type family ( f : : j ~ > k ~ > k ) ( z : : k ) ( xs : : [ j ] ) : : k where
Foldr f z ' [ ] = z
Foldr f z ( x ' : xs ) = ( f @@ x ) z xs
The difference is that instead of taking a type family or type constructor f : : j - > k - > k , we have it take the defunctionalization symbol f : : j ~ > ( k ~ > k ) .
Instead of taking a type family or type constructor , we take that dummy type constructor .
Now we just need to have our defunctionalization symbols for MergeStateList :
View full source
data MergeStateSym0 : : DoorState ~ > DoorState ~ > DoorState
type instance Apply MergeStateSym0 s = MergeStateSym1 s
data MergeStateSym1 : : DoorState - > DoorState ~ > DoorState
type instance Apply ( MergeStateSym1 s ) t = MergeState s t
type MergeStateSym2 s t = MergeState s t
And now we can write MergeStateList :
View full source
type MergeStateList ss = Foldr MergeStateSym0 ' Opened ss
( If you “ see ” MergeStateSym0 , you should read it was MergeState , but partially applied )
This compiles !
ghci > : kind ! MergeStateList ' [ ' Closed , ' Opened , ' Locked ]
' Locked
ghci > : kind ! MergeStateList ' [ ' Closed , ' Opened ]
' Closed
View full source
collapseHallway : : Hallway ss - > Door ( MergeStateList ss )
collapseHallway HEnd = UnsafeMkDoor " End of Hallway "
collapseHallway ( d : < # ds ) = d ` mergeDoor ` collapseHallway ds
( Note : Unfortunately , we do have to use our our own here , that we just defined , instead of using the one that comes with singletons , because of some outstanding issues with how the singletons TH processes alternative implementations of foldr from Prelude . In general , the issue is that we should only expect type families to work with singletons if the definition of the type family perfectly matches the structure of how we implement our value - level functions like collapseHallway )
Singletons to make things nicertop
Admittedly this is all a huge mess of boilerplate . The code we had to write more than tripled , and we also have an unsightly number of defunctionalization symbols and Apply instance boilerplate for every function .
Luckily , the singletons library is here to help . You can just write :
$ ( singletons [ d|
data DoorState = Opened | Closed | Locked
deriving ( Show , Eq , Ord )
mergeState : : DoorState - > DoorState - > DoorState
mergeState = : : ( a - > b - > b ) - > b - > [ a ] - > b
foldr _ z [ ] = z
foldr f z ( x : xs ) = f x ( foldr f z xs )
mergeStateList : : [ DoorState ] - > DoorState
mergeStateList = foldr mergeState Opened
| ] )
And all of these defunctionalization symbols are generated for you ; singletons is also able to recognize that foldr is a higher - order function and translate its lifted version to take a defunctionalization symbol a ~ > b ~ > b.
That the template haskell also generates SingI instances for all of your defunctionalization symbols , too ( more on that in a bit ) .
It ’s okay to stay “ in the world of singletons ” for the most part , and let singletons handle the composition of functions for you . However , it ’s still important to know what the singletons library generates , because sometimes it ’s still useful to manually create defunctionalization symbols and work with them .
The naming convention for non - symbolic names ( non - operators ) like myFunction are just to call them MyFunctionSym0 for the completely unapplied defunctionalization symbol , for the type constructor that expects one argument before returning a defunctionalization symbol , MyFunctionSym2 for the type constructor that expects two arguments before returning a defunctionalization symbol , etc .
For operator names like + + , the naming convention is to have + + @#@$ be the completely unapplied defunctionalization symbol , + + @#@$$ be the type constructor that expects one argument before returning a defunctionalization symbol , + + @#@$$$ be the type constructor that takes two arguments before returning a defunctionalization symbol , etc .
Another helpful thing that singletons does is that it also generates defunctionalization symbols for type families and type synonyms you define in the Template Haskell , as well — so if you write
$ ( singletons [ d|
type MyTypeFamily ( b : : ) : : Type where
MyTypeFamily ' False = Int
MyTypeFamily ' True = String
| ] )
and
$ ( singletons [ d|
type MyTypeSynonym a = ( a , [ a ] )
| ] )
singletons will generate :
data MyTypeFamilySym0 : : Bool ~ > Type
type instance Apply MyTypeFamilySym0 b = MyTypeFamily b
type b = MyTypeFamily b
and
data MyTypeSynonymSym0 : : Type ~ > Type
type instance Apply MyTypeSynonym b = MyTypeSynonym a
type MyTypeSynonymSym1 a = MyTypeSynonym a
Bringing it All Togethertop
Just to show off the library , remember that singletons also promotes typeclasses ?
Because DoorState is a monoid with respect to merging , we can actually write and promote a Monoid instance : ( requires singletons-2.5 or higher )
$ ( singletons [ d|
instance Semigroup DoorState where
( < > ) = mergeState
instance where
= Opened
mappend = ( < > )
| ] )
We can promote fold :
$ ( singletons [ d|
fold : : Monoid b = > [ b ] - > b
fold [ ] = fold ( x : xs ) = x < > fold xs
| ] )
And we can write collapseHallway in terms of those instead :)
View full source
collapseHallway '
: : Hallway ss
- > Door ( Fold ss )
collapseHallway ' HEnd = UnsafeMkDoor " End of Hallway "
collapseHallway ' ( d : < # ds ) = d ` mergeDoor ` collapseHallway ' ds
collapseSomeHallway ' : : SomeHallway - > SomeDoor
collapseSomeHallway ' ( ss : & : d ) =
sFold ss
: & : collapseHallway ' d
( Note again unfortunately that we have to define our own fold instead of using the one from singletons and the SFoldable typeclass , because of issue # 339 )
Thoughts on symbols may feel like a bit of a mess , and the naming convention is arguably less than aesthetically satisfying . But , as you work with them more and more , you start to appreciate them on a deeper level .
At the end of the day , you can compare defunctionalization as turning “ functions ” into just constructors you can match on , just like any other data or type constructor . That ’s because they are just type constructors !
In a sense , defining defunctionalization symbols is a lot like working with pattern synonyms of your functions , instead of directly passing the functions themselves . At the type family and type class level , you can “ pattern match ” on these functions .
For a comparison at the value level – you ca n’t pattern match on ( + ) , ( - ) , ( * ) , and ( / ):
invertOperation : : ( Double - > Dobule - > Double ) - > ( Double - > Double - > Double )
invertOperation ( + ) = ( - )
invertOperation ( - ) = ( + )
invertOperation ( * ) = ( / )
invertOperation ( / ) = ( * )
You ca n’t quite match on the equality of functions to some list of patterns . But , what you can do is create constructors representing your functions , and match on those .
This essentially fixes the “ type lambda problem ” of type inference and typeclass resolution . You ca n’t match on arbitrary lambdas , but you can match on dummy constructors representing type functions .
And a bit of the magic here , also , is the fact that you do n’t always need to make our own defunctionalization symbols from scratch — you can create them based on other ones in a compositional way . This is the basis of libraries like decidable .
For example , suppose we wanted to build defunctionalization symbols for MergeStateList . We can actually build them directly from defunctionalization symbols for .
Check out the defunctionalization symbols for :
View full source
data FoldrSym0 : : ( j ~ > k ~ > k ) ~ > k ~ > [ j ] ~ > k
type instance Apply FoldrSym0 f = FoldrSym1 f
data FoldrSym1 : : ( j ~ > k ~ > k ) - > k ~ > [ j ] ~ > k
type instance Apply ( FoldrSym1 f ) z = FoldrSym2 f z
data FoldrSym2 : : ( j ~ > k ~ > k ) - > k - > [ j ] ~ > k
type instance Apply ( FoldrSym2 f z ) xs = Foldr f z xs
type FoldrSym3 f z xs = Foldr f z xs
We can actually use these to define our MergeStateList defunctionalization symbols , since defunctionalization symbols are first - class :
View full source
type MergeStateListSym0 = FoldrSym2 MergeStateSym0 ' Opened
And you can just write collapseHallway as :
collapseHallway : : Hallway ss - > Door ( MergeStateListSym0 @@ ss )
collapseHallway : : Hallway ss - > Door ( FoldrSym2 MergeStateSym0 ' Opened @@ ss )
You never have to actually define MergeStateList as a function or type family !
The whole time , we ’re just building defunctionalization symbols in terms of other defunctionalization symbols . And , at the end , when we finally want to interpret the complex function we construct , we use Apply , or @@.
You can think of FoldrSym1 and FoldrSym2 as defunctionalization symbol constructors – they ’re combinators that take in defunctionalization symbols ( like MergeStateSym0 ) and return new ones .
Sigmatop
Let ’s look at a nice tool that is made possible using defunctionalization symbols : dependent pairs . I talk a bit about dependent pairs ( or dependent sums ) in part 2 of this series , and also in my dependent types in Haskell series .
Essentially , a dependent pair is a tuple where the type of the second field depends on the value of the first one . This is basically what SomeDoor was :
data SomeDoor : : Type where
MkSomeDoor : : Sing x - > Door x - > SomeDoor
The type of the Door x depends on the value of the Sing x , which you can read as essentially storing the x.
We made SomeDoor pretty ad - hoc . But what if we wanted to make some other predicate ? Well , we can make a generic dependent pair by parameterizing it on the dependence between the first and second field . Singletons provides the Sigma type , in the Data . Singletons . Sigma module :
data Sigma k : : ( k ~ > Type ) - > Type where
(: & :) : : Sing x - > ( f @@ x ) - > Sigma k f
type Σ k = Sigma k
If you squint carefully , you can see that Sigma k is just SomeDoor , but parameterized over Door . Instead of always holding Door x , we can have it parameterized on an arbitrary function f and have it hold an f @@ x.
We can actually define SomeDoor in terms of Sigma :
View full source
type SomeDoor = Sigma DoorState ( TyCon1 Door )
mkSomeDoor : : DoorState - > String - > SomeDoor
mkSomeDoor ds mat = withSomeSing ds $ \dsSing - >
dsSing : & : mkDoor dsSing mat
( Remember is the defunctionalization symbol constructor that turns any normal type constructor j - > k into a defunctionalization symbol j ~ > k )
That ’s because a Sigma DoorState ( TyCon1 Door ) contains a Sing ( x : : DoorState ) and a TyCon1 Door @@ x , or a Door x.
This is a simple relationship , but one can imagine a Sigma parameterized on an even more complex type - level function . We ’ll explore more of these in the exercises .
For some context , Sigma is an interesting data type ( the “ dependent sum ” ) that is ubiquitous in dependently typed programming .
Singletons of
One last thing to tie it all together – let ’s write collapseHallway in a way that we do n’t know the types of the doors .
Luckily , we now have a SomeHallway type for free :
View full source
type SomeHallway = Sigma [ DoorState ] ( )
The easy way would be to just use sMergeStateList that we defined :
View full source
collapseSomeHallway : : SomeHallway - > SomeDoor
collapseSomeHallway ( ss : & : d ) =
But what if we did n’t write sMergeStateList , and we constructed our defunctionalization symbols from scratch ?
View full source
collapseHallway ''
: : Hallway ss
- > Door ( FoldrSym2 MergeStateSym0 ' Opened @@ ss )
collapseHallway '' HEnd = UnsafeMkDoor " End of Hallway "
collapseHallway '' ( d : < # ds ) = d ` mergeDoor ` collapseHallway '' ds
collapseSomeHallway '' : : SomeHallway - > SomeDoor
: & : collapseHallway '' d
This will be our final defunctionalization lesson . How do we turn a singleton of ss into a singleton of FoldrSym2 MergeStateSym0 ' Opened @@ s ?
First – we have at the value level , as . We glossed over this earlier , but singletons generates the following function for us :
type family ( f : : j ~ > k ~ > k ) ( z : : k ) ( xs : : [ j ] ) : : k where
Foldr f z ' [ ] = z
Foldr f z ( x ' : xs ) = ( f @@ x ) z xs
sFoldr
: : Sing ( f : : j ~ > k ~ > k )
- > Sing ( z : : k )
- > Sing ( xs : : [ j ] )
- > Sing ( Foldr f z xs : : k )
sFoldr f z SNil = z
sFoldr f z ( x ` SCons ` xs ) = ( f @@ x ) z xs
Where ( @@ ) : : Sing f - > Sing x - > Sing ( f @@ x ) ( or applySing ) is the singleton / value - level counterpart of Apply or ( @@).1
So we can write :
collapseSomeHallway '' : : SomeHallway - > SomeDoor
collapseSomeHallway '' ( ss : & : d ) = sFoldr ? ? ? ? SOpened ss
: & : collapseHallwa''y d
But how do we get a Sing MergeStateSym0 ?
We can use the singFun family of functions :
singFun2 @MergeStateSym0 sMergeState
: : Sing MergeStateSym0
But , also , conveniently , the singletons library generates a SingI instance for MergeStateSym0 , if you defined mergeState using the singletons template haskell :
sing : : Sing MergeStateSym0
And finally , we get our answer :
View full source
collapseSomeHallway '' : : SomeHallway - > SomeDoor
collapseSomeHallway '' ( ss : & : d ) =
sFoldr ( singFun2 @MergeStateSym0 sMergeState ) SOpened ss
: & : collapseHallway '' d
Closing Uptop
Woo ! Congratulations , you ’ve made it to the end of the this Introduction to Singletons tetralogy ! This last and final part understandably ramps things up pretty quickly , so do n’t be afraid to re - read it a few times until it all sinks in before jumping into the exercises .
I hope you enjoyed this journey deep into the motivation , philosophy , mechanics , and usage of this great library . Hopefully these toy examples have been able to show you a lot of ways that type - level programming can help your programs today , both in type safety and in writing more expressive programs . And also , I hope that you can also see now how to leverage the full power of the singletons library to make those gains a reality .
There are a few corners of the library we have n’t gone over ( like the TypeLits- and TypeRep - based singletons – if you ’re interested , check out this post where I talk a lot about them ) , but I ’d like to hope as well that this series has equipped you to be able to dive into the library documentation and decipher what it holds , armed with the knowledge you now have . ( We also look at TypeLits briefly in the exercises )
You can download the source code here — Door4Final.hs contains the final versions of all our definitions , and Defunctionalization.hs contains all of our defunctionalization - from - scratch work . These are designed as stack scripts that you can load into ghci . Just execute the scripts :
$ ./Door4Final.hs
ghci >
And you ’ll be dropped into a ghci session with all of the definitions in scope .
As always , please try out the exercises , which are designed to help solidify the concepts we went over here ! And if you ever have any future questions , feel free to leave a comment or find me on twitter or in freenode # haskell , where I idle as jle ` .
Looking
Some final things to note before truly embracing singletons : remember that , as a library , singletons was always meant to become obsolete . It ’s a library that only exists because does n’t have real dependent types yet .
Dependent is coming some day ! It ’s mostly driven by one solo man , , but every year buzz does get bigger . In a recent progress report , we do know that we realistically wo n’t have dependent types before 2020 . That means that this tutorial will still remain relevant for at least another two years :)
How will things be different in a world of Haskell with real dependent types ? Well , for a good guess , take a look at Dissertation !
One day , hopefully , we wo n’t need singletons to work with types at the value - level ; we would just be able to directly pattern match and manipulate the types within the language and use them as first - class values , with a nice story for dependent sums . And some day , I hope we wo n’t need any more dances with defunctionalization symbols to write higher - order functions at the type level — maybe we ’ll have a nicer way to work with partially applied type - level functions ( maybe they ’ll just be normal functions ? ) , and we do n’t need to think any different about higher - order or first - order functions .
So , as a final word — , everyone ! May you leverage the great singletons library to its full potential , and may we also all dream of a day where singletons becomes obsolete . But may we all enjoy the wonderful journey along the way .
Until next time !
Let ’s try combining type families with proofs ! In doing so , hopefully we can also see the value of using dependent proofs to show how we can manipulate proofs as first - class values that the compiler can verify .
Remember from Part 3 ?
View full source
data : : DoorState - > Type where
KnockClosed : : ' Closed
KnockLocked : : ' Locked
Closed and Locked doors are knockable . But , if you merge two knockable doors … is the result also always knockable ?
I say yes , but do n’t take my word for it . Prove it using Knockable !
View full source
mergedIsKnockable
: : s
- > Knockable t
- > Knockable ( MergeState s t )
mergedIsKnockable is only implementable if the merging of two DoorStates that are knockable is also knockable . See if you can write the implementation !
Solution here !
Write a function to append two hallways together .
appendHallways
: : Hallway ss
- > Hallway ts
- > Hallway ? ? ? ?
from singletons — implement any type families you might need from scratch !
Remember the important principle that your type family must mirror the implementation of the functions that use it .
Next , for fun , use appendHallways to implement appendSomeHallways :
View full source
type SomeHallway = Sigma [ DoorState ] ( )
appendSomeHallways
: : SomeHallway
- > SomeHallway
- > SomeHallway
Solution here !
Can you use Sigma to define a door that must be knockable ?
To do this , try directly defining the defunctionalization symbol KnockableDoor : : DoorState ~ > Type ( or use singletons to generate it for you — remember that singletons can also promote type families ) so that :
type SomeKnockableDoor = Sigma DoorState KnockableDoor
will contain a Door that must be knockable .
Try doing it for both ( a ) the “ dependent proof ” version ( with the data type ) and for ( b ) the type family version ( with the StatePass type family ) .
Solutions here ! I gave four different ways of doing it , for a full range of manual vs. auto - promoted defunctionalization symbols and vs. Pass - based methods .
Hint : Look at the definition of SomeDoor in terms of Sigma :
type SomeDoor = Sigma DoorState ( TyCon1 Door )
Hint : Try having KnockableDoor return a tuple .
Take a look at the API of the Data . Singletons . TypeLits module , based on the API exposed in GHC.TypeNats module from base .
Using this , you can use Sigma to create a predicate that a given number is even :
data IsHalfOf : : > Type
type instance Apply ( IsHalfOf n ) m = n : ~ : ( m * 2 )
type IsEven n = ( IsHalfOf n )
( * ) is multiplication from the Data . Singletons . Prelude . Num module . ( You must have the -XNoStarIsType extension on for this to work in GHC 8.6 + ) , and : ~ : is the predicate of equality from Part 3 :
data (: ~ :) : : k - > k - > Type where
Refl : : a : ~ : a
( It ’s only possible to make a value of type a : ~ : b using : : a : ~ : a , so it ’s only possible to make a value of that type when a and b are equal . I like to use with type application syntax , like , so it ’s clear what we are saying is the same on both sides ; : : a : ~ : a )
The only way to construct an IsEven n is to provide a number m where m * 2 is n. We can do this by using SNat @m , which is the singleton constructor for the kind ( just like how STrue and SFalse are the singleton constructors for the kind ):
tenIsEven : : IsEven 10
tenIsEven = SNat @5 : & : Refl @10
is the constructor of type n : ~ : ( m * 2 )
sevenIsEven : : IsEven 10
Write a similar type IsOdd n that can only be constructed if n is odd .
type IsOdd n = ( ? ? ? ? n )
And construct a proof that 7 is odd :
View full source
sevenIsOdd : : IsOdd 7
Solution here !
On a sad note , one exercise I ’d like to be able to add is to ask you to write decision functions and proofs for and IsOdd . Unfortunately , is not rich enough to support this out of the box without a lot of extra tooling !
A common beginner Haskeller exercise is to implement map in terms of foldr :
map : : ( a - > b ) - > [ a ] _ > [ b ]
map f = foldr ( (: ) . f ) [ ]
Let ’s do the same thing at the type level , manually .
Directly implement a type - level Map , with kind ( j ~ > k ) - > [ j ] - > [ k ] , in terms of :
type Map f xs = Foldr ? ? ? ? ? ? ? ? xs
Try to mirror the value - level definition , passing in ( :) . f , and use the promoted version of ( . ) from the singletons library , in Data . Singletons . Prelude . You might find helpful !
Solution here !
Make a SomeHallway from a list of SomeDoor :
View full source
type SomeDoor = Sigma DoorState ( TyCon1 Door )
type SomeHallway = Sigma [ DoorState ] ( )
mkSomeHallway : : [ SomeDoor ] - > SomeHallway
Remember that the singleton constructors for list are SNil ( for [ ] ) and SCons ( for ( :)) !
Solution here !
-to-singletons-4.html
Justin Le
Introduction to Singletons (Part 4)
Monday October 22, 2018
functional programming at the type level.
GHC 8.6.1
nightly-2018-09-29 (singletons-2.5)
Review
View full source
$(singletons [d|
data DoorState = Opened | Closed | Locked
deriving (Show, Eq, Ord)
|])
data Door :: DoorState -> Type where
UnsafeMkDoor :: { doorMaterial :: String } -> Door s
mkDoor :: Sing s -> String -> Door s
mkDoor _ = UnsafeMkDoor
And we talked about using Sing s, or SDoorState s, to represent the state of the door (in its type) as a run-time value. We’ve been using a wrapper to existentially hide the door state type, but also stuffing in a singleton to let us recover the type information once we want it again:
data SomeDoor :: Type where
MkSomeDoor :: Sing s -> Door s -> SomeDoor
mkSomeDoor :: DoorState -> String -> SomeDoor
mkSomeDoor ds mat = withSomeSing ds $ \dsSing ->
MkSomeDoor dsSing (mkDoor dsSing mat)
In Part 3 we talked about a Pass data type that we used to talk about whether or not we can walk through or knock on a door:
$(singletons [d|
data Pass = Obstruct | Allow
deriving (Show, Eq, Ord)
|])
And we defined type-level functions on it using singletons Template Haskell:
$(singletons [d|
statePass :: DoorState -> Pass
statePass Opened = Allow
statePass Closed = Obstruct
statePass Locked = Obstruct
|])
This essentially generates these three things:
statePass :: DoorState -> Pass
statePass Opened = Allow
statePass Closed = Obstruct
statePass Locked = Obstruct
type family StatePass (s :: DoorState) :: Pass where
StatePass 'Opened = 'Allow
StatePass 'Closed = 'Obstruct
StatePass 'Locked = 'Obstruct
sStatePass :: Sing s -> Sing (StatePass s)
sStatePass = \case
SOpened -> SAllow
SClosed -> SObstruct
SLocked -> SObstruct
And we can use StatePass as a type-level function while using sStatePass to manipulate the singletons representing s and StatePass s.
We used this as a constraint to restrict how we can call our functions:
View full source
knockP :: (StatePass s ~ 'Obstruct) => Door s -> IO ()
knockP d = putStrLn $ "Knock knock on " ++ doorMaterial d ++ " door!"
But then we wondered…is there a way to not only restrict our functions, but to describe how the inputs and outputs are related to each other?
Inputs and Outputstop
In the past we have settled with very simple relationships, like:
closeDoor :: Door 'Opened -> Door 'Closed
This means that the relationship between the input and output is that the input is opened…and is then closed.
However, armed with promotion of type-level functions, writing more complex relationships becomes fairly straightforward!
We can write a function mergeDoor that “merges” two doors together, in sequence:
mergeDoor :: Door s -> Door t -> Door ????
mergeDoor d e = UnsafeMkDoor $ doorMaterial d ++ " and " ++ doorMaterial e
A merged door will have a material that is composite of the original materials. But, what will the new DoorState be? What goes in the ??? above?
Well, if we can write the function as a normal function in values…singletons lets us use it as a function on types. Let’s write that relationship. Let’s say merging takes on the higher “security” option — merging opened with locked is locked, merging closed with opened is closed, merging locked with closed is locked.
$(singletons [d|
mergeState :: DoorState -> DoorState -> DoorState
mergeState Opened d = d
mergeState Closed Opened = Closed
mergeState Closed Closed = Closed
mergeState Closed Locked = Locked
mergeState Locked _ = Locked
|])
$(singletons [d|
mergeState :: DoorState -> DoorState -> DoorState
mergeState = max
|])
This makes writing mergeDoor’s type clean to read:
View full source
mergeDoor
:: Door s
-> Door t
-> Door (MergeState s t)
mergeDoor d e = UnsafeMkDoor $ doorMaterial d ++ " and " ++ doorMaterial e
And, with the help of singletons, we can also write this for our doors where we don’t know the types until runtime:
View full source
mergeSomeDoor :: SomeDoor -> SomeDoor -> SomeDoor
mergeSomeDoor (MkSomeDoor s d) (MkSomeDoor t e) =
MkSomeDoor (sMergeState s t) (mergeDoor d e)
To see why this typechecks properly, compare the types of sMergeState and mergeDoor:
sMergeState :: Sing s -> Sing t -> Sing (MergeState s t)
mergeDoor :: Door s -> Door t -> Door (MergeState s t)
MkSomeDoor :: Sing (MergeState s t) -> Door (MergeState s t) -> SomeDoor
Because the results both create types MergeState s t, MkSomeDoor is happy to apply them to each other, and everything typechecks. However, if, say, we directly stuffed s or t into MkSomeDoor, things would fall apart and not typecheck.
And so now we have full expressiveness in determining input and output relationships! Once we unlock the power of type-level functions with singletons, writing type-level relationships become as simple as writing value-level ones. If you can write a value-level function, you can write a type-level function.
Kicking it up a notchtop
How far we can really take this?
Let’s make a data type that represents a series of hallways, each linked by a door. A hallway is either an empty stretch with no door, or two hallways linked by a door. We’ll structure it like a linked list, and store the list of all door states as a type-level list as a type parameter:
View full source
data Hallway :: [DoorState] -> Type where
(:<#) :: Door s
-> Hallway ss
infixr 5 :<#
(If you need a refresher on type-level lists, check out the quick introduction in Part 1 and Exercise 4 in Part 2)
So we might have:
ghci> let door1 = mkDoor SClosed "Oak"
ghci> let door2 = mkDoor SOpened "Spruce"
ghci> let door3 = mkDoor SLocked "Acacia"
ghci> :t door1 :<# door2 :<# door3 :<# HEnd
Hallway '[ 'Closed, 'Opened, 'Locked ]
That is, a Hallway '[ s, t, u ] is a hallway consisting of a Door s, a Door t, and a Door u, constructed like a linked list in Haskell.
Now, let’s write a function to collapse all doors in a hallway down to a single door:
collapseHallway :: Hallway ss -> Door ?????
Basically, we want to merge all of the doors one after the other, collapsing it until we have a single door state. Luckily, MergeState is both commutative and associative and has an identity, so this can be defined sensibly.
First, let’s think about the type we want. What will the result of merging ss be?
We can pattern match and collapse an entire list down item-by-item:
$(singletons [d|
mergeStateList :: [DoorState] -> DoorState
mergeStateList (s:ss) = s `mergeState` mergeStateList ss
|])
Again, remember that this also defines the type family MergeStateList and the singleton function sMergeStateList :: Sing ss -> Sing (MergeStateList ss).
With this, we can write collapseHallway:
View full source
collapseHallway :: Hallway ss -> Door (MergeStateList ss)
collapseHallway HEnd = mkDoor SOpened "End of Hallway"
collapseHallway (d :<# ds) = d `mergeDoor` collapseHallway ds
Now, because the structure of collapseHallway perfectly mirrors the structure of mergeStateList, this all typechecks, and we’re done!
ghci> collapseHallway (door1 :<# door2 :<# door3 :<# HEnd)
UnsafeMkDoor "Oak and Spruce and Acacia and End of Hallway"
:: Door 'Locked
Note one nice benefit – the door state of collapseHallway (door1 :<# door2 :<# door3 :<# HEnd) is known at compile-time to be Door 'Locked, if the types of all of the component doors are also known!
Functional Programmingtop
We went over that all a bit fast, but some of you might have noticed that the definition of mergeStateList bears a really strong resemblance to a very common Haskell list processing pattern:
mergeStateList :: [DoorState] -> DoorState
mergeStateList (s:ss) = s `mergeState` mergeStateList ss
The algorithm is to basically [] with Opened, and all (:) with mergeState. If this sounds familiar, that’s because this is exactly a right fold! (In fact, hlint actually made this suggestion to me while I was writing this)
mergeStateList :: [DoorState] -> DoorState
mergeStateList = foldr mergeState Opened
In Haskell, we are always encouraged to use higher-order functions whenever possible instead of explicit recursion, both because explicit recursion opens you up to a lot of potential bugs, and also because using established higher-order functions make your code more readable.
So, as Haskellers, let us hold ourselves to a higher standard and not be satisfied with a MergeState written using explicit recursion. Let us instead go full fold — ONWARD HO!
The Problemtop
Initial attempts to write a higher-order type-level function as a type family, however, serve to temper our enthusiasm.
type family Foldr (f :: j -> k -> k) (z :: k) (xs :: [j]) :: k where
Foldr f z '[] = z
Foldr f z (x ': xs) = f x (Foldr f z xs)
So far so good right? So we should expect to be able to write MergeStateList using Foldr, MergeState, and 'Opened
type MergeStateList ss = Foldr MergeState 'Opened ss
Ah, but the compiler is here to tell you this isn’t allowed in Haskell:
• The type family ‘MergeState’ should have 2 arguments, but has been given none
• In the equations for closed type family ‘MergeStateList’
In the type family declaration for ‘MergeStateList’
What happened? To figure out, we have to remember that pesky restriction on type synonyms and type families: they can not be used partially applied (“unsaturated”), and must always be fully applied (“saturated”). For the most part, only type constructors (like Maybe, Either, IO) and lifted DataKinds data constructors (like 'Just, '(:)) in Haskell can ever be partially applied at the type level. We therefore can’t use MergeState as an argument to Foldr, because MergeState must always be fully applied.
Unfortunately for us, this makes our Foldr effectively useless. That’s because we’re always going to want to pass in type families (like MergeState), so there’s pretty much literally no way to ever actually call Foldr except with type constructors or lifted DataKinds data constructors.
So…back to the drawing board?
Defunctionalizationtop
I like to mentally think of the singletons library as having two parts: the first is linking lifted DataKinds types with run-time values to allow us to manipulate types at runtime as first-class values. The second is a system for effective functional programming at the type level.
To make a working Foldr, we’re going to have to jump into that second half: defunctionalization.
Defunctionalization is a technique invented in the early 70’s as a way of compiling higher-order functions into first-order functions in target languages. The main idea is:
Instead of working with functions, work with symbols representing functions.
Build your final functions and values by composing and combining these symbols.
At the end of it all, have a single Apply function interpret all of your symbols and produce the value you want.
In singletons these symbols are implemented as “dummy” empty data constructors, and Apply is a type family.
To help us understand singleton’s defunctionalization system better, let’s build our own defunctionalization system from scratch.
First, a little trick to make things easier to read:
View full source
data TyFun a b
type a ~> b = TyFun a b -> Type
infixr 0 ~>
Our First Symbolstop
Now we can define a dummy data type like Id, which represents the identity function id:
View full source
data Id :: a ~> a
The “actual” kind of Id is Id :: TyFun a a -> Type; you can imagine TyFun a a as a phantom parameter that signifies that Id represents a function from a to a. It’s essentially a nice trick to allow you to write Id :: a ~> a as a kind signature.
Now, Id is not a function…it’s a dummy type constructor that represents a function a -> a. A type constructor of kind a ~> a represents a defunctionalization symbol – a type constructor that represents a function from a to a.
To interpret it, we need to write our global interpreter function:
View full source
type family Apply (f :: a ~> b) (x :: a) :: b
That’s the syntax for the definition of an open type family in Haskell: users are free to add their own instances, just like how type classes are normally open in Haskell.
Let’s tell Apply how to interpret Id:
View full source
type instance Apply Id x = x
The above is the actual function definition, like writing id x = x. We can now call Id to get an actual type in return:
ghci> :kind! Apply Id 'True
'True
(Remember, :kind! is the ghci command to evaluate a type family)
Let’s define another one! We’ll implement Not:
View full source
data Not :: Bool ~> Bool
type instance Apply Not 'False = 'True
type instance Apply Not 'True = 'False
We can try it out:
ghci> :kind! Apply Not 'True
'False
ghci> :kind! Apply Not 'False
'True
It can be convenient to define an infix synonym for Apply:
View full source
type f @@ a = Apply f a
infixl 9 @@
Then we can write:
ghci> :kind! Not @@ 'False
'True
ghci> :kind! Id @@ 'True
'True
Remember, Id and Not are not actual functions — they’re just dummy data types (“defunctionalization symbols”), and we define the functions they represent through the global Apply type function.
A Bit of Principletop
So we’ve got the basics of defunctionalization — instead of using functions directly, use dummy symbols that encode your functions that are interpreted using Apply. Let’s add a bit of principle to make this all a bit more scalable.
The singletons library adopts a few conventions for linking all of these together. Using the Not function as an example, if we wanted to lift the function:
not :: Bool -> Bool
not False = True
not True = Flse
We already know about the type family and singleton function this would produce:
type family Not (x :: Bool) :: Bool where
Not 'False = 'True
Not 'True = 'False
sNot :: Sing x -> Sing (Not x)
sNot SFalse = STrue
sNot STrue = SFalse
But the singletons library also produces the following defunctionalization symbols, according to a naming convention:
data NotSym0 :: Bool ~> Bool
type instance Apply NotSym0 x = Not x
type NotSym1 x = Not x
NotSym0 is the defunctionalization symbol associated with the Not type family, defined so that NotSym0 @@ x = Not x. Its purpose is to allow us to pass in Not as an un-applied function. The Sym0 suffix is a naming convention, and the 0 stands for “expects 0 arguments”. Similarly for NotSym1 – the 1 stands for “expects 1 argument”.
Two-Argument Functionstop
Let’s look at a slightly more complicated example – a two-argument function. Let’s define the boolean “and”:
$(singletons [d|
and :: Bool -> (Bool -> Bool)
and False _ = False
and True x = x
])
this will generate:
type family And (x :: Bool) (y :: Bool) :: Bool where
And 'False x = 'False
And 'True x = x
sAnd :: Sing x -> Sing y -> Sing (And x y)
sAnd SFalse x = SFalse
sAnd STrue x = x
And the defunctionalization symbols:
data AndSym0 :: Bool ~> (Bool ~> Bool)
type instance Apply AndSym0 x = AndSym1 x
data AndSym1 (x :: Bool) :: (Bool ~> Bool)
data AndSym1 :: Bool -> (Bool ~> Bool)
type instance Apply (AndSym1 x) y = And x y
type AndSym2 x y = And x y
AndSym0 is a defunctionalization symbol representing a “fully unapplied” (“completely unsaturated”) version of And. AndSym1 x is a defunctionalization symbol representing a “partially applied” version of And — partially applied to x (its kind is AndSym1 :: Bool -> (Bool ~> Bool)).
The application of AndSym0 to x gives you AndSym1 x:
ghci> :kind! AndSym0 @@ 'False
AndSym1 'False
Remember its kind AndSym0 :: Bool ~> (Bool ~> Bool) (or just AndSym0 :: Bool ~> Bool ~> Bool): it takes a Bool, and returns a Bool ~> Bool defunctionalization symbol.
The application of AndSym1 x to y gives you And x y:
ghci> :kind! AndSym1 'False @@ 'True
ghci> :kind! AndSym1 'True @@ 'True
'True
A note to remember: AndSym1 'True is the defunctionalization symbol, and not AndSym1 itself. AndSym1 has kind Bool -> (Bool ~> Bool), but AndSym1 'True has kind Bool ~> Bool — the kind of a defunctionalization symbol. AndSym1 is a sort of “defunctionalization symbol constructor”.
Also note here that we encounter the fact that singletons also provides “defunctionalization symbols” for “nullary” type functions like False and True, where:
type FalseSym0 = 'False
type TrueSym0 = 'True
Just like how it defines AndSym0 for consistency, as well.
Symbols for type constructorstop
One extra interesting defunctionalization symbol we can write: we turn lift any type constructor into a “free” defunctionalization symbol:
View full source
data TyCon1
type instance Apply (TyCon1 t) a = t a
Basically the Apply instance just applies the type constructor t to its input a.
ghci> :kind! TyCon1 Maybe @@ Int
Maybe Int
ghci> :kind! TyCon1 'Right @@ 'False
'Right 'False
We can use this to give a normal j -> k type constructor to a function that expects a j ~> k defunctionalization symbol.
Bring Me a Higher Ordertop
Okay, so now we have these tokens that represent “unapplied” versions of functions. So what?
Well, remember the problem with our implementation of Foldr? We couldn’t pass in a type family, since type families must be passed fully applied. So, instead of having Foldr expect a type family…we can make it expect a defunctionalization symbol instead. Remember, defunctionalization symbols represent the “unapplied” versions of type families, so they are exactly the tools we need!
View full source
type family Foldr (f :: j ~> k ~> k) (z :: k) (xs :: [j]) :: k where
Foldr f z '[] = z
Foldr f z (x ': xs) = (f @@ x) @@ Foldr f z xs
The difference is that instead of taking a type family or type constructor f :: j -> k -> k, we have it take the defunctionalization symbol f :: j ~> (k ~> k).
Instead of taking a type family or type constructor, we take that dummy type constructor.
Now we just need to have our defunctionalization symbols for MergeStateList:
View full source
data MergeStateSym0 :: DoorState ~> DoorState ~> DoorState
type instance Apply MergeStateSym0 s = MergeStateSym1 s
data MergeStateSym1 :: DoorState -> DoorState ~> DoorState
type instance Apply (MergeStateSym1 s) t = MergeState s t
type MergeStateSym2 s t = MergeState s t
And now we can write MergeStateList:
View full source
type MergeStateList ss = Foldr MergeStateSym0 'Opened ss
(If you “see” MergeStateSym0, you should read it was MergeState, but partially applied)
This compiles!
ghci> :kind! MergeStateList '[ 'Closed, 'Opened, 'Locked ]
'Locked
ghci> :kind! MergeStateList '[ 'Closed, 'Opened ]
'Closed
View full source
collapseHallway :: Hallway ss -> Door (MergeStateList ss)
collapseHallway HEnd = UnsafeMkDoor "End of Hallway"
collapseHallway (d :<# ds) = d `mergeDoor` collapseHallway ds
(Note: Unfortunately, we do have to use our our own Foldr here, that we just defined, instead of using the one that comes with singletons, because of some outstanding issues with how the singletons TH processes alternative implementations of foldr from Prelude. In general, the issue is that we should only expect type families to work with singletons if the definition of the type family perfectly matches the structure of how we implement our value-level functions like collapseHallway)
Singletons to make things nicertop
Admittedly this is all a huge mess of boilerplate. The code we had to write more than tripled, and we also have an unsightly number of defunctionalization symbols and Apply instance boilerplate for every function.
Luckily, the singletons library is here to help. You can just write:
$(singletons [d|
data DoorState = Opened | Closed | Locked
deriving (Show, Eq, Ord)
mergeState :: DoorState -> DoorState -> DoorState
mergeState = max
foldr :: (a -> b -> b) -> b -> [a] -> b
foldr _ z [] = z
foldr f z (x:xs) = f x (foldr f z xs)
mergeStateList :: [DoorState] -> DoorState
mergeStateList = foldr mergeState Opened
|])
And all of these defunctionalization symbols are generated for you; singletons is also able to recognize that foldr is a higher-order function and translate its lifted version to take a defunctionalization symbol a ~> b ~> b.
That the template haskell also generates SingI instances for all of your defunctionalization symbols, too (more on that in a bit).
It’s okay to stay “in the world of singletons” for the most part, and let singletons handle the composition of functions for you. However, it’s still important to know what the singletons library generates, because sometimes it’s still useful to manually create defunctionalization symbols and work with them.
The naming convention for non-symbolic names (non-operators) like myFunction are just to call them MyFunctionSym0 for the completely unapplied defunctionalization symbol, MyFunctionSym1 for the type constructor that expects one argument before returning a defunctionalization symbol, MyFunctionSym2 for the type constructor that expects two arguments before returning a defunctionalization symbol, etc.
For operator names like ++, the naming convention is to have ++@#@$ be the completely unapplied defunctionalization symbol, ++@#@$$ be the type constructor that expects one argument before returning a defunctionalization symbol, ++@#@$$$ be the type constructor that takes two arguments before returning a defunctionalization symbol, etc.
Another helpful thing that singletons does is that it also generates defunctionalization symbols for type families and type synonyms you define in the Template Haskell, as well — so if you write
$(singletons [d|
type MyTypeFamily (b :: Bool) :: Type where
MyTypeFamily 'False = Int
MyTypeFamily 'True = String
|])
and
$(singletons [d|
type MyTypeSynonym a = (a, [a])
|])
singletons will generate:
data MyTypeFamilySym0 :: Bool ~> Type
type instance Apply MyTypeFamilySym0 b = MyTypeFamily b
type MyTypeFamilySym1 b = MyTypeFamily b
and
data MyTypeSynonymSym0 :: Type ~> Type
type instance Apply MyTypeSynonym b = MyTypeSynonym a
type MyTypeSynonymSym1 a = MyTypeSynonym a
Bringing it All Togethertop
Just to show off the library, remember that singletons also promotes typeclasses?
Because DoorState is a monoid with respect to merging, we can actually write and promote a Monoid instance: (requires singletons-2.5 or higher)
$(singletons [d|
instance Semigroup DoorState where
(<>) = mergeState
instance Monoid DoorState where
mempty = Opened
mappend = (<>)
|])
We can promote fold:
$(singletons [d|
fold :: Monoid b => [b] -> b
fold [] = mempty
fold (x:xs) = x <> fold xs
|])
And we can write collapseHallway in terms of those instead :)
View full source
collapseHallway'
:: Hallway ss
-> Door (Fold ss)
collapseHallway' HEnd = UnsafeMkDoor "End of Hallway"
collapseHallway' (d :<# ds) = d `mergeDoor` collapseHallway' ds
collapseSomeHallway' :: SomeHallway -> SomeDoor
collapseSomeHallway' (ss :&: d) =
sFold ss
:&: collapseHallway' d
(Note again unfortunately that we have to define our own fold instead of using the one from singletons and the SFoldable typeclass, because of issue #339)
Thoughts on Symbolstop
Defunctionalization symbols may feel like a bit of a mess, and the naming convention is arguably less than aesthetically satisfying. But, as you work with them more and more, you start to appreciate them on a deeper level.
At the end of the day, you can compare defunctionalization as turning “functions” into just constructors you can match on, just like any other data or type constructor. That’s because they are just type constructors!
In a sense, defining defunctionalization symbols is a lot like working with pattern synonyms of your functions, instead of directly passing the functions themselves. At the type family and type class level, you can “pattern match” on these functions.
For a comparison at the value level – you can’t pattern match on (+), (-), (*), and (/):
invertOperation :: (Double -> Dobule -> Double) -> (Double -> Double -> Double)
invertOperation (+) = (-)
invertOperation (-) = (+)
invertOperation (*) = (/)
invertOperation (/) = (*)
You can’t quite match on the equality of functions to some list of patterns. But, what you can do is create constructors representing your functions, and match on those.
This essentially fixes the “type lambda problem” of type inference and typeclass resolution. You can’t match on arbitrary lambdas, but you can match on dummy constructors representing type functions.
And a bit of the magic here, also, is the fact that you don’t always need to make our own defunctionalization symbols from scratch — you can create them based on other ones in a compositional way. This is the basis of libraries like decidable.
For example, suppose we wanted to build defunctionalization symbols for MergeStateList. We can actually build them directly from defunctionalization symbols for Foldr.
Check out the defunctionalization symbols for Foldr:
View full source
data FoldrSym0 :: (j ~> k ~> k) ~> k ~> [j] ~> k
type instance Apply FoldrSym0 f = FoldrSym1 f
data FoldrSym1 :: (j ~> k ~> k) -> k ~> [j] ~> k
type instance Apply (FoldrSym1 f) z = FoldrSym2 f z
data FoldrSym2 :: (j ~> k ~> k) -> k -> [j] ~> k
type instance Apply (FoldrSym2 f z) xs = Foldr f z xs
type FoldrSym3 f z xs = Foldr f z xs
We can actually use these to define our MergeStateList defunctionalization symbols, since defunctionalization symbols are first-class:
View full source
type MergeStateListSym0 = FoldrSym2 MergeStateSym0 'Opened
And you can just write collapseHallway as:
collapseHallway :: Hallway ss -> Door (MergeStateListSym0 @@ ss)
collapseHallway :: Hallway ss -> Door (FoldrSym2 MergeStateSym0 'Opened @@ ss)
You never have to actually define MergeStateList as a function or type family!
The whole time, we’re just building defunctionalization symbols in terms of other defunctionalization symbols. And, at the end, when we finally want to interpret the complex function we construct, we use Apply, or @@.
You can think of FoldrSym1 and FoldrSym2 as defunctionalization symbol constructors – they’re combinators that take in defunctionalization symbols (like MergeStateSym0) and return new ones.
Sigmatop
Let’s look at a nice tool that is made possible using defunctionalization symbols: dependent pairs. I talk a bit about dependent pairs (or dependent sums) in part 2 of this series, and also in my dependent types in Haskell series.
Essentially, a dependent pair is a tuple where the type of the second field depends on the value of the first one. This is basically what SomeDoor was:
data SomeDoor :: Type where
MkSomeDoor :: Sing x -> Door x -> SomeDoor
The type of the Door x depends on the value of the Sing x, which you can read as essentially storing the x.
We made SomeDoor pretty ad-hoc. But what if we wanted to make some other predicate? Well, we can make a generic dependent pair by parameterizing it on the dependence between the first and second field. Singletons provides the Sigma type, in the Data.Singletons.Sigma module:
data Sigma k :: (k ~> Type) -> Type where
(:&:) :: Sing x -> (f @@ x) -> Sigma k f
type Σ k = Sigma k
If you squint carefully, you can see that Sigma k is just SomeDoor, but parameterized over Door. Instead of always holding Door x, we can have it parameterized on an arbitrary function f and have it hold an f @@ x.
We can actually define SomeDoor in terms of Sigma:
View full source
type SomeDoor = Sigma DoorState (TyCon1 Door)
mkSomeDoor :: DoorState -> String -> SomeDoor
mkSomeDoor ds mat = withSomeSing ds $ \dsSing ->
dsSing :&: mkDoor dsSing mat
(Remember TyCon1 is the defunctionalization symbol constructor that turns any normal type constructor j -> k into a defunctionalization symbol j ~> k)
That’s because a Sigma DoorState (TyCon1 Door) contains a Sing (x :: DoorState) and a TyCon1 Door @@ x, or a Door x.
This is a simple relationship, but one can imagine a Sigma parameterized on an even more complex type-level function. We’ll explore more of these in the exercises.
For some context, Sigma is an interesting data type (the “dependent sum”) that is ubiquitous in dependently typed programming.
Singletons of Defunctionalization Symbolstop
One last thing to tie it all together – let’s write collapseHallway in a way that we don’t know the types of the doors.
Luckily, we now have a SomeHallway type for free:
View full source
type SomeHallway = Sigma [DoorState] (TyCon1 Hallway)
The easy way would be to just use sMergeStateList that we defined:
View full source
collapseSomeHallway :: SomeHallway -> SomeDoor
collapseSomeHallway (ss :&: d) = sMergeStateList ss
:&: collapseHallway d
But what if we didn’t write sMergeStateList, and we constructed our defunctionalization symbols from scratch?
View full source
collapseHallway''
:: Hallway ss
-> Door (FoldrSym2 MergeStateSym0 'Opened @@ ss)
collapseHallway'' HEnd = UnsafeMkDoor "End of Hallway"
collapseHallway'' (d :<# ds) = d `mergeDoor` collapseHallway'' ds
collapseSomeHallway'' :: SomeHallway -> SomeDoor
:&: collapseHallway'' d
This will be our final defunctionalization lesson. How do we turn a singleton of ss into a singleton of FoldrSym2 MergeStateSym0 'Opened @@ s ?
First – we have Foldr at the value level, as sFoldr. We glossed over this earlier, but singletons generates the following function for us:
type family Foldr (f :: j ~> k ~> k) (z :: k) (xs :: [j]) :: k where
Foldr f z '[] = z
Foldr f z (x ': xs) = (f @@ x) @@ Foldr f z xs
sFoldr
:: Sing (f :: j ~> k ~> k)
-> Sing (z :: k)
-> Sing (xs :: [j])
-> Sing (Foldr f z xs :: k)
sFoldr f z SNil = z
sFoldr f z (x `SCons` xs) = (f @@ x) @@ sFoldr f z xs
Where (@@) :: Sing f -> Sing x -> Sing (f @@ x) (or applySing) is the singleton/value-level counterpart of Apply or (@@).1
So we can write:
collapseSomeHallway'' :: SomeHallway -> SomeDoor
collapseSomeHallway'' (ss :&: d) = sFoldr ???? SOpened ss
:&: collapseHallwa''y d
But how do we get a Sing MergeStateSym0?
We can use the singFun family of functions:
singFun2 @MergeStateSym0 sMergeState
:: Sing MergeStateSym0
But, also, conveniently, the singletons library generates a SingI instance for MergeStateSym0, if you defined mergeState using the singletons template haskell:
sing :: Sing MergeStateSym0
And finally, we get our answer:
View full source
collapseSomeHallway'' :: SomeHallway -> SomeDoor
collapseSomeHallway'' (ss :&: d) =
sFoldr (singFun2 @MergeStateSym0 sMergeState) SOpened ss
:&: collapseHallway'' d
Closing Uptop
Woo! Congratulations, you’ve made it to the end of the this Introduction to Singletons tetralogy! This last and final part understandably ramps things up pretty quickly, so don’t be afraid to re-read it a few times until it all sinks in before jumping into the exercises.
I hope you enjoyed this journey deep into the motivation, philosophy, mechanics, and usage of this great library. Hopefully these toy examples have been able to show you a lot of ways that type-level programming can help your programs today, both in type safety and in writing more expressive programs. And also, I hope that you can also see now how to leverage the full power of the singletons library to make those gains a reality.
There are a few corners of the library we haven’t gone over (like the TypeLits- and TypeRep-based singletons – if you’re interested, check out this post where I talk a lot about them), but I’d like to hope as well that this series has equipped you to be able to dive into the library documentation and decipher what it holds, armed with the knowledge you now have. (We also look at TypeLits briefly in the exercises)
You can download the source code here — Door4Final.hs contains the final versions of all our definitions, and Defunctionalization.hs contains all of our defunctionalization-from-scratch work. These are designed as stack scripts that you can load into ghci. Just execute the scripts:
$ ./Door4Final.hs
ghci>
And you’ll be dropped into a ghci session with all of the definitions in scope.
As always, please try out the exercises, which are designed to help solidify the concepts we went over here! And if you ever have any future questions, feel free to leave a comment or find me on twitter or in freenode #haskell, where I idle as jle`.
Looking Forwardtop
Some final things to note before truly embracing singletons: remember that, as a library, singletons was always meant to become obsolete. It’s a library that only exists because Haskell doesn’t have real dependent types yet.
Dependent Haskell is coming some day! It’s mostly driven by one solo man, Richard Eisenberg, but every year buzz does get bigger. In a recent progress report, we do know that we realistically won’t have dependent types before 2020. That means that this tutorial will still remain relevant for at least another two years :)
How will things be different in a world of Haskell with real dependent types? Well, for a good guess, take a look at Richard Eisenberg’s Dissertation!
One day, hopefully, we won’t need singletons to work with types at the value-level; we would just be able to directly pattern match and manipulate the types within the language and use them as first-class values, with a nice story for dependent sums. And some day, I hope we won’t need any more dances with defunctionalization symbols to write higher-order functions at the type level — maybe we’ll have a nicer way to work with partially applied type-level functions (maybe they’ll just be normal functions?), and we don’t need to think any different about higher-order or first-order functions.
So, as a final word — Happy Haskelling, everyone! May you leverage the great singletons library to its full potential, and may we also all dream of a day where singletons becomes obsolete. But may we all enjoy the wonderful journey along the way.
Until next time!
Exercisestop
Let’s try combining type families with proofs! In doing so, hopefully we can also see the value of using dependent proofs to show how we can manipulate proofs as first-class values that the compiler can verify.
Remember Knockable from Part 3?
View full source
data Knockable :: DoorState -> Type where
KnockClosed :: Knockable 'Closed
KnockLocked :: Knockable 'Locked
Closed and Locked doors are knockable. But, if you merge two knockable doors…is the result also always knockable?
I say yes, but don’t take my word for it. Prove it using Knockable!
View full source
mergedIsKnockable
:: Knockable s
-> Knockable t
-> Knockable (MergeState s t)
mergedIsKnockable is only implementable if the merging of two DoorStates that are knockable is also knockable. See if you can write the implementation!
Solution here!
Write a function to append two hallways together.
appendHallways
:: Hallway ss
-> Hallway ts
-> Hallway ????
from singletons — implement any type families you might need from scratch!
Remember the important principle that your type family must mirror the implementation of the functions that use it.
Next, for fun, use appendHallways to implement appendSomeHallways:
View full source
type SomeHallway = Sigma [DoorState] (TyCon1 Hallway)
appendSomeHallways
:: SomeHallway
-> SomeHallway
-> SomeHallway
Solution here!
Can you use Sigma to define a door that must be knockable?
To do this, try directly defining the defunctionalization symbol KnockableDoor :: DoorState ~> Type (or use singletons to generate it for you — remember that singletons can also promote type families) so that:
type SomeKnockableDoor = Sigma DoorState KnockableDoor
will contain a Door that must be knockable.
Try doing it for both (a) the “dependent proof” version (with the Knockable data type) and for (b) the type family version (with the StatePass type family).
Solutions here! I gave four different ways of doing it, for a full range of manual vs. auto-promoted defunctionalization symbols and Knockable vs. Pass-based methods.
Hint: Look at the definition of SomeDoor in terms of Sigma:
type SomeDoor = Sigma DoorState (TyCon1 Door)
Hint: Try having KnockableDoor return a tuple.
Take a look at the API of the Data.Singletons.TypeLits module, based on the API exposed in GHC.TypeNats module from base.
Using this, you can use Sigma to create a predicate that a given Nat number is even:
data IsHalfOf :: Nat -> Nat ~> Type
type instance Apply (IsHalfOf n) m = n :~: (m * 2)
type IsEven n = Sigma Nat (IsHalfOf n)
(*) is multiplication from the Data.Singletons.Prelude.Num module. (You must have the -XNoStarIsType extension on for this to work in GHC 8.6+), and :~: is the predicate of equality from Part 3:
data (:~:) :: k -> k -> Type where
Refl :: a :~: a
(It’s only possible to make a value of type a :~: b using Refl :: a :~: a, so it’s only possible to make a value of that type when a and b are equal. I like to use Refl with type application syntax, like Refl @a, so it’s clear what we are saying is the same on both sides; Refl @a :: a :~: a)
The only way to construct an IsEven n is to provide a number m where m * 2 is n. We can do this by using SNat @m, which is the singleton constructor for the Nat kind (just like how STrue and SFalse are the singleton constructors for the Bool kind):
tenIsEven :: IsEven 10
tenIsEven = SNat @5 :&: Refl @10
sevenIsEven :: IsEven 10
sevenIsEven = SNat @4 :&: Refl
Write a similar type IsOdd n that can only be constructed if n is odd.
type IsOdd n = Sigma Nat (???? n)
And construct a proof that 7 is odd:
View full source
sevenIsOdd :: IsOdd 7
Solution here!
On a sad note, one exercise I’d like to be able to add is to ask you to write decision functions and proofs for IsEven and IsOdd. Unfortunately, Nat is not rich enough to support this out of the box without a lot of extra tooling!
A common beginner Haskeller exercise is to implement map in terms of foldr:
map :: (a -> b) -> [a] _> [b]
map f = foldr ((:) . f) []
Let’s do the same thing at the type level, manually.
Directly implement a type-level Map, with kind (j ~> k) -> [j] -> [k], in terms of Foldr:
type Map f xs = Foldr ???? ???? xs
Try to mirror the value-level definition, passing in (:) . f, and use the promoted version of (.) from the singletons library, in Data.Singletons.Prelude. You might find TyCon2 helpful!
Solution here!
Make a SomeHallway from a list of SomeDoor:
View full source
type SomeDoor = Sigma DoorState (TyCon1 Door)
type SomeHallway = Sigma [DoorState] (TyCon1 Hallway)
mkSomeHallway :: [SomeDoor] -> SomeHallway
Remember that the singleton constructors for list are SNil (for []) and SCons (for (:))!
Solution here!
-}
|
d27614716437eb1837588e280874f40c843ff322c62760d543bb27ba7c7cd7c6 | ghc/packages-dph | Vectorised.hs | -- Vectorised "all closest pairs":
-- This was
{-# LANGUAGE ParallelArrays #-}
{-# OPTIONS -fvectorise #-}
{-# OPTIONS -fno-spec-constr-count #-}
module Vectorised (closestPA, closeststupidPA) where
import Points2D.Types
import Data.Array.Parallel
import Data.Array.Parallel.Prelude.Double as D
import qualified Data.Array.Parallel.Prelude.Int as I
import qualified Prelude as P
--------- dph-lifted-copy implementations
-- These functions are in -copy but not in -vseg.
-- I've tried to implement them but got a vectorisation error:
-- "Can't vectorise expression GHC.Prim.Int#"
--
bpermuteP :: [:a:] -> [:Int:] -> [:a:]
bpermuteP as is = mapP (\i -> as !: i) is
indexedP :: [:a:] -> [:(Int,a):]
indexedP xs = zipP (I.enumFromToP 0 (lengthP xs I.- 1)) xs
updateP :: [:a:] -> [:(Int,a):] -> [:a:]
updateP as is = snd' (unzipP (mapP find (indexedP as)))
where
find (i,a)
| [:v:] <- filterP (\(i',_) -> i I.== i') is
= v
| otherwise
= (i,a)
snd' (_,b) = b
-- | Distance squared.
-- Because most uses of this are just finding the minimum, the sqrt is unnecessary.
distance :: Point -> Point -> Double
distance (x1, y1) (x2, y2)
= (x2 D.- x1) D.* (x2 D.- x1)
D.+ (y2 D.- y1) D.* (y2 D.- y1)
-- | Distance squared.
Distance between two points , but return a very large number if they 're the same ...
distancex :: Point -> Point -> Double
distancex a b
= let d = distance a b
in if d D.== 0 then 1e100 else d
-- | Naive closest pairs.
An n^2 algorithm for finding closest pairs .
-- Our divide and conquer drops back to this once there are few enough points
closeststupid :: [: Point :] -> [:(Point,Point):]
closeststupid pts
= let is = [: minIndexP [: distancex a b | b <- pts :] | a <- pts :]
in bpermuteP [: (a,b) | a <- pts, b <- pts :] is
| Find the points within distance @d@ of the edge along x=@x0@.
Only the first element of each pair is checked .
-- Returns pairs with indices within original input array.
near_boundary
:: [:(Point,Point):] -- ^ Input pairs
-> Double -- ^ X dimension of boundary
-> Double -- ^ Maximum distance from X boundary
-> [:(Int,(Point,Point)):]
near_boundary a x0 d
= filterP check (indexedP a)
where
check (_,((x1,_),_)) = D.abs (x1 D.- x0) D.< d
| Given two arrays of pairs where the firsts are both near some boundary ,
update the first array with any closer points in the second array .
new_nearest
:: [:(Int,(Point,Point)):] -- ^ Input pairs
-> [:(Int,(Point,Point)):] -- ^ Check each input pair against these to find any closer pairs
-> [:(Int,(Point,Point)):]
new_nearest a b
| lengthP b I.== 0 = a
| otherwise
= let bp = mapP (\(_,(pt1,_)) -> pt1) b
is = [: minIndexP [: distance pt1 pt2 | pt2 <- bp :] | (_,(pt1,_)) <- a :]
na = [: (k,(pt1,check pt1 pn pt2)) | (k,(pt1,pt2)) <- a, pn <- bpermuteP bp is :]
in na
where
check pt1 pn pt2
= if distance pt1 pn D.< distance pt1 pt2
then pn
else pt2
| Merge two arrays of pairs that have been split on the x axis .
To do this , we find the maximum distance between any two points ,
-- then find the points in each array within that distance of the split.
-- We check each of these boundary points against the other boundary
-- to see if they are closer.
merge_pairs
:: Double -- ^ Split point
-> [:(Point,Point):] -- ^ `Above' pairs
-> [:(Point,Point):] -- ^ `Below' pairs
-> [:(Point,Point):]
merge_pairs x0 a b
= let d = sqrt (D.max (maximumP (mapP dist a)) (maximumP (mapP dist b)))
an = near_boundary a x0 d
bn = near_boundary b x0 d
a' = a `updateP` new_nearest an bn
b' = b `updateP` new_nearest bn an
in a' +:+ b'
where
dist (a,b) = distance a b
-- | For each point, find its closest neighbour.
-- Once there are few enough points, we use a naive n^2 algorithm.
-- Otherwise, the median x is found and the array is split into
-- those below and those above.
The two halves are recursed upon and then the results merged ( see @merge_pairs@ ) .
closest :: [:Point:] -> [:(Point,Point):]
closest pts
| lengthP pts I.< 250 = closeststupid pts
| otherwise =
let (xs,ys) = unzipP pts
xd = maximumP xs D.- minimumP xs
yd = maximumP ys D.- minimumP ys
mid = median xs
top = filterP (\(x,_) -> x D.>= mid) pts
bot = filterP (\(x,_) -> x D.< mid) pts
top' = closest top
bot' = closest bot
pair = merge_pairs mid top' bot'
in pair
closestPA :: PArray Point -> PArray (Point,Point)
closestPA ps = toPArrayP (closest (fromPArrayP ps))
closeststupidPA :: PArray Point -> PArray (Point,Point)
closeststupidPA ps = toPArrayP (closeststupid (fromPArrayP ps))
-- | Find median of an array, using quickselect
median :: [: Double :] -> Double
median xs = median' xs (lengthP xs `I.div` 2)
-- | Find the @k@th smallest element.
-- A pivot is selected and the array is partitioned into those smaller and larger than the pivot.
If the number of elements smaller than pivot is greater or equal to @k@ , then the pivot must be larger than the
-- @k@th smallest element, and we recurse into the smaller elements.
-- Otherwise the @k@th element must be larger or equal to the pivot.
-- Since lesser elements are not in the greater array, we are no longer looking for the
@k@th smallest element , but the @k - ( length xs - length gs)@th smallest .
median':: [: Double :] -> Int -> Double
median' xs k =
let p = xs !: (lengthP xs `I.div` 2)
ls = [:x | x <- xs, x D.< p:]
in if k I.< (lengthP ls)
then median' ls k
else
let gs = [:x | x <- xs, x D.> p:]
len = lengthP xs I.- lengthP gs
in if k I.>= len
then median' gs (k I.- len)
else p
| null | https://raw.githubusercontent.com/ghc/packages-dph/64eca669f13f4d216af9024474a3fc73ce101793/dph-examples/examples/spectral/ClosestPairs/dph/Vectorised.hs | haskell | Vectorised "all closest pairs":
This was
# LANGUAGE ParallelArrays #
# OPTIONS -fvectorise #
# OPTIONS -fno-spec-constr-count #
------- dph-lifted-copy implementations
These functions are in -copy but not in -vseg.
I've tried to implement them but got a vectorisation error:
"Can't vectorise expression GHC.Prim.Int#"
| Distance squared.
Because most uses of this are just finding the minimum, the sqrt is unnecessary.
| Distance squared.
| Naive closest pairs.
Our divide and conquer drops back to this once there are few enough points
Returns pairs with indices within original input array.
^ Input pairs
^ X dimension of boundary
^ Maximum distance from X boundary
^ Input pairs
^ Check each input pair against these to find any closer pairs
then find the points in each array within that distance of the split.
We check each of these boundary points against the other boundary
to see if they are closer.
^ Split point
^ `Above' pairs
^ `Below' pairs
| For each point, find its closest neighbour.
Once there are few enough points, we use a naive n^2 algorithm.
Otherwise, the median x is found and the array is split into
those below and those above.
| Find median of an array, using quickselect
| Find the @k@th smallest element.
A pivot is selected and the array is partitioned into those smaller and larger than the pivot.
@k@th smallest element, and we recurse into the smaller elements.
Otherwise the @k@th element must be larger or equal to the pivot.
Since lesser elements are not in the greater array, we are no longer looking for the |
module Vectorised (closestPA, closeststupidPA) where
import Points2D.Types
import Data.Array.Parallel
import Data.Array.Parallel.Prelude.Double as D
import qualified Data.Array.Parallel.Prelude.Int as I
import qualified Prelude as P
bpermuteP :: [:a:] -> [:Int:] -> [:a:]
bpermuteP as is = mapP (\i -> as !: i) is
indexedP :: [:a:] -> [:(Int,a):]
indexedP xs = zipP (I.enumFromToP 0 (lengthP xs I.- 1)) xs
updateP :: [:a:] -> [:(Int,a):] -> [:a:]
updateP as is = snd' (unzipP (mapP find (indexedP as)))
where
find (i,a)
| [:v:] <- filterP (\(i',_) -> i I.== i') is
= v
| otherwise
= (i,a)
snd' (_,b) = b
distance :: Point -> Point -> Double
distance (x1, y1) (x2, y2)
= (x2 D.- x1) D.* (x2 D.- x1)
D.+ (y2 D.- y1) D.* (y2 D.- y1)
Distance between two points , but return a very large number if they 're the same ...
distancex :: Point -> Point -> Double
distancex a b
= let d = distance a b
in if d D.== 0 then 1e100 else d
An n^2 algorithm for finding closest pairs .
closeststupid :: [: Point :] -> [:(Point,Point):]
closeststupid pts
= let is = [: minIndexP [: distancex a b | b <- pts :] | a <- pts :]
in bpermuteP [: (a,b) | a <- pts, b <- pts :] is
| Find the points within distance @d@ of the edge along x=@x0@.
Only the first element of each pair is checked .
near_boundary
-> [:(Int,(Point,Point)):]
near_boundary a x0 d
= filterP check (indexedP a)
where
check (_,((x1,_),_)) = D.abs (x1 D.- x0) D.< d
| Given two arrays of pairs where the firsts are both near some boundary ,
update the first array with any closer points in the second array .
new_nearest
-> [:(Int,(Point,Point)):]
new_nearest a b
| lengthP b I.== 0 = a
| otherwise
= let bp = mapP (\(_,(pt1,_)) -> pt1) b
is = [: minIndexP [: distance pt1 pt2 | pt2 <- bp :] | (_,(pt1,_)) <- a :]
na = [: (k,(pt1,check pt1 pn pt2)) | (k,(pt1,pt2)) <- a, pn <- bpermuteP bp is :]
in na
where
check pt1 pn pt2
= if distance pt1 pn D.< distance pt1 pt2
then pn
else pt2
| Merge two arrays of pairs that have been split on the x axis .
To do this , we find the maximum distance between any two points ,
merge_pairs
-> [:(Point,Point):]
merge_pairs x0 a b
= let d = sqrt (D.max (maximumP (mapP dist a)) (maximumP (mapP dist b)))
an = near_boundary a x0 d
bn = near_boundary b x0 d
a' = a `updateP` new_nearest an bn
b' = b `updateP` new_nearest bn an
in a' +:+ b'
where
dist (a,b) = distance a b
The two halves are recursed upon and then the results merged ( see @merge_pairs@ ) .
closest :: [:Point:] -> [:(Point,Point):]
closest pts
| lengthP pts I.< 250 = closeststupid pts
| otherwise =
let (xs,ys) = unzipP pts
xd = maximumP xs D.- minimumP xs
yd = maximumP ys D.- minimumP ys
mid = median xs
top = filterP (\(x,_) -> x D.>= mid) pts
bot = filterP (\(x,_) -> x D.< mid) pts
top' = closest top
bot' = closest bot
pair = merge_pairs mid top' bot'
in pair
closestPA :: PArray Point -> PArray (Point,Point)
closestPA ps = toPArrayP (closest (fromPArrayP ps))
closeststupidPA :: PArray Point -> PArray (Point,Point)
closeststupidPA ps = toPArrayP (closeststupid (fromPArrayP ps))
median :: [: Double :] -> Double
median xs = median' xs (lengthP xs `I.div` 2)
If the number of elements smaller than pivot is greater or equal to @k@ , then the pivot must be larger than the
@k@th smallest element , but the @k - ( length xs - length gs)@th smallest .
median':: [: Double :] -> Int -> Double
median' xs k =
let p = xs !: (lengthP xs `I.div` 2)
ls = [:x | x <- xs, x D.< p:]
in if k I.< (lengthP ls)
then median' ls k
else
let gs = [:x | x <- xs, x D.> p:]
len = lengthP xs I.- lengthP gs
in if k I.>= len
then median' gs (k I.- len)
else p
|
8c3ab47f5241cb15d81d06b2ffa8f9d04ccf33bb702d1147c13b8ab6f23d6866 | justinethier/nugget | cmd-line-husk.scm | #! /usr/bin/env huski
;
This is the example code from SRFI-22
; -22/srfi-22.html
;
; A clone of the UNIX cat command, written in scheme.
; To run from the command line:
;
; ./cat.scm filename
;
(define (main arguments)
(for-each display-file (cdr arguments))
0)
(define (display-file filename)
(call-with-input-file filename
(lambda (port)
(let loop ()
(let ((thing (read-char port)))
(if (not (eof-object? thing))
(begin
(write-char thing)
(loop))))))))
| null | https://raw.githubusercontent.com/justinethier/nugget/0c4e3e9944684ea83191671d58b5c8c342f64343/cyclone/examples/cmd-line-husk.scm | scheme |
-22/srfi-22.html
A clone of the UNIX cat command, written in scheme.
To run from the command line:
./cat.scm filename
| #! /usr/bin/env huski
This is the example code from SRFI-22
(define (main arguments)
(for-each display-file (cdr arguments))
0)
(define (display-file filename)
(call-with-input-file filename
(lambda (port)
(let loop ()
(let ((thing (read-char port)))
(if (not (eof-object? thing))
(begin
(write-char thing)
(loop))))))))
|
3987ed24faa37d54436282d1a3d3185a801b574bf3b0345e1d9b4f399bd62488 | BekaValentine/SimpleFP-v2 | Program.hs | {-# OPTIONS -Wall #-}
-- | This module defines what it means to be a program in the dependently
-- typed lambda calculus.
module Modular.Core.Program where
import Utils.Plicity
import Utils.Pretty
import Modular.Core.ConSig
import Modular.Core.DeclArg
import Modular.Core.Term
import Data.List (intercalate)
| A ' Statement ' is either a ' TypeDeclaration ' or a ' TermDeclaration ' .
data Statement
= TyDecl TypeDeclaration
| TmDecl TermDeclaration
instance Show Statement where
show (TyDecl td) = show td
show (TmDecl td) = show td
-- | A term can be declared either with a simple equality, as in
--
-- > let not : Bool -> Bool
-- > = \b -> case b of
-- > | True -> False
-- > | False -> True
-- > end
-- > end
--
-- or with a pattern match, as in
--
-- > let not : Bool -> Bool where
-- > | not True = False
-- > | not False = True
-- > end
data TermDeclaration
= TermDeclaration String Term Term
| WhereDeclaration String Term [([Plicity],([String],[Pattern],Term))]
instance Show TermDeclaration where
show (TermDeclaration n ty def) =
"let " ++ n ++ " : " ++ pretty ty ++ " = " ++ pretty def ++ " end"
show (WhereDeclaration n ty preclauses)
= "let " ++ n ++ " : " ++ pretty ty ++ " where "
++ intercalate " | " (map showPreclause preclauses)
where
showPreclause :: ([Plicity],([String],[Pattern],Term)) -> String
showPreclause (plics,(_,ps,b))
= intercalate
" || "
(map showPattern (zip plics ps))
++ " -> " ++ pretty b
showPattern :: (Plicity,Pattern) -> String
showPattern (Expl,p) = parenthesize (Just (ConPatArg Expl)) p
showPattern (Impl,p) = parenthesize (Just (ConPatArg Impl)) p
| A type is declared with a GADT - like notation , however instead of giving
the type of a constructor , as in Haskell or Agda , a constructor 's signature
-- is given via exemplified application, as in:
--
-- @
-- data List (a : Type) where
-- | Nil : List a
-- | Cons (x : a) (xs : List a) : List a
-- end
-- @
--
-- Types with no constructors need no @where@:
--
-- > data Void end
data TypeDeclaration
= TypeDeclaration String [DeclArg] [(String,ConSig)]
instance Show TypeDeclaration where
show (TypeDeclaration tycon tyargs []) =
"data " ++ tycon ++ concat (map (\x -> " " ++ show x) tyargs) ++ " end"
show (TypeDeclaration tycon tyargs alts) =
"data " ++ tycon ++ concat (map (\x -> " " ++ show x) tyargs) ++ " where"
++ concat [ "\n" ++ c ++ " : " ++ show sig | (c,sig) <- alts ]
++ "\nend"
-- | Settings for hiding or using names from a module.
data HidingUsing
= Hiding [String]
| Using [String]
-- | Settings for opening a module's names for use.
data OpenSettings
= OpenSettings
{ openModule :: String
, openAs :: Maybe String
, openHidingUsing :: Maybe HidingUsing
, openRenaming :: [(String,String)]
}
instance Show OpenSettings where
show (OpenSettings m a hu r)
= m ++ a' ++ hu' ++ r'
where
a' = case a of
Nothing -> ""
Just m' -> " as " ++ m'
hu' = case hu of
Nothing -> ""
Just (Hiding ns) -> " hiding (" ++ intercalate "," ns ++ ")"
Just (Using ns) -> " using (" ++ intercalate "," ns ++ ")"
r' = case r of
[] -> ""
_ -> " renaming ("
++ intercalate
", "
[ n ++ " to " ++ n'
| (n,n') <- r
]
++ ")"
-- | Modules with imports of other modules.
data Module
= Module String [OpenSettings] [Statement]
instance Show Module where
show (Module n [] stmts)
= "module " ++ n ++ " where\n\n"
++ intercalate "\n\n" (map show stmts) ++ "\n\nend"
show (Module n settings stmts)
= "module " ++ n ++ " opening " ++ intercalate " | " (map show settings)
++ " where\n\n" ++ intercalate "\n\n" (map show stmts) ++ "\n\nend"
-- | A program is just a series of 'Module's.
newtype Program = Program [Module]
instance Show Program where
show (Program stmts) = intercalate "\n\n" (map show stmts) | null | https://raw.githubusercontent.com/BekaValentine/SimpleFP-v2/ae00ec809caefcd13664395b0ae2fc66145f6a74/src/Modular/Core/Program.hs | haskell | # OPTIONS -Wall #
| This module defines what it means to be a program in the dependently
typed lambda calculus.
| A term can be declared either with a simple equality, as in
> let not : Bool -> Bool
> = \b -> case b of
> | True -> False
> | False -> True
> end
> end
or with a pattern match, as in
> let not : Bool -> Bool where
> | not True = False
> | not False = True
> end
is given via exemplified application, as in:
@
data List (a : Type) where
| Nil : List a
| Cons (x : a) (xs : List a) : List a
end
@
Types with no constructors need no @where@:
> data Void end
| Settings for hiding or using names from a module.
| Settings for opening a module's names for use.
| Modules with imports of other modules.
| A program is just a series of 'Module's. |
module Modular.Core.Program where
import Utils.Plicity
import Utils.Pretty
import Modular.Core.ConSig
import Modular.Core.DeclArg
import Modular.Core.Term
import Data.List (intercalate)
| A ' Statement ' is either a ' TypeDeclaration ' or a ' TermDeclaration ' .
data Statement
= TyDecl TypeDeclaration
| TmDecl TermDeclaration
instance Show Statement where
show (TyDecl td) = show td
show (TmDecl td) = show td
data TermDeclaration
= TermDeclaration String Term Term
| WhereDeclaration String Term [([Plicity],([String],[Pattern],Term))]
instance Show TermDeclaration where
show (TermDeclaration n ty def) =
"let " ++ n ++ " : " ++ pretty ty ++ " = " ++ pretty def ++ " end"
show (WhereDeclaration n ty preclauses)
= "let " ++ n ++ " : " ++ pretty ty ++ " where "
++ intercalate " | " (map showPreclause preclauses)
where
showPreclause :: ([Plicity],([String],[Pattern],Term)) -> String
showPreclause (plics,(_,ps,b))
= intercalate
" || "
(map showPattern (zip plics ps))
++ " -> " ++ pretty b
showPattern :: (Plicity,Pattern) -> String
showPattern (Expl,p) = parenthesize (Just (ConPatArg Expl)) p
showPattern (Impl,p) = parenthesize (Just (ConPatArg Impl)) p
| A type is declared with a GADT - like notation , however instead of giving
the type of a constructor , as in Haskell or Agda , a constructor 's signature
data TypeDeclaration
= TypeDeclaration String [DeclArg] [(String,ConSig)]
instance Show TypeDeclaration where
show (TypeDeclaration tycon tyargs []) =
"data " ++ tycon ++ concat (map (\x -> " " ++ show x) tyargs) ++ " end"
show (TypeDeclaration tycon tyargs alts) =
"data " ++ tycon ++ concat (map (\x -> " " ++ show x) tyargs) ++ " where"
++ concat [ "\n" ++ c ++ " : " ++ show sig | (c,sig) <- alts ]
++ "\nend"
data HidingUsing
= Hiding [String]
| Using [String]
data OpenSettings
= OpenSettings
{ openModule :: String
, openAs :: Maybe String
, openHidingUsing :: Maybe HidingUsing
, openRenaming :: [(String,String)]
}
instance Show OpenSettings where
show (OpenSettings m a hu r)
= m ++ a' ++ hu' ++ r'
where
a' = case a of
Nothing -> ""
Just m' -> " as " ++ m'
hu' = case hu of
Nothing -> ""
Just (Hiding ns) -> " hiding (" ++ intercalate "," ns ++ ")"
Just (Using ns) -> " using (" ++ intercalate "," ns ++ ")"
r' = case r of
[] -> ""
_ -> " renaming ("
++ intercalate
", "
[ n ++ " to " ++ n'
| (n,n') <- r
]
++ ")"
data Module
= Module String [OpenSettings] [Statement]
instance Show Module where
show (Module n [] stmts)
= "module " ++ n ++ " where\n\n"
++ intercalate "\n\n" (map show stmts) ++ "\n\nend"
show (Module n settings stmts)
= "module " ++ n ++ " opening " ++ intercalate " | " (map show settings)
++ " where\n\n" ++ intercalate "\n\n" (map show stmts) ++ "\n\nend"
newtype Program = Program [Module]
instance Show Program where
show (Program stmts) = intercalate "\n\n" (map show stmts) |
cc9c1fc7f13b38e47437e41c6dfa9d06fc460064828ae21228683f326845df71 | hopbit/sonic-pi-snippets | mel_list.sps | # key: mel list
# point_line: 0
# point_index: 0
# --
# cdur - gama C Dur
# cj - coco jumbo
# nem - nothing else matters
# scom - sweet child o' mine
# soy - shape of you
# * rfiy - river flows in you
| null | https://raw.githubusercontent.com/hopbit/sonic-pi-snippets/2232854ac9587fc2f9f684ba04d7476e2dbaa288/melodies/mel_list.sps | scheme | # key: mel list
# point_line: 0
# point_index: 0
# --
# cdur - gama C Dur
# cj - coco jumbo
# nem - nothing else matters
# scom - sweet child o' mine
# soy - shape of you
# * rfiy - river flows in you
| |
845f52a495b85a78bb1287350d487262414fdc5ff77e874cff8f5eedab05d078 | vascokk/rivus_cep | event4.erl | -module(event4).
-behaviour(event_behaviour).
-export([get_param_by_name/2, get_param_names/0]).
get_param_by_name(Event, ParamName) ->
case ParamName of
name -> element(1, Event);
attr1 -> element(2, Event);
attr2 -> element(3, Event);
qttr3 -> element(4, Event);
attr4 -> element(5, Event)
end.
get_param_names() ->
[attr1, attr2, attr3, attr4]. | null | https://raw.githubusercontent.com/vascokk/rivus_cep/e9fe6ed79201d852065f7fb2a24a880414031d27/test/event4.erl | erlang | -module(event4).
-behaviour(event_behaviour).
-export([get_param_by_name/2, get_param_names/0]).
get_param_by_name(Event, ParamName) ->
case ParamName of
name -> element(1, Event);
attr1 -> element(2, Event);
attr2 -> element(3, Event);
qttr3 -> element(4, Event);
attr4 -> element(5, Event)
end.
get_param_names() ->
[attr1, attr2, attr3, attr4]. | |
5ca0335a8e2ed3e309a8672ea62bf95cec684557537f4371e179e0488871e22e | burtonsamograd/med | redisplay.lisp | (in-package :med)
(defun redraw-screen ()
"Redraw the whole screen. For use when the display is corrupted."
;; Flush the current screen and line cache.
(setf (editor-current-screen *editor*) nil
(display-line-cache *editor*) '()))
(defun pane-top-line (buffer)
(let ((top-line (buffer-property buffer 'pane-top-line)))
(when (not top-line)
(setf top-line (make-mark (first-line buffer) 0 :left)
(buffer-property buffer 'pane-top-line) top-line))
top-line))
(defclass display-line ()
((%line :initarg :line :reader display-line-line)
(%version :initarg :version :reader display-line-version)
(%start :initarg :start :reader display-line-start)
(%end :initarg :end :reader display-line-end)
(%representation :initarg :representation :accessor display-line-representation)))
;; Lines are currently fixed-height.
(defun window-rows ()
(multiple-value-bind (left right top bottom)
(mezzano.gui.widgets:frame-size (frame *editor*))
(- (truncate (- (mezzano.gui.compositor:height (window *editor*)) top bottom)
(mezzano.gui.font:line-height (font *editor*))) 2)))
(defun flush-display-line (mark)
"Flush the display line containing MARK."
(setf (display-line-cache *editor*)
(remove-if (lambda (line)
Munch the entire line .
(eql (display-line-line line) (mark-line mark)))
(display-line-cache *editor*))))
(defun flush-display-lines-in-region (mark-1 mark-2)
"Flush display lines containing the region specified by MARK-1 and MARK-2."
(let ((first (min (line-number (mark-line mark-1))
(line-number (mark-line mark-2))))
(last (max (line-number (mark-line mark-1))
(line-number (mark-line mark-2)))))
(setf (display-line-cache *editor*)
(remove-if (lambda (line)
(<= first (line-number (display-line-line line)) last))
(display-line-cache *editor*)))))
(defun flush-stale-lines ()
"Flush any display lines with the wrong version."
(setf (display-line-cache *editor*)
(remove-if (lambda (line)
(not (eql (display-line-version line)
(line-version (display-line-line line)))))
(display-line-cache *editor*))))
(defun editor-width ()
"Return the width of the display area in pixels."
(multiple-value-bind (left right top bottom)
(mezzano.gui.widgets:frame-size (frame *editor*))
(- (mezzano.gui.compositor:width (window *editor*)) left right)))
(defun region-bounds (mark-1 mark-2)
"Return a bunch of boundary information for the region."
(cond ((eql (mark-line mark-1) (mark-line mark-2))
;; Same line.
(when (> (mark-charpos mark-1) (mark-charpos mark-2))
(rotatef mark-1 mark-2))
(values (mark-line mark-1) (mark-charpos mark-1) nil
(mark-line mark-2) (mark-charpos mark-2) nil))
2 or more lines .
(when (> (line-number (mark-line mark-1)) (line-number (mark-line mark-2)))
(rotatef mark-1 mark-2))
(values (mark-line mark-1) (mark-charpos mark-1) (line-number (mark-line mark-1))
(mark-line mark-2) (mark-charpos mark-2) (line-number (mark-line mark-2))))))
(defun render-display-line-2 (line start &optional invert)
(multiple-value-bind (line-1 line-1-charpos line-1-number line-2 line-2-charpos line-2-number)
(region-bounds (buffer-point (current-buffer *editor*)) (buffer-mark (current-buffer *editor*)))
(loop
with pen = 0
with font = (font *editor*)
with font-bold = (font-bold *editor*)
with baseline = (mezzano.gui.font:ascender font)
with foreground = (if invert (background-colour *editor*) (foreground-colour *editor*))
with background = (if invert (foreground-colour *editor*) (background-colour *editor*))
with line-height = (mezzano.gui.font:line-height font)
with win-width = (editor-width)
with point = (buffer-point (current-buffer *editor*))
with mark-active = (buffer-mark-active (current-buffer *editor*))
with buffer = (make-array (list line-height win-width)
:element-type '(unsigned-byte 32)
:initial-element background)
for ch-position from start below (line-length line)
for glyph = (mezzano.gui.font:character-to-glyph font (line-character line ch-position))
for mask = (mezzano.gui.font:glyph-mask glyph)
for advance = (mezzano.gui.font:glyph-advance glyph)
do
(when (> (+ pen advance) win-width)
(return (values buffer ch-position)))
(let ((at-point (and (eql line (mark-line point))
(eql ch-position (mark-charpos point))))
(in-region (and mark-active
(or (if line-1-number
(or (< line-1-number (line-number line) line-2-number)
(and (eql line line-1)
(<= line-1-charpos ch-position))
(and (eql line line-2)
(< ch-position line-2-charpos)))
(and (eql line line-1)
(<= line-1-charpos ch-position)
(< ch-position line-2-charpos)))))))
;; Invert the point.
(when at-point
(mezzano.gui:bitset line-height advance
foreground
buffer 0 pen))
(mezzano.gui:bitset-argb-xrgb-mask-8 (array-dimension mask 0) (array-dimension mask 1)
(if at-point
background
foreground)
mask 0 0
buffer
(- baseline (mezzano.gui.font:glyph-yoff glyph))
(+ pen (mezzano.gui.font:glyph-xoff glyph)))
;; Underline the region.
;; (when in-region
( mezzano.gui : bitset - argb - xrgb 1 advance
;; (if at-point
;; background
;; foreground)
;; buffer baseline pen))
(incf pen advance))
finally
;; Reached end of line, check for the point.
(when (and (eql line (mark-line point))
(eql ch-position (mark-charpos point)))
Point is here , render it past the last character .
(let* ((glyph (mezzano.gui.font:character-to-glyph font #\Space))
(advance (mezzano.gui.font:glyph-advance glyph)))
FIXME , how to display point at end of line & display line properly . also fix blit crash bug .
(mezzano.gui:bitset line-height advance
foreground
buffer 0 pen))))
;; TODO: Render underline to end of line region spans whole line.
(return (values buffer ch-position)))))
(defun render-display-line-1 (line start &optional invert)
(multiple-value-bind (buffer end)
(render-display-line-2 line start invert)
(let ((display-line (make-instance 'display-line
:line line
:version (line-version line)
:start start
:end end
:representation buffer)))
(push display-line (display-line-cache *editor*))
display-line)))
(defun render-display-line (line fn &optional invert)
"Render display lines for real line LINE, calling FN with each display line."
(cond ((zerop (line-length line))
(funcall fn (or (get-display-line-from-cache line 0)
(render-display-line-1 line 0 invert))))
(t (do ((start 0))
((>= start (line-length line)))
(let ((display-line (or (get-display-line-from-cache line start)
(render-display-line-1 line start invert))))
(funcall fn display-line)
(setf start (display-line-end display-line)))))))
(defun get-display-line-from-cache (line start)
(dolist (display-line (display-line-cache *editor*))
(when (and (eql (display-line-line display-line) line)
(eql (display-line-start display-line) start))
MRU cache .
(setf (display-line-cache *editor*) (remove display-line (display-line-cache *editor*)))
(push display-line (display-line-cache *editor*))
(return display-line))))
(defun blit-display-line (line y)
(multiple-value-bind (left right top bottom)
(mezzano.gui.widgets:frame-size (frame *editor*))
(let* ((fb (mezzano.gui.compositor:window-buffer (window *editor*)))
(line-height (mezzano.gui.font:line-height (font *editor*)))
(real-y (+ top (* y line-height)))
(win-width (editor-width)))
(if line
Blitting line .
(mezzano.gui:bitblt line-height win-width
(display-line-representation line)
0 0
fb
real-y left)
;; Line is empty.
(mezzano.gui:bitset line-height win-width
(background-colour *editor*)
fb
real-y left))
(mezzano.gui.compositor:damage-window (window *editor*)
left real-y
win-width line-height))))
(defun recenter (buffer)
"Move BUFFER's top line so that the point is displayed."
(let* ((point (buffer-point buffer))
(top-line (mark-line point))
(rendered-lines (make-array (ceiling (window-rows) 2) :fill-pointer 0 :adjustable t))
(point-display-line nil))
;; Move (window-rows)/2 lines up from point.
(dotimes (i (ceiling (window-rows) 2))
(when (not (previous-line top-line))
(return))
(setf top-line (previous-line top-line)))
;; Render display lines until point is reached.
(do ((line top-line (next-line line)))
;; Should always top when the point's line has been reached.
()
(render-display-line line
(lambda (display-line)
(vector-push-extend display-line rendered-lines)
(when (and (eql (mark-line point) (display-line-line display-line))
(<= (display-line-start display-line) (mark-charpos point))
(or (and (eql (display-line-end display-line) (line-length (display-line-line display-line)))
(eql (display-line-end display-line) (mark-charpos point)))
(< (mark-charpos point) (display-line-end display-line))))
;; This is point line, stop here.
(setf point-display-line (1- (length rendered-lines)))
(return)))))
;; Walk (window-rows)/2 display lines backwards from point. This is the new top-line.
(let ((new-top-line (aref rendered-lines (max 0 (- point-display-line (truncate (window-rows) 2)))))
(top-line-mark (buffer-property buffer 'pane-top-line)))
(setf (mark-line top-line-mark) (display-line-line new-top-line))
(mark-charpos top-line-mark) (display-line-start new-top-line))))
(defun minibuffer-rows ()
(if (eql (current-buffer *editor*) *minibuffer*)
(1+ (truncate (line-number (last-line *minibuffer*)) 10000))
1))
(defvar *mode-line-buffer* (make-instance 'buffer))
(defun render-mode-line ()
(let* ((buffer (current-buffer *editor*)))
(unless (eql buffer *minibuffer*)
(insert *mode-line-buffer*
(format nil " [~A] ~A L~S C~S (~A)"
(if (buffer-modified buffer) "*" " ")
(buffer-property buffer 'name)
(1+ (truncate (line-number (mark-line (buffer-point buffer))) 10000))
(1+ (mark-charpos (buffer-point buffer)))
;;(buffer-current-package buffer)
*package* ; TODO: uncomment above when buffer-current-package is faster
))
(render-display-line (first-line *mode-line-buffer*)
(lambda (l) (blit-display-line l (- (window-rows) (1- (minibuffer-rows))))) t)
(with-mark (point (buffer-point *mode-line-buffer*))
(move-beginning-of-buffer *mode-line-buffer*)
(delete-region *mode-line-buffer* point (buffer-point *mode-line-buffer*))))))
(defun redisplay ()
"Perform an incremental redisplay cycle.
Returns true when the screen is up-to-date, false if the screen is dirty and there is pending input."
(handler-case
(progn
(when (not (eql (length (editor-current-screen *editor*)) (window-rows)))
(setf (editor-current-screen *editor*) (make-array (window-rows) :initial-element t)))
(check-pending-input)
(let* ((buffer (current-buffer *editor*))
(current-screen (editor-current-screen *editor*))
(new-screen (make-array (window-rows) :fill-pointer 0 :initial-element nil))
(point-line nil)
(top-line (pane-top-line buffer))
(point (buffer-point buffer))
(previous-point-position (buffer-property buffer 'pane-previous-point-position))
(mark (buffer-mark buffer))
(previous-mark-position (buffer-property buffer 'pane-previous-mark-position)))
(mezzano.supervisor::with-mutex ((buffer-lock buffer))
(when (not previous-point-position)
(setf previous-point-position (copy-mark point :right)
(buffer-property buffer 'pane-previous-point-position) previous-point-position))
(when (not previous-mark-position)
(setf previous-mark-position (copy-mark mark :left)
(buffer-property buffer 'pane-previous-mark-position) previous-mark-position))
;; If the point has moved, then invalidate the line that contained the point and the line that
;; now holds the point.
(when (not (mark= point previous-point-position))
(flush-display-line previous-point-position)
(flush-display-line point))
;; If the mark changes state, flush lines within the region.
(when (or (and (not (buffer-mark-active buffer))
(buffer-property buffer 'pane-mark-was-active))
(and (buffer-mark-active buffer)
(not (buffer-property buffer 'pane-mark-was-active))))
(flush-display-lines-in-region point mark))
;; If the mark is active and the point moves, flush lines between the old point position
;; and the new position.
;; FIXME: This will cause a bunch of lines to be redrawn when the point & mark are exchanged.
(when (and (buffer-mark-active buffer)
(not (mark= point previous-point-position)))
(flush-display-lines-in-region point previous-point-position))
;; If the mark is or was active and moves, flush lines between the old mark position
;; and the new position.
;; FIXME: This will cause a bunch of lines to be redrawn when the point & mark are exchanged.
(when (and (or (buffer-mark-active buffer)
(buffer-property buffer 'pane-mark-was-active))
(not (mark= mark previous-mark-position)))
(flush-display-lines-in-region mark previous-mark-position))
;; Finally, flush any stale lines.
(flush-stale-lines)
;; Update tracking properties.
(setf (buffer-property buffer 'pane-mark-was-active) (buffer-mark-active buffer))
(move-mark-to-mark previous-point-position point)
(move-mark-to-mark previous-mark-position mark)
;; Generate WINDOW-ROWS display lines, starting at TOP-LINE.
;; TODO: Don't start from the beginning of the top-line, use the charpos instead.
(setf (mark-charpos top-line) 0)
(do ((line (mark-line top-line) (next-line line)))
;; Stop when there are no more lines or the screen has been filled up.
((null line))
(render-display-line line
(lambda (display-line)
(check-pending-input)
(vector-push display-line new-screen)
(when (and (eql (mark-line point) (display-line-line display-line))
(<= (display-line-start display-line) (mark-charpos point))
(or (and (eql (display-line-end display-line) (line-length (display-line-line display-line)))
(eql (display-line-end display-line) (mark-charpos point)))
(< (mark-charpos point) (display-line-end display-line))))
(setf point-line display-line))
(when (eql (fill-pointer new-screen) (window-rows))
(return)))))
(setf (fill-pointer new-screen) (window-rows))
;; If the point is not within the screen bounds, then recenter and retry.
(when (and (eql *current-editor* *editor*)
(not point-line))
(recenter buffer)
(return-from redisplay nil))
;; Compare against the current screen, blitting when needed.
(if (eql buffer *minibuffer*)
(let ((minibuffer-rows (minibuffer-rows)))
(do ((y 0 (incf y)))
((= y minibuffer-rows))
(let ((line (aref new-screen y)))
(unless (eql (aref current-screen y) line)
(blit-display-line line (+ y (- (window-rows) minibuffer-rows) 2))
(setf (aref current-screen y) line)
(check-pending-input)))))
(progn
(dotimes (y (window-rows))
(let ((line (aref new-screen y)))
(unless (eql (aref current-screen y) line)
(blit-display-line line y)
(setf (aref current-screen y) line)
(check-pending-input))))
render the messages line TODO : long message line output
(let ((line (let ((line (last-line *messages*)))
(if (zerop (line-length line))
(previous-line (last-line *messages*))
line))))
(when line
(render-display-line line
(lambda (l) (blit-display-line l (1+ (window-rows)))))))))
(render-mode-line)
;; Prune the cache.
(setf (display-line-cache *editor*) (subseq (display-line-cache *editor*) 0 (* (window-rows) 4))))
t))
(pending-input ()
nil)))
(defclass force-redisplay () ())
(defmethod dispatch-event (editor (event force-redisplay))
(setf (pending-redisplay editor) t))
(defparameter *force-redisplay-event* (make-instance 'force-redisplay))
(defun force-redisplay ()
(dolist (editor *editors*)
(mezzano.supervisor::fifo-push *force-redisplay-event* (fifo editor))))
| null | https://raw.githubusercontent.com/burtonsamograd/med/667c45032f60831447ad0eafd4d5c9a9748b4366/redisplay.lisp | lisp | Flush the current screen and line cache.
Lines are currently fixed-height.
Same line.
Invert the point.
Underline the region.
(when in-region
(if at-point
background
foreground)
buffer baseline pen))
Reached end of line, check for the point.
TODO: Render underline to end of line region spans whole line.
Line is empty.
Move (window-rows)/2 lines up from point.
Render display lines until point is reached.
Should always top when the point's line has been reached.
This is point line, stop here.
Walk (window-rows)/2 display lines backwards from point. This is the new top-line.
(buffer-current-package buffer)
TODO: uncomment above when buffer-current-package is faster
If the point has moved, then invalidate the line that contained the point and the line that
now holds the point.
If the mark changes state, flush lines within the region.
If the mark is active and the point moves, flush lines between the old point position
and the new position.
FIXME: This will cause a bunch of lines to be redrawn when the point & mark are exchanged.
If the mark is or was active and moves, flush lines between the old mark position
and the new position.
FIXME: This will cause a bunch of lines to be redrawn when the point & mark are exchanged.
Finally, flush any stale lines.
Update tracking properties.
Generate WINDOW-ROWS display lines, starting at TOP-LINE.
TODO: Don't start from the beginning of the top-line, use the charpos instead.
Stop when there are no more lines or the screen has been filled up.
If the point is not within the screen bounds, then recenter and retry.
Compare against the current screen, blitting when needed.
Prune the cache. | (in-package :med)
(defun redraw-screen ()
"Redraw the whole screen. For use when the display is corrupted."
(setf (editor-current-screen *editor*) nil
(display-line-cache *editor*) '()))
(defun pane-top-line (buffer)
(let ((top-line (buffer-property buffer 'pane-top-line)))
(when (not top-line)
(setf top-line (make-mark (first-line buffer) 0 :left)
(buffer-property buffer 'pane-top-line) top-line))
top-line))
(defclass display-line ()
((%line :initarg :line :reader display-line-line)
(%version :initarg :version :reader display-line-version)
(%start :initarg :start :reader display-line-start)
(%end :initarg :end :reader display-line-end)
(%representation :initarg :representation :accessor display-line-representation)))
(defun window-rows ()
(multiple-value-bind (left right top bottom)
(mezzano.gui.widgets:frame-size (frame *editor*))
(- (truncate (- (mezzano.gui.compositor:height (window *editor*)) top bottom)
(mezzano.gui.font:line-height (font *editor*))) 2)))
(defun flush-display-line (mark)
"Flush the display line containing MARK."
(setf (display-line-cache *editor*)
(remove-if (lambda (line)
Munch the entire line .
(eql (display-line-line line) (mark-line mark)))
(display-line-cache *editor*))))
(defun flush-display-lines-in-region (mark-1 mark-2)
"Flush display lines containing the region specified by MARK-1 and MARK-2."
(let ((first (min (line-number (mark-line mark-1))
(line-number (mark-line mark-2))))
(last (max (line-number (mark-line mark-1))
(line-number (mark-line mark-2)))))
(setf (display-line-cache *editor*)
(remove-if (lambda (line)
(<= first (line-number (display-line-line line)) last))
(display-line-cache *editor*)))))
(defun flush-stale-lines ()
"Flush any display lines with the wrong version."
(setf (display-line-cache *editor*)
(remove-if (lambda (line)
(not (eql (display-line-version line)
(line-version (display-line-line line)))))
(display-line-cache *editor*))))
(defun editor-width ()
"Return the width of the display area in pixels."
(multiple-value-bind (left right top bottom)
(mezzano.gui.widgets:frame-size (frame *editor*))
(- (mezzano.gui.compositor:width (window *editor*)) left right)))
(defun region-bounds (mark-1 mark-2)
"Return a bunch of boundary information for the region."
(cond ((eql (mark-line mark-1) (mark-line mark-2))
(when (> (mark-charpos mark-1) (mark-charpos mark-2))
(rotatef mark-1 mark-2))
(values (mark-line mark-1) (mark-charpos mark-1) nil
(mark-line mark-2) (mark-charpos mark-2) nil))
2 or more lines .
(when (> (line-number (mark-line mark-1)) (line-number (mark-line mark-2)))
(rotatef mark-1 mark-2))
(values (mark-line mark-1) (mark-charpos mark-1) (line-number (mark-line mark-1))
(mark-line mark-2) (mark-charpos mark-2) (line-number (mark-line mark-2))))))
(defun render-display-line-2 (line start &optional invert)
(multiple-value-bind (line-1 line-1-charpos line-1-number line-2 line-2-charpos line-2-number)
(region-bounds (buffer-point (current-buffer *editor*)) (buffer-mark (current-buffer *editor*)))
(loop
with pen = 0
with font = (font *editor*)
with font-bold = (font-bold *editor*)
with baseline = (mezzano.gui.font:ascender font)
with foreground = (if invert (background-colour *editor*) (foreground-colour *editor*))
with background = (if invert (foreground-colour *editor*) (background-colour *editor*))
with line-height = (mezzano.gui.font:line-height font)
with win-width = (editor-width)
with point = (buffer-point (current-buffer *editor*))
with mark-active = (buffer-mark-active (current-buffer *editor*))
with buffer = (make-array (list line-height win-width)
:element-type '(unsigned-byte 32)
:initial-element background)
for ch-position from start below (line-length line)
for glyph = (mezzano.gui.font:character-to-glyph font (line-character line ch-position))
for mask = (mezzano.gui.font:glyph-mask glyph)
for advance = (mezzano.gui.font:glyph-advance glyph)
do
(when (> (+ pen advance) win-width)
(return (values buffer ch-position)))
(let ((at-point (and (eql line (mark-line point))
(eql ch-position (mark-charpos point))))
(in-region (and mark-active
(or (if line-1-number
(or (< line-1-number (line-number line) line-2-number)
(and (eql line line-1)
(<= line-1-charpos ch-position))
(and (eql line line-2)
(< ch-position line-2-charpos)))
(and (eql line line-1)
(<= line-1-charpos ch-position)
(< ch-position line-2-charpos)))))))
(when at-point
(mezzano.gui:bitset line-height advance
foreground
buffer 0 pen))
(mezzano.gui:bitset-argb-xrgb-mask-8 (array-dimension mask 0) (array-dimension mask 1)
(if at-point
background
foreground)
mask 0 0
buffer
(- baseline (mezzano.gui.font:glyph-yoff glyph))
(+ pen (mezzano.gui.font:glyph-xoff glyph)))
( mezzano.gui : bitset - argb - xrgb 1 advance
(incf pen advance))
finally
(when (and (eql line (mark-line point))
(eql ch-position (mark-charpos point)))
Point is here , render it past the last character .
(let* ((glyph (mezzano.gui.font:character-to-glyph font #\Space))
(advance (mezzano.gui.font:glyph-advance glyph)))
FIXME , how to display point at end of line & display line properly . also fix blit crash bug .
(mezzano.gui:bitset line-height advance
foreground
buffer 0 pen))))
(return (values buffer ch-position)))))
(defun render-display-line-1 (line start &optional invert)
(multiple-value-bind (buffer end)
(render-display-line-2 line start invert)
(let ((display-line (make-instance 'display-line
:line line
:version (line-version line)
:start start
:end end
:representation buffer)))
(push display-line (display-line-cache *editor*))
display-line)))
(defun render-display-line (line fn &optional invert)
"Render display lines for real line LINE, calling FN with each display line."
(cond ((zerop (line-length line))
(funcall fn (or (get-display-line-from-cache line 0)
(render-display-line-1 line 0 invert))))
(t (do ((start 0))
((>= start (line-length line)))
(let ((display-line (or (get-display-line-from-cache line start)
(render-display-line-1 line start invert))))
(funcall fn display-line)
(setf start (display-line-end display-line)))))))
(defun get-display-line-from-cache (line start)
(dolist (display-line (display-line-cache *editor*))
(when (and (eql (display-line-line display-line) line)
(eql (display-line-start display-line) start))
MRU cache .
(setf (display-line-cache *editor*) (remove display-line (display-line-cache *editor*)))
(push display-line (display-line-cache *editor*))
(return display-line))))
(defun blit-display-line (line y)
(multiple-value-bind (left right top bottom)
(mezzano.gui.widgets:frame-size (frame *editor*))
(let* ((fb (mezzano.gui.compositor:window-buffer (window *editor*)))
(line-height (mezzano.gui.font:line-height (font *editor*)))
(real-y (+ top (* y line-height)))
(win-width (editor-width)))
(if line
Blitting line .
(mezzano.gui:bitblt line-height win-width
(display-line-representation line)
0 0
fb
real-y left)
(mezzano.gui:bitset line-height win-width
(background-colour *editor*)
fb
real-y left))
(mezzano.gui.compositor:damage-window (window *editor*)
left real-y
win-width line-height))))
(defun recenter (buffer)
"Move BUFFER's top line so that the point is displayed."
(let* ((point (buffer-point buffer))
(top-line (mark-line point))
(rendered-lines (make-array (ceiling (window-rows) 2) :fill-pointer 0 :adjustable t))
(point-display-line nil))
(dotimes (i (ceiling (window-rows) 2))
(when (not (previous-line top-line))
(return))
(setf top-line (previous-line top-line)))
(do ((line top-line (next-line line)))
()
(render-display-line line
(lambda (display-line)
(vector-push-extend display-line rendered-lines)
(when (and (eql (mark-line point) (display-line-line display-line))
(<= (display-line-start display-line) (mark-charpos point))
(or (and (eql (display-line-end display-line) (line-length (display-line-line display-line)))
(eql (display-line-end display-line) (mark-charpos point)))
(< (mark-charpos point) (display-line-end display-line))))
(setf point-display-line (1- (length rendered-lines)))
(return)))))
(let ((new-top-line (aref rendered-lines (max 0 (- point-display-line (truncate (window-rows) 2)))))
(top-line-mark (buffer-property buffer 'pane-top-line)))
(setf (mark-line top-line-mark) (display-line-line new-top-line))
(mark-charpos top-line-mark) (display-line-start new-top-line))))
(defun minibuffer-rows ()
(if (eql (current-buffer *editor*) *minibuffer*)
(1+ (truncate (line-number (last-line *minibuffer*)) 10000))
1))
(defvar *mode-line-buffer* (make-instance 'buffer))
(defun render-mode-line ()
(let* ((buffer (current-buffer *editor*)))
(unless (eql buffer *minibuffer*)
(insert *mode-line-buffer*
(format nil " [~A] ~A L~S C~S (~A)"
(if (buffer-modified buffer) "*" " ")
(buffer-property buffer 'name)
(1+ (truncate (line-number (mark-line (buffer-point buffer))) 10000))
(1+ (mark-charpos (buffer-point buffer)))
))
(render-display-line (first-line *mode-line-buffer*)
(lambda (l) (blit-display-line l (- (window-rows) (1- (minibuffer-rows))))) t)
(with-mark (point (buffer-point *mode-line-buffer*))
(move-beginning-of-buffer *mode-line-buffer*)
(delete-region *mode-line-buffer* point (buffer-point *mode-line-buffer*))))))
(defun redisplay ()
"Perform an incremental redisplay cycle.
Returns true when the screen is up-to-date, false if the screen is dirty and there is pending input."
(handler-case
(progn
(when (not (eql (length (editor-current-screen *editor*)) (window-rows)))
(setf (editor-current-screen *editor*) (make-array (window-rows) :initial-element t)))
(check-pending-input)
(let* ((buffer (current-buffer *editor*))
(current-screen (editor-current-screen *editor*))
(new-screen (make-array (window-rows) :fill-pointer 0 :initial-element nil))
(point-line nil)
(top-line (pane-top-line buffer))
(point (buffer-point buffer))
(previous-point-position (buffer-property buffer 'pane-previous-point-position))
(mark (buffer-mark buffer))
(previous-mark-position (buffer-property buffer 'pane-previous-mark-position)))
(mezzano.supervisor::with-mutex ((buffer-lock buffer))
(when (not previous-point-position)
(setf previous-point-position (copy-mark point :right)
(buffer-property buffer 'pane-previous-point-position) previous-point-position))
(when (not previous-mark-position)
(setf previous-mark-position (copy-mark mark :left)
(buffer-property buffer 'pane-previous-mark-position) previous-mark-position))
(when (not (mark= point previous-point-position))
(flush-display-line previous-point-position)
(flush-display-line point))
(when (or (and (not (buffer-mark-active buffer))
(buffer-property buffer 'pane-mark-was-active))
(and (buffer-mark-active buffer)
(not (buffer-property buffer 'pane-mark-was-active))))
(flush-display-lines-in-region point mark))
(when (and (buffer-mark-active buffer)
(not (mark= point previous-point-position)))
(flush-display-lines-in-region point previous-point-position))
(when (and (or (buffer-mark-active buffer)
(buffer-property buffer 'pane-mark-was-active))
(not (mark= mark previous-mark-position)))
(flush-display-lines-in-region mark previous-mark-position))
(flush-stale-lines)
(setf (buffer-property buffer 'pane-mark-was-active) (buffer-mark-active buffer))
(move-mark-to-mark previous-point-position point)
(move-mark-to-mark previous-mark-position mark)
(setf (mark-charpos top-line) 0)
(do ((line (mark-line top-line) (next-line line)))
((null line))
(render-display-line line
(lambda (display-line)
(check-pending-input)
(vector-push display-line new-screen)
(when (and (eql (mark-line point) (display-line-line display-line))
(<= (display-line-start display-line) (mark-charpos point))
(or (and (eql (display-line-end display-line) (line-length (display-line-line display-line)))
(eql (display-line-end display-line) (mark-charpos point)))
(< (mark-charpos point) (display-line-end display-line))))
(setf point-line display-line))
(when (eql (fill-pointer new-screen) (window-rows))
(return)))))
(setf (fill-pointer new-screen) (window-rows))
(when (and (eql *current-editor* *editor*)
(not point-line))
(recenter buffer)
(return-from redisplay nil))
(if (eql buffer *minibuffer*)
(let ((minibuffer-rows (minibuffer-rows)))
(do ((y 0 (incf y)))
((= y minibuffer-rows))
(let ((line (aref new-screen y)))
(unless (eql (aref current-screen y) line)
(blit-display-line line (+ y (- (window-rows) minibuffer-rows) 2))
(setf (aref current-screen y) line)
(check-pending-input)))))
(progn
(dotimes (y (window-rows))
(let ((line (aref new-screen y)))
(unless (eql (aref current-screen y) line)
(blit-display-line line y)
(setf (aref current-screen y) line)
(check-pending-input))))
render the messages line TODO : long message line output
(let ((line (let ((line (last-line *messages*)))
(if (zerop (line-length line))
(previous-line (last-line *messages*))
line))))
(when line
(render-display-line line
(lambda (l) (blit-display-line l (1+ (window-rows)))))))))
(render-mode-line)
(setf (display-line-cache *editor*) (subseq (display-line-cache *editor*) 0 (* (window-rows) 4))))
t))
(pending-input ()
nil)))
(defclass force-redisplay () ())
(defmethod dispatch-event (editor (event force-redisplay))
(setf (pending-redisplay editor) t))
(defparameter *force-redisplay-event* (make-instance 'force-redisplay))
(defun force-redisplay ()
(dolist (editor *editors*)
(mezzano.supervisor::fifo-push *force-redisplay-event* (fifo editor))))
|
e9d01a02e36a401bae02704628aa7ac68eacf491b862daff0814505f62ab1a19 | wireapp/wire-server | Scope.hs | {-# LANGUAGE StrictData #-}
-- This file is part of the Wire Server implementation.
--
Copyright ( C ) 2022 Wire Swiss GmbH < >
--
-- This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero 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 Affero General Public License for more
-- details.
--
You should have received a copy of the GNU Affero General Public License along
-- with this program. If not, see </>.
module Galley.Data.Scope where
import Cassandra hiding (Value)
import Imports
data Scope = ReusableCode
deriving (Eq, Show, Generic)
instance Cql Scope where
ctype = Tagged IntColumn
toCql ReusableCode = CqlInt 1
fromCql (CqlInt 1) = pure ReusableCode
fromCql _ = Left "unknown Scope"
| null | https://raw.githubusercontent.com/wireapp/wire-server/97286de4e9745b89e0146c0cb556b1f90e660133/services/galley/src/Galley/Data/Scope.hs | haskell | # LANGUAGE StrictData #
This file is part of the Wire Server implementation.
This program is free software: you can redistribute it and/or modify it under
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 Affero General Public License for more
details.
with this program. If not, see </>. |
Copyright ( C ) 2022 Wire Swiss GmbH < >
the terms of the GNU Affero General Public License as published by the Free
Software Foundation , either version 3 of the License , or ( at your option ) any
You should have received a copy of the GNU Affero General Public License along
module Galley.Data.Scope where
import Cassandra hiding (Value)
import Imports
data Scope = ReusableCode
deriving (Eq, Show, Generic)
instance Cql Scope where
ctype = Tagged IntColumn
toCql ReusableCode = CqlInt 1
fromCql (CqlInt 1) = pure ReusableCode
fromCql _ = Left "unknown Scope"
|
d3078ee94caff3c36e62e8fe72dafe0cbd06e8fc4c1116d45a79ae084024e100 | dinosaure/prettym | enclosure.ml | [@@@warning "-32"]
module type V = sig
type t
val pp : t Fmt.t
val sentinel : t
val weight : t -> int
val merge : t -> t -> t option
end
module RBQ (V : V) = struct
module Queue = Ke.Fke.Weighted
type t = {
a : V.t array;
c : int;
m : int;
q : (int, Bigarray.int_elt) Queue.t;
}
XXX(dinosaure ): [ ke ] is limited to [ Bigarray.kind ] . We make an [ array ]
which will contain values and [ q ] will contain index of them . Length of [ a ]
is length of [ q ] . By this way , length is a power of two and [ a ] follows
same assertions ( see [ mask ] ) as [ Ke ] .
[ c ] will be the cursor in [ a ] . [ m ] is the capacity . It 's a good example of
[ ke ] with something else than [ Bigarray.kind ] .
which will contain values and [q] will contain index of them. Length of [a]
is length of [q]. By this way, length is a power of two and [a] follows
same assertions (see [mask]) as [Ke].
[c] will be the cursor in [a]. [m] is the capacity. It's a good example of
[ke] with something else than [Bigarray.kind]. *)
let make capacity =
let q, capacity = Queue.create ~capacity Bigarray.Int in
{ a = Array.make capacity V.sentinel; c = 0; m = capacity; q }
let pp ppf t =
let a = Array.make (Queue.length t.q) V.sentinel in
let x = ref 0 in
Queue.iter
(fun i ->
a.(!x) <- t.a.(i);
incr x)
t.q;
Fmt.pf ppf "{ @[<hov>a = %a;@ c = %d;@ m = %d;@ q = %a;@] }"
Fmt.(Dump.array V.pp)
a t.c t.m (Queue.dump Fmt.int) t.q
let available t = Queue.available t.q
let is_empty t = Queue.is_empty t.q
let[@inline always] mask x t = x land (t.m - 1)
let push t v =
let i = mask t.c t in
match Queue.push t.q i with
| Some q ->
t.a.(i) <- v;
Ok { t with c = succ t.c; q }
| None -> Error t
let shift_exn t =
let i, q = Queue.pop_exn t.q in
(t.a.(i), { t with q })
let cons t v =
let i = mask t.c t in
match Queue.cons t.q i with
| Some q ->
t.a.(i) <- v;
Ok { t with c = succ t.c; q }
| None -> Error t
exception Full
let cons_exn t v = match cons t v with Ok t -> t | Error _ -> raise Full
let weight t = Queue.fold (fun a i -> a + V.weight t.a.(i)) 0 t.q
let to_list t =
let res = ref [] in
Queue.rev_iter (fun i -> res := t.a.(i) :: !res) t.q;
!res
end
let pp_chr =
Fmt.using (function '\032' .. '\126' as x -> x | _ -> '.') Fmt.char
let pp_scalar :
type buffer.
get:(buffer -> int -> char) -> length:(buffer -> int) -> buffer Fmt.t =
fun ~get ~length ppf b ->
let l = length b in
for i = 0 to l / 16 do
Fmt.pf ppf "%08x: " (i * 16);
let j = ref 0 in
while !j < 16 do
if (i * 16) + !j < l then
Fmt.pf ppf "%02x" (Char.code @@ get b ((i * 16) + !j))
else Fmt.pf ppf " ";
if !j mod 2 <> 0 then Fmt.pf ppf " ";
incr j
done;
Fmt.pf ppf " ";
j := 0;
while !j < 16 do
if (i * 16) + !j < l then Fmt.pf ppf "%a" pp_chr (get b ((i * 16) + !j))
else Fmt.pf ppf " ";
incr j
done;
Fmt.pf ppf "@,"
done
module RBA = Ke.Fke.Weighted
module Buffer = struct
type t = Bigstring of Bigstringaf.t | String of string | Bytes of bytes
let pp ppf = function
| Bigstring x ->
pp_scalar ~length:Bigstringaf.length ~get:Bigstringaf.get ppf x
| String x -> pp_scalar ~length:String.length ~get:String.get ppf x
| Bytes x -> pp_scalar ~length:Bytes.length ~get:Bytes.get ppf x
let weight = function
| Bigstring x -> Bigstringaf.length x
| String x -> String.length x
| Bytes x -> Bytes.length x
let sub buffer off len =
match buffer with
| Bigstring x -> Bigstring (Bigstringaf.sub x ~off ~len)
| String x -> String (String.sub x off len)
| Bytes x -> Bytes (Bytes.sub x off len)
end
module IOVec = struct
type t = { buffer : Buffer.t; off : int; len : int }
let weight { len; _ } = len
let pp ppf t =
Fmt.pf ppf "{ @[<hov>buffer= @[<hov>%a@];@ off= %d;@ len= %d;@] }" Buffer.pp
t.buffer t.off t.len
let sentinel =
let deadbeef = "\222\173\190\239" in
{ buffer = Buffer.String deadbeef; off = 0; len = String.length deadbeef }
let make buffer off len = { buffer; off; len }
let length { len; _ } = len
let lengthv = List.fold_left (fun a x -> length x + a) 0
let shift { buffer; off; len } n =
assert (n <= len);
{ buffer; off = off + n; len = len - n }
let split { buffer; off; len } n =
assert (n <= len);
( { buffer = Buffer.sub buffer off n; off = 0; len = n },
{ buffer = Buffer.sub buffer (off + n) (len - n); off = 0; len = len - n }
)
let merge a b =
match (a, b) with
| { buffer = Buffer.Bytes a'; _ }, { buffer = Buffer.Bytes b'; _ } ->
assert (a' == b');
if a.off + a.len = b.off then
Some { buffer = Buffer.Bytes a'; off = a.off; len = a.len + b.len }
else None
| { buffer = Buffer.Bigstring a'; _ }, { buffer = Buffer.Bigstring _; _ } ->
if a.off + a.len = b.off then
Some
{ buffer = Buffer.Bigstring a'; off = a.off; len = a.len + b.len }
else None
| _, _ -> None
end
module RBS = RBQ (IOVec)
type emitter = IOVec.t list -> int
type encoder = {
sched : RBS.t;
write : (char, Bigarray.int8_unsigned_elt) RBA.t;
flush : (int * (int -> encoder -> unit)) Ke.Fke.t;
written : int;
received : int;
emitter : emitter;
}
let pp_flush ppf _ = Fmt.string ppf "#flush"
let pp ppf t =
Fmt.pf ppf
"{ @[<hov>sched= @[<hov>%a@];@ write= @[<hov>%a@];@ flush= @[<hov>%a@];@ \
written= %d;@ received= %d;@ emitter= #emitter;@] }"
RBS.pp t.sched (RBA.pp pp_chr) t.write (Ke.Fke.pp pp_flush) t.flush
t.written t.received
let is_empty t = RBS.is_empty t.sched
XXX(dinosaure ): [ sched ] is a queue of [ ] . [ write ] is a
ring - buffer/[Bigstringaf.t ] . [ flush ] is a queue which can contain
user - defined operation at a break point . [ written ] is how many bytes we
sended to the user ( afterwards a * flush * operation ) . [ received ] is how many
bytes we received from the user .
The goal is to have two ways to fill output :
- an heavy way with [ write _ * ] operations which will do internally a [ blit ] .
- a soft way with [ shedule _ * ] operations which will store a pointer .
The complexity is under [ sched ] where it stores pointer from user but pointer
from [ write ] queue too . Indeed , [ write _ ] operations did not do only a [ blit ]
but then they store resulted/*blitted * [ Bigstringaf.t ] part to [ sched ] .
When we want to shift a part of [ encoder ] , * * all * * buffers are stored in
[ sched ] . So we need to shift [ sched ] . However , resulted [ ] can be
physically a part of [ write ] . In this context , we need to shift [ write ] .
ring-buffer/[Bigstringaf.t]. [flush] is a queue which can contain
user-defined operation at a break point. [written] is how many bytes we
sended to the user (afterwards a *flush* operation). [received] is how many
bytes we received from the user.
The goal is to have two ways to fill output:
- an heavy way with [write_*] operations which will do internally a [blit].
- a soft way with [shedule_*] operations which will store a pointer.
The complexity is under [sched] where it stores pointer from user but pointer
from [write] queue too. Indeed, [write_] operations did not do only a [blit]
but then they store resulted/*blitted* [Bigstringaf.t] part to [sched].
When we want to shift a part of [encoder], **all** buffers are stored in
[sched]. So we need to shift [sched]. However, resulted [IOVec] can be
physically a part of [write]. In this context, we need to shift [write]. *)
let create ~emitter len =
let write, _ = RBA.create ~capacity:len Bigarray.Char in
{
sched = RBS.make (len * 2);
write;
flush = Ke.Fke.empty;
written = 0;
received = 0;
emitter;
}
let check iovec { write; _ } =
match iovec with
| { IOVec.buffer = Buffer.Bigstring x; _ } -> (
let buf = RBA.unsafe_bigarray write in
match Overlap.array1 x buf with Some (_, _, _) -> true | None -> false)
| _ -> false
let shift_buffers written t =
let rec go written acc t =
match RBS.shift_exn t.sched with
| iovec, shifted ->
let len = IOVec.length iovec in
if written > len then
go (written - len) (iovec :: acc)
{
t with
sched = shifted;
write =
(if check iovec t then RBA.N.shift_exn t.write len else t.write);
}
else if written > 0 then
let last, rest = IOVec.split iovec written in
( List.rev (last :: acc),
{
t with
sched = RBS.cons_exn shifted rest;
write =
(if check iovec t then
RBA.N.shift_exn t.write (IOVec.length last)
else t.write);
} )
else (List.rev acc, t)
| exception RBS.Queue.Empty -> (List.rev acc, t)
in
go written [] t
let shift_flushes written t =
let rec go t =
try
let (threshold, f), flush = Ke.Fke.pop_exn t.flush in
if compare (t.written + written - min_int) (threshold - min_int) >= 0 then
let () = f written { t with flush } in
go { t with flush }
else t
with Ke.Fke.Empty -> t
in
go t
let shift n t =
let lst, t = shift_buffers n t in
( lst,
let t = shift_flushes (IOVec.lengthv lst) t in
{ t with written = t.written + n } )
let has t = RBS.weight t.sched
let drain drain t =
let rec go rest t =
match RBS.shift_exn t.sched with
| iovec, shifted ->
let len = IOVec.length iovec in
if rest >= len then
go (rest - len)
{
t with
sched = shifted;
write =
(if check iovec t then RBA.N.shift_exn t.write len else t.write);
}
else
{
t with
sched = RBS.cons_exn shifted (IOVec.shift iovec rest);
write =
(if check iovec t then RBA.N.shift_exn t.write rest else t.write);
}
| exception RBS.Queue.Empty -> t
in
let t = go drain t in
{ t with written = t.written + drain }
let flush k t =
let t = shift_flushes (has t) t in
let n = t.emitter (RBS.to_list t.sched) in
let t = drain n t in
k { t with written = t.written + n }
let rec schedule k ~length ~buffer ?(off = 0) ?len v t =
let len = match len with Some len -> len | None -> length v - off in
match RBS.push t.sched (IOVec.make (buffer v) off len) with
| Ok sched ->
TODO : merge [ Bigstringaf.t ] .
k { t with sched; received = t.received + len }
| Error _ ->
let max = RBS.available t.sched in
let k t =
(schedule [@tailcall]) k ~length ~buffer ~off:(off + max)
~len:(len - max) v t
in
schedule (flush k) ~length ~buffer ~off ~len:max v t
external identity : 'a -> 'a = "%identity"
let kschedule_string =
let length = String.length in
let buffer x = Buffer.String x in
fun k t ?(off = 0) ?len v -> schedule k ~length ~buffer ~off ?len v t
let schedule_string = kschedule_string identity
let kschedule_bytes =
let length = Bytes.length in
let buffer x = Buffer.Bytes x in
fun k t ?(off = 0) ?len v -> schedule k ~length ~buffer ~off ?len v t
let schedule_bytes = kschedule_bytes identity
let kschedule_bigstring =
let length = Bigarray.Array1.dim in
let buffer x = Buffer.Bigstring x in
fun k t ?(off = 0) ?len v -> schedule k ~length ~buffer ~off ?len v t
let schedule_bigstring = kschedule_bigstring identity
let schedule_flush f t = { t with flush = Ke.Fke.push t.flush (t.received, f) }
let kschedulev k l t =
let rec go t = function
| [] -> k t
| (length, off, len, buffer) :: r ->
schedule
(fun t -> (go [@tailcall]) t r)
~length ?off ?len ~buffer:identity buffer t
in
go t l
let schedulev = kschedulev identity
let kschedulev_bigstring k l t =
let rec go t = function
| [] -> k t
| buffer :: r ->
kschedule_bigstring (fun t -> (go [@tailcall]) t r) t buffer
in
go t l
let schedulev_bigstring = kschedulev_bigstring identity
let rec kwrite k ~blit ~length ?(off = 0) ?len buffer t =
let len = match len with Some len -> len | None -> length buffer - off in
let available = RBA.available t.write in
XXX(dinosaure ): we can factorize the first and the second branch .
if available >= len then
let areas, write = RBA.N.push_exn t.write ~blit ~length ~off ~len buffer in
kschedulev_bigstring k areas { t with write }
else if available > 0 then
let k t =
(kwrite [@tailcall]) k ~blit ~length ~off:(off + available)
~len:(len - available) buffer t
in
let areas, write =
RBA.N.push_exn t.write ~blit ~length ~off ~len:available buffer
in
kschedulev_bigstring (flush k) areas { t with write }
else
let k t = (kwrite [@tailcall]) k ~blit ~length ~off ~len buffer t in
flush k t
let write = kwrite identity
let kwritev k l t =
let rec go t = function
| [] -> k t
| (blit, length, off, len, buffer) :: r ->
kwrite (fun t -> (go [@tailcall]) t r) ~blit ~length ?off ?len buffer t
in
go t l
let bigarray_blit_from_string src src_off dst dst_off len =
Bigstringaf.blit_from_string src ~src_off dst ~dst_off ~len
let bigarray_blit_from_bytes src src_off dst dst_off len =
Bigstringaf.blit_from_bytes src ~src_off dst ~dst_off ~len
let bigarray_blit src src_off dst dst_off len =
Bigarray.Array1.(blit (sub src src_off len) (sub dst dst_off len))
let bigarray_blit_to_bytes src src_off dst dst_off len =
Bigstringaf.blit_to_bytes src ~src_off dst ~dst_off ~len
let kwrite_string =
let length = String.length in
let blit = bigarray_blit_from_string in
fun k ?(off = 0) ?len a t -> kwrite k ~blit ~length ~off ?len a t
let write_string = kwrite_string identity
let kwrite_bytes =
let length = Bytes.length in
let blit = bigarray_blit_from_bytes in
fun k ?(off = 0) ?len a t -> kwrite k ~blit ~length ~off ?len a t
let write_bytes = kwrite_bytes identity
let kwrite_bigstring =
let length = Bigarray.Array1.dim in
let blit = bigarray_blit in
fun k ?(off = 0) ?len a t -> kwrite k ~blit ~length ~off ?len a t
let write_bigstring = kwrite_bigstring identity
let kwrite_char =
let length _ = assert false in
let blit src src_off dst dst_off len =
assert (src_off = 0);
assert (len = 1);
Bigstringaf.set dst dst_off src
in
fun k a t -> kwrite k ~length ~blit ~off:0 ~len:1 a t
let write_char = kwrite_char identity
let kwrite_uint8 =
let length _ = assert false in
let blit src src_off dst dst_off len =
assert (src_off = 0);
assert (len = 1);
Bigstringaf.set dst dst_off (Char.unsafe_chr src)
in
fun k a t -> kwrite k ~length ~blit ~off:0 ~len:1 a t
let write_uint8 = kwrite_uint8 identity
module type S = sig
val kwrite_uint16 : (encoder -> 'v) -> int -> encoder -> 'v
val write_uint16 : int -> encoder -> encoder
val kwrite_uint32 : (encoder -> 'v) -> int32 -> encoder -> 'v
val write_uint32 : int32 -> encoder -> encoder
val kwrite_uint64 : (encoder -> 'v) -> int64 -> encoder -> 'v
val write_uint64 : int64 -> encoder -> encoder
end
module type ENDIAN = sig
type t = Bigstringaf.t
val set_int16 : t -> int -> int -> unit
val set_int32 : t -> int -> int32 -> unit
val set_int64 : t -> int -> int64 -> unit
end
module Make (X : ENDIAN) : S = struct
let _length _ = assert false
let kwrite_uint16 =
let length = _length in
let blit src src_off dst dst_off len =
assert (src_off = 0);
assert (len = 2);
X.set_int16 dst dst_off src
in
fun k a t -> kwrite k ~length ~blit ~off:0 ~len:2 a t
let write_uint16 = kwrite_uint16 identity
let kwrite_uint32 =
let length = _length in
let blit src src_off dst dst_off len =
assert (src_off = 0);
assert (len = 4);
X.set_int32 dst dst_off src
in
fun k a t -> kwrite k ~length ~blit ~off:0 ~len:4 a t
let write_uint32 = kwrite_uint32 identity
let kwrite_uint64 =
let length = _length in
let blit src src_off dst dst_off len =
assert (src_off = 0);
assert (len = 8);
X.set_int64 dst dst_off src
in
fun k a t -> kwrite k ~length ~blit ~off:0 ~len:8 a t
let write_uint64 = kwrite_uint64 identity
end
module LE' = struct
type t = Bigstringaf.t
let set_int16 = Bigstringaf.set_int16_le
let set_int32 = Bigstringaf.set_int32_le
let set_int64 = Bigstringaf.set_int64_le
end
module BE' = struct
type t = Bigstringaf.t
let set_int16 = Bigstringaf.set_int16_be
let set_int32 = Bigstringaf.set_int32_be
let set_int64 = Bigstringaf.set_int64_be
end
module LE = Make (LE')
module BE = Make (BE')
| null | https://raw.githubusercontent.com/dinosaure/prettym/8b0832d7fa70c918ae5660dbc20f9e5ff53a07f6/lib/enclosure.ml | ocaml | [@@@warning "-32"]
module type V = sig
type t
val pp : t Fmt.t
val sentinel : t
val weight : t -> int
val merge : t -> t -> t option
end
module RBQ (V : V) = struct
module Queue = Ke.Fke.Weighted
type t = {
a : V.t array;
c : int;
m : int;
q : (int, Bigarray.int_elt) Queue.t;
}
XXX(dinosaure ): [ ke ] is limited to [ Bigarray.kind ] . We make an [ array ]
which will contain values and [ q ] will contain index of them . Length of [ a ]
is length of [ q ] . By this way , length is a power of two and [ a ] follows
same assertions ( see [ mask ] ) as [ Ke ] .
[ c ] will be the cursor in [ a ] . [ m ] is the capacity . It 's a good example of
[ ke ] with something else than [ Bigarray.kind ] .
which will contain values and [q] will contain index of them. Length of [a]
is length of [q]. By this way, length is a power of two and [a] follows
same assertions (see [mask]) as [Ke].
[c] will be the cursor in [a]. [m] is the capacity. It's a good example of
[ke] with something else than [Bigarray.kind]. *)
let make capacity =
let q, capacity = Queue.create ~capacity Bigarray.Int in
{ a = Array.make capacity V.sentinel; c = 0; m = capacity; q }
let pp ppf t =
let a = Array.make (Queue.length t.q) V.sentinel in
let x = ref 0 in
Queue.iter
(fun i ->
a.(!x) <- t.a.(i);
incr x)
t.q;
Fmt.pf ppf "{ @[<hov>a = %a;@ c = %d;@ m = %d;@ q = %a;@] }"
Fmt.(Dump.array V.pp)
a t.c t.m (Queue.dump Fmt.int) t.q
let available t = Queue.available t.q
let is_empty t = Queue.is_empty t.q
let[@inline always] mask x t = x land (t.m - 1)
let push t v =
let i = mask t.c t in
match Queue.push t.q i with
| Some q ->
t.a.(i) <- v;
Ok { t with c = succ t.c; q }
| None -> Error t
let shift_exn t =
let i, q = Queue.pop_exn t.q in
(t.a.(i), { t with q })
let cons t v =
let i = mask t.c t in
match Queue.cons t.q i with
| Some q ->
t.a.(i) <- v;
Ok { t with c = succ t.c; q }
| None -> Error t
exception Full
let cons_exn t v = match cons t v with Ok t -> t | Error _ -> raise Full
let weight t = Queue.fold (fun a i -> a + V.weight t.a.(i)) 0 t.q
let to_list t =
let res = ref [] in
Queue.rev_iter (fun i -> res := t.a.(i) :: !res) t.q;
!res
end
let pp_chr =
Fmt.using (function '\032' .. '\126' as x -> x | _ -> '.') Fmt.char
let pp_scalar :
type buffer.
get:(buffer -> int -> char) -> length:(buffer -> int) -> buffer Fmt.t =
fun ~get ~length ppf b ->
let l = length b in
for i = 0 to l / 16 do
Fmt.pf ppf "%08x: " (i * 16);
let j = ref 0 in
while !j < 16 do
if (i * 16) + !j < l then
Fmt.pf ppf "%02x" (Char.code @@ get b ((i * 16) + !j))
else Fmt.pf ppf " ";
if !j mod 2 <> 0 then Fmt.pf ppf " ";
incr j
done;
Fmt.pf ppf " ";
j := 0;
while !j < 16 do
if (i * 16) + !j < l then Fmt.pf ppf "%a" pp_chr (get b ((i * 16) + !j))
else Fmt.pf ppf " ";
incr j
done;
Fmt.pf ppf "@,"
done
module RBA = Ke.Fke.Weighted
module Buffer = struct
type t = Bigstring of Bigstringaf.t | String of string | Bytes of bytes
let pp ppf = function
| Bigstring x ->
pp_scalar ~length:Bigstringaf.length ~get:Bigstringaf.get ppf x
| String x -> pp_scalar ~length:String.length ~get:String.get ppf x
| Bytes x -> pp_scalar ~length:Bytes.length ~get:Bytes.get ppf x
let weight = function
| Bigstring x -> Bigstringaf.length x
| String x -> String.length x
| Bytes x -> Bytes.length x
let sub buffer off len =
match buffer with
| Bigstring x -> Bigstring (Bigstringaf.sub x ~off ~len)
| String x -> String (String.sub x off len)
| Bytes x -> Bytes (Bytes.sub x off len)
end
module IOVec = struct
type t = { buffer : Buffer.t; off : int; len : int }
let weight { len; _ } = len
let pp ppf t =
Fmt.pf ppf "{ @[<hov>buffer= @[<hov>%a@];@ off= %d;@ len= %d;@] }" Buffer.pp
t.buffer t.off t.len
let sentinel =
let deadbeef = "\222\173\190\239" in
{ buffer = Buffer.String deadbeef; off = 0; len = String.length deadbeef }
let make buffer off len = { buffer; off; len }
let length { len; _ } = len
let lengthv = List.fold_left (fun a x -> length x + a) 0
let shift { buffer; off; len } n =
assert (n <= len);
{ buffer; off = off + n; len = len - n }
let split { buffer; off; len } n =
assert (n <= len);
( { buffer = Buffer.sub buffer off n; off = 0; len = n },
{ buffer = Buffer.sub buffer (off + n) (len - n); off = 0; len = len - n }
)
let merge a b =
match (a, b) with
| { buffer = Buffer.Bytes a'; _ }, { buffer = Buffer.Bytes b'; _ } ->
assert (a' == b');
if a.off + a.len = b.off then
Some { buffer = Buffer.Bytes a'; off = a.off; len = a.len + b.len }
else None
| { buffer = Buffer.Bigstring a'; _ }, { buffer = Buffer.Bigstring _; _ } ->
if a.off + a.len = b.off then
Some
{ buffer = Buffer.Bigstring a'; off = a.off; len = a.len + b.len }
else None
| _, _ -> None
end
module RBS = RBQ (IOVec)
type emitter = IOVec.t list -> int
type encoder = {
sched : RBS.t;
write : (char, Bigarray.int8_unsigned_elt) RBA.t;
flush : (int * (int -> encoder -> unit)) Ke.Fke.t;
written : int;
received : int;
emitter : emitter;
}
let pp_flush ppf _ = Fmt.string ppf "#flush"
let pp ppf t =
Fmt.pf ppf
"{ @[<hov>sched= @[<hov>%a@];@ write= @[<hov>%a@];@ flush= @[<hov>%a@];@ \
written= %d;@ received= %d;@ emitter= #emitter;@] }"
RBS.pp t.sched (RBA.pp pp_chr) t.write (Ke.Fke.pp pp_flush) t.flush
t.written t.received
let is_empty t = RBS.is_empty t.sched
XXX(dinosaure ): [ sched ] is a queue of [ ] . [ write ] is a
ring - buffer/[Bigstringaf.t ] . [ flush ] is a queue which can contain
user - defined operation at a break point . [ written ] is how many bytes we
sended to the user ( afterwards a * flush * operation ) . [ received ] is how many
bytes we received from the user .
The goal is to have two ways to fill output :
- an heavy way with [ write _ * ] operations which will do internally a [ blit ] .
- a soft way with [ shedule _ * ] operations which will store a pointer .
The complexity is under [ sched ] where it stores pointer from user but pointer
from [ write ] queue too . Indeed , [ write _ ] operations did not do only a [ blit ]
but then they store resulted/*blitted * [ Bigstringaf.t ] part to [ sched ] .
When we want to shift a part of [ encoder ] , * * all * * buffers are stored in
[ sched ] . So we need to shift [ sched ] . However , resulted [ ] can be
physically a part of [ write ] . In this context , we need to shift [ write ] .
ring-buffer/[Bigstringaf.t]. [flush] is a queue which can contain
user-defined operation at a break point. [written] is how many bytes we
sended to the user (afterwards a *flush* operation). [received] is how many
bytes we received from the user.
The goal is to have two ways to fill output:
- an heavy way with [write_*] operations which will do internally a [blit].
- a soft way with [shedule_*] operations which will store a pointer.
The complexity is under [sched] where it stores pointer from user but pointer
from [write] queue too. Indeed, [write_] operations did not do only a [blit]
but then they store resulted/*blitted* [Bigstringaf.t] part to [sched].
When we want to shift a part of [encoder], **all** buffers are stored in
[sched]. So we need to shift [sched]. However, resulted [IOVec] can be
physically a part of [write]. In this context, we need to shift [write]. *)
let create ~emitter len =
let write, _ = RBA.create ~capacity:len Bigarray.Char in
{
sched = RBS.make (len * 2);
write;
flush = Ke.Fke.empty;
written = 0;
received = 0;
emitter;
}
let check iovec { write; _ } =
match iovec with
| { IOVec.buffer = Buffer.Bigstring x; _ } -> (
let buf = RBA.unsafe_bigarray write in
match Overlap.array1 x buf with Some (_, _, _) -> true | None -> false)
| _ -> false
let shift_buffers written t =
let rec go written acc t =
match RBS.shift_exn t.sched with
| iovec, shifted ->
let len = IOVec.length iovec in
if written > len then
go (written - len) (iovec :: acc)
{
t with
sched = shifted;
write =
(if check iovec t then RBA.N.shift_exn t.write len else t.write);
}
else if written > 0 then
let last, rest = IOVec.split iovec written in
( List.rev (last :: acc),
{
t with
sched = RBS.cons_exn shifted rest;
write =
(if check iovec t then
RBA.N.shift_exn t.write (IOVec.length last)
else t.write);
} )
else (List.rev acc, t)
| exception RBS.Queue.Empty -> (List.rev acc, t)
in
go written [] t
let shift_flushes written t =
let rec go t =
try
let (threshold, f), flush = Ke.Fke.pop_exn t.flush in
if compare (t.written + written - min_int) (threshold - min_int) >= 0 then
let () = f written { t with flush } in
go { t with flush }
else t
with Ke.Fke.Empty -> t
in
go t
let shift n t =
let lst, t = shift_buffers n t in
( lst,
let t = shift_flushes (IOVec.lengthv lst) t in
{ t with written = t.written + n } )
let has t = RBS.weight t.sched
let drain drain t =
let rec go rest t =
match RBS.shift_exn t.sched with
| iovec, shifted ->
let len = IOVec.length iovec in
if rest >= len then
go (rest - len)
{
t with
sched = shifted;
write =
(if check iovec t then RBA.N.shift_exn t.write len else t.write);
}
else
{
t with
sched = RBS.cons_exn shifted (IOVec.shift iovec rest);
write =
(if check iovec t then RBA.N.shift_exn t.write rest else t.write);
}
| exception RBS.Queue.Empty -> t
in
let t = go drain t in
{ t with written = t.written + drain }
let flush k t =
let t = shift_flushes (has t) t in
let n = t.emitter (RBS.to_list t.sched) in
let t = drain n t in
k { t with written = t.written + n }
let rec schedule k ~length ~buffer ?(off = 0) ?len v t =
let len = match len with Some len -> len | None -> length v - off in
match RBS.push t.sched (IOVec.make (buffer v) off len) with
| Ok sched ->
TODO : merge [ Bigstringaf.t ] .
k { t with sched; received = t.received + len }
| Error _ ->
let max = RBS.available t.sched in
let k t =
(schedule [@tailcall]) k ~length ~buffer ~off:(off + max)
~len:(len - max) v t
in
schedule (flush k) ~length ~buffer ~off ~len:max v t
external identity : 'a -> 'a = "%identity"
let kschedule_string =
let length = String.length in
let buffer x = Buffer.String x in
fun k t ?(off = 0) ?len v -> schedule k ~length ~buffer ~off ?len v t
let schedule_string = kschedule_string identity
let kschedule_bytes =
let length = Bytes.length in
let buffer x = Buffer.Bytes x in
fun k t ?(off = 0) ?len v -> schedule k ~length ~buffer ~off ?len v t
let schedule_bytes = kschedule_bytes identity
let kschedule_bigstring =
let length = Bigarray.Array1.dim in
let buffer x = Buffer.Bigstring x in
fun k t ?(off = 0) ?len v -> schedule k ~length ~buffer ~off ?len v t
let schedule_bigstring = kschedule_bigstring identity
let schedule_flush f t = { t with flush = Ke.Fke.push t.flush (t.received, f) }
let kschedulev k l t =
let rec go t = function
| [] -> k t
| (length, off, len, buffer) :: r ->
schedule
(fun t -> (go [@tailcall]) t r)
~length ?off ?len ~buffer:identity buffer t
in
go t l
let schedulev = kschedulev identity
let kschedulev_bigstring k l t =
let rec go t = function
| [] -> k t
| buffer :: r ->
kschedule_bigstring (fun t -> (go [@tailcall]) t r) t buffer
in
go t l
let schedulev_bigstring = kschedulev_bigstring identity
let rec kwrite k ~blit ~length ?(off = 0) ?len buffer t =
let len = match len with Some len -> len | None -> length buffer - off in
let available = RBA.available t.write in
XXX(dinosaure ): we can factorize the first and the second branch .
if available >= len then
let areas, write = RBA.N.push_exn t.write ~blit ~length ~off ~len buffer in
kschedulev_bigstring k areas { t with write }
else if available > 0 then
let k t =
(kwrite [@tailcall]) k ~blit ~length ~off:(off + available)
~len:(len - available) buffer t
in
let areas, write =
RBA.N.push_exn t.write ~blit ~length ~off ~len:available buffer
in
kschedulev_bigstring (flush k) areas { t with write }
else
let k t = (kwrite [@tailcall]) k ~blit ~length ~off ~len buffer t in
flush k t
let write = kwrite identity
let kwritev k l t =
let rec go t = function
| [] -> k t
| (blit, length, off, len, buffer) :: r ->
kwrite (fun t -> (go [@tailcall]) t r) ~blit ~length ?off ?len buffer t
in
go t l
let bigarray_blit_from_string src src_off dst dst_off len =
Bigstringaf.blit_from_string src ~src_off dst ~dst_off ~len
let bigarray_blit_from_bytes src src_off dst dst_off len =
Bigstringaf.blit_from_bytes src ~src_off dst ~dst_off ~len
let bigarray_blit src src_off dst dst_off len =
Bigarray.Array1.(blit (sub src src_off len) (sub dst dst_off len))
let bigarray_blit_to_bytes src src_off dst dst_off len =
Bigstringaf.blit_to_bytes src ~src_off dst ~dst_off ~len
let kwrite_string =
let length = String.length in
let blit = bigarray_blit_from_string in
fun k ?(off = 0) ?len a t -> kwrite k ~blit ~length ~off ?len a t
let write_string = kwrite_string identity
let kwrite_bytes =
let length = Bytes.length in
let blit = bigarray_blit_from_bytes in
fun k ?(off = 0) ?len a t -> kwrite k ~blit ~length ~off ?len a t
let write_bytes = kwrite_bytes identity
let kwrite_bigstring =
let length = Bigarray.Array1.dim in
let blit = bigarray_blit in
fun k ?(off = 0) ?len a t -> kwrite k ~blit ~length ~off ?len a t
let write_bigstring = kwrite_bigstring identity
let kwrite_char =
let length _ = assert false in
let blit src src_off dst dst_off len =
assert (src_off = 0);
assert (len = 1);
Bigstringaf.set dst dst_off src
in
fun k a t -> kwrite k ~length ~blit ~off:0 ~len:1 a t
let write_char = kwrite_char identity
let kwrite_uint8 =
let length _ = assert false in
let blit src src_off dst dst_off len =
assert (src_off = 0);
assert (len = 1);
Bigstringaf.set dst dst_off (Char.unsafe_chr src)
in
fun k a t -> kwrite k ~length ~blit ~off:0 ~len:1 a t
let write_uint8 = kwrite_uint8 identity
module type S = sig
val kwrite_uint16 : (encoder -> 'v) -> int -> encoder -> 'v
val write_uint16 : int -> encoder -> encoder
val kwrite_uint32 : (encoder -> 'v) -> int32 -> encoder -> 'v
val write_uint32 : int32 -> encoder -> encoder
val kwrite_uint64 : (encoder -> 'v) -> int64 -> encoder -> 'v
val write_uint64 : int64 -> encoder -> encoder
end
module type ENDIAN = sig
type t = Bigstringaf.t
val set_int16 : t -> int -> int -> unit
val set_int32 : t -> int -> int32 -> unit
val set_int64 : t -> int -> int64 -> unit
end
module Make (X : ENDIAN) : S = struct
let _length _ = assert false
let kwrite_uint16 =
let length = _length in
let blit src src_off dst dst_off len =
assert (src_off = 0);
assert (len = 2);
X.set_int16 dst dst_off src
in
fun k a t -> kwrite k ~length ~blit ~off:0 ~len:2 a t
let write_uint16 = kwrite_uint16 identity
let kwrite_uint32 =
let length = _length in
let blit src src_off dst dst_off len =
assert (src_off = 0);
assert (len = 4);
X.set_int32 dst dst_off src
in
fun k a t -> kwrite k ~length ~blit ~off:0 ~len:4 a t
let write_uint32 = kwrite_uint32 identity
let kwrite_uint64 =
let length = _length in
let blit src src_off dst dst_off len =
assert (src_off = 0);
assert (len = 8);
X.set_int64 dst dst_off src
in
fun k a t -> kwrite k ~length ~blit ~off:0 ~len:8 a t
let write_uint64 = kwrite_uint64 identity
end
module LE' = struct
type t = Bigstringaf.t
let set_int16 = Bigstringaf.set_int16_le
let set_int32 = Bigstringaf.set_int32_le
let set_int64 = Bigstringaf.set_int64_le
end
module BE' = struct
type t = Bigstringaf.t
let set_int16 = Bigstringaf.set_int16_be
let set_int32 = Bigstringaf.set_int32_be
let set_int64 = Bigstringaf.set_int64_be
end
module LE = Make (LE')
module BE = Make (BE')
| |
cdf7611fd9f0c5b61ecc018c1e2836e875691c76f5e4ca5f92d1453b675a4571 | DaiF1/Oditor | display.ml |
file : display.ml
dependencies : editor.ml colors.ml
Editor display functions
file: display.ml
dependencies: editor.ml colors.ml
Editor display functions
*)
open Editor;;
open Colors;;
(* Draw text on editor, tildes if buffer empty *)
let draw_rows () =
(* Oditor text description. Visible only with empty buffer *)
let welcome_text =
let text = "Oditor -- An editor for OCaml, in OCaml" and len = 39 in
let offset = (term.cols - len) / 2 in
"~" ^ String.make offset ' ' ^ text ^ "\r\n"
(* Oditor version text. Visible only with empty buffer *)
and version_text =
let offset = (term.cols - 13) / 2 in
"~" ^ String.make offset ' ' ^ "version " ^ version ^ "\r\n"
(* Bottom status bar string *)
and status_bar =
Cursor position in file ( in % )
let completion = if term.numlines = 0 then 100
else int_of_float (float_of_int (term.y + term.rowoff) /.
float_of_int (term.numlines - 1) *. 100.0)
(* Current file name *)
in let file = if term.filename = "" then "[No Name]" else term.filename
(* Editor mode *)
in let status =
"\x1b[7m\x1b[1m " ^ string_of_mode term.mode ^ " \x1b[0m " ^ file
(* Current lign and completion *)
and stats = "line " ^ string_of_int (term.y + term.rowoff) ^ " (" ^
string_of_int completion ^ "%)" in
(* the '+11' is to nullify the escape codes for formatting text *)
let offset = (term.cols - String.length status - String.length stats + 11)
in status ^ String.make offset ' ' ^ stats
(* Cut lign if larger than term size
param line: line to process (string)
param off: terminal x offset *)
in let cut_lign line off =
let max = term.cols in
let l = String.length line in
let len = if l - off > max then max
else l - off in
if len > 0 then String.sub line off len
else ""
(* Return text buffer after applying vertical offset
param text: text to load
param off: line offset before current text *)
in let rec prepare_text text off = match (text, off) with
| (t, 0) -> t
| ([], _) -> []
| (_::t, o) -> prepare_text t (o - 1)
(* Draw each line of text on screen
param y: current lign index
param text: text to write *)
in let rec draw y text = match (y, text) with
(* Last line of the screen. Used to write in command mode *)
Clear lign
let str = if term.mode = COMMAND then ":" ^ term.command
else term.help in
output_string stdout str
(* Status bar lign *)
Clear lign
output_string stdout status_bar;
output_string stdout "\r\n"; draw (y - 1) l
(* Default state. Write lign to screen *)
| (y, l::t) ->
Clear lign
output_string stdout (cut_lign (hl_row l DEFAULT) term.colsoff);
output_string stdout "\r\n"; draw (y - 1) t
(* Buffer empty case. Writes '~' or welcome_text to screen *)
Clear lign
if term.text = [] then
begin
if y = term.rows / 2 + 2 then output_string stdout welcome_text
else if y = term.rows / 2 then output_string stdout version_text
else output_string stdout "~\r\n"
end
else output_string stdout "~\r\n";
draw (y - 1) []
in draw (term.rows - 1) (prepare_text term.text term.rowoff);;
(* Show or hide cursor
param hide: true if cursor needs to be hidden *)
let toggle_cursor hide =
if hide then output_string stdout "\x1b[?25l"
else output_string stdout "\x1b[?25h";;
(* Refresh editor screen *)
let refresh_screen () =
load_term_size ();
toggle_cursor true;
(* Reset cursor position *)
output_string stdout "\x1b[H";
draw_rows ();
(* Set cursor to current position *)
output_string stdout (Printf.sprintf "\x1b[%d;%dH" (term.y + 1) (term.x + 1));
toggle_cursor false;
flush stdout;;
(* Clear terminal screen *)
let clear_screen () =
(* Clear screen *)
output_string stdout "\x1b[2J";
(* Reset cursor position *)
output_string stdout "\x1b[H";
flush stdout;;
| null | https://raw.githubusercontent.com/DaiF1/Oditor/9f49ce05281f3253c166475b21c282a1e36c99f7/editor/display.ml | ocaml | Draw text on editor, tildes if buffer empty
Oditor text description. Visible only with empty buffer
Oditor version text. Visible only with empty buffer
Bottom status bar string
Current file name
Editor mode
Current lign and completion
the '+11' is to nullify the escape codes for formatting text
Cut lign if larger than term size
param line: line to process (string)
param off: terminal x offset
Return text buffer after applying vertical offset
param text: text to load
param off: line offset before current text
Draw each line of text on screen
param y: current lign index
param text: text to write
Last line of the screen. Used to write in command mode
Status bar lign
Default state. Write lign to screen
Buffer empty case. Writes '~' or welcome_text to screen
Show or hide cursor
param hide: true if cursor needs to be hidden
Refresh editor screen
Reset cursor position
Set cursor to current position
Clear terminal screen
Clear screen
Reset cursor position |
file : display.ml
dependencies : editor.ml colors.ml
Editor display functions
file: display.ml
dependencies: editor.ml colors.ml
Editor display functions
*)
open Editor;;
open Colors;;
let draw_rows () =
let welcome_text =
let text = "Oditor -- An editor for OCaml, in OCaml" and len = 39 in
let offset = (term.cols - len) / 2 in
"~" ^ String.make offset ' ' ^ text ^ "\r\n"
and version_text =
let offset = (term.cols - 13) / 2 in
"~" ^ String.make offset ' ' ^ "version " ^ version ^ "\r\n"
and status_bar =
Cursor position in file ( in % )
let completion = if term.numlines = 0 then 100
else int_of_float (float_of_int (term.y + term.rowoff) /.
float_of_int (term.numlines - 1) *. 100.0)
in let file = if term.filename = "" then "[No Name]" else term.filename
in let status =
"\x1b[7m\x1b[1m " ^ string_of_mode term.mode ^ " \x1b[0m " ^ file
and stats = "line " ^ string_of_int (term.y + term.rowoff) ^ " (" ^
string_of_int completion ^ "%)" in
let offset = (term.cols - String.length status - String.length stats + 11)
in status ^ String.make offset ' ' ^ stats
in let cut_lign line off =
let max = term.cols in
let l = String.length line in
let len = if l - off > max then max
else l - off in
if len > 0 then String.sub line off len
else ""
in let rec prepare_text text off = match (text, off) with
| (t, 0) -> t
| ([], _) -> []
| (_::t, o) -> prepare_text t (o - 1)
in let rec draw y text = match (y, text) with
Clear lign
let str = if term.mode = COMMAND then ":" ^ term.command
else term.help in
output_string stdout str
Clear lign
output_string stdout status_bar;
output_string stdout "\r\n"; draw (y - 1) l
| (y, l::t) ->
Clear lign
output_string stdout (cut_lign (hl_row l DEFAULT) term.colsoff);
output_string stdout "\r\n"; draw (y - 1) t
Clear lign
if term.text = [] then
begin
if y = term.rows / 2 + 2 then output_string stdout welcome_text
else if y = term.rows / 2 then output_string stdout version_text
else output_string stdout "~\r\n"
end
else output_string stdout "~\r\n";
draw (y - 1) []
in draw (term.rows - 1) (prepare_text term.text term.rowoff);;
let toggle_cursor hide =
if hide then output_string stdout "\x1b[?25l"
else output_string stdout "\x1b[?25h";;
let refresh_screen () =
load_term_size ();
toggle_cursor true;
output_string stdout "\x1b[H";
draw_rows ();
output_string stdout (Printf.sprintf "\x1b[%d;%dH" (term.y + 1) (term.x + 1));
toggle_cursor false;
flush stdout;;
let clear_screen () =
output_string stdout "\x1b[2J";
output_string stdout "\x1b[H";
flush stdout;;
|
ab3053e12e72a86c0f5f1465ec23564aeb50c2df6935432285a779e0d7854b6b | heroku/logplex | tcp_proxy_sup.erl | Copyright ( c ) 2011 < >
%%
%% 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.
-module(tcp_proxy_sup).
-behaviour(supervisor).
%% API
-export([start_link/0, start_child/0]).
%% Supervisor callbacks
-export([init/1]).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
start_child() ->
supervisor:start_child(?MODULE, []).
init([]) ->
{ok, {{simple_one_for_one, 0, 1}, [
{tcp_proxy, {tcp_proxy, start_link, []}, temporary, brutal_kill, worker, [tcp_proxy]}
]}}.
| null | https://raw.githubusercontent.com/heroku/logplex/fc520c44cf4687726d5d51464d3264ddc6abb0ba/src/tcp_proxy_sup.erl | erlang |
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
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.
API
Supervisor callbacks | Copyright ( c ) 2011 < >
files ( the " Software " ) , to deal in the Software without
copies of the Software , and to permit persons to whom the
included in all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
-module(tcp_proxy_sup).
-behaviour(supervisor).
-export([start_link/0, start_child/0]).
-export([init/1]).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
start_child() ->
supervisor:start_child(?MODULE, []).
init([]) ->
{ok, {{simple_one_for_one, 0, 1}, [
{tcp_proxy, {tcp_proxy, start_link, []}, temporary, brutal_kill, worker, [tcp_proxy]}
]}}.
|
37d9649a900da6891231ff15a22455dcb344b294ac53deb95587e10515db65bb | aharisu/vise | vim-function.scm | '(
abs
append
argv
atan2
bufexists
bufname
byte2line
ceil
cindent
complete
confirm
cosh
cursor
did_filetype
empty
eventhandler
exp
extend
filewritable
findfile
fmod
foldclosed
foldtext
function
getbufline
getcharmod
getcmdtype
getfperm
getftype
getmatches
getqflist
gettabvar
getwinposy
globpath
haslocaldir
histdel
hlexists
iconv
input
inputrestore
insert
items
len
line
localtime
map
match
matchdelete
matchstr
min
mode
nextnonblank
pathshorten
prevnonblank
pumvisible
readfile
reltimestr
remote_foreground
remote_read
remove
repeat
reverse
search
searchpair
searchpos
serverlist
setcmdpos
setloclist
setpos
setreg
settabwinvar
shellescape
sin
sort
spellbadword
split
str2float
strchars
strftime
string
strpart
strtrans
submatch
synconcealed
synIDattr
synstack
tabpagebuflist
tabpagewinnr
taglist
tanh
tolower
tr
type
undotree
virtcol
winbufnr
winheight
winnr
winrestview
winwidth
acos
argc
asin
browse
buflisted
bufnr
byteidx
changenr
clearmatches
complete_add
copy
count
deepcopy
diff_filler
escape
executable
expand
feedkeys
filter
float2nr
fnameescape
foldclosedend
foldtextresult
garbagecollect
getbufvar
getcmdline
getcwd
getfsize
getline
getpid
getreg
gettabwinvar
getwinvar
has
hasmapto
histget
hlID
indent
inputdialog
inputsave
isdirectory
join
libcall
line2byte
log
maparg
matchadd
matchend
max
mkdir
mzeval
nr2char
pow
printf
range
reltime
remote_expr
remote_peek
remote_send
rename
resolve
round
searchdecl
searchpairpos
server2client
setbufvar
setline
setmatches
setqflist
settabvar
setwinvar
simplify
sinh
soundfold
spellsuggest
sqrt
str2nr
strdisplaywidth
stridx
strlen
strridx
strwidth
substitute
synID
synIDtrans
system
tabpagenr
tagfiles
tan
tempname
toupper
trunc
undofile
values
visualmode
wincol
winline
winrestcmd
winsaveview
writefile
add
argidx
atan
browsedir
bufloaded
bufwinnr
call
char2nr
col
complete_check
cos
cscope_connection
delete
diff_hlID
eval
exists
expr8
filereadable
finddir
floor
fnamemodify
foldlevel
foreground
get
getchar
getcmdpos
getfontname
getftime
getloclist
getpos
getregtype
getwinposx
glob
has_key
histadd
histnr
hostname
index
inputlist
inputsecret
islocked
keys
libcallnr
lispindent
log10
mapcheck
matcharg
matchlist
)
| null | https://raw.githubusercontent.com/aharisu/vise/6d0f54b0fe28e7d2c3b2b91cb3ef5ff847a11484/autoload/vgen/vim-function.scm | scheme | '(
abs
append
argv
atan2
bufexists
bufname
byte2line
ceil
cindent
complete
confirm
cosh
cursor
did_filetype
empty
eventhandler
exp
extend
filewritable
findfile
fmod
foldclosed
foldtext
function
getbufline
getcharmod
getcmdtype
getfperm
getftype
getmatches
getqflist
gettabvar
getwinposy
globpath
haslocaldir
histdel
hlexists
iconv
input
inputrestore
insert
items
len
line
localtime
map
match
matchdelete
matchstr
min
mode
nextnonblank
pathshorten
prevnonblank
pumvisible
readfile
reltimestr
remote_foreground
remote_read
remove
repeat
reverse
search
searchpair
searchpos
serverlist
setcmdpos
setloclist
setpos
setreg
settabwinvar
shellescape
sin
sort
spellbadword
split
str2float
strchars
strftime
string
strpart
strtrans
submatch
synconcealed
synIDattr
synstack
tabpagebuflist
tabpagewinnr
taglist
tanh
tolower
tr
type
undotree
virtcol
winbufnr
winheight
winnr
winrestview
winwidth
acos
argc
asin
browse
buflisted
bufnr
byteidx
changenr
clearmatches
complete_add
copy
count
deepcopy
diff_filler
escape
executable
expand
feedkeys
filter
float2nr
fnameescape
foldclosedend
foldtextresult
garbagecollect
getbufvar
getcmdline
getcwd
getfsize
getline
getpid
getreg
gettabwinvar
getwinvar
has
hasmapto
histget
hlID
indent
inputdialog
inputsave
isdirectory
join
libcall
line2byte
log
maparg
matchadd
matchend
max
mkdir
mzeval
nr2char
pow
printf
range
reltime
remote_expr
remote_peek
remote_send
rename
resolve
round
searchdecl
searchpairpos
server2client
setbufvar
setline
setmatches
setqflist
settabvar
setwinvar
simplify
sinh
soundfold
spellsuggest
sqrt
str2nr
strdisplaywidth
stridx
strlen
strridx
strwidth
substitute
synID
synIDtrans
system
tabpagenr
tagfiles
tan
tempname
toupper
trunc
undofile
values
visualmode
wincol
winline
winrestcmd
winsaveview
writefile
add
argidx
atan
browsedir
bufloaded
bufwinnr
call
char2nr
col
complete_check
cos
cscope_connection
delete
diff_hlID
eval
exists
expr8
filereadable
finddir
floor
fnamemodify
foldlevel
foreground
get
getchar
getcmdpos
getfontname
getftime
getloclist
getpos
getregtype
getwinposx
glob
has_key
histadd
histnr
hostname
index
inputlist
inputsecret
islocked
keys
libcallnr
lispindent
log10
mapcheck
matcharg
matchlist
)
| |
51e7883ad754fb3f5eb5ed4c935ffc3e28981552d89495ab77b41a867382ad80 | YoungTurks/hackerdict | auth.clj | (ns hackerdict.rest.auth
(:require [compojure.core :refer [defroutes GET]]
[hackerdict.helpers.auth :as auth]
[hackerdict.helpers.user :as user-helper]
[hackerdict.util.rest :as rest]))
(defroutes auth-routes
(GET "/login" {session :session}
(if-let [token (:token session)]
(rest/response {:status 400
:body "Already logged in."})
(let [state (auth/random-state)
uri (auth/authorize-uri state)]
(rest/response {:status 302
:headers {"Location" uri}
:session (assoc session :state state)}))))
(GET "/auth" {params :params session :session}
(if (= (:state params) (:state session))
(if-let [token (auth/access-token (:code params))]
(do
(let [user (user-helper/upsert-user! token)]
(rest/response {:status 302
:headers {"Location" "/"}
:session (merge (dissoc session :state)
{:token token :user user})})))
(rest/response {:status 500
:body "Cannot get token."
:session (dissoc session :state)}))
(rest/response {:status 400
:body "Sessions doesn't match."
:session (dissoc session :state)})))
(GET "/logout" {session :session}
(if-let [token (:token session)]
(rest/response {:status 302
:headers {"Location" "/"}
:session (dissoc session :token :user)})
(rest/response {:status 400
:body "Not logged in."}))))
| null | https://raw.githubusercontent.com/YoungTurks/hackerdict/44e5c285b3195718c4d5bc9cb4423623f22d3da3/src/hackerdict/rest/auth.clj | clojure | (ns hackerdict.rest.auth
(:require [compojure.core :refer [defroutes GET]]
[hackerdict.helpers.auth :as auth]
[hackerdict.helpers.user :as user-helper]
[hackerdict.util.rest :as rest]))
(defroutes auth-routes
(GET "/login" {session :session}
(if-let [token (:token session)]
(rest/response {:status 400
:body "Already logged in."})
(let [state (auth/random-state)
uri (auth/authorize-uri state)]
(rest/response {:status 302
:headers {"Location" uri}
:session (assoc session :state state)}))))
(GET "/auth" {params :params session :session}
(if (= (:state params) (:state session))
(if-let [token (auth/access-token (:code params))]
(do
(let [user (user-helper/upsert-user! token)]
(rest/response {:status 302
:headers {"Location" "/"}
:session (merge (dissoc session :state)
{:token token :user user})})))
(rest/response {:status 500
:body "Cannot get token."
:session (dissoc session :state)}))
(rest/response {:status 400
:body "Sessions doesn't match."
:session (dissoc session :state)})))
(GET "/logout" {session :session}
(if-let [token (:token session)]
(rest/response {:status 302
:headers {"Location" "/"}
:session (dissoc session :token :user)})
(rest/response {:status 400
:body "Not logged in."}))))
| |
95f2c65e8d7d37176c59bf82b494ea1a533a3c620b76caf4d98cb6d364ef5557 | liquidz/misaki | _config.clj | {
;; directory setting
:public-dir "public/"
:template-dir "template/"
;; clojurescript compile options
;; src-dir base is `:template-dir`
;; output-dir base is `:public-dir`
:cljs {:optimizations :advanced}
:compiler ["cljs"]
}
| null | https://raw.githubusercontent.com/liquidz/misaki/b8104e632058e3b3da4487513d10e666e5914ec9/test/files/compiler/cljs/core/_config.clj | clojure | directory setting
clojurescript compile options
src-dir base is `:template-dir`
output-dir base is `:public-dir` | {
:public-dir "public/"
:template-dir "template/"
:cljs {:optimizations :advanced}
:compiler ["cljs"]
}
|
146ec57e02e3c7af083e4632e29d34c0f7295c2c3102308ac7dc88f14a41b6fa | baskeboler/cljs-karaoke-client | subs.cljs | (ns cljs-karaoke.editor.subs
(:require [re-frame.core :as rf]
[clojure.string :as cstr]
[cljs-karaoke.protocols :as p]
[cljs-karaoke.subs.audio :as audio-subs]))
(rf/reg-sub
::editor-state
(fn [db _]
(:editor-state db)))
(rf/reg-sub
::current-frame
:<- [::editor-state]
(fn [editor-state _]
(:current-frame editor-state)))
(rf/reg-sub
::song-name
:<- [::editor-state]
(fn [editor-state _]
(:song-name editor-state)))
(rf/reg-sub
::current-frame-property
:<- [::current-frame]
(fn [current-frame [_ k]]
(get current-frame k)))
(rf/reg-sub
::frames
:<- [::editor-state]
(fn [editor-state _]
(:frames editor-state)))
(rf/reg-sub
::current-state
:<- [::editor-state]
(fn [editor-state _]
(:current-state editor-state)))
(def mode-titles
{:text-entry "Frame text definition"
:segment-selection "Divide text into segments"
:segment-timing "Synchronize segments with audio track"
:frame-preview "Preview work in progress"})
(rf/reg-sub
::mode-title
:<- [::current-state]
(fn [current-state _]
(mode-titles current-state)))
(rf/reg-sub
::segments-ready?
:<- [::editor-state]
(fn [{:keys [current-frame]} _]
(= (reduce + (:segment-sizes current-frame))
(count (:text current-frame)))))
(rf/reg-sub
::segment-timings-ready?
:<- [::editor-state]
(fn [{:keys [current-frame]} _]
(= (count (:segment-offsets current-frame))
(count (:segments current-frame)))))
(rf/reg-sub
::active-segment
:<- [::current-frame-property :segments]
:<- [::current-frame-property :segment-offsets]
:<- [:cljs-karaoke.subs/song-position-ms]
(fn [[segments offsets position] _]
(->> (vec (vals segments))
(mapv (fn [o s] (merge s {:offset o})) offsets)
(filterv #(<= (:offset %) position))
(reduce (fn [res o]
(cond
(nil? res) o
(> (:offset o) (:offset res)) o
:otherwise res))))))
(rf/reg-sub
::active-frame
:<- [::frames]
:<- [:cljs-karaoke.subs/song-position-ms]
(fn [[frames position] _]
(reduce
(fn [res f]
(cond
(nil? res) f
(and (> (:offset f) (:offset res))
(> position (:offset f))) f
:otherwise res))
frames)))
;; (rf/reg-sub
;; ::frame-count
;; :<- [::frames]
;; (fn [frames _]
;; (count frames)))
(defn flip [function]
(fn
([] function)
([x] (function x))
([x y] (function y x))
([x y z] (function z y x))
([x y z w] (function w z y x))
([x y z w & rest] (->> rest
(concat [x y z w])
reverse
(apply function)))))
(rf/reg-sub
::word-count
:<- [::frames]
(fn [frames _]
(->> frames
(mapv :events)
(mapv (fn [events]
(->> events
(mapv :text)
(apply str)
((flip cstr/split) #" ")
(count))))
(reduce + 0))))
(rf/reg-sub
::frame-count
:<- [::frames]
(fn [frames _]
(count frames)))
(rf/reg-sub
::words-per-frame
:<- [::word-count]
:<- [::frame-count]
(fn [[word-count frame-count] _]
(/ word-count frame-count)))
| null | https://raw.githubusercontent.com/baskeboler/cljs-karaoke-client/bb6512435eaa436d35034886be99213625847ee0/src/main/cljs_karaoke/editor/subs.cljs | clojure | (rf/reg-sub
::frame-count
:<- [::frames]
(fn [frames _]
(count frames))) | (ns cljs-karaoke.editor.subs
(:require [re-frame.core :as rf]
[clojure.string :as cstr]
[cljs-karaoke.protocols :as p]
[cljs-karaoke.subs.audio :as audio-subs]))
(rf/reg-sub
::editor-state
(fn [db _]
(:editor-state db)))
(rf/reg-sub
::current-frame
:<- [::editor-state]
(fn [editor-state _]
(:current-frame editor-state)))
(rf/reg-sub
::song-name
:<- [::editor-state]
(fn [editor-state _]
(:song-name editor-state)))
(rf/reg-sub
::current-frame-property
:<- [::current-frame]
(fn [current-frame [_ k]]
(get current-frame k)))
(rf/reg-sub
::frames
:<- [::editor-state]
(fn [editor-state _]
(:frames editor-state)))
(rf/reg-sub
::current-state
:<- [::editor-state]
(fn [editor-state _]
(:current-state editor-state)))
(def mode-titles
{:text-entry "Frame text definition"
:segment-selection "Divide text into segments"
:segment-timing "Synchronize segments with audio track"
:frame-preview "Preview work in progress"})
(rf/reg-sub
::mode-title
:<- [::current-state]
(fn [current-state _]
(mode-titles current-state)))
(rf/reg-sub
::segments-ready?
:<- [::editor-state]
(fn [{:keys [current-frame]} _]
(= (reduce + (:segment-sizes current-frame))
(count (:text current-frame)))))
(rf/reg-sub
::segment-timings-ready?
:<- [::editor-state]
(fn [{:keys [current-frame]} _]
(= (count (:segment-offsets current-frame))
(count (:segments current-frame)))))
(rf/reg-sub
::active-segment
:<- [::current-frame-property :segments]
:<- [::current-frame-property :segment-offsets]
:<- [:cljs-karaoke.subs/song-position-ms]
(fn [[segments offsets position] _]
(->> (vec (vals segments))
(mapv (fn [o s] (merge s {:offset o})) offsets)
(filterv #(<= (:offset %) position))
(reduce (fn [res o]
(cond
(nil? res) o
(> (:offset o) (:offset res)) o
:otherwise res))))))
(rf/reg-sub
::active-frame
:<- [::frames]
:<- [:cljs-karaoke.subs/song-position-ms]
(fn [[frames position] _]
(reduce
(fn [res f]
(cond
(nil? res) f
(and (> (:offset f) (:offset res))
(> position (:offset f))) f
:otherwise res))
frames)))
(defn flip [function]
(fn
([] function)
([x] (function x))
([x y] (function y x))
([x y z] (function z y x))
([x y z w] (function w z y x))
([x y z w & rest] (->> rest
(concat [x y z w])
reverse
(apply function)))))
(rf/reg-sub
::word-count
:<- [::frames]
(fn [frames _]
(->> frames
(mapv :events)
(mapv (fn [events]
(->> events
(mapv :text)
(apply str)
((flip cstr/split) #" ")
(count))))
(reduce + 0))))
(rf/reg-sub
::frame-count
:<- [::frames]
(fn [frames _]
(count frames)))
(rf/reg-sub
::words-per-frame
:<- [::word-count]
:<- [::frame-count]
(fn [[word-count frame-count] _]
(/ word-count frame-count)))
|
5c1e5fd9c1fb9f46abdf3ef5d1c150054e4a6a7449121041b992942db0b5b981 | LeastAuthority/wormhole-client | App.hs | -- | Description: a file-transfer monad transformer
# LANGUAGE GeneralizedNewtypeDeriving #
module Transit.Internal.App
( Env(..)
, App
, prepareAppEnv
, app
, runApp
, send
, receive
)
where
import Protolude hiding (toS)
import Protolude.Conv (toS)
import qualified Data.Text as Text
import qualified Data.Text.IO as TIO
import qualified MagicWormhole
import qualified System.Console.Haskeline as H
import qualified System.Console.Haskeline.Completion as HC
import qualified Crypto.Spake2 as Spake2
import System.IO.Error (IOError)
import System.Random (randomR, getStdGen)
import Data.String (String)
import Control.Monad.Except (liftEither)
import Data.Text.PgpWordlist.Internal.Words (wordList)
import Data.Text.PgpWordlist.Internal.Types (EvenWord(..), OddWord(..))
import System.Directory (getTemporaryDirectory, removeDirectoryRecursive)
import System.IO.Temp (createTempDirectory)
import Transit.Internal.Conf (Cmdline(..), Command(..), Options(..))
import Transit.Internal.Errors (Error(..), CommunicationError(..))
import Transit.Internal.FileTransfer(MessageType(..), sendFile, receiveFile)
import Transit.Internal.Peer (sendOffer, receiveOffer, receiveMessageAck, sendMessageAck, decodeTransitMsg)
import Transit.Internal.Network (connectToTor)
-- | Magic Wormhole transit app environment
data Env
= Env { side :: MagicWormhole.Side
^ random 5 - byte bytestring
, config :: Cmdline
-- ^ configuration like relay and transit url
}
| Create an ' Env ' , given the AppID and ' '
prepareAppEnv :: Cmdline -> IO Env
prepareAppEnv cmdlineOptions = do
side' <- MagicWormhole.generateSide
return $ Env side' cmdlineOptions
allocateCode :: [(Word8, EvenWord, OddWord)] -> IO Text
allocateCode wordlist = do
g <- getStdGen
let (r1, g') = randomR (0, 255) g
(r2, _) = randomR (0, 255) g'
Just (_, evenW, _) = atMay wordlist r2
Just (_, _, oddW) = atMay wordlist r1
return $ Text.concat [unOddWord oddW, "-", unEvenWord evenW]
printSendHelpText :: Text -> IO ()
printSendHelpText passcode = do
TIO.putStrLn $ "Wormhole code is: " <> passcode
TIO.putStrLn "On the other computer, please run:"
TIO.putStrLn ""
TIO.putStrLn $ "wormhole receive " <> passcode
data CompletionConfig
= CompletionConfig {
nameplates :: [Text]
-- ^ List of nameplates identifiers on the server
, oddWords :: [Text]
-- ^ PGP Odd words
, evenWords :: [Text]
-- ^ PGP Even words
, numWords :: Int
-- ^ Number of PGP words used in wormhole code
}
simpleCompletion :: Text -> HC.Completion
simpleCompletion text = (HC.simpleCompletion (toS text)) { HC.isFinished = False }
completeWord :: MonadIO m => CompletionConfig -> HC.CompletionFunc m
completeWord completionConfig = HC.completeWord Nothing "" completionFunc
where
completionFunc :: Monad m => String -> m [HC.Completion]
completionFunc word = do
let (completed, partial) = Text.breakOnEnd "-" (toS word)
hypenCount = Text.count "-" completed
wordlist | hypenCount == 0 = nameplates completionConfig
| odd hypenCount = oddWords completionConfig
| otherwise = evenWords completionConfig
suffix = if hypenCount < numWords completionConfig
then "-"
else ""
completions = map (\w -> completed `Text.append` (w `Text.append` suffix)) .
filter (Text.isPrefixOf partial) $ wordlist
return $ map simpleCompletion completions
-- | Take an input code from the user with code completion.
-- In order for the code completion to work, we need to find
-- the possible open nameplates, the possible words and then
-- do the completion as the user types the code.
-- TODO: This function does too much. Perfect target for refactoring.
getCode :: MagicWormhole.Session -> [(Word8, EvenWord, OddWord)] -> IO Text
getCode session wordlist = do
nameplates' <- MagicWormhole.list session
let ns = [ n | MagicWormhole.Nameplate n <- nameplates' ]
evens = [ unEvenWord n | (_, n, _) <- wordlist]
odds = [ unOddWord m | (_, _, m) <- wordlist]
completionConfig = CompletionConfig {
nameplates = ns,
oddWords = odds,
evenWords = evens,
numWords = 2
}
putText "Enter the receive wormhole code: "
H.runInputT (settings completionConfig) getInput
where
settings :: MonadIO m => CompletionConfig -> H.Settings m
settings completionConfig = H.Settings
{ H.complete = completeWord completionConfig
, H.historyFile = Nothing
, H.autoAddHistory = False
}
getInput :: H.InputT IO Text
getInput = do
minput <- H.getInputLine ""
case minput of
Nothing -> return ""
Just input -> return (toS input)
-- | App Monad Transformer that reads the configuration from 'Env', runs
a computation over the IO Monad and returns either the value ' a ' or ' Error '
newtype App a = App {
getApp :: ReaderT Env (ExceptT Error IO) a
} deriving (Functor, Applicative, Monad, MonadIO, MonadReader Env, MonadError Error)
| run the App Monad Transformer
runApp :: App a -> Env -> IO (Either Error a)
runApp appM env = runExceptT (runReaderT (getApp appM) env)
transitPurpose :: MagicWormhole.AppID -> ByteString
transitPurpose (MagicWormhole.AppID appid) = toS appid <> "/transit-key"
-- | Given the magic-wormhole session, appid, pass code, a function to print a helpful message
on the command the receiver needs to type ( simplest would be just a ` putStrLn ` ) and the
-- path on the disk of the sender of the file that needs to be sent, `sendFile` sends it via
-- the wormhole securely. The receiver, on successfully receiving the file, would compute
-- a sha256 sum of the encrypted file and sends it across to the sender, along with an
-- acknowledgement, which the sender can verify.
send :: MagicWormhole.Session -> Text -> MessageType -> Bool -> App ()
send session code tfd useTor = do
env <- ask
first establish a wormhole session with the receiver and
-- then talk the filetransfer protocol over it as follows.
let cmdlineOptions = config env
let args = options cmdlineOptions
let appid = appId args
let transitserver = transitUrl args
nameplate <- liftIO $ MagicWormhole.allocate session
mailbox <- liftIO $ MagicWormhole.claim session nameplate
peer <- liftIO $ MagicWormhole.open session mailbox -- XXX: We should run `close` in the case of exceptions?
let (MagicWormhole.Nameplate n) = nameplate
let passcode = toS n <> "-" <> toS code
liftIO $ printSendHelpText passcode
result <- liftIO $ MagicWormhole.withEncryptedConnection peer (Spake2.makePassword (toS passcode))
(\conn ->
case tfd of
TMsg msg -> do
let offer = MagicWormhole.Message msg
sendOffer conn offer
-- wait for "answer" message with "message_ack" key
first NetworkError <$> receiveMessageAck conn
TFile fileOrDirpath -> do
let transitKey = MagicWormhole.deriveKey conn (transitPurpose appid)
bracket
-- acquire resource
(do
systemTmpDir <- getTemporaryDirectory
createTempDirectory systemTmpDir "wormhole")
-- release resource
removeDirectoryRecursive
-- do the computation in between: send the file
(sendFile conn transitserver transitKey fileOrDirpath useTor)
)
liftEither result
-- | receive a text message or file from the wormhole peer.
receive :: MagicWormhole.Session -> Text -> Bool -> App ()
receive session code useTor = do
env <- ask
-- establish the connection
let cmdlineOptions = config env
let args = options cmdlineOptions
let appid = appId args
let transitserver = transitUrl args
let codeSplit = Text.split (=='-') code
let (Just nameplate) = headMay codeSplit
mailbox <- liftIO $ MagicWormhole.claim session (MagicWormhole.Nameplate nameplate)
peer <- liftIO $ MagicWormhole.open session mailbox
result <- liftIO $ MagicWormhole.withEncryptedConnection peer (Spake2.makePassword (toS (Text.strip code)))
(\conn -> do
-- unfortunately, the receiver has no idea which message to expect.
If the sender is only sending a text message , it gets an offer first .
if the sender is sending a file / directory , then transit comes first
-- and then offer comes in. `Transit.receiveOffer' will attempt to interpret
-- the bytestring as an offer message. If that fails, it passes the raw bytestring
-- as a Left value so that we can try to decode it as a TransitMsg.
someOffer <- receiveOffer conn
case someOffer of
Right (MagicWormhole.Message message) -> do
TIO.putStrLn message
result <- try (sendMessageAck conn "ok") :: IO (Either IOError ())
return $ bimap (const (NetworkError (ConnectionError "sending the ack message failed"))) identity result
Right (MagicWormhole.File _ _) -> do
sendMessageAck conn "not_ok"
return $ Left (NetworkError (ConnectionError "did not expect a file offer"))
Right MagicWormhole.Directory {} ->
return $ Left (NetworkError (UnknownPeerMessage "directory offer is not supported"))
-- ok, we received the Transit Message, send back a transit message
Left received ->
case decodeTransitMsg (toS received) of
Left e -> return $ Left (NetworkError e)
Right transitMsg -> do
let transitKey = MagicWormhole.deriveKey conn (transitPurpose appid)
receiveFile conn transitserver transitKey transitMsg useTor
)
liftEither result
-- | A file transfer application that takes an 'Env' and depending on the
-- config options, either sends or receives a file, directory or a text
-- message from the peer.
app :: App ()
app = do
env <- ask
let cmdlineOptions = config env
args = options cmdlineOptions
appid = appId args
endpoint = relayEndpoint args
command = cmd cmdlineOptions
case command of
Send tfd useTor -> do
maybeSock <- maybeGetConnectionSocket endpoint useTor
case maybeSock of
Right sock' ->
liftIO (MagicWormhole.runClient endpoint appid (side env) sock' $ \session ->
runApp (sendSession tfd session useTor) env) >>= liftEither
Left e -> liftEither (Left e)
Receive maybeCode useTor -> do
maybeSock <- maybeGetConnectionSocket endpoint useTor
case maybeSock of
Right sock' ->
liftIO (MagicWormhole.runClient endpoint appid (side env) sock' $ \session ->
runApp (receiveSession maybeCode session useTor) env) >>= liftEither
Left e -> liftEither (Left e)
where
getWormholeCode :: MagicWormhole.Session -> Maybe Text -> IO Text
getWormholeCode session Nothing = getCode session wordList
getWormholeCode _ (Just code) = return code
sendSession offerMsg session useTor = do
code <- liftIO $ allocateCode wordList
send session (toS code) offerMsg useTor
receiveSession maybeCode session useTor = do
code <- liftIO $ getWormholeCode session maybeCode
receive session code useTor
maybeGetConnectionSocket endpoint useTor | useTor == True = do
res <- liftIO $ connectToTor endpoint
return $ bimap NetworkError Just res
| otherwise = return (Right Nothing)
| null | https://raw.githubusercontent.com/LeastAuthority/wormhole-client/d00200e0f49a154688da1a882f8aef1df6469ba7/src/Transit/Internal/App.hs | haskell | | Description: a file-transfer monad transformer
| Magic Wormhole transit app environment
^ configuration like relay and transit url
^ List of nameplates identifiers on the server
^ PGP Odd words
^ PGP Even words
^ Number of PGP words used in wormhole code
| Take an input code from the user with code completion.
In order for the code completion to work, we need to find
the possible open nameplates, the possible words and then
do the completion as the user types the code.
TODO: This function does too much. Perfect target for refactoring.
| App Monad Transformer that reads the configuration from 'Env', runs
| Given the magic-wormhole session, appid, pass code, a function to print a helpful message
path on the disk of the sender of the file that needs to be sent, `sendFile` sends it via
the wormhole securely. The receiver, on successfully receiving the file, would compute
a sha256 sum of the encrypted file and sends it across to the sender, along with an
acknowledgement, which the sender can verify.
then talk the filetransfer protocol over it as follows.
XXX: We should run `close` in the case of exceptions?
wait for "answer" message with "message_ack" key
acquire resource
release resource
do the computation in between: send the file
| receive a text message or file from the wormhole peer.
establish the connection
unfortunately, the receiver has no idea which message to expect.
and then offer comes in. `Transit.receiveOffer' will attempt to interpret
the bytestring as an offer message. If that fails, it passes the raw bytestring
as a Left value so that we can try to decode it as a TransitMsg.
ok, we received the Transit Message, send back a transit message
| A file transfer application that takes an 'Env' and depending on the
config options, either sends or receives a file, directory or a text
message from the peer. | # LANGUAGE GeneralizedNewtypeDeriving #
module Transit.Internal.App
( Env(..)
, App
, prepareAppEnv
, app
, runApp
, send
, receive
)
where
import Protolude hiding (toS)
import Protolude.Conv (toS)
import qualified Data.Text as Text
import qualified Data.Text.IO as TIO
import qualified MagicWormhole
import qualified System.Console.Haskeline as H
import qualified System.Console.Haskeline.Completion as HC
import qualified Crypto.Spake2 as Spake2
import System.IO.Error (IOError)
import System.Random (randomR, getStdGen)
import Data.String (String)
import Control.Monad.Except (liftEither)
import Data.Text.PgpWordlist.Internal.Words (wordList)
import Data.Text.PgpWordlist.Internal.Types (EvenWord(..), OddWord(..))
import System.Directory (getTemporaryDirectory, removeDirectoryRecursive)
import System.IO.Temp (createTempDirectory)
import Transit.Internal.Conf (Cmdline(..), Command(..), Options(..))
import Transit.Internal.Errors (Error(..), CommunicationError(..))
import Transit.Internal.FileTransfer(MessageType(..), sendFile, receiveFile)
import Transit.Internal.Peer (sendOffer, receiveOffer, receiveMessageAck, sendMessageAck, decodeTransitMsg)
import Transit.Internal.Network (connectToTor)
data Env
= Env { side :: MagicWormhole.Side
^ random 5 - byte bytestring
, config :: Cmdline
}
| Create an ' Env ' , given the AppID and ' '
prepareAppEnv :: Cmdline -> IO Env
prepareAppEnv cmdlineOptions = do
side' <- MagicWormhole.generateSide
return $ Env side' cmdlineOptions
allocateCode :: [(Word8, EvenWord, OddWord)] -> IO Text
allocateCode wordlist = do
g <- getStdGen
let (r1, g') = randomR (0, 255) g
(r2, _) = randomR (0, 255) g'
Just (_, evenW, _) = atMay wordlist r2
Just (_, _, oddW) = atMay wordlist r1
return $ Text.concat [unOddWord oddW, "-", unEvenWord evenW]
printSendHelpText :: Text -> IO ()
printSendHelpText passcode = do
TIO.putStrLn $ "Wormhole code is: " <> passcode
TIO.putStrLn "On the other computer, please run:"
TIO.putStrLn ""
TIO.putStrLn $ "wormhole receive " <> passcode
data CompletionConfig
= CompletionConfig {
nameplates :: [Text]
, oddWords :: [Text]
, evenWords :: [Text]
, numWords :: Int
}
simpleCompletion :: Text -> HC.Completion
simpleCompletion text = (HC.simpleCompletion (toS text)) { HC.isFinished = False }
completeWord :: MonadIO m => CompletionConfig -> HC.CompletionFunc m
completeWord completionConfig = HC.completeWord Nothing "" completionFunc
where
completionFunc :: Monad m => String -> m [HC.Completion]
completionFunc word = do
let (completed, partial) = Text.breakOnEnd "-" (toS word)
hypenCount = Text.count "-" completed
wordlist | hypenCount == 0 = nameplates completionConfig
| odd hypenCount = oddWords completionConfig
| otherwise = evenWords completionConfig
suffix = if hypenCount < numWords completionConfig
then "-"
else ""
completions = map (\w -> completed `Text.append` (w `Text.append` suffix)) .
filter (Text.isPrefixOf partial) $ wordlist
return $ map simpleCompletion completions
getCode :: MagicWormhole.Session -> [(Word8, EvenWord, OddWord)] -> IO Text
getCode session wordlist = do
nameplates' <- MagicWormhole.list session
let ns = [ n | MagicWormhole.Nameplate n <- nameplates' ]
evens = [ unEvenWord n | (_, n, _) <- wordlist]
odds = [ unOddWord m | (_, _, m) <- wordlist]
completionConfig = CompletionConfig {
nameplates = ns,
oddWords = odds,
evenWords = evens,
numWords = 2
}
putText "Enter the receive wormhole code: "
H.runInputT (settings completionConfig) getInput
where
settings :: MonadIO m => CompletionConfig -> H.Settings m
settings completionConfig = H.Settings
{ H.complete = completeWord completionConfig
, H.historyFile = Nothing
, H.autoAddHistory = False
}
getInput :: H.InputT IO Text
getInput = do
minput <- H.getInputLine ""
case minput of
Nothing -> return ""
Just input -> return (toS input)
a computation over the IO Monad and returns either the value ' a ' or ' Error '
newtype App a = App {
getApp :: ReaderT Env (ExceptT Error IO) a
} deriving (Functor, Applicative, Monad, MonadIO, MonadReader Env, MonadError Error)
| run the App Monad Transformer
runApp :: App a -> Env -> IO (Either Error a)
runApp appM env = runExceptT (runReaderT (getApp appM) env)
transitPurpose :: MagicWormhole.AppID -> ByteString
transitPurpose (MagicWormhole.AppID appid) = toS appid <> "/transit-key"
on the command the receiver needs to type ( simplest would be just a ` putStrLn ` ) and the
send :: MagicWormhole.Session -> Text -> MessageType -> Bool -> App ()
send session code tfd useTor = do
env <- ask
first establish a wormhole session with the receiver and
let cmdlineOptions = config env
let args = options cmdlineOptions
let appid = appId args
let transitserver = transitUrl args
nameplate <- liftIO $ MagicWormhole.allocate session
mailbox <- liftIO $ MagicWormhole.claim session nameplate
let (MagicWormhole.Nameplate n) = nameplate
let passcode = toS n <> "-" <> toS code
liftIO $ printSendHelpText passcode
result <- liftIO $ MagicWormhole.withEncryptedConnection peer (Spake2.makePassword (toS passcode))
(\conn ->
case tfd of
TMsg msg -> do
let offer = MagicWormhole.Message msg
sendOffer conn offer
first NetworkError <$> receiveMessageAck conn
TFile fileOrDirpath -> do
let transitKey = MagicWormhole.deriveKey conn (transitPurpose appid)
bracket
(do
systemTmpDir <- getTemporaryDirectory
createTempDirectory systemTmpDir "wormhole")
removeDirectoryRecursive
(sendFile conn transitserver transitKey fileOrDirpath useTor)
)
liftEither result
receive :: MagicWormhole.Session -> Text -> Bool -> App ()
receive session code useTor = do
env <- ask
let cmdlineOptions = config env
let args = options cmdlineOptions
let appid = appId args
let transitserver = transitUrl args
let codeSplit = Text.split (=='-') code
let (Just nameplate) = headMay codeSplit
mailbox <- liftIO $ MagicWormhole.claim session (MagicWormhole.Nameplate nameplate)
peer <- liftIO $ MagicWormhole.open session mailbox
result <- liftIO $ MagicWormhole.withEncryptedConnection peer (Spake2.makePassword (toS (Text.strip code)))
(\conn -> do
If the sender is only sending a text message , it gets an offer first .
if the sender is sending a file / directory , then transit comes first
someOffer <- receiveOffer conn
case someOffer of
Right (MagicWormhole.Message message) -> do
TIO.putStrLn message
result <- try (sendMessageAck conn "ok") :: IO (Either IOError ())
return $ bimap (const (NetworkError (ConnectionError "sending the ack message failed"))) identity result
Right (MagicWormhole.File _ _) -> do
sendMessageAck conn "not_ok"
return $ Left (NetworkError (ConnectionError "did not expect a file offer"))
Right MagicWormhole.Directory {} ->
return $ Left (NetworkError (UnknownPeerMessage "directory offer is not supported"))
Left received ->
case decodeTransitMsg (toS received) of
Left e -> return $ Left (NetworkError e)
Right transitMsg -> do
let transitKey = MagicWormhole.deriveKey conn (transitPurpose appid)
receiveFile conn transitserver transitKey transitMsg useTor
)
liftEither result
app :: App ()
app = do
env <- ask
let cmdlineOptions = config env
args = options cmdlineOptions
appid = appId args
endpoint = relayEndpoint args
command = cmd cmdlineOptions
case command of
Send tfd useTor -> do
maybeSock <- maybeGetConnectionSocket endpoint useTor
case maybeSock of
Right sock' ->
liftIO (MagicWormhole.runClient endpoint appid (side env) sock' $ \session ->
runApp (sendSession tfd session useTor) env) >>= liftEither
Left e -> liftEither (Left e)
Receive maybeCode useTor -> do
maybeSock <- maybeGetConnectionSocket endpoint useTor
case maybeSock of
Right sock' ->
liftIO (MagicWormhole.runClient endpoint appid (side env) sock' $ \session ->
runApp (receiveSession maybeCode session useTor) env) >>= liftEither
Left e -> liftEither (Left e)
where
getWormholeCode :: MagicWormhole.Session -> Maybe Text -> IO Text
getWormholeCode session Nothing = getCode session wordList
getWormholeCode _ (Just code) = return code
sendSession offerMsg session useTor = do
code <- liftIO $ allocateCode wordList
send session (toS code) offerMsg useTor
receiveSession maybeCode session useTor = do
code <- liftIO $ getWormholeCode session maybeCode
receive session code useTor
maybeGetConnectionSocket endpoint useTor | useTor == True = do
res <- liftIO $ connectToTor endpoint
return $ bimap NetworkError Just res
| otherwise = return (Right Nothing)
|
e7b40e0066586ed4e223fa00f9189f7b794045237937de956f9684bf802ae9e4 | herd/herdtools7 | toolsConstant.mli | (****************************************************************************)
(* the diy toolsuite *)
(* *)
, University College London , UK .
, INRIA Paris - Rocquencourt , France .
(* *)
Copyright 2017 - present Institut National de Recherche en Informatique et
(* en Automatique and the authors. All rights reserved. *)
(* *)
This software is governed by the CeCILL - B license under French law and
(* abiding by the rules of distribution of free software. You can use, *)
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
(****************************************************************************)
type v = (Int64Scalar.t,ParsedPteVal.t,InstrLit.t) Constant.t
val pp : bool (* hexa *) -> v -> string
val pp_norm : bool (* hexa *) -> v -> string
val pp_v : v -> string
val compare : v -> v -> int
val eq : v -> v -> bool
| null | https://raw.githubusercontent.com/herd/herdtools7/b22ec02af1300a45e2b646cce4253ecd4fa7f250/tools/toolsConstant.mli | ocaml | **************************************************************************
the diy toolsuite
en Automatique and the authors. All rights reserved.
abiding by the rules of distribution of free software. You can use,
**************************************************************************
hexa
hexa | , University College London , UK .
, INRIA Paris - Rocquencourt , France .
Copyright 2017 - present Institut National de Recherche en Informatique et
This software is governed by the CeCILL - B license under French law and
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
type v = (Int64Scalar.t,ParsedPteVal.t,InstrLit.t) Constant.t
val pp_v : v -> string
val compare : v -> v -> int
val eq : v -> v -> bool
|
34f96d9503d9446bf5e694d6590f0b81f71be4724c164ea501d34cefcb323021 | ocamllabs/ocaml-modular-implicits | stypes.mli | (***********************************************************************)
(* *)
(* OCaml *)
(* *)
, projet , INRIA Rocquencourt
(* *)
Copyright 2003 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
(* Recording and dumping (partial) type information *)
must be true
open Typedtree;;
type annotation =
| Ti_pat of pattern
| Ti_expr of expression
| Ti_class of class_expr
| Ti_mod of module_expr
| An_call of Location.t * Annot.call
| An_ident of Location.t * string * Annot.ident
;;
val record : annotation -> unit;;
val record_phrase : Location.t -> unit;;
val dump : string option -> unit;;
val get_location : annotation -> Location.t;;
val get_info : unit -> annotation list;;
| null | https://raw.githubusercontent.com/ocamllabs/ocaml-modular-implicits/92e45da5c8a4c2db8b2cd5be28a5bec2ac2181f1/typing/stypes.mli | ocaml | *********************************************************************
OCaml
*********************************************************************
Recording and dumping (partial) type information | , projet , INRIA Rocquencourt
Copyright 2003 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
must be true
open Typedtree;;
type annotation =
| Ti_pat of pattern
| Ti_expr of expression
| Ti_class of class_expr
| Ti_mod of module_expr
| An_call of Location.t * Annot.call
| An_ident of Location.t * string * Annot.ident
;;
val record : annotation -> unit;;
val record_phrase : Location.t -> unit;;
val dump : string option -> unit;;
val get_location : annotation -> Location.t;;
val get_info : unit -> annotation list;;
|
5616978db6a2776025fbcd13534d043a6cd090b2e6bd0190067e09b9f3f05951 | locusmath/locus | impl.clj | (ns locus.order.galois.mapping.impl
(:require [locus.set.logic.core.set :refer :all]
[locus.set.logic.limit.product :refer :all]
[locus.set.mapping.general.core.object :refer :all]
[locus.set.logic.sequence.object :refer :all]
[locus.con.core.setpart :refer :all]
[locus.con.core.object :refer [projection]]
[locus.set.logic.structure.protocols :refer :all]
[locus.set.copresheaf.structure.core.protocols :refer :all]
[locus.set.quiver.relation.binary.product :refer :all]
[locus.set.quiver.relation.binary.br :refer :all]
[locus.set.quiver.relation.binary.sr :refer :all]
[locus.set.quiver.relation.binary.vertices :refer :all]
[locus.set.quiver.relation.binary.vertexset :refer :all]
[locus.set.quiver.binary.core.object :refer :all]
[locus.set.copresheaf.quiver.unital.object :refer :all]
[locus.order.general.core.object :refer :all]
[locus.order.general.core.morphism :refer :all]
[locus.set.quiver.structure.core.protocols :refer :all]))
Let F : A - > B and G : B - > A together be a connection of preorders . Then the lower
; adjoint of this Galois connection is a residuated mapping and the upper adjoint is a
; coresiduated mapping, and either of these objects presented by themselves is enough
; to reconstruct the entire adjunction. A residuated mapping is also defined as a
; monotone map that reflects principal idelas.
(deftype ResiduatedMapping [source target func]
AbstractMorphism
(source-object [this] source)
(target-object [this] target)
StructuredDifunction
(first-function [this]
(->SetFunction (morphisms source) (morphisms target) (partial map func)))
(second-function [this]
(->SetFunction (objects source) (objects target) func))
ConcreteMorphism
(inputs [this] (underlying-set source))
(outputs [this] (underlying-set target))
clojure.lang.IFn
(invoke [this arg] (func arg))
(applyTo [this args] (clojure.lang.AFn/applyToHelper this args)))
(derive ResiduatedMapping :locus.set.copresheaf.structure.core.protocols/monotone-map)
(defmulti to-residuated-mapping type)
(defmethod to-residuated-mapping ResiduatedMapping
[^ResiduatedMapping mapping] mapping)
; The dual concept of a residuated mapping is a coresiduated mapping. While a residuated mapping
; is a monotone map that reflects principal ideals, a coresiduated mapping is a monotone map
; that reflects principal filters. The category of Galois connection can be represented either
; in terms of the category of orders and residuated mappings or in terms of the category of
; orders and coresiduated mappings.
(deftype CoresiduatedMapping [source target func]
AbstractMorphism
(source-object [this] source)
(target-object [this] target)
StructuredDifunction
(first-function [this]
(->SetFunction (morphisms source) (morphisms target) (partial map func)))
(second-function [this]
(->SetFunction (objects source) (objects target) func))
ConcreteMorphism
(inputs [this] (underlying-set source))
(outputs [this] (underlying-set target))
clojure.lang.IFn
(invoke [this arg] (func arg))
(applyTo [this args] (clojure.lang.AFn/applyToHelper this args)))
(derive CoresiduatedMapping :locus.set.copresheaf.structure.core.protocols/monotone-map)
(defmulti to-coresiduated-mapping type)
(defmethod to-coresiduated-mapping CoresiduatedMapping
[^CoresiduatedMapping mapping] mapping)
Residuated and coresiduated mappings both form categories
(defmethod compose* ResiduatedMapping
[^ResiduatedMapping a, ^ResiduatedMapping b]
(->ResiduatedMapping
(source-object b)
(target-object a)
(comp (.-func a) (.-func b))))
(defmethod compose* CoresiduatedMapping
[^CoresiduatedMapping a, ^CoresiduatedMapping b]
(->CoresiduatedMapping
(source-object b)
(target-object a)
(comp (.-func a) (.-func b))))
; The other adjoints of a residuated mapping or a coresiduated mapping can be uniquely determined
(defn residual
[mapping]
(let [source-relation (underlying-relation (source-object mapping))]
(->CoresiduatedMapping
(target-object mapping)
(source-object mapping)
(fn [i]
(first (maximal-member-vertices source-relation (reflect-principal-ideal mapping i)))))))
(defn coresidual
[mapping]
(let [source-relation (underlying-relation (source-object mapping))]
(->ResiduatedMapping
(target-object mapping)
(source-object mapping)
(fn [i]
(first (minimal-member-vertices source-relation (reflect-principal-filter mapping i)))))))
; Ontology of residuated and coresiduated mappingss
(defmethod residuated-mapping? ResiduatedMapping
[^ResiduatedMapping mapping] true)
(defmethod coresiduated-mapping? CoresiduatedMapping
[^CoresiduatedMapping mapping] true) | null | https://raw.githubusercontent.com/locusmath/locus/fb6068bd78977b51fd3c5783545a5f9986e4235c/src/clojure/locus/order/galois/mapping/impl.clj | clojure | adjoint of this Galois connection is a residuated mapping and the upper adjoint is a
coresiduated mapping, and either of these objects presented by themselves is enough
to reconstruct the entire adjunction. A residuated mapping is also defined as a
monotone map that reflects principal idelas.
The dual concept of a residuated mapping is a coresiduated mapping. While a residuated mapping
is a monotone map that reflects principal ideals, a coresiduated mapping is a monotone map
that reflects principal filters. The category of Galois connection can be represented either
in terms of the category of orders and residuated mappings or in terms of the category of
orders and coresiduated mappings.
The other adjoints of a residuated mapping or a coresiduated mapping can be uniquely determined
Ontology of residuated and coresiduated mappingss | (ns locus.order.galois.mapping.impl
(:require [locus.set.logic.core.set :refer :all]
[locus.set.logic.limit.product :refer :all]
[locus.set.mapping.general.core.object :refer :all]
[locus.set.logic.sequence.object :refer :all]
[locus.con.core.setpart :refer :all]
[locus.con.core.object :refer [projection]]
[locus.set.logic.structure.protocols :refer :all]
[locus.set.copresheaf.structure.core.protocols :refer :all]
[locus.set.quiver.relation.binary.product :refer :all]
[locus.set.quiver.relation.binary.br :refer :all]
[locus.set.quiver.relation.binary.sr :refer :all]
[locus.set.quiver.relation.binary.vertices :refer :all]
[locus.set.quiver.relation.binary.vertexset :refer :all]
[locus.set.quiver.binary.core.object :refer :all]
[locus.set.copresheaf.quiver.unital.object :refer :all]
[locus.order.general.core.object :refer :all]
[locus.order.general.core.morphism :refer :all]
[locus.set.quiver.structure.core.protocols :refer :all]))
Let F : A - > B and G : B - > A together be a connection of preorders . Then the lower
(deftype ResiduatedMapping [source target func]
AbstractMorphism
(source-object [this] source)
(target-object [this] target)
StructuredDifunction
(first-function [this]
(->SetFunction (morphisms source) (morphisms target) (partial map func)))
(second-function [this]
(->SetFunction (objects source) (objects target) func))
ConcreteMorphism
(inputs [this] (underlying-set source))
(outputs [this] (underlying-set target))
clojure.lang.IFn
(invoke [this arg] (func arg))
(applyTo [this args] (clojure.lang.AFn/applyToHelper this args)))
(derive ResiduatedMapping :locus.set.copresheaf.structure.core.protocols/monotone-map)
(defmulti to-residuated-mapping type)
(defmethod to-residuated-mapping ResiduatedMapping
[^ResiduatedMapping mapping] mapping)
(deftype CoresiduatedMapping [source target func]
AbstractMorphism
(source-object [this] source)
(target-object [this] target)
StructuredDifunction
(first-function [this]
(->SetFunction (morphisms source) (morphisms target) (partial map func)))
(second-function [this]
(->SetFunction (objects source) (objects target) func))
ConcreteMorphism
(inputs [this] (underlying-set source))
(outputs [this] (underlying-set target))
clojure.lang.IFn
(invoke [this arg] (func arg))
(applyTo [this args] (clojure.lang.AFn/applyToHelper this args)))
(derive CoresiduatedMapping :locus.set.copresheaf.structure.core.protocols/monotone-map)
(defmulti to-coresiduated-mapping type)
(defmethod to-coresiduated-mapping CoresiduatedMapping
[^CoresiduatedMapping mapping] mapping)
Residuated and coresiduated mappings both form categories
(defmethod compose* ResiduatedMapping
[^ResiduatedMapping a, ^ResiduatedMapping b]
(->ResiduatedMapping
(source-object b)
(target-object a)
(comp (.-func a) (.-func b))))
(defmethod compose* CoresiduatedMapping
[^CoresiduatedMapping a, ^CoresiduatedMapping b]
(->CoresiduatedMapping
(source-object b)
(target-object a)
(comp (.-func a) (.-func b))))
(defn residual
[mapping]
(let [source-relation (underlying-relation (source-object mapping))]
(->CoresiduatedMapping
(target-object mapping)
(source-object mapping)
(fn [i]
(first (maximal-member-vertices source-relation (reflect-principal-ideal mapping i)))))))
(defn coresidual
[mapping]
(let [source-relation (underlying-relation (source-object mapping))]
(->ResiduatedMapping
(target-object mapping)
(source-object mapping)
(fn [i]
(first (minimal-member-vertices source-relation (reflect-principal-filter mapping i)))))))
(defmethod residuated-mapping? ResiduatedMapping
[^ResiduatedMapping mapping] true)
(defmethod coresiduated-mapping? CoresiduatedMapping
[^CoresiduatedMapping mapping] true) |
28de82a640d1ba70af7fe0078aa39f4e13b3bdca9f3e95908c6153962154f199 | gilith/hol-light | printer.ml | (* ========================================================================= *)
(* Simplistic HOL Light prettyprinter, using the OCaml "Format" library. *)
(* *)
, University of Cambridge Computer Laboratory
(* *)
( c ) Copyright , University of Cambridge 1998
( c ) Copyright , 1998 - 2007
( c ) Copyright , 2017
( c ) Copyright , , 2017 - 2018
(* ========================================================================= *)
needs "nets.ml";;
(* ------------------------------------------------------------------------- *)
(* Character discrimination. *)
(* ------------------------------------------------------------------------- *)
let isspace,issep,isbra,issymb,isalpha,isnum,isalnum =
let charcode s = Char.code(String.get s 0) in
let spaces = " \t\n\r"
and separators = ",;"
and brackets = "()[]{}"
and symbs = "\\!@#$%^&*-+|\\<=>/?~.:"
and alphas = "'abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ"
and nums = "0123456789" in
let allchars = spaces^separators^brackets^symbs^alphas^nums in
let csetsize = itlist (max o charcode) (explode allchars) 256 in
let ctable = Array.make csetsize 0 in
do_list (fun c -> Array.set ctable (charcode c) 1) (explode spaces);
do_list (fun c -> Array.set ctable (charcode c) 2) (explode separators);
do_list (fun c -> Array.set ctable (charcode c) 4) (explode brackets);
do_list (fun c -> Array.set ctable (charcode c) 8) (explode symbs);
do_list (fun c -> Array.set ctable (charcode c) 16) (explode alphas);
do_list (fun c -> Array.set ctable (charcode c) 32) (explode nums);
let isspace c = Array.get ctable (charcode c) = 1
and issep c = Array.get ctable (charcode c) = 2
and isbra c = Array.get ctable (charcode c) = 4
and issymb c = Array.get ctable (charcode c) = 8
and isalpha c = Array.get ctable (charcode c) = 16
and isnum c = Array.get ctable (charcode c) = 32
and isalnum c = Array.get ctable (charcode c) >= 16 in
isspace,issep,isbra,issymb,isalpha,isnum,isalnum;;
(* ------------------------------------------------------------------------- *)
(* Reserved words. *)
(* ------------------------------------------------------------------------- *)
let reserve_words,unreserve_words,is_reserved_word,reserved_words =
let reswords = ref ["("; ")"; "["; "]"; "{"; "}";
":"; ";"; "."; "|";
"let"; "in"; "and"; "if"; "then"; "else";
"match"; "with"; "function"; "->"; "when"] in
(fun ns -> reswords := union (!reswords) ns),
(fun ns -> reswords := subtract (!reswords) ns),
(fun n -> mem n (!reswords)),
(fun () -> !reswords);;
(* ------------------------------------------------------------------------- *)
(* Functions to access the global tables controlling special parse status. *)
(* *)
(* o List of binders; *)
(* *)
(* o List of prefixes (right-associated unary functions like negation). *)
(* *)
(* o List of infixes with their precedences and associations. *)
(* *)
(* Note that these tables are independent of constant/variable status or *)
(* whether an identifier is symbolic. *)
(* ------------------------------------------------------------------------- *)
let unparse_as_binder,parse_as_binder,parses_as_binder,binders =
let binder_list = ref ([]:string list) in
(fun n -> binder_list := subtract (!binder_list) [n]),
(fun n -> binder_list := union (!binder_list) [n]),
(fun n -> mem n (!binder_list)),
(fun () -> !binder_list);;
let unparse_as_prefix,parse_as_prefix,is_prefix,prefixes =
let prefix_list = ref ([]:string list) in
(fun n -> prefix_list := subtract (!prefix_list) [n]),
(fun n -> prefix_list := union (!prefix_list) [n]),
(fun n -> mem n (!prefix_list)),
(fun () -> !prefix_list);;
let unparse_as_infix,parse_as_infix,get_infix_status,infixes =
let cmp (s,(x,a)) (t,(y,b)) =
x < y || x = y && a > b || x = y && a = b && s < t in
let infix_list = ref ([]:(string * (int * string)) list) in
(fun n -> infix_list := filter (((<>) n) o fst) (!infix_list)),
(fun (n,d) -> infix_list := sort cmp
((n,d)::(filter (((<>) n) o fst) (!infix_list)))),
(fun n -> assoc n (!infix_list)),
(fun () -> !infix_list);;
(* ------------------------------------------------------------------------- *)
Interface mapping .
(* ------------------------------------------------------------------------- *)
let the_interface = ref ([] :(string * (string * hol_type)) list);;
let the_overload_skeletons = ref ([] : (string * hol_type) list);;
(* ------------------------------------------------------------------------- *)
(* Now the printer. *)
(* ------------------------------------------------------------------------- *)
include Format;;
set_max_boxes 100;;
(* ------------------------------------------------------------------------- *)
(* Flag determining whether interface/overloading is reversed on printing. *)
(* ------------------------------------------------------------------------- *)
let reverse_interface_mapping = ref true;;
(* ------------------------------------------------------------------------- *)
(* Determine binary operators that print without surrounding spaces. *)
(* ------------------------------------------------------------------------- *)
let unspaced_binops = ref [","; ".."; "$"];;
(* ------------------------------------------------------------------------- *)
(* Binary operators to print at start of line when breaking. *)
(* ------------------------------------------------------------------------- *)
let prebroken_binops = ref ["==>"];;
(* ------------------------------------------------------------------------- *)
Force explicit indications of bound variables in set abstractions .
(* ------------------------------------------------------------------------- *)
let print_unambiguous_comprehensions = ref false;;
(* ------------------------------------------------------------------------- *)
Print the universal set UNIV : A->bool as " (: A ) " .
(* ------------------------------------------------------------------------- *)
let typify_universal_set = ref true;;
(* ------------------------------------------------------------------------- *)
(* Flag controlling whether hypotheses print. *)
(* ------------------------------------------------------------------------- *)
let print_all_thm = ref true;;
(* ------------------------------------------------------------------------- *)
(* Get the name of a constant or variable. *)
(* ------------------------------------------------------------------------- *)
let name_of tm =
match tm with
Var(x,ty) | Const(x,ty) -> x
| _ -> "";;
(* ------------------------------------------------------------------------- *)
(* Printer for types. *)
(* ------------------------------------------------------------------------- *)
let pp_print_type,pp_print_qtype =
let soc sep flag ss =
if ss = [] then "" else
let s = end_itlist (fun s1 s2 -> s1^sep^s2) ss in
if flag then "("^s^")" else s in
let rec sot pr ty =
try dest_vartype ty with Failure _ ->
try string_of_num(dest_finty ty) with Failure _ ->
match dest_type ty with
con,[] -> con
| "fun",[ty1;ty2] -> soc "->" (pr > 0) [sot 1 ty1; sot 0 ty2]
| "sum",[ty1;ty2] -> soc "+" (pr > 2) [sot 3 ty1; sot 2 ty2]
| "prod",[ty1;ty2] -> soc "#" (pr > 4) [sot 5 ty1; sot 4 ty2]
| "cart",[ty1;ty2] -> soc "^" (pr > 6) [sot 6 ty1; sot 7 ty2]
| con,args -> (soc "," true (map (sot 0) args))^con in
(fun fmt ty -> pp_print_string fmt (sot 0 ty)),
(fun fmt ty -> pp_print_string fmt ("`:" ^ sot 0 ty ^ "`"));;
(* ------------------------------------------------------------------------- *)
Allow the installation of user printers . Must fail quickly if N / A.
(* ------------------------------------------------------------------------- *)
let install_user_printer,delete_user_printer,try_user_printer =
let user_printers = ref ([]:(string*(formatter->term->unit))list) in
(fun pr -> user_printers := pr::(!user_printers)),
(fun s -> user_printers := snd(remove (fun (s',_) -> s = s')
(!user_printers))),
(fun fmt -> fun tm -> tryfind (fun (_,pr) -> pr fmt tm) (!user_printers));;
(* ------------------------------------------------------------------------- *)
(* Printer for terms. *)
(* ------------------------------------------------------------------------- *)
let pp_print_term =
let reverse_interface (s0,ty0) =
if not(!reverse_interface_mapping) then s0 else
try fst(find (fun (s,(s',ty)) -> s' = s0 && can (type_match ty ty0) [])
(!the_interface))
with Failure _ -> s0 in
let DEST_BINARY c tm =
try let il,r = dest_comb tm in
let i,l = dest_comb il in
if i = c ||
(is_const i && is_const c &&
reverse_interface(dest_const i) = reverse_interface(dest_const c))
then l,r else fail()
with Failure _ -> failwith "DEST_BINARY"
and ARIGHT s =
match snd(get_infix_status s) with
"right" -> true | _ -> false in
let rec powerof10 n =
if abs_num n </ Int 1 then false
else if n =/ Int 1 then true
else powerof10 (n // Int 10) in
let bool_of_term t =
match t with
Const("T",_) -> true
| Const("F",_) -> false
| _ -> failwith "bool_of_term" in
let code_of_term t =
let f,tms = strip_comb t in
if not(is_const f && fst(dest_const f) = "ASCII")
|| not(length tms = 8) then failwith "code_of_term"
else
itlist (fun b f -> if b then 1 + 2 * f else 2 * f)
(map bool_of_term (rev tms)) 0 in
let rec dest_clause tm =
let pbod = snd(strip_exists(body(body tm))) in
let s,args = strip_comb pbod in
if name_of s = "_UNGUARDED_PATTERN" && length args = 2 then
[rand(rator(hd args));rand(rator(hd(tl args)))]
else if name_of s = "_GUARDED_PATTERN" && length args = 3 then
[rand(rator(hd args)); hd(tl args); rand(rator(hd(tl(tl args))))]
else failwith "dest_clause" in
let rec dest_clauses tm =
let s,args = strip_comb tm in
if name_of s = "_SEQPATTERN" && length args = 2 then
dest_clause (hd args)::dest_clauses(hd(tl args))
else [dest_clause tm] in
let pp_numeral fmt tm =
let s = string_of_num (dest_numeral tm) in
let n = String.length s in
let rec pp_digit i =
let c = String.get s i in
let () = Format.pp_print_char fmt c in
let i = i + 1 in
if i = n then () else
let () = Format.pp_print_cut fmt () in
pp_digit i in
let () = Format.pp_open_box fmt 0 in
let () = pp_digit 0 in
let () = Format.pp_close_box fmt () in
() in
let pdest_cond tm =
match tm with
Comb(Comb(Comb(Const("COND",_),i),t),e) -> (i,t),e
| _ -> failwith "pdest_cond" in
fun fmt ->
let rec print_term prec tm =
try try_user_printer fmt tm with Failure _ ->
try pp_numeral fmt tm with Failure _ ->
try (let tms = dest_list tm in
try if fst(dest_type(hd(snd(dest_type(type_of tm))))) <> "char"
then fail() else
let ccs = map (String.make 1 o Char.chr o code_of_term) tms in
let s = "\"" ^ String.escaped (implode ccs) ^ "\"" in
pp_print_string fmt s
with Failure _ ->
pp_open_box fmt 0; pp_print_string fmt "[";
pp_open_box fmt 0; print_term_sequence true ";" 0 tms;
pp_close_box fmt (); pp_print_string fmt "]";
pp_close_box fmt ())
with Failure _ ->
if is_gabs tm then print_binder prec tm else
let hop,args = strip_comb tm in
let s0 = name_of hop
and ty0 = type_of hop in
let s = reverse_interface (s0,ty0) in
try if s = "EMPTY" && is_const tm && args = [] then
pp_print_string fmt "{}" else fail()
with Failure _ ->
try if s = "UNIV" && !typify_universal_set && is_const tm && args = []
then
let ty = fst(dest_fun_ty(type_of tm)) in
(pp_print_string fmt "(:";
pp_print_type fmt ty;
pp_print_string fmt ")")
else fail()
with Failure _ ->
try if s <> "INSERT" then fail() else
let mems,oth = splitlist (dest_binary "INSERT") tm in
if is_const oth && fst(dest_const oth) = "EMPTY" then
(pp_open_box fmt 0; pp_print_string fmt "{"; pp_open_box fmt 0;
print_term_sequence true "," 14 mems;
pp_close_box fmt (); pp_print_string fmt "}"; pp_close_box fmt ())
else fail()
with Failure _ ->
try if not (s = "GSPEC") then fail() else
let evs,bod = strip_exists(body(rand tm)) in
let bod1,babs = dest_comb bod in
let bod2,bod3 = dest_comb bod1 in
if fst (dest_const bod2) <> "/\\" then fail() else
let bod4,fabs = dest_comb bod3 in
let bod5,bod6 = dest_comb bod4 in
if fst (dest_const bod5) <> "=" then fail() else
pp_print_string fmt "{";
print_term 0 fabs;
pp_print_string fmt " | ";
(let fvs = frees fabs and bvs = frees babs in
if not(!print_unambiguous_comprehensions) &&
set_eq evs
(if (length fvs <= 1 || bvs = []) then fvs
else intersect fvs bvs)
then ()
else (print_term_sequence false "," 14 evs;
pp_print_string fmt " | "));
print_term 0 babs;
pp_print_string fmt "}"
with Failure _ ->
try let eqs,bod = dest_let tm in
(if prec = 0 then pp_open_hvbox fmt 0
else (pp_open_hvbox fmt 1; pp_print_string fmt "(");
pp_print_string fmt "let ";
print_term 0 (mk_eq(hd eqs));
do_list (fun (v,t) -> pp_print_break fmt 1 0;
pp_print_string fmt "and ";
print_term 0 (mk_eq(v,t)))
(tl eqs);
pp_print_string fmt " in";
pp_print_break fmt 1 0;
print_term 0 bod;
if prec = 0 then () else pp_print_string fmt ")";
pp_close_box fmt ())
with Failure _ -> try
if s <> "DECIMAL" then fail() else
let n_num = dest_numeral (hd args)
and n_den = dest_numeral (hd(tl args)) in
if not(powerof10 n_den) then fail() else
let s_num = string_of_num(quo_num n_num n_den) in
let s_den = implode(tl(explode(string_of_num
(n_den +/ (mod_num n_num n_den))))) in
pp_print_string fmt
("#"^s_num^(if n_den = Int 1 then "" else ".")^s_den)
with Failure _ -> try
if s <> "_MATCH" || length args <> 2 then failwith "" else
let cls = dest_clauses(hd(tl args)) in
(if prec = 0 then () else pp_print_string fmt "(";
pp_open_hvbox fmt 0;
pp_print_string fmt "match ";
print_term 0 (hd args);
pp_print_string fmt " with";
pp_print_break fmt 1 2;
print_clauses cls;
pp_close_box fmt ();
if prec = 0 then () else pp_print_string fmt ")")
with Failure _ -> try
if s <> "_FUNCTION" || length args <> 1 then failwith "" else
let cls = dest_clauses(hd args) in
(if prec = 0 then () else pp_print_string fmt "(";
pp_open_hvbox fmt 0;
pp_print_string fmt "function";
pp_print_break fmt 1 2;
print_clauses cls;
pp_close_box fmt ();
if prec = 0 then () else pp_print_string fmt ")")
with Failure _ ->
if s = "COND" && length args = 3 then
((if prec = 0 then () else pp_print_string fmt "(");
pp_open_hvbox fmt (-1);
(let ccls,ecl = splitlist pdest_cond tm in
if length ccls <= 4 then
(pp_print_string fmt "if ";
print_term 0 (hd args);
pp_print_break fmt 0 0;
pp_print_string fmt " then ";
print_term 0 (hd(tl args));
pp_print_break fmt 0 0;
pp_print_string fmt " else ";
print_term 0 (hd(tl(tl args)))
)
else
(pp_print_string fmt "if ";
print_term 0 (fst(hd ccls));
pp_print_string fmt " then ";
print_term 0 (snd(hd ccls));
pp_print_break fmt 0 0;
do_list (fun (i,t) ->
pp_print_string fmt " else if ";
print_term 0 i;
pp_print_string fmt " then ";
print_term 0 t;
pp_print_break fmt 0 0) (tl ccls);
pp_print_string fmt " else ";
print_term 0 ecl));
pp_close_box fmt ();
(if prec = 0 then () else pp_print_string fmt ")"))
else if is_prefix s && length args = 1 then
(if prec = 1000 then pp_print_string fmt "(" else ();
pp_print_string fmt s;
(if isalnum s ||
s = "--" &&
length args = 1 &&
(try let l,r = dest_comb(hd args) in
let s0 = name_of l and ty0 = type_of l in
reverse_interface (s0,ty0) = "--" ||
mem (fst(dest_const l)) ["real_of_num"; "int_of_num"]
with Failure _ -> false) ||
s = "~" && length args = 1 && is_neg(hd args)
then pp_print_string fmt " " else ());
print_term 999 (hd args);
if prec = 1000 then pp_print_string fmt ")" else ())
else if parses_as_binder s && length args = 1 && is_gabs (hd args) then
print_binder prec tm
else if can get_infix_status s && length args = 2 then
let bargs =
if ARIGHT s then
let tms,tmt = splitlist (DEST_BINARY hop) tm in tms@[tmt]
else
let tmt,tms = rev_splitlist (DEST_BINARY hop) tm in tmt::tms in
let newprec = fst(get_infix_status s) in
(if newprec <= prec then
(pp_open_hvbox fmt 1; pp_print_string fmt "(")
else pp_open_hvbox fmt 0;
print_term newprec (hd bargs);
do_list (fun x -> if mem s (!unspaced_binops) then ()
else if mem s (!prebroken_binops)
then pp_print_break fmt 1 0
else pp_print_string fmt " ";
pp_print_string fmt s;
if mem s (!unspaced_binops)
then pp_print_break fmt 0 0
else if mem s (!prebroken_binops)
then pp_print_string fmt " "
else pp_print_break fmt 1 0;
print_term newprec x) (tl bargs);
if newprec <= prec then pp_print_string fmt ")" else ();
pp_close_box fmt ())
else if (is_const hop || is_var hop) && args = [] then
let s' = if parses_as_binder s || can get_infix_status s || is_prefix s
then "("^s^")" else s in
pp_print_string fmt s'
else
let l,r = dest_comb tm in
(pp_open_hvbox fmt 0;
if prec = 1000 then pp_print_string fmt "(" else ();
print_term 999 l;
(if try mem (fst(dest_const l)) ["real_of_num"; "int_of_num"]
with Failure _ -> false
then () else pp_print_space fmt ());
print_term 1000 r;
if prec = 1000 then pp_print_string fmt ")" else ();
pp_close_box fmt ())
and print_term_sequence break sep prec tms =
if tms = [] then () else
(print_term prec (hd tms);
let ttms = tl tms in
if ttms = [] then () else
(pp_print_string fmt sep;
(if break then pp_print_space fmt ());
print_term_sequence break sep prec ttms))
and print_binder prec tm =
let absf = is_gabs tm in
let s = if absf then "\\" else name_of(rator tm) in
let rec collectvs tm =
if absf then
if is_abs tm then
let v,t = dest_abs tm in
let vs,bod = collectvs t in (false,v)::vs,bod
else if is_gabs tm then
let v,t = dest_gabs tm in
let vs,bod = collectvs t in (true,v)::vs,bod
else [],tm
else if is_comb tm && name_of(rator tm) = s then
if is_abs(rand tm) then
let v,t = dest_abs(rand tm) in
let vs,bod = collectvs t in (false,v)::vs,bod
else if is_gabs(rand tm) then
let v,t = dest_gabs(rand tm) in
let vs,bod = collectvs t in (true,v)::vs,bod
else [],tm
else [],tm in
let vs,bod = collectvs tm in
((if prec = 0 then pp_open_hvbox fmt 4
else (pp_open_hvbox fmt 5; pp_print_string fmt "("));
pp_print_string fmt s;
(if isalnum s then pp_print_string fmt " " else ());
do_list (fun (b,x) ->
(if b then pp_print_string fmt "(" else ());
print_term 0 x;
(if b then pp_print_string fmt ")" else ());
pp_print_string fmt " ") (butlast vs);
(if fst(last vs) then pp_print_string fmt "(" else ());
print_term 0 (snd(last vs));
(if fst(last vs) then pp_print_string fmt ")" else ());
pp_print_string fmt ".";
(if length vs = 1 then pp_print_string fmt " "
else pp_print_space fmt ());
print_term 0 bod;
(if prec = 0 then () else pp_print_string fmt ")");
pp_close_box fmt ())
and print_clauses cls =
match cls with
[c] -> print_clause c
| c::cs -> (print_clause c;
pp_print_break fmt 1 0;
pp_print_string fmt "| ";
print_clauses cs)
and print_clause cl =
match cl with
[p;g;r] -> (print_term 1 p;
pp_print_string fmt " when ";
print_term 1 g;
pp_print_string fmt " -> ";
print_term 1 r)
| [p;r] -> (print_term 1 p;
pp_print_string fmt " -> ";
print_term 1 r)
in print_term 0;;
(* ------------------------------------------------------------------------- *)
(* Print term with quotes. *)
(* ------------------------------------------------------------------------- *)
let pp_print_qterm fmt tm =
pp_print_string fmt "`";
pp_print_term fmt tm;
pp_print_string fmt "`";;
(* ------------------------------------------------------------------------- *)
(* Printer for theorems. *)
(* ------------------------------------------------------------------------- *)
let pp_print_sequent fmt seq =
let (asl,tm) = Sequent.dest seq in
(if not (asl = []) then
(if !print_all_thm then
(pp_print_term fmt (hd asl);
do_list (fun x -> pp_print_string fmt ",";
pp_print_space fmt ();
pp_print_term fmt x)
(tl asl))
else pp_print_string fmt "...";
pp_print_space fmt ())
else ();
pp_open_hbox fmt();
pp_print_string fmt "|- ";
pp_print_term fmt tm;
pp_close_box fmt ());;
let pp_print_thm fmt th = pp_print_sequent fmt (Sequent.from_thm th);;
(* ------------------------------------------------------------------------- *)
(* Print on standard output. *)
(* ------------------------------------------------------------------------- *)
let print_type = pp_print_type std_formatter;;
let print_qtype = pp_print_qtype std_formatter;;
let print_term = pp_print_term std_formatter;;
let print_qterm = pp_print_qterm std_formatter;;
let print_thm = pp_print_thm std_formatter;;
let print_sequent = pp_print_sequent std_formatter;;
(* ------------------------------------------------------------------------- *)
(* Install all the printers. *)
(* ------------------------------------------------------------------------- *)
#install_printer pp_print_qtype;;
#install_printer pp_print_qterm;;
#install_printer pp_print_thm;;
#install_printer pp_print_sequent;;
(* ------------------------------------------------------------------------- *)
(* Conversions to string. *)
(* ------------------------------------------------------------------------- *)
let print_to_string printer =
let buf = Buffer.create 16 in
let fmt = formatter_of_buffer buf in
let () = pp_set_max_boxes fmt 100 in
let print = printer fmt in
let flush = pp_print_flush fmt in
fun x ->
let () = pp_set_margin fmt (get_margin ()) in
let () = print x in
let () = flush () in
let s = Buffer.contents buf in
let () = Buffer.reset buf in
s;;
let string_of_type = print_to_string pp_print_type;;
let string_of_term = print_to_string pp_print_term;;
let string_of_thm = print_to_string pp_print_thm;;
let string_of_sequent = print_to_string pp_print_sequent;;
Sequent.install_to_string string_of_sequent;;
| null | https://raw.githubusercontent.com/gilith/hol-light/f3f131963f2298b4d65ee5fead6e986a4a14237a/printer.ml | ocaml | =========================================================================
Simplistic HOL Light prettyprinter, using the OCaml "Format" library.
=========================================================================
-------------------------------------------------------------------------
Character discrimination.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Reserved words.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Functions to access the global tables controlling special parse status.
o List of binders;
o List of prefixes (right-associated unary functions like negation).
o List of infixes with their precedences and associations.
Note that these tables are independent of constant/variable status or
whether an identifier is symbolic.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Now the printer.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Flag determining whether interface/overloading is reversed on printing.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Determine binary operators that print without surrounding spaces.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Binary operators to print at start of line when breaking.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Flag controlling whether hypotheses print.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Get the name of a constant or variable.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Printer for types.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Printer for terms.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Print term with quotes.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Printer for theorems.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Print on standard output.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Install all the printers.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Conversions to string.
------------------------------------------------------------------------- | , University of Cambridge Computer Laboratory
( c ) Copyright , University of Cambridge 1998
( c ) Copyright , 1998 - 2007
( c ) Copyright , 2017
( c ) Copyright , , 2017 - 2018
needs "nets.ml";;
let isspace,issep,isbra,issymb,isalpha,isnum,isalnum =
let charcode s = Char.code(String.get s 0) in
let spaces = " \t\n\r"
and separators = ",;"
and brackets = "()[]{}"
and symbs = "\\!@#$%^&*-+|\\<=>/?~.:"
and alphas = "'abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ"
and nums = "0123456789" in
let allchars = spaces^separators^brackets^symbs^alphas^nums in
let csetsize = itlist (max o charcode) (explode allchars) 256 in
let ctable = Array.make csetsize 0 in
do_list (fun c -> Array.set ctable (charcode c) 1) (explode spaces);
do_list (fun c -> Array.set ctable (charcode c) 2) (explode separators);
do_list (fun c -> Array.set ctable (charcode c) 4) (explode brackets);
do_list (fun c -> Array.set ctable (charcode c) 8) (explode symbs);
do_list (fun c -> Array.set ctable (charcode c) 16) (explode alphas);
do_list (fun c -> Array.set ctable (charcode c) 32) (explode nums);
let isspace c = Array.get ctable (charcode c) = 1
and issep c = Array.get ctable (charcode c) = 2
and isbra c = Array.get ctable (charcode c) = 4
and issymb c = Array.get ctable (charcode c) = 8
and isalpha c = Array.get ctable (charcode c) = 16
and isnum c = Array.get ctable (charcode c) = 32
and isalnum c = Array.get ctable (charcode c) >= 16 in
isspace,issep,isbra,issymb,isalpha,isnum,isalnum;;
let reserve_words,unreserve_words,is_reserved_word,reserved_words =
let reswords = ref ["("; ")"; "["; "]"; "{"; "}";
":"; ";"; "."; "|";
"let"; "in"; "and"; "if"; "then"; "else";
"match"; "with"; "function"; "->"; "when"] in
(fun ns -> reswords := union (!reswords) ns),
(fun ns -> reswords := subtract (!reswords) ns),
(fun n -> mem n (!reswords)),
(fun () -> !reswords);;
let unparse_as_binder,parse_as_binder,parses_as_binder,binders =
let binder_list = ref ([]:string list) in
(fun n -> binder_list := subtract (!binder_list) [n]),
(fun n -> binder_list := union (!binder_list) [n]),
(fun n -> mem n (!binder_list)),
(fun () -> !binder_list);;
let unparse_as_prefix,parse_as_prefix,is_prefix,prefixes =
let prefix_list = ref ([]:string list) in
(fun n -> prefix_list := subtract (!prefix_list) [n]),
(fun n -> prefix_list := union (!prefix_list) [n]),
(fun n -> mem n (!prefix_list)),
(fun () -> !prefix_list);;
let unparse_as_infix,parse_as_infix,get_infix_status,infixes =
let cmp (s,(x,a)) (t,(y,b)) =
x < y || x = y && a > b || x = y && a = b && s < t in
let infix_list = ref ([]:(string * (int * string)) list) in
(fun n -> infix_list := filter (((<>) n) o fst) (!infix_list)),
(fun (n,d) -> infix_list := sort cmp
((n,d)::(filter (((<>) n) o fst) (!infix_list)))),
(fun n -> assoc n (!infix_list)),
(fun () -> !infix_list);;
Interface mapping .
let the_interface = ref ([] :(string * (string * hol_type)) list);;
let the_overload_skeletons = ref ([] : (string * hol_type) list);;
include Format;;
set_max_boxes 100;;
let reverse_interface_mapping = ref true;;
let unspaced_binops = ref [","; ".."; "$"];;
let prebroken_binops = ref ["==>"];;
Force explicit indications of bound variables in set abstractions .
let print_unambiguous_comprehensions = ref false;;
Print the universal set UNIV : A->bool as " (: A ) " .
let typify_universal_set = ref true;;
let print_all_thm = ref true;;
let name_of tm =
match tm with
Var(x,ty) | Const(x,ty) -> x
| _ -> "";;
let pp_print_type,pp_print_qtype =
let soc sep flag ss =
if ss = [] then "" else
let s = end_itlist (fun s1 s2 -> s1^sep^s2) ss in
if flag then "("^s^")" else s in
let rec sot pr ty =
try dest_vartype ty with Failure _ ->
try string_of_num(dest_finty ty) with Failure _ ->
match dest_type ty with
con,[] -> con
| "fun",[ty1;ty2] -> soc "->" (pr > 0) [sot 1 ty1; sot 0 ty2]
| "sum",[ty1;ty2] -> soc "+" (pr > 2) [sot 3 ty1; sot 2 ty2]
| "prod",[ty1;ty2] -> soc "#" (pr > 4) [sot 5 ty1; sot 4 ty2]
| "cart",[ty1;ty2] -> soc "^" (pr > 6) [sot 6 ty1; sot 7 ty2]
| con,args -> (soc "," true (map (sot 0) args))^con in
(fun fmt ty -> pp_print_string fmt (sot 0 ty)),
(fun fmt ty -> pp_print_string fmt ("`:" ^ sot 0 ty ^ "`"));;
Allow the installation of user printers . Must fail quickly if N / A.
let install_user_printer,delete_user_printer,try_user_printer =
let user_printers = ref ([]:(string*(formatter->term->unit))list) in
(fun pr -> user_printers := pr::(!user_printers)),
(fun s -> user_printers := snd(remove (fun (s',_) -> s = s')
(!user_printers))),
(fun fmt -> fun tm -> tryfind (fun (_,pr) -> pr fmt tm) (!user_printers));;
let pp_print_term =
let reverse_interface (s0,ty0) =
if not(!reverse_interface_mapping) then s0 else
try fst(find (fun (s,(s',ty)) -> s' = s0 && can (type_match ty ty0) [])
(!the_interface))
with Failure _ -> s0 in
let DEST_BINARY c tm =
try let il,r = dest_comb tm in
let i,l = dest_comb il in
if i = c ||
(is_const i && is_const c &&
reverse_interface(dest_const i) = reverse_interface(dest_const c))
then l,r else fail()
with Failure _ -> failwith "DEST_BINARY"
and ARIGHT s =
match snd(get_infix_status s) with
"right" -> true | _ -> false in
let rec powerof10 n =
if abs_num n </ Int 1 then false
else if n =/ Int 1 then true
else powerof10 (n // Int 10) in
let bool_of_term t =
match t with
Const("T",_) -> true
| Const("F",_) -> false
| _ -> failwith "bool_of_term" in
let code_of_term t =
let f,tms = strip_comb t in
if not(is_const f && fst(dest_const f) = "ASCII")
|| not(length tms = 8) then failwith "code_of_term"
else
itlist (fun b f -> if b then 1 + 2 * f else 2 * f)
(map bool_of_term (rev tms)) 0 in
let rec dest_clause tm =
let pbod = snd(strip_exists(body(body tm))) in
let s,args = strip_comb pbod in
if name_of s = "_UNGUARDED_PATTERN" && length args = 2 then
[rand(rator(hd args));rand(rator(hd(tl args)))]
else if name_of s = "_GUARDED_PATTERN" && length args = 3 then
[rand(rator(hd args)); hd(tl args); rand(rator(hd(tl(tl args))))]
else failwith "dest_clause" in
let rec dest_clauses tm =
let s,args = strip_comb tm in
if name_of s = "_SEQPATTERN" && length args = 2 then
dest_clause (hd args)::dest_clauses(hd(tl args))
else [dest_clause tm] in
let pp_numeral fmt tm =
let s = string_of_num (dest_numeral tm) in
let n = String.length s in
let rec pp_digit i =
let c = String.get s i in
let () = Format.pp_print_char fmt c in
let i = i + 1 in
if i = n then () else
let () = Format.pp_print_cut fmt () in
pp_digit i in
let () = Format.pp_open_box fmt 0 in
let () = pp_digit 0 in
let () = Format.pp_close_box fmt () in
() in
let pdest_cond tm =
match tm with
Comb(Comb(Comb(Const("COND",_),i),t),e) -> (i,t),e
| _ -> failwith "pdest_cond" in
fun fmt ->
let rec print_term prec tm =
try try_user_printer fmt tm with Failure _ ->
try pp_numeral fmt tm with Failure _ ->
try (let tms = dest_list tm in
try if fst(dest_type(hd(snd(dest_type(type_of tm))))) <> "char"
then fail() else
let ccs = map (String.make 1 o Char.chr o code_of_term) tms in
let s = "\"" ^ String.escaped (implode ccs) ^ "\"" in
pp_print_string fmt s
with Failure _ ->
pp_open_box fmt 0; pp_print_string fmt "[";
pp_open_box fmt 0; print_term_sequence true ";" 0 tms;
pp_close_box fmt (); pp_print_string fmt "]";
pp_close_box fmt ())
with Failure _ ->
if is_gabs tm then print_binder prec tm else
let hop,args = strip_comb tm in
let s0 = name_of hop
and ty0 = type_of hop in
let s = reverse_interface (s0,ty0) in
try if s = "EMPTY" && is_const tm && args = [] then
pp_print_string fmt "{}" else fail()
with Failure _ ->
try if s = "UNIV" && !typify_universal_set && is_const tm && args = []
then
let ty = fst(dest_fun_ty(type_of tm)) in
(pp_print_string fmt "(:";
pp_print_type fmt ty;
pp_print_string fmt ")")
else fail()
with Failure _ ->
try if s <> "INSERT" then fail() else
let mems,oth = splitlist (dest_binary "INSERT") tm in
if is_const oth && fst(dest_const oth) = "EMPTY" then
(pp_open_box fmt 0; pp_print_string fmt "{"; pp_open_box fmt 0;
print_term_sequence true "," 14 mems;
pp_close_box fmt (); pp_print_string fmt "}"; pp_close_box fmt ())
else fail()
with Failure _ ->
try if not (s = "GSPEC") then fail() else
let evs,bod = strip_exists(body(rand tm)) in
let bod1,babs = dest_comb bod in
let bod2,bod3 = dest_comb bod1 in
if fst (dest_const bod2) <> "/\\" then fail() else
let bod4,fabs = dest_comb bod3 in
let bod5,bod6 = dest_comb bod4 in
if fst (dest_const bod5) <> "=" then fail() else
pp_print_string fmt "{";
print_term 0 fabs;
pp_print_string fmt " | ";
(let fvs = frees fabs and bvs = frees babs in
if not(!print_unambiguous_comprehensions) &&
set_eq evs
(if (length fvs <= 1 || bvs = []) then fvs
else intersect fvs bvs)
then ()
else (print_term_sequence false "," 14 evs;
pp_print_string fmt " | "));
print_term 0 babs;
pp_print_string fmt "}"
with Failure _ ->
try let eqs,bod = dest_let tm in
(if prec = 0 then pp_open_hvbox fmt 0
else (pp_open_hvbox fmt 1; pp_print_string fmt "(");
pp_print_string fmt "let ";
print_term 0 (mk_eq(hd eqs));
do_list (fun (v,t) -> pp_print_break fmt 1 0;
pp_print_string fmt "and ";
print_term 0 (mk_eq(v,t)))
(tl eqs);
pp_print_string fmt " in";
pp_print_break fmt 1 0;
print_term 0 bod;
if prec = 0 then () else pp_print_string fmt ")";
pp_close_box fmt ())
with Failure _ -> try
if s <> "DECIMAL" then fail() else
let n_num = dest_numeral (hd args)
and n_den = dest_numeral (hd(tl args)) in
if not(powerof10 n_den) then fail() else
let s_num = string_of_num(quo_num n_num n_den) in
let s_den = implode(tl(explode(string_of_num
(n_den +/ (mod_num n_num n_den))))) in
pp_print_string fmt
("#"^s_num^(if n_den = Int 1 then "" else ".")^s_den)
with Failure _ -> try
if s <> "_MATCH" || length args <> 2 then failwith "" else
let cls = dest_clauses(hd(tl args)) in
(if prec = 0 then () else pp_print_string fmt "(";
pp_open_hvbox fmt 0;
pp_print_string fmt "match ";
print_term 0 (hd args);
pp_print_string fmt " with";
pp_print_break fmt 1 2;
print_clauses cls;
pp_close_box fmt ();
if prec = 0 then () else pp_print_string fmt ")")
with Failure _ -> try
if s <> "_FUNCTION" || length args <> 1 then failwith "" else
let cls = dest_clauses(hd args) in
(if prec = 0 then () else pp_print_string fmt "(";
pp_open_hvbox fmt 0;
pp_print_string fmt "function";
pp_print_break fmt 1 2;
print_clauses cls;
pp_close_box fmt ();
if prec = 0 then () else pp_print_string fmt ")")
with Failure _ ->
if s = "COND" && length args = 3 then
((if prec = 0 then () else pp_print_string fmt "(");
pp_open_hvbox fmt (-1);
(let ccls,ecl = splitlist pdest_cond tm in
if length ccls <= 4 then
(pp_print_string fmt "if ";
print_term 0 (hd args);
pp_print_break fmt 0 0;
pp_print_string fmt " then ";
print_term 0 (hd(tl args));
pp_print_break fmt 0 0;
pp_print_string fmt " else ";
print_term 0 (hd(tl(tl args)))
)
else
(pp_print_string fmt "if ";
print_term 0 (fst(hd ccls));
pp_print_string fmt " then ";
print_term 0 (snd(hd ccls));
pp_print_break fmt 0 0;
do_list (fun (i,t) ->
pp_print_string fmt " else if ";
print_term 0 i;
pp_print_string fmt " then ";
print_term 0 t;
pp_print_break fmt 0 0) (tl ccls);
pp_print_string fmt " else ";
print_term 0 ecl));
pp_close_box fmt ();
(if prec = 0 then () else pp_print_string fmt ")"))
else if is_prefix s && length args = 1 then
(if prec = 1000 then pp_print_string fmt "(" else ();
pp_print_string fmt s;
(if isalnum s ||
s = "--" &&
length args = 1 &&
(try let l,r = dest_comb(hd args) in
let s0 = name_of l and ty0 = type_of l in
reverse_interface (s0,ty0) = "--" ||
mem (fst(dest_const l)) ["real_of_num"; "int_of_num"]
with Failure _ -> false) ||
s = "~" && length args = 1 && is_neg(hd args)
then pp_print_string fmt " " else ());
print_term 999 (hd args);
if prec = 1000 then pp_print_string fmt ")" else ())
else if parses_as_binder s && length args = 1 && is_gabs (hd args) then
print_binder prec tm
else if can get_infix_status s && length args = 2 then
let bargs =
if ARIGHT s then
let tms,tmt = splitlist (DEST_BINARY hop) tm in tms@[tmt]
else
let tmt,tms = rev_splitlist (DEST_BINARY hop) tm in tmt::tms in
let newprec = fst(get_infix_status s) in
(if newprec <= prec then
(pp_open_hvbox fmt 1; pp_print_string fmt "(")
else pp_open_hvbox fmt 0;
print_term newprec (hd bargs);
do_list (fun x -> if mem s (!unspaced_binops) then ()
else if mem s (!prebroken_binops)
then pp_print_break fmt 1 0
else pp_print_string fmt " ";
pp_print_string fmt s;
if mem s (!unspaced_binops)
then pp_print_break fmt 0 0
else if mem s (!prebroken_binops)
then pp_print_string fmt " "
else pp_print_break fmt 1 0;
print_term newprec x) (tl bargs);
if newprec <= prec then pp_print_string fmt ")" else ();
pp_close_box fmt ())
else if (is_const hop || is_var hop) && args = [] then
let s' = if parses_as_binder s || can get_infix_status s || is_prefix s
then "("^s^")" else s in
pp_print_string fmt s'
else
let l,r = dest_comb tm in
(pp_open_hvbox fmt 0;
if prec = 1000 then pp_print_string fmt "(" else ();
print_term 999 l;
(if try mem (fst(dest_const l)) ["real_of_num"; "int_of_num"]
with Failure _ -> false
then () else pp_print_space fmt ());
print_term 1000 r;
if prec = 1000 then pp_print_string fmt ")" else ();
pp_close_box fmt ())
and print_term_sequence break sep prec tms =
if tms = [] then () else
(print_term prec (hd tms);
let ttms = tl tms in
if ttms = [] then () else
(pp_print_string fmt sep;
(if break then pp_print_space fmt ());
print_term_sequence break sep prec ttms))
and print_binder prec tm =
let absf = is_gabs tm in
let s = if absf then "\\" else name_of(rator tm) in
let rec collectvs tm =
if absf then
if is_abs tm then
let v,t = dest_abs tm in
let vs,bod = collectvs t in (false,v)::vs,bod
else if is_gabs tm then
let v,t = dest_gabs tm in
let vs,bod = collectvs t in (true,v)::vs,bod
else [],tm
else if is_comb tm && name_of(rator tm) = s then
if is_abs(rand tm) then
let v,t = dest_abs(rand tm) in
let vs,bod = collectvs t in (false,v)::vs,bod
else if is_gabs(rand tm) then
let v,t = dest_gabs(rand tm) in
let vs,bod = collectvs t in (true,v)::vs,bod
else [],tm
else [],tm in
let vs,bod = collectvs tm in
((if prec = 0 then pp_open_hvbox fmt 4
else (pp_open_hvbox fmt 5; pp_print_string fmt "("));
pp_print_string fmt s;
(if isalnum s then pp_print_string fmt " " else ());
do_list (fun (b,x) ->
(if b then pp_print_string fmt "(" else ());
print_term 0 x;
(if b then pp_print_string fmt ")" else ());
pp_print_string fmt " ") (butlast vs);
(if fst(last vs) then pp_print_string fmt "(" else ());
print_term 0 (snd(last vs));
(if fst(last vs) then pp_print_string fmt ")" else ());
pp_print_string fmt ".";
(if length vs = 1 then pp_print_string fmt " "
else pp_print_space fmt ());
print_term 0 bod;
(if prec = 0 then () else pp_print_string fmt ")");
pp_close_box fmt ())
and print_clauses cls =
match cls with
[c] -> print_clause c
| c::cs -> (print_clause c;
pp_print_break fmt 1 0;
pp_print_string fmt "| ";
print_clauses cs)
and print_clause cl =
match cl with
[p;g;r] -> (print_term 1 p;
pp_print_string fmt " when ";
print_term 1 g;
pp_print_string fmt " -> ";
print_term 1 r)
| [p;r] -> (print_term 1 p;
pp_print_string fmt " -> ";
print_term 1 r)
in print_term 0;;
let pp_print_qterm fmt tm =
pp_print_string fmt "`";
pp_print_term fmt tm;
pp_print_string fmt "`";;
let pp_print_sequent fmt seq =
let (asl,tm) = Sequent.dest seq in
(if not (asl = []) then
(if !print_all_thm then
(pp_print_term fmt (hd asl);
do_list (fun x -> pp_print_string fmt ",";
pp_print_space fmt ();
pp_print_term fmt x)
(tl asl))
else pp_print_string fmt "...";
pp_print_space fmt ())
else ();
pp_open_hbox fmt();
pp_print_string fmt "|- ";
pp_print_term fmt tm;
pp_close_box fmt ());;
let pp_print_thm fmt th = pp_print_sequent fmt (Sequent.from_thm th);;
let print_type = pp_print_type std_formatter;;
let print_qtype = pp_print_qtype std_formatter;;
let print_term = pp_print_term std_formatter;;
let print_qterm = pp_print_qterm std_formatter;;
let print_thm = pp_print_thm std_formatter;;
let print_sequent = pp_print_sequent std_formatter;;
#install_printer pp_print_qtype;;
#install_printer pp_print_qterm;;
#install_printer pp_print_thm;;
#install_printer pp_print_sequent;;
let print_to_string printer =
let buf = Buffer.create 16 in
let fmt = formatter_of_buffer buf in
let () = pp_set_max_boxes fmt 100 in
let print = printer fmt in
let flush = pp_print_flush fmt in
fun x ->
let () = pp_set_margin fmt (get_margin ()) in
let () = print x in
let () = flush () in
let s = Buffer.contents buf in
let () = Buffer.reset buf in
s;;
let string_of_type = print_to_string pp_print_type;;
let string_of_term = print_to_string pp_print_term;;
let string_of_thm = print_to_string pp_print_thm;;
let string_of_sequent = print_to_string pp_print_sequent;;
Sequent.install_to_string string_of_sequent;;
|
f3f700fbbcbb60d24bec837fe42aacade8bef22fa54f8c0f7676bff37cf822e9 | unnohideyuki/bunny | sample210.hs | a `myeq` b = case (a, b) of
(LT, LT) -> True
(EQ, EQ) -> True
(GT, GT) -> True
(_ , _ ) -> False
main = do print $ LT `myeq` LT
print $ EQ `myeq` GT
| null | https://raw.githubusercontent.com/unnohideyuki/bunny/501856ff48f14b252b674585f25a2bf3801cb185/compiler/test/samples/sample210.hs | haskell | a `myeq` b = case (a, b) of
(LT, LT) -> True
(EQ, EQ) -> True
(GT, GT) -> True
(_ , _ ) -> False
main = do print $ LT `myeq` LT
print $ EQ `myeq` GT
| |
46d4003a756563a5837b339c8b0ebaf9d5d89e37078ce57dce16dd13652916b5 | janestreet/toplevel_expect_test | toplevel_expect_test_types.mli | module Chunk : sig
type t =
{ ocaml_code : string
; toplevel_response : string
}
[@@deriving sexp]
end
module Part : sig
type t =
{ name : string
; chunks : Chunk.t list
}
[@@deriving sexp]
end
module Document : sig
type t =
{ parts : Part.t list
; matched : bool (** Whether the actual output matched the expectations *)
}
[@@deriving sexp]
end
| null | https://raw.githubusercontent.com/janestreet/toplevel_expect_test/b30b2ced87ab3742942f6e5aedfe2b243c80e10d/types/toplevel_expect_test_types.mli | ocaml | * Whether the actual output matched the expectations | module Chunk : sig
type t =
{ ocaml_code : string
; toplevel_response : string
}
[@@deriving sexp]
end
module Part : sig
type t =
{ name : string
; chunks : Chunk.t list
}
[@@deriving sexp]
end
module Document : sig
type t =
{ parts : Part.t list
}
[@@deriving sexp]
end
|
867b75b28599370119b3de9d85bb0729039a32a5834d3f5af58f3c3912ff31d5 | esengie/fpl-exploration-tool | Infer.hs | module CodeGen.Infer (
genInfer
) where
import Control.Monad.Reader
import Control.Monad.State
import Control.Monad.Except (throwError, lift)
import Language.Haskell.Exts.Simple
import Control.Lens
import Debug.Trace
import qualified Data.Set as Set
import qualified Data.Map as Map
import SortCheck
import AST hiding (Var, name)
import qualified AST(Term(Var))
import AST.Axiom hiding (name)
import CodeGen.Common
import CodeGen.MonadInstance (funToPat)
import CodeGen.RightSide.Infer (buildRightInfer)
import CodeGen.RightSide.Helpers (tmAlias)
--------------------------------------------------------------------------
fsymLeft :: FunctionalSymbol -> [Pat]
fsymLeft f = [PVar (Ident "ctx"), funToPat f]
fsymLeftAlias :: FunctionalSymbol -> [Pat]
fsymLeftAlias f = [PVar (Ident "ctx"), PAsPat tmAlias $ funToPat f]
errStarStar :: String -> Exp
errStarStar str = App (Var (UnQual (Ident "report"))) (Lit (String str))
genInfer :: GenM ()
genInfer = do
st <- ask
--- Var work
let varL = fsymLeft (FunSym "Var" [varSort] varSort)
let varR = app (var $ name "ctx") (var $ name $ vars !! 0)
------
--- Errors of type ty(*) = *
let sortsL = (\x -> fsymLeft $ FunSym (sortToTyCtor x) [] varSort) <$> sortsWO_tm st
let sortsR = (errStarStar . sortToTyCtor) <$> sortsWO_tm st
------
let fsyms = Map.elems (st^.SortCheck.funSyms)
let fLeft = fsymLeftAlias <$> fsyms
-- We've checked our lang, can unJust
let fRight' = (\f -> buildRightInfer (st^.SortCheck.funSyms)
f
$ (unJust . funToAx st) f)
<$> fsyms
fRight <- lift . lift $ sequence fRight'
--- Gather and build a resulting function
let res = funDecl "infer" (varL : sortsL ++ fLeft) (varR : sortsR ++ fRight)
replaceDecls "infer" [res]
---
| null | https://raw.githubusercontent.com/esengie/fpl-exploration-tool/bf655e65d215da4d7cae703dda7a7fde1a180b43/src/langGenerator/CodeGen/Infer.hs | haskell | ------------------------------------------------------------------------
- Var work
----
- Errors of type ty(*) = *
----
We've checked our lang, can unJust
- Gather and build a resulting function
- | module CodeGen.Infer (
genInfer
) where
import Control.Monad.Reader
import Control.Monad.State
import Control.Monad.Except (throwError, lift)
import Language.Haskell.Exts.Simple
import Control.Lens
import Debug.Trace
import qualified Data.Set as Set
import qualified Data.Map as Map
import SortCheck
import AST hiding (Var, name)
import qualified AST(Term(Var))
import AST.Axiom hiding (name)
import CodeGen.Common
import CodeGen.MonadInstance (funToPat)
import CodeGen.RightSide.Infer (buildRightInfer)
import CodeGen.RightSide.Helpers (tmAlias)
fsymLeft :: FunctionalSymbol -> [Pat]
fsymLeft f = [PVar (Ident "ctx"), funToPat f]
fsymLeftAlias :: FunctionalSymbol -> [Pat]
fsymLeftAlias f = [PVar (Ident "ctx"), PAsPat tmAlias $ funToPat f]
errStarStar :: String -> Exp
errStarStar str = App (Var (UnQual (Ident "report"))) (Lit (String str))
genInfer :: GenM ()
genInfer = do
st <- ask
let varL = fsymLeft (FunSym "Var" [varSort] varSort)
let varR = app (var $ name "ctx") (var $ name $ vars !! 0)
let sortsL = (\x -> fsymLeft $ FunSym (sortToTyCtor x) [] varSort) <$> sortsWO_tm st
let sortsR = (errStarStar . sortToTyCtor) <$> sortsWO_tm st
let fsyms = Map.elems (st^.SortCheck.funSyms)
let fLeft = fsymLeftAlias <$> fsyms
let fRight' = (\f -> buildRightInfer (st^.SortCheck.funSyms)
f
$ (unJust . funToAx st) f)
<$> fsyms
fRight <- lift . lift $ sequence fRight'
let res = funDecl "infer" (varL : sortsL ++ fLeft) (varR : sortsR ++ fRight)
replaceDecls "infer" [res]
|
4d6ee5eca62b5b5c0ab49b03e2f326ce6aad376eade5823a65ce8f7f710f777e | charlieg/Sparser | percentages1.lisp | ;;; -*- Mode:LISP; Syntax:Common-Lisp; Package:(SPARSER LISP) -*-
copyright ( c ) 1992 - 1998 -- all rights reserved
;;;
;;; File: "percentages"
;;; Module: "grammar;model:core:numbers:"
Version : 1.3 July 1998
1.1 ( 7/16/92 v2.3 ) pilot instances of the new representation regime
1.2 ( 1/10/94 ) stubbed measurement to get around load - order paradox
( ) added string printer
1.3 ( 7/5/98 ) redone with a schematic realization .
(in-package :sparser)
;; referenced by percent before it's loaded itself, so we supply a stub
(define-category measurement
:specializes nil)
;;;--------
;;; object
;;;--------
(define-category percent
:instantiates :self
:specializes measurement
:binds ((number . number))
:index (:temporary :list)
:realization (:tree-family item+idiomatic-head
:mapping ((np . :self)
(np-head . ("percent" "%"))
(modifier . number)
(result-type . :self)
(item . number))))
(defun string/percent (p)
(format nil "~A%" (string-for (value-of 'number p))))
| null | https://raw.githubusercontent.com/charlieg/Sparser/b9bb7d01d2e40f783f3214fc104062db3d15e608/Sparser/code/s/grammar/model/core/numbers/percentages1.lisp | lisp | -*- Mode:LISP; Syntax:Common-Lisp; Package:(SPARSER LISP) -*-
File: "percentages"
Module: "grammar;model:core:numbers:"
referenced by percent before it's loaded itself, so we supply a stub
--------
object
-------- | copyright ( c ) 1992 - 1998 -- all rights reserved
Version : 1.3 July 1998
1.1 ( 7/16/92 v2.3 ) pilot instances of the new representation regime
1.2 ( 1/10/94 ) stubbed measurement to get around load - order paradox
( ) added string printer
1.3 ( 7/5/98 ) redone with a schematic realization .
(in-package :sparser)
(define-category measurement
:specializes nil)
(define-category percent
:instantiates :self
:specializes measurement
:binds ((number . number))
:index (:temporary :list)
:realization (:tree-family item+idiomatic-head
:mapping ((np . :self)
(np-head . ("percent" "%"))
(modifier . number)
(result-type . :self)
(item . number))))
(defun string/percent (p)
(format nil "~A%" (string-for (value-of 'number p))))
|
42c8bf4ad81c9240763d51896d42597892e18777739c46a07e8b49d767a136ec | hexlet-codebattle/battle_asserts | check_phone_number.clj | (ns battle-asserts.issues.check-phone-number
(:require [clojure.test.check.generators :as gen]
[clojure.string :as s]))
(def level :medium)
(def tags ["strings"])
(def description
{:en "Write a function to validate some strings that could potentially represent phone numbers."
:ru "Напишите функцию, которая валидирует строку и проверяет, может ли она быть телефонным номером."})
(def signature
{:input [{:argument-name "candidate" :type {:name "string"}}]
:output {:type {:name "boolean"}}})
(defn- gen-phone-part []
(let [numbers (s/join #"" (gen/sample (gen/choose 1 9) (gen/generate (gen/choose 2 3))))
updated (rand-nth [numbers (s/join #"" [numbers (gen/generate gen/char-ascii)])])
final (rand-nth [updated (str "(" updated ")")])]
[numbers updated final]))
(defn- gen-phone-number []
(let [first-part (rand-nth (gen-phone-part))
second-part (rand-nth (gen-phone-part))
third-part (rand-nth (gen-phone-part))
combined-parts [first-part second-part third-part]
result (rand-nth [(s/join #" " combined-parts)
(s/join #"" combined-parts)
(s/join #"-" combined-parts)])]
result))
(defn arguments-generator []
(let [numbers (repeatedly 40 gen-phone-number)]
(gen/tuple (gen/elements numbers))))
(def test-data
[{:expected true :arguments ["5555555555"]}
{:expected true :arguments ["555555555"]}
{:expected true :arguments ["555-5555"]}
{:expected true :arguments ["(555) 555-5555"]}
{:expected true :arguments ["(555) 555-555"]}
{:expected true :arguments ["(555) 555-555-5555"]}
{:expected false :arguments ["(555) 555a-555-5555"]}
{:expected false :arguments ["555*-555-5555"]}
{:expected false :arguments ["55a-555-5555"]}
{:expected true :arguments ["55-55-55"]}
{:expected true :arguments ["55 55 55"]}])
(defn solution [candidate]
(not (nil?
(re-matches #"^((8|0|((\+|00)\d{1,2}))[\- ]?)?(\(?\d{3}\)?[\- ]?)?[\d\- ]{6,12}$"
candidate))))
| null | https://raw.githubusercontent.com/hexlet-codebattle/battle_asserts/253dfe65e08336818321a19eacd7b8e07516e7d4/src/battle_asserts/issues/check_phone_number.clj | clojure | (ns battle-asserts.issues.check-phone-number
(:require [clojure.test.check.generators :as gen]
[clojure.string :as s]))
(def level :medium)
(def tags ["strings"])
(def description
{:en "Write a function to validate some strings that could potentially represent phone numbers."
:ru "Напишите функцию, которая валидирует строку и проверяет, может ли она быть телефонным номером."})
(def signature
{:input [{:argument-name "candidate" :type {:name "string"}}]
:output {:type {:name "boolean"}}})
(defn- gen-phone-part []
(let [numbers (s/join #"" (gen/sample (gen/choose 1 9) (gen/generate (gen/choose 2 3))))
updated (rand-nth [numbers (s/join #"" [numbers (gen/generate gen/char-ascii)])])
final (rand-nth [updated (str "(" updated ")")])]
[numbers updated final]))
(defn- gen-phone-number []
(let [first-part (rand-nth (gen-phone-part))
second-part (rand-nth (gen-phone-part))
third-part (rand-nth (gen-phone-part))
combined-parts [first-part second-part third-part]
result (rand-nth [(s/join #" " combined-parts)
(s/join #"" combined-parts)
(s/join #"-" combined-parts)])]
result))
(defn arguments-generator []
(let [numbers (repeatedly 40 gen-phone-number)]
(gen/tuple (gen/elements numbers))))
(def test-data
[{:expected true :arguments ["5555555555"]}
{:expected true :arguments ["555555555"]}
{:expected true :arguments ["555-5555"]}
{:expected true :arguments ["(555) 555-5555"]}
{:expected true :arguments ["(555) 555-555"]}
{:expected true :arguments ["(555) 555-555-5555"]}
{:expected false :arguments ["(555) 555a-555-5555"]}
{:expected false :arguments ["555*-555-5555"]}
{:expected false :arguments ["55a-555-5555"]}
{:expected true :arguments ["55-55-55"]}
{:expected true :arguments ["55 55 55"]}])
(defn solution [candidate]
(not (nil?
(re-matches #"^((8|0|((\+|00)\d{1,2}))[\- ]?)?(\(?\d{3}\)?[\- ]?)?[\d\- ]{6,12}$"
candidate))))
| |
02ba38a17b29294b57c60843a2caffe364c704c2812485511871aa40615e87e6 | anmonteiro/lumo | build_api_tests.cljs | (ns ^{:doc "For importing a new test make sure that:
- you get rid of all the io/file, in lumo you can pass the string path directly
- you transform .getAbsolutePath to path/resolve
- you transform .delete to fs/unlinkSync"}
lumo.build-api-tests
(:require-macros [cljs.env.macros :as env]
[cljs.analyzer.macros :as ana])
(:require [clojure.test :as t :refer [deftest is testing async use-fixtures]]
[clojure.string :as string]
[cljs.env :as env]
[cljs.analyzer :as ana]
[lumo.io :refer [spit slurp]]
[lumo.test-util :as test]
[lumo.build.api :as build]
[lumo.closure :as closure]
[lumo.util :as util]
child_process
fs
path))
(use-fixtures :once
;; backup and restore package.json cause we are executing these in the lumo
;; folder.
{:before (fn [] (fs/copyFileSync "package.json" "package.json.bak"))
:after (fn [] (fs/copyFileSync "package.json.bak" "package.json"))})
(deftest test-target-file-for-cljs-ns
(is (= (build/target-file-for-cljs-ns 'example.core-lib nil)
(test/platform-path "out/example/core_lib.js")))
(is (= (build/target-file-for-cljs-ns 'example.core-lib "output")
(test/platform-path "output/example/core_lib.js"))))
(deftest test-cljs-dependents-for-macro-namespaces
(env/with-compiler-env (env/default-compiler-env)
(swap! env/*compiler* assoc :cljs.analyzer/namespaces
{ 'example.core
{:require-macros {'example.macros 'example.macros
'mac 'example.macros}
:name 'example.core}
'example.util
{:require-macros {'example.macros 'example.macros
'mac 'example.macros}
:name 'example.util}
'example.helpers
{:require-macros {'example.macros-again 'example.macros-again
'mac 'example.macros-again}
:name 'example.helpers }
'example.fun
{:require-macros nil
:name 'example.fun }})
(is (= (set (build/cljs-dependents-for-macro-namespaces ['example.macros]))
#{'example.core 'example.util}))
(is (= (set (build/cljs-dependents-for-macro-namespaces ['example.macros-again]))
#{'example.helpers}))
(is (= (set (build/cljs-dependents-for-macro-namespaces ['example.macros 'example.macros-again]))
#{'example.core 'example.util 'example.helpers}))
(is (= (set (build/cljs-dependents-for-macro-namespaces ['example.not-macros]))
#{}))))
(def test-cenv (atom {}))
(def test-env (assoc-in (ana/empty-env) [:ns :name] 'cljs.user))
;; basic
(binding [ana/*cljs-ns* 'cljs.user
ana/*analyze-deps* false]
(env/with-compiler-env test-cenv
(ana/no-warn
(ana/analyze test-env
'(ns cljs.user
(:use [clojure.string :only [join]]))))))
;; linear
(binding [ana/*cljs-ns* 'cljs.user
ana/*analyze-deps* false]
(env/with-compiler-env test-cenv
(ana/no-warn
(ana/analyze test-env
'(ns foo.core)))))
(binding [ana/*cljs-ns* 'cljs.user
ana/*analyze-deps* false]
(env/with-compiler-env test-cenv
(ana/no-warn
(ana/analyze test-env
'(ns bar.core
(:require [foo.core :as foo]))))))
(binding [ana/*cljs-ns* 'cljs.user
ana/*analyze-deps* false]
(env/with-compiler-env test-cenv
(ana/no-warn
(ana/analyze test-env
'(ns baz.core
(:require [bar.core :as bar]))))))
;; graph
(binding [ana/*cljs-ns* 'cljs.user
ana/*analyze-deps* false]
(env/with-compiler-env test-cenv
(ana/no-warn
(ana/analyze test-env
'(ns graph.foo.core)))))
(binding [ana/*cljs-ns* 'cljs.user
ana/*analyze-deps* false]
(env/with-compiler-env test-cenv
(ana/no-warn
(ana/analyze test-env
'(ns graph.bar.core
(:require [graph.foo.core :as foo]))))))
(binding [ana/*cljs-ns* 'cljs.user
ana/*analyze-deps* false]
(env/with-compiler-env test-cenv
(ana/no-warn
(ana/analyze test-env
'(ns graph.baz.core
(:require [graph.foo.core :as foo]
[graph.bar.core :as bar]))))))
( deftest cljs-1469
;; (let [out (.getPath (io/file (test/tmp-dir) "loader-test-out"))
;; srcs "samples/hello/src"
;; [common-tmp app-tmp] (mapv #(File/createTempFile % ".js")
;; ["common" "app"])
;; opts {:optimizations :simple
;; :output-dir out
;; :modules {:common {:entries #{"hello.foo.bar"}
;; :output-to (.getAbsolutePath common-tmp)}
;; :app {:entries #{"hello.core"}
;; :output-to (.getAbsolutePath app-tmp)}}}]
;; (test/delete-out-files out)
( common - tmp )
( app - tmp )
( is ( every ? # ( zero ? ( .length % ) ) [ common - tmp app - tmp ] )
;; "The initial files are empty")
;; (build/build srcs opts)
( is ( not ( every ? # ( zero ? ( .length % ) ) [ common - tmp app - tmp ] ) )
;; "The files are not empty after compilation")))
;; (deftest cljs-1500-test-modules
;; (let [out (io/file (test/tmp-dir) "cljs-1500-out")
;; project (test/project-with-modules (str out))
;; modules (-> project :opts :modules)]
;; (test/delete-out-files out)
;; (build/build (build/inputs (:inputs project)) (:opts project))
;; (is (re-find #"Loading modules A and B" (slurp (-> modules :cljs-base :output-to))))
;; (is (re-find #"Module A loaded" (slurp (-> modules :module-a :output-to))))
;; (is (re-find #"Module B loaded" (slurp (-> modules :module-b :output-to))))))
(deftest cljs-1883-test-foreign-libs-use-relative-path
(let [out (path/join (test/tmp-dir) "cljs-1883-out")
root (path/join "src" "test" "cljs_build")
opts {:foreign-libs
[{:file (str (path/join root "thirdparty" "add.js"))
:provides ["thirdparty.add"]}]
:output-dir (str out)
:main 'foreign-libs.core
:target :nodejs}]
(test/delete-out-files out)
(build/build (build/inputs (path/join root "foreign_libs") (path/join root "thirdparty")) opts)
(let [foreign-lib-file (path/join out (-> opts :foreign-libs first :file))]
(is (fs/existsSync foreign-lib-file))
(is (= (->> (fs/readFileSync (path/join out "foreign_libs" "core.js") "utf8")
(re-matches #"[\s\S]*(goog\.require\('thirdparty.add'\);)[\s\S]*")
(second))
"goog.require('thirdparty.add');")))))
(deftest cljs-1537-circular-deps
(let [out (path/join (test/tmp-dir) "cljs-1537-test-out")
root "src/test/cljs_build"]
(test/delete-out-files out)
(try
(build/build
(build/inputs
(path/join root "circular_deps" "a.cljs")
(path/join root "circular_deps" "b.cljs"))
{:main 'circular-deps.a
:optimizations :none
:output-dir out}
(env/default-compiler-env))
(is false)
(catch js/Error error
(is (re-find #"Circular dependency detected circular-deps.b -> circular-deps.a -> circular-deps.b"
(-> error .-cause .-message)))))))
( defn loader - test - project [ output - dir ]
;; {:inputs (str (io/file "src" "test" "cljs_build" "loader_test"))
;; :opts
;; {:output-dir output-dir
;; :optimizations :none
;; :verbose true
;; :foreign-libs [{:file "src/test/cljs_build/loader_test/foreignA.js"
;; :provides ["foreign.a"]}
;; {:file "src/test/cljs_build/loader_test/foreignB.js"
;; :provides ["foreign.b"]
;; :requires ["foreign.a"]}]
;; :modules
;; {:foo
;; {:output-to (str (io/file output-dir "foo.js"))
;; :entries #{'loader-test.foo}}
;; :bar
;; {:output-to (str (io/file output-dir "bar.js"))
;; :entries #{'loader-test.bar}}}}})
;; (deftest cljs-2077-test-loader
;; (let [out (.getPath (io/file (test/tmp-dir) "loader-test-out"))]
;; (test/delete-out-files out)
;; (let [{:keys [inputs opts]} (loader-test-project out)
;; loader (io/file out "cljs" "loader.js")]
;; (build/build (build/inputs inputs) opts)
;; (is (.exists loader))
;; (is (not (nil? (re-find #"[\\/]loader_test[\\/]foo\.js" (slurp loader))))))
;; (test/delete-out-files out)
;; (let [{:keys [inputs opts]} (merge-with merge (loader-test-project out)
;; {:opts {:optimizations :advanced
;; :source-map true}})]
;; (build/build (build/inputs inputs) opts))
;; (testing "string inputs in modules"
;; (test/delete-out-files out)
;; (let [{:keys [inputs opts]} (merge-with merge (loader-test-project out)
;; {:opts {:optimizations :whitespace}})]
;; (build/build (build/inputs inputs) opts)))
( testing " CLJS-2309 foreign libs order preserved "
;; (test/delete-out-files out)
;; (let [{:keys [inputs opts]} (merge-with merge (loader-test-project out)
;; {:opts {:optimizations :advanced}})]
;; (build/build (build/inputs inputs) opts)
;; (is (not (nil? (re-find #"foreignA[\s\S]+foreignB" (slurp (io/file out "foo.js"))))))))))
(deftest test-npm-deps-simple
(let [out (path/join (test/tmp-dir) "npm-deps-simple-test-out")
{:keys [inputs opts]} {:inputs (path/join "src" "test" "cljs_build")
:opts {:main 'npm-deps-test.core
:output-dir out
:optimizations :none
:install-deps true
:npm-deps {:left-pad "1.1.3"}
:foreign-libs [{:module-type :es6
:file "src/test/cljs/es6_dep.js"
:provides ["es6_calc"]}
{:module-type :es6
:file "src/test/cljs/es6_default_hello.js"
:provides ["es6_default_hello"]}]
:closure-warnings {:check-types :off}}}
cenv (env/default-compiler-env)]
(test/delete-out-files out)
(build/build (build/inputs (path/join inputs "npm_deps_test/core.cljs")) opts cenv)
(is (fs/existsSync (path/join out "node_modules/left-pad/index.js")))
(is (contains? (:js-module-index @cenv) "left-pad"))))
(deftest test-npm-deps
(let [cenv (env/default-compiler-env)
out (path/join (test/tmp-dir) "npm-deps-test-out")
{:keys [inputs opts]} {:inputs (path/join "src" "test" "cljs_build")
:opts {:main 'npm-deps-test.string-requires
:output-dir out
:optimizations :none
:install-deps true
:npm-deps {:react "15.6.1"
:react-dom "15.6.1"
:lodash-es "4.17.4"
:lodash "4.17.4"}
:closure-warnings {:check-types :off
:non-standard-jsdoc :off
:parse-error :off}}}]
(test/delete-out-files out)
(testing "mix of symbol & string-based requires"
(test/delete-node-modules)
(build/build (build/inputs (path/join inputs "npm_deps_test/string_requires.cljs")) opts cenv)
(is (fs/existsSync (path/join out "node_modules/react/react.js")))
(is (contains? (:js-module-index @cenv) "react"))
(is (contains? (:js-module-index @cenv) "react-dom/server"))
(is (not (nil? (re-find #"\.\.[\\/]node_modules[\\/]react-dom[\\/]server\.js" (slurp (path/join out "cljs_deps.js")))))))
(testing "builds with string requires are idempotent"
(build/build (build/inputs (path/join inputs "npm_deps_test/string_requires.cljs")) opts cenv)
(is (not (nil? (re-find #"\.\.[\\/]node_modules[\\/]react-dom[\\/]server\.js" (slurp (path/join out "cljs_deps.js")))))))))
(deftest test-preloads
(let [out (path/join (test/tmp-dir) "preloads-test-out")
{:keys [inputs opts]} {:inputs (path/join "src" "test" "cljs")
:opts {:main 'preloads-test.core
:preloads '[preloads-test.preload]
:output-dir out
:optimizations :none
:closure-warnings {:check-types :off}}}
cenv (env/default-compiler-env)]
(test/delete-out-files out)
(build/build
(build/inputs (path/join inputs "preloads_test/core.cljs"))
opts cenv)
(is (fs/existsSync (path/join out "preloads_test/preload.cljs")))
(is (contains? (get-in @cenv [:cljs.analyzer/namespaces 'preloads-test.preload :defs]) 'preload-var))))
(deftest test-libs-cljs-2152
(let [out (path/join (test/tmp-dir) "libs-test-out")
{:keys [inputs opts]} {:inputs (path/join "src" "test" "cljs_build")
:opts {:main 'libs-test.core
:output-dir out
:libs ["src/test/cljs/js_libs"]
:optimizations :none
:closure-warnings {:check-types :off}}}
cenv (env/default-compiler-env)]
(test/delete-out-files out)
(build/build (build/inputs
(path/join inputs "libs_test/core.cljs")
"src/test/cljs/js_libs")
opts cenv)
(is (fs/existsSync (path/join out "tabby.js")))))
(defn collecting-warning-handler [state]
(fn [warning-type env extra]
(when (warning-type ana/*cljs-warnings*)
(when-let [s (ana/error-message warning-type extra)]
(swap! state conj s)))))
(deftest test-emit-node-requires-cljs-2213
(test/delete-node-modules)
(testing "simplest case, require"
(let [ws (atom [])
out (path/join (test/tmp-dir) "emit-node-requires-test-out")
{:keys [inputs opts]} {:inputs (path/join "src" "test" "cljs_build")
:opts {:main 'emit-node-requires-test.core
:output-dir out
:optimizations :none
:target :nodejs
:install-deps true
:npm-deps {:react "15.6.1"
:react-dom "15.6.1"}
:closure-warnings {:check-types :off
:non-standard-jsdoc :off
:parse-error :off}}}
cenv (env/default-compiler-env opts)]
(test/delete-out-files out)
(ana/with-warning-handlers [(collecting-warning-handler ws)]
(build/build (build/inputs (path/join inputs "emit_node_requires_test/core.cljs")) opts cenv))
;; wasn't processed by Closure
(is (not (fs/existsSync (path/join out "node_modules/react/react.js"))))
(is (fs/existsSync (path/join out "emit_node_requires_test/core.js")))
(is (true? (boolean (re-find #"emit_node_requires_test\.core\.node\$module\$react_dom\$server = require\('react-dom/server'\);"
(slurp (path/join out "emit_node_requires_test/core.js"))))))
(is (true? (boolean (re-find #"emit_node_requires_test\.core\.node\$module\$react_dom\$server\.renderToString"
(slurp (path/join out "emit_node_requires_test/core.js"))))))
(is (empty? @ws))))
(testing "Node native modules, CLJS-2218"
(let [ws (atom [])
out (path/join (test/tmp-dir) "emit-node-requires-test-out")
{:keys [inputs opts]} {:inputs (path/join "src" "test" "cljs_build")
:opts {:main 'emit-node-requires-test.native-modules
:output-dir out
:optimizations :none
:target :nodejs
:closure-warnings {:check-types :off}}}
cenv (env/default-compiler-env opts)]
(test/delete-out-files out)
(test/delete-node-modules)
(ana/with-warning-handlers [(collecting-warning-handler ws)]
(build/build (build/inputs (path/join inputs "emit_node_requires_test/native_modules.cljs")) opts cenv))
(is (fs/existsSync (path/join out "emit_node_requires_test/native_modules.js")))
(is (true? (boolean (re-find #"emit_node_requires_test\.native_modules\.node\$module\$path\.isAbsolute"
(slurp (path/join out "emit_node_requires_test/native_modules.js"))))))
(is (empty? @ws)))))
(deftest cljs-test-compilation
(testing "success"
(let [out (path/join (test/tmp-dir) "compilation-test-out")
root "src/test/cljs_build"]
(test/delete-out-files out)
(is (build/build
(path/join root "hello" "world.cljs")
{:main 'hello
:optimizations :none
:output-dir out}
(env/default-compiler-env))
"Successful compilation should return")))
(testing "failure"
(let [out (path/join (test/tmp-dir) "compilation-test-out")
root "src/test/cljs_build"]
(test/delete-out-files out)
(try
(build/build
(path/join root "hello" "broken_world.cljs")
{:main 'hello
:optimizations :none
:output-dir out}
(env/default-compiler-env))
(is false)
(catch js/Error e
(is (some? e) "Failed compilation should throw"))))))
;; (deftest test-emit-global-requires-cljs-2214
;; (testing "simplest case, require"
;; (let [ws (atom [])
;; out (.getPath (io/file (test/tmp-dir) "emit-global-requires-test-out"))
;; {:keys [inputs opts]} {:inputs (str (io/file "src" "test" "cljs_build"))
;; :opts {:main 'emit-node-requires-test.core
;; :output-dir out
;; :optimizations :none
;; ;; Doesn't matter what :file is used here, as long at it exists
;; :foreign-libs [{:file "src/test/cljs_build/thirdparty/add.js"
;; :provides ["react"]
;; :global-exports '{react React}}
;; {:file "src/test/cljs_build/thirdparty/add.js"
;; :provides ["react-dom"]
;; :requires ["react"]
;; :global-exports '{react-dom ReactDOM}}
;; {:file "src/test/cljs_build/thirdparty/add.js"
;; :provides ["react-dom/server"]
;; :requires ["react-dom"]
;; :global-exports '{react-dom/server ReactDOMServer}}]}}
;; cenv (env/default-compiler-env)]
;; (test/delete-out-files out)
( / with - warning - handlers [ ( collecting - warning - handler ws ) ]
( build / build ( build / inputs ( io / file inputs " emit_global_requires_test / core.cljs " ) ) opts ) )
;; (is (.exists (io/file out "emit_global_requires_test/core.js")))
;; (is (true? (boolean (re-find #"emit_global_requires_test\.core\.global\$module\$react_dom\$server = goog\.global\.ReactDOMServer;"
;; (slurp (io/file out "emit_global_requires_test/core.js"))))))
;; (is (true? (boolean (re-find #"emit_global_requires_test\.core\.global\$module\$react_dom\$server\.renderToString"
;; (slurp (io/file out "emit_global_requires_test/core.js"))))))
;; (is (empty? @ws)))))
;; (deftest test-data-readers
;; (let [out (.getPath (io/file (test/tmp-dir) "data-readers-test-out"))
;; {:keys [inputs opts]} {:inputs (str (io/file "src" "test" "cljs"))
;; :opts {:main 'data-readers-test.core
;; :output-dir out
;; :optimizations :none
;; :closure-warnings {:check-types :off}}}
cenv ( env / default - compiler - env ) ]
;; (test/delete-out-files out)
( build / build ( build / inputs ( io / file inputs " data_readers_test " ) ) opts cenv )
( is ( contains ? ( - > @cenv : : / data - readers ) ' test / custom - identity ) ) ) )
;; (deftest test-data-readers-records
;; (let [out (.getPath (io/file (test/tmp-dir) "data-readers-test-records-out"))
;; {:keys [inputs opts]} {:inputs (str (io/file "src" "test" "cljs"))
;; :opts {:main 'data-readers-test.records
;; :output-dir out
;; :optimizations :none
;; :closure-warnings {:check-types :off}}}
cenv ( env / default - compiler - env ) ]
;; (test/delete-out-files out)
( build / build ( build / inputs ( io / file inputs " data_readers_test " ) ) opts cenv )
;; (is (true? (boolean (re-find #"data_readers_test.records.map__GT_Foo\("
;; (slurp (io/file out "data_readers_test" "records.js"))))))))
;; (deftest test-cljs-2249
( let [ out ( io / file ( test / tmp - dir ) " cljs-2249 - out " )
;; root (io/file "src" "test" "cljs_build")
;; opts {:output-dir (str out)
;; :main 'foreign-libs-cljs-2249.core
;; :target :nodejs}]
;; (test/delete-out-files out)
;; (build/build (build/inputs (io/file root "foreign_libs_cljs_2249")) opts)
;; (is (.exists (io/file out "calculator_global.js")))
;; (test/delete-out-files out)
;; (closure/build (build/inputs (io/file root "foreign_libs_cljs_2249")) opts)
;; (is (.exists (io/file out "calculator_global.js")))))
(deftest test-node-modules-cljs-2246
(test/delete-node-modules)
(spit "package.json" (js/JSON.stringify (clj->js {:dependencies {:left-pad "1.1.3"}
:devDependencies {"@cljs-oss/module-deps" "*"}})))
(child_process/execSync (string/join " "
(cond->> ["npm" "--no-package-lock" "install"]
util/windows? (into ["cmd" "/c"]))))
(let [ws (atom [])
out (path/join (test/tmp-dir) "node-modules-opt-test-out")
{:keys [inputs opts]} {:inputs (str (path/join "src" "test" "cljs_build"))
:opts {:main 'node-modules-opt-test.core
:output-dir out
:optimizations :none
:closure-warnings {:check-types :off}}}
cenv (env/default-compiler-env opts)]
(test/delete-out-files out)
(ana/with-warning-handlers [(collecting-warning-handler ws)]
(build/build (build/inputs (path/join inputs "node_modules_opt_test/core.cljs")) opts cenv))
(is (fs/existsSync (path/join out "node_modules/left-pad/index.js")))
(is (contains? (:js-module-index @cenv) "left-pad"))
(is (empty? @ws)))
(fs/unlinkSync "package.json")
(test/delete-node-modules))
(deftest test-deps-api-cljs-2255
(let [out (path/join (test/tmp-dir) "cljs-2255-test-out")]
(test/delete-out-files out)
(test/delete-node-modules)
(spit "package.json" "{}")
(build/install-node-deps! {:left-pad "1.1.3"} {:output-dir out})
(is (fs/existsSync (path/join "node_modules" "left-pad" "package.json")))
(test/delete-out-files out)
(test/delete-node-modules)
(spit "package.json" "{}")
(build/install-node-deps!
{:react "15.6.1"
:react-dom "15.6.1"}
{:output-dir out})
(let [modules (build/get-node-deps '[react "react-dom/server"] {:output-dir out})]
(is (true? (some (fn [module]
(= module {:module-type :es6
:file (path/resolve "node_modules/react/react.js")
:provides ["react"
"react/react.js"
"react/react"]}))
modules)))
(is (true? (some (fn [module]
(= module {:module-type :es6
:file (path/resolve "node_modules/react/lib/React.js")
:provides ["react/lib/React.js" "react/lib/React"]}))
modules)))
(is (true? (some (fn [module]
(= module {:module-type :es6
:file (path/resolve "node_modules/react-dom/server.js")
:provides ["react-dom/server.js" "react-dom/server"]}))
modules))))
(test/delete-out-files out)
(test/delete-node-modules)
(fs/unlinkSync "package.json")))
( deftest test - cljs-2296
( let [ out ( .getPath ( io / file ( test / tmp - dir ) " cljs-2296 - test - out " ) )
;; {:keys [inputs opts]} {:inputs (str (io/file "src" "test" "cljs_build"))
;; :opts {:main 'foreign_libs_dir_test.core
;; :output-dir out
;; :optimizations :none
;; :target :nodejs
;; ;; :file is a directory
;; :foreign-libs [{:file "src/test/cljs_build/foreign-libs-dir"
;; :module-type :commonjs}]}}]
;; (test/delete-out-files out)
;; (build/build (build/inputs (io/file inputs "foreign_libs_dir_test/core.cljs")) opts)
( is ( .exists ( io / file out " src / test / cljs_build / foreign - libs - dir / vendor / lib.js " ) ) )
;; (is (re-find #"goog\.provide\(\"module\$[A-Za-z0-9$_]+?src\$test\$cljs_build\$foreign_libs_dir\$vendor\$lib\"\)"
( slurp ( io / file out " src / test / cljs_build / foreign - libs - dir / vendor / lib.js " ) ) ) ) ) )
;; (deftest cljs-2334-test-foreign-libs-that-are-modules
;; (test/delete-node-modules)
;; (let [out "cljs-2334-out"
;; root (io/file "src" "test" "cljs_build")
;; opts {:foreign-libs
[ { : file ( str ( io / file root " foreign_libs_cljs_2334 " " lib.js " ) )
;; :module-type :es6
: provides [ " " ] } ]
;; :npm-deps {:left-pad "1.1.3"}
;; :install-deps true
;; :output-dir (str out)}]
;; (test/delete-out-files out)
;; (build/build (build/inputs (io/file root "foreign_libs_cljs_2334")) opts)
( let [ foreign - lib - file ( io / file out ( - > opts : foreign - libs first : file ) )
;; index-js (slurp (io/file "cljs-2334-out" "node_modules" "left-pad" "index.js"))]
;; (is (.exists foreign-lib-file))
;; (is (re-find #"module\$.*\$node_modules\$left_pad\$index=" index-js))
;; (is (not (re-find #"module\.exports" index-js)))
;; ;; assert Closure finds and processes the left-pad dep in node_modules
;; ;; if it can't be found the require will be issued to module$left_pad
;; ;; so we assert it's of the form module$path$to$node_modules$left_pad$index
;; (is (re-find #"module\$.*\$node_modules\$left_pad\$index\[\"default\"\]\(42,5,0\)" (slurp foreign-lib-file))))
;; (test/delete-out-files out)
;; (test/delete-node-modules)))
TODO - when module splitting will be available to JS GCC -
;; (deftest cljs-2519-test-cljs-base-entries
;; (let [dir (io/file "src" "test" "cljs_build" "code-split")
;; out (io/file (test/tmp-dir) "cljs-base-entries")
;; opts {:output-dir (str out)
;; :asset-path "/out"
;; :optimizations :none
;; :modules {:a {:entries '#{code.split.a}
;; :output-to (io/file out "a.js")}
;; :b {:entries '#{code.split.b}
;; :output-to (io/file out "b.js")}
;; :c {:entries '#{code.split.c}
;; :output-to (io/file out "c.js")}}}]
;; (test/delete-out-files out)
;; (build/build (build/inputs dir) opts)
;; (testing "Module :cljs-base"
;; (let [content (slurp (io/file out "cljs_base.js"))]
;; (testing "requires code.split.d (used in :b and :c)"
;; (is (test/document-write? content 'code.split.d)))))
;; (testing "Module :a"
;; (let [content (slurp (-> opts :modules :a :output-to))]
;; (testing "requires code.split.a"
;; (is (test/document-write? content 'code.split.a)))
;; (testing "requires cljs.pprint (only used in :a)"
;; (is (test/document-write? content 'cljs.pprint)))))
;; (testing "Module :b"
;; (let [content (slurp (-> opts :modules :b :output-to))]
( testing " requires code.split.b "
( is ( test / document - write ? content ' code.split.b ) ) ) ) )
;; (testing "Module :c"
;; (let [content (slurp (-> opts :modules :c :output-to))]
;; (testing "requires code.split.c"
;; (is (test/document-write? content 'code.split.c)))))))
TODO when --package_json_entry_names will be exposed in JS GCC -
;; (deftest test-cljs-2592
;; (test/delete-node-modules)
;; (spit (io/file "package.json") "{}")
;; (let [cenv (env/default-compiler-env)
;; dir (io/file "src" "test" "cljs_build" "package_json_resolution_test")
;; out (io/file (test/tmp-dir) "package_json_resolution_test")
;; opts {:main 'package-json-resolution-test.core
;; :output-dir (str out)
;; :output-to (str (io/file out "main.js"))
;; :optimizations :none
;; :install-deps true
: npm - deps { : " 1.2.2 "
;; :graphql "0.13.1"}
;; :package-json-resolution :nodejs
;; :closure-warnings {:check-types :off
;; :non-standard-jsdoc :off}}]
;; (test/delete-out-files out)
( build / build ( build / inputs dir ) opts cenv )
;; (testing "processes the iterall index.js"
;; (let [index-js (io/file out "node_modules/iterall/index.js")]
;; (is (.exists index-js))
( is ( contains ? (: js - module - index @cenv ) " iterall " ) )
;; (is (re-find #"goog\.provide\(\"module\$.*\$node_modules\$iterall\$index\"\)" (slurp index-js)))))
;; (testing "processes the graphql index.js"
;; (let [index-js (io/file out "node_modules/graphql/index.js")
;; execution-index-js (io/file out "node_modules/graphql/execution/index.js")
;; ast-from-value-js (io/file out "node_modules/grapqhl/utilities/astFromValue.js")]
;; (is (.exists index-js))
( is ( contains ? (: js - module - index @cenv ) " graphql " ) )
;; (is (re-find #"goog\.provide\(\"module\$.*\$node_modules\$graphql\$index\"\)" (slurp index-js)))))
;; (testing "processes a nested index.js in graphql"
;; (let [nested-index-js (io/file out "node_modules/graphql/execution/index.js")]
;; (is (.exists nested-index-js))
( is ( contains ? (: js - module - index @cenv ) " graphql / execution " ) )
;; (is (re-find #"goog\.provide\(\"module\$.*\$node_modules\$graphql\$execution\$index\"\)" (slurp nested-index-js)))))
;; (testing "processes cross-package imports"
;; (let [ast-from-value-js (io/file out "node_modules/graphql/utilities/astFromValue.js")]
;; (is (.exists ast-from-value-js))
;; (is (re-find #"goog.require\(\"module\$.*\$node_modules\$iterall\$index\"\);" (slurp ast-from-value-js)))))
;; (testing "adds dependencies to cljs_deps.js"
;; (let [deps-js (io/file out "cljs_deps.js")]
;; (is (re-find #"goog\.addDependency\(\"..\/node_modules\/iterall\/index.js\"" (slurp deps-js)))
;; (is (re-find #"goog\.addDependency\(\"..\/node_modules\/graphql\/index.js\"" (slurp deps-js)))
;; (is (re-find #"goog\.addDependency\(\"..\/node_modules\/graphql\/execution/index.js\"" (slurp deps-js)))))
;; (testing "adds the right module names to the core.cljs build output"
;; (let [core-js (io/file out "package_json_resolution_test/core.js")]
( is ( re - find # " goog\.require\('module\$.*\$node_modules\$iterall\$index'\ ) ; " ( slurp core - js ) ) )
( is ( re - find # " module\$.+\$node_modules\$iterall\$index\[\"default\"\]\.isCollection " ( slurp core - js ) ) )
;; (is (re-find #"goog\.require\('module\$.*\$node_modules\$graphql\$index'\);" (slurp core-js)))
;; (is (re-find #"module\$.+\$node_modules\$graphql\$index\[\"default\"\]" (slurp core-js))))))
;; (.delete (io/file "package.json"))
;; (test/delete-node-modules))
| null | https://raw.githubusercontent.com/anmonteiro/lumo/6709c9f1b7b342c8108e6ed6e034e19dc786f00b/src/test/lumo/lumo/build_api_tests.cljs | clojure | backup and restore package.json cause we are executing these in the lumo
folder.
basic
linear
graph
(let [out (.getPath (io/file (test/tmp-dir) "loader-test-out"))
srcs "samples/hello/src"
[common-tmp app-tmp] (mapv #(File/createTempFile % ".js")
["common" "app"])
opts {:optimizations :simple
:output-dir out
:modules {:common {:entries #{"hello.foo.bar"}
:output-to (.getAbsolutePath common-tmp)}
:app {:entries #{"hello.core"}
:output-to (.getAbsolutePath app-tmp)}}}]
(test/delete-out-files out)
"The initial files are empty")
(build/build srcs opts)
"The files are not empty after compilation")))
(deftest cljs-1500-test-modules
(let [out (io/file (test/tmp-dir) "cljs-1500-out")
project (test/project-with-modules (str out))
modules (-> project :opts :modules)]
(test/delete-out-files out)
(build/build (build/inputs (:inputs project)) (:opts project))
(is (re-find #"Loading modules A and B" (slurp (-> modules :cljs-base :output-to))))
(is (re-find #"Module A loaded" (slurp (-> modules :module-a :output-to))))
(is (re-find #"Module B loaded" (slurp (-> modules :module-b :output-to))))))
{:inputs (str (io/file "src" "test" "cljs_build" "loader_test"))
:opts
{:output-dir output-dir
:optimizations :none
:verbose true
:foreign-libs [{:file "src/test/cljs_build/loader_test/foreignA.js"
:provides ["foreign.a"]}
{:file "src/test/cljs_build/loader_test/foreignB.js"
:provides ["foreign.b"]
:requires ["foreign.a"]}]
:modules
{:foo
{:output-to (str (io/file output-dir "foo.js"))
:entries #{'loader-test.foo}}
:bar
{:output-to (str (io/file output-dir "bar.js"))
:entries #{'loader-test.bar}}}}})
(deftest cljs-2077-test-loader
(let [out (.getPath (io/file (test/tmp-dir) "loader-test-out"))]
(test/delete-out-files out)
(let [{:keys [inputs opts]} (loader-test-project out)
loader (io/file out "cljs" "loader.js")]
(build/build (build/inputs inputs) opts)
(is (.exists loader))
(is (not (nil? (re-find #"[\\/]loader_test[\\/]foo\.js" (slurp loader))))))
(test/delete-out-files out)
(let [{:keys [inputs opts]} (merge-with merge (loader-test-project out)
{:opts {:optimizations :advanced
:source-map true}})]
(build/build (build/inputs inputs) opts))
(testing "string inputs in modules"
(test/delete-out-files out)
(let [{:keys [inputs opts]} (merge-with merge (loader-test-project out)
{:opts {:optimizations :whitespace}})]
(build/build (build/inputs inputs) opts)))
(test/delete-out-files out)
(let [{:keys [inputs opts]} (merge-with merge (loader-test-project out)
{:opts {:optimizations :advanced}})]
(build/build (build/inputs inputs) opts)
(is (not (nil? (re-find #"foreignA[\s\S]+foreignB" (slurp (io/file out "foo.js"))))))))))
wasn't processed by Closure
(deftest test-emit-global-requires-cljs-2214
(testing "simplest case, require"
(let [ws (atom [])
out (.getPath (io/file (test/tmp-dir) "emit-global-requires-test-out"))
{:keys [inputs opts]} {:inputs (str (io/file "src" "test" "cljs_build"))
:opts {:main 'emit-node-requires-test.core
:output-dir out
:optimizations :none
;; Doesn't matter what :file is used here, as long at it exists
:foreign-libs [{:file "src/test/cljs_build/thirdparty/add.js"
:provides ["react"]
:global-exports '{react React}}
{:file "src/test/cljs_build/thirdparty/add.js"
:provides ["react-dom"]
:requires ["react"]
:global-exports '{react-dom ReactDOM}}
{:file "src/test/cljs_build/thirdparty/add.js"
:provides ["react-dom/server"]
:requires ["react-dom"]
:global-exports '{react-dom/server ReactDOMServer}}]}}
cenv (env/default-compiler-env)]
(test/delete-out-files out)
(is (.exists (io/file out "emit_global_requires_test/core.js")))
(is (true? (boolean (re-find #"emit_global_requires_test\.core\.global\$module\$react_dom\$server = goog\.global\.ReactDOMServer;"
(slurp (io/file out "emit_global_requires_test/core.js"))))))
(is (true? (boolean (re-find #"emit_global_requires_test\.core\.global\$module\$react_dom\$server\.renderToString"
(slurp (io/file out "emit_global_requires_test/core.js"))))))
(is (empty? @ws)))))
(deftest test-data-readers
(let [out (.getPath (io/file (test/tmp-dir) "data-readers-test-out"))
{:keys [inputs opts]} {:inputs (str (io/file "src" "test" "cljs"))
:opts {:main 'data-readers-test.core
:output-dir out
:optimizations :none
:closure-warnings {:check-types :off}}}
(test/delete-out-files out)
(deftest test-data-readers-records
(let [out (.getPath (io/file (test/tmp-dir) "data-readers-test-records-out"))
{:keys [inputs opts]} {:inputs (str (io/file "src" "test" "cljs"))
:opts {:main 'data-readers-test.records
:output-dir out
:optimizations :none
:closure-warnings {:check-types :off}}}
(test/delete-out-files out)
(is (true? (boolean (re-find #"data_readers_test.records.map__GT_Foo\("
(slurp (io/file out "data_readers_test" "records.js"))))))))
(deftest test-cljs-2249
root (io/file "src" "test" "cljs_build")
opts {:output-dir (str out)
:main 'foreign-libs-cljs-2249.core
:target :nodejs}]
(test/delete-out-files out)
(build/build (build/inputs (io/file root "foreign_libs_cljs_2249")) opts)
(is (.exists (io/file out "calculator_global.js")))
(test/delete-out-files out)
(closure/build (build/inputs (io/file root "foreign_libs_cljs_2249")) opts)
(is (.exists (io/file out "calculator_global.js")))))
{:keys [inputs opts]} {:inputs (str (io/file "src" "test" "cljs_build"))
:opts {:main 'foreign_libs_dir_test.core
:output-dir out
:optimizations :none
:target :nodejs
;; :file is a directory
:foreign-libs [{:file "src/test/cljs_build/foreign-libs-dir"
:module-type :commonjs}]}}]
(test/delete-out-files out)
(build/build (build/inputs (io/file inputs "foreign_libs_dir_test/core.cljs")) opts)
(is (re-find #"goog\.provide\(\"module\$[A-Za-z0-9$_]+?src\$test\$cljs_build\$foreign_libs_dir\$vendor\$lib\"\)"
(deftest cljs-2334-test-foreign-libs-that-are-modules
(test/delete-node-modules)
(let [out "cljs-2334-out"
root (io/file "src" "test" "cljs_build")
opts {:foreign-libs
:module-type :es6
:npm-deps {:left-pad "1.1.3"}
:install-deps true
:output-dir (str out)}]
(test/delete-out-files out)
(build/build (build/inputs (io/file root "foreign_libs_cljs_2334")) opts)
index-js (slurp (io/file "cljs-2334-out" "node_modules" "left-pad" "index.js"))]
(is (.exists foreign-lib-file))
(is (re-find #"module\$.*\$node_modules\$left_pad\$index=" index-js))
(is (not (re-find #"module\.exports" index-js)))
;; assert Closure finds and processes the left-pad dep in node_modules
;; if it can't be found the require will be issued to module$left_pad
;; so we assert it's of the form module$path$to$node_modules$left_pad$index
(is (re-find #"module\$.*\$node_modules\$left_pad\$index\[\"default\"\]\(42,5,0\)" (slurp foreign-lib-file))))
(test/delete-out-files out)
(test/delete-node-modules)))
(deftest cljs-2519-test-cljs-base-entries
(let [dir (io/file "src" "test" "cljs_build" "code-split")
out (io/file (test/tmp-dir) "cljs-base-entries")
opts {:output-dir (str out)
:asset-path "/out"
:optimizations :none
:modules {:a {:entries '#{code.split.a}
:output-to (io/file out "a.js")}
:b {:entries '#{code.split.b}
:output-to (io/file out "b.js")}
:c {:entries '#{code.split.c}
:output-to (io/file out "c.js")}}}]
(test/delete-out-files out)
(build/build (build/inputs dir) opts)
(testing "Module :cljs-base"
(let [content (slurp (io/file out "cljs_base.js"))]
(testing "requires code.split.d (used in :b and :c)"
(is (test/document-write? content 'code.split.d)))))
(testing "Module :a"
(let [content (slurp (-> opts :modules :a :output-to))]
(testing "requires code.split.a"
(is (test/document-write? content 'code.split.a)))
(testing "requires cljs.pprint (only used in :a)"
(is (test/document-write? content 'cljs.pprint)))))
(testing "Module :b"
(let [content (slurp (-> opts :modules :b :output-to))]
(testing "Module :c"
(let [content (slurp (-> opts :modules :c :output-to))]
(testing "requires code.split.c"
(is (test/document-write? content 'code.split.c)))))))
(deftest test-cljs-2592
(test/delete-node-modules)
(spit (io/file "package.json") "{}")
(let [cenv (env/default-compiler-env)
dir (io/file "src" "test" "cljs_build" "package_json_resolution_test")
out (io/file (test/tmp-dir) "package_json_resolution_test")
opts {:main 'package-json-resolution-test.core
:output-dir (str out)
:output-to (str (io/file out "main.js"))
:optimizations :none
:install-deps true
:graphql "0.13.1"}
:package-json-resolution :nodejs
:closure-warnings {:check-types :off
:non-standard-jsdoc :off}}]
(test/delete-out-files out)
(testing "processes the iterall index.js"
(let [index-js (io/file out "node_modules/iterall/index.js")]
(is (.exists index-js))
(is (re-find #"goog\.provide\(\"module\$.*\$node_modules\$iterall\$index\"\)" (slurp index-js)))))
(testing "processes the graphql index.js"
(let [index-js (io/file out "node_modules/graphql/index.js")
execution-index-js (io/file out "node_modules/graphql/execution/index.js")
ast-from-value-js (io/file out "node_modules/grapqhl/utilities/astFromValue.js")]
(is (.exists index-js))
(is (re-find #"goog\.provide\(\"module\$.*\$node_modules\$graphql\$index\"\)" (slurp index-js)))))
(testing "processes a nested index.js in graphql"
(let [nested-index-js (io/file out "node_modules/graphql/execution/index.js")]
(is (.exists nested-index-js))
(is (re-find #"goog\.provide\(\"module\$.*\$node_modules\$graphql\$execution\$index\"\)" (slurp nested-index-js)))))
(testing "processes cross-package imports"
(let [ast-from-value-js (io/file out "node_modules/graphql/utilities/astFromValue.js")]
(is (.exists ast-from-value-js))
(is (re-find #"goog.require\(\"module\$.*\$node_modules\$iterall\$index\"\);" (slurp ast-from-value-js)))))
(testing "adds dependencies to cljs_deps.js"
(let [deps-js (io/file out "cljs_deps.js")]
(is (re-find #"goog\.addDependency\(\"..\/node_modules\/iterall\/index.js\"" (slurp deps-js)))
(is (re-find #"goog\.addDependency\(\"..\/node_modules\/graphql\/index.js\"" (slurp deps-js)))
(is (re-find #"goog\.addDependency\(\"..\/node_modules\/graphql\/execution/index.js\"" (slurp deps-js)))))
(testing "adds the right module names to the core.cljs build output"
(let [core-js (io/file out "package_json_resolution_test/core.js")]
(is (re-find #"goog\.require\('module\$.*\$node_modules\$graphql\$index'\);" (slurp core-js)))
(is (re-find #"module\$.+\$node_modules\$graphql\$index\[\"default\"\]" (slurp core-js))))))
(.delete (io/file "package.json"))
(test/delete-node-modules)) | (ns ^{:doc "For importing a new test make sure that:
- you get rid of all the io/file, in lumo you can pass the string path directly
- you transform .getAbsolutePath to path/resolve
- you transform .delete to fs/unlinkSync"}
lumo.build-api-tests
(:require-macros [cljs.env.macros :as env]
[cljs.analyzer.macros :as ana])
(:require [clojure.test :as t :refer [deftest is testing async use-fixtures]]
[clojure.string :as string]
[cljs.env :as env]
[cljs.analyzer :as ana]
[lumo.io :refer [spit slurp]]
[lumo.test-util :as test]
[lumo.build.api :as build]
[lumo.closure :as closure]
[lumo.util :as util]
child_process
fs
path))
(use-fixtures :once
{:before (fn [] (fs/copyFileSync "package.json" "package.json.bak"))
:after (fn [] (fs/copyFileSync "package.json.bak" "package.json"))})
(deftest test-target-file-for-cljs-ns
(is (= (build/target-file-for-cljs-ns 'example.core-lib nil)
(test/platform-path "out/example/core_lib.js")))
(is (= (build/target-file-for-cljs-ns 'example.core-lib "output")
(test/platform-path "output/example/core_lib.js"))))
(deftest test-cljs-dependents-for-macro-namespaces
(env/with-compiler-env (env/default-compiler-env)
(swap! env/*compiler* assoc :cljs.analyzer/namespaces
{ 'example.core
{:require-macros {'example.macros 'example.macros
'mac 'example.macros}
:name 'example.core}
'example.util
{:require-macros {'example.macros 'example.macros
'mac 'example.macros}
:name 'example.util}
'example.helpers
{:require-macros {'example.macros-again 'example.macros-again
'mac 'example.macros-again}
:name 'example.helpers }
'example.fun
{:require-macros nil
:name 'example.fun }})
(is (= (set (build/cljs-dependents-for-macro-namespaces ['example.macros]))
#{'example.core 'example.util}))
(is (= (set (build/cljs-dependents-for-macro-namespaces ['example.macros-again]))
#{'example.helpers}))
(is (= (set (build/cljs-dependents-for-macro-namespaces ['example.macros 'example.macros-again]))
#{'example.core 'example.util 'example.helpers}))
(is (= (set (build/cljs-dependents-for-macro-namespaces ['example.not-macros]))
#{}))))
(def test-cenv (atom {}))
(def test-env (assoc-in (ana/empty-env) [:ns :name] 'cljs.user))
(binding [ana/*cljs-ns* 'cljs.user
ana/*analyze-deps* false]
(env/with-compiler-env test-cenv
(ana/no-warn
(ana/analyze test-env
'(ns cljs.user
(:use [clojure.string :only [join]]))))))
(binding [ana/*cljs-ns* 'cljs.user
ana/*analyze-deps* false]
(env/with-compiler-env test-cenv
(ana/no-warn
(ana/analyze test-env
'(ns foo.core)))))
(binding [ana/*cljs-ns* 'cljs.user
ana/*analyze-deps* false]
(env/with-compiler-env test-cenv
(ana/no-warn
(ana/analyze test-env
'(ns bar.core
(:require [foo.core :as foo]))))))
(binding [ana/*cljs-ns* 'cljs.user
ana/*analyze-deps* false]
(env/with-compiler-env test-cenv
(ana/no-warn
(ana/analyze test-env
'(ns baz.core
(:require [bar.core :as bar]))))))
(binding [ana/*cljs-ns* 'cljs.user
ana/*analyze-deps* false]
(env/with-compiler-env test-cenv
(ana/no-warn
(ana/analyze test-env
'(ns graph.foo.core)))))
(binding [ana/*cljs-ns* 'cljs.user
ana/*analyze-deps* false]
(env/with-compiler-env test-cenv
(ana/no-warn
(ana/analyze test-env
'(ns graph.bar.core
(:require [graph.foo.core :as foo]))))))
(binding [ana/*cljs-ns* 'cljs.user
ana/*analyze-deps* false]
(env/with-compiler-env test-cenv
(ana/no-warn
(ana/analyze test-env
'(ns graph.baz.core
(:require [graph.foo.core :as foo]
[graph.bar.core :as bar]))))))
( deftest cljs-1469
( common - tmp )
( app - tmp )
( is ( every ? # ( zero ? ( .length % ) ) [ common - tmp app - tmp ] )
( is ( not ( every ? # ( zero ? ( .length % ) ) [ common - tmp app - tmp ] ) )
(deftest cljs-1883-test-foreign-libs-use-relative-path
(let [out (path/join (test/tmp-dir) "cljs-1883-out")
root (path/join "src" "test" "cljs_build")
opts {:foreign-libs
[{:file (str (path/join root "thirdparty" "add.js"))
:provides ["thirdparty.add"]}]
:output-dir (str out)
:main 'foreign-libs.core
:target :nodejs}]
(test/delete-out-files out)
(build/build (build/inputs (path/join root "foreign_libs") (path/join root "thirdparty")) opts)
(let [foreign-lib-file (path/join out (-> opts :foreign-libs first :file))]
(is (fs/existsSync foreign-lib-file))
(is (= (->> (fs/readFileSync (path/join out "foreign_libs" "core.js") "utf8")
(re-matches #"[\s\S]*(goog\.require\('thirdparty.add'\);)[\s\S]*")
(second))
"goog.require('thirdparty.add');")))))
(deftest cljs-1537-circular-deps
(let [out (path/join (test/tmp-dir) "cljs-1537-test-out")
root "src/test/cljs_build"]
(test/delete-out-files out)
(try
(build/build
(build/inputs
(path/join root "circular_deps" "a.cljs")
(path/join root "circular_deps" "b.cljs"))
{:main 'circular-deps.a
:optimizations :none
:output-dir out}
(env/default-compiler-env))
(is false)
(catch js/Error error
(is (re-find #"Circular dependency detected circular-deps.b -> circular-deps.a -> circular-deps.b"
(-> error .-cause .-message)))))))
( defn loader - test - project [ output - dir ]
( testing " CLJS-2309 foreign libs order preserved "
(deftest test-npm-deps-simple
(let [out (path/join (test/tmp-dir) "npm-deps-simple-test-out")
{:keys [inputs opts]} {:inputs (path/join "src" "test" "cljs_build")
:opts {:main 'npm-deps-test.core
:output-dir out
:optimizations :none
:install-deps true
:npm-deps {:left-pad "1.1.3"}
:foreign-libs [{:module-type :es6
:file "src/test/cljs/es6_dep.js"
:provides ["es6_calc"]}
{:module-type :es6
:file "src/test/cljs/es6_default_hello.js"
:provides ["es6_default_hello"]}]
:closure-warnings {:check-types :off}}}
cenv (env/default-compiler-env)]
(test/delete-out-files out)
(build/build (build/inputs (path/join inputs "npm_deps_test/core.cljs")) opts cenv)
(is (fs/existsSync (path/join out "node_modules/left-pad/index.js")))
(is (contains? (:js-module-index @cenv) "left-pad"))))
(deftest test-npm-deps
(let [cenv (env/default-compiler-env)
out (path/join (test/tmp-dir) "npm-deps-test-out")
{:keys [inputs opts]} {:inputs (path/join "src" "test" "cljs_build")
:opts {:main 'npm-deps-test.string-requires
:output-dir out
:optimizations :none
:install-deps true
:npm-deps {:react "15.6.1"
:react-dom "15.6.1"
:lodash-es "4.17.4"
:lodash "4.17.4"}
:closure-warnings {:check-types :off
:non-standard-jsdoc :off
:parse-error :off}}}]
(test/delete-out-files out)
(testing "mix of symbol & string-based requires"
(test/delete-node-modules)
(build/build (build/inputs (path/join inputs "npm_deps_test/string_requires.cljs")) opts cenv)
(is (fs/existsSync (path/join out "node_modules/react/react.js")))
(is (contains? (:js-module-index @cenv) "react"))
(is (contains? (:js-module-index @cenv) "react-dom/server"))
(is (not (nil? (re-find #"\.\.[\\/]node_modules[\\/]react-dom[\\/]server\.js" (slurp (path/join out "cljs_deps.js")))))))
(testing "builds with string requires are idempotent"
(build/build (build/inputs (path/join inputs "npm_deps_test/string_requires.cljs")) opts cenv)
(is (not (nil? (re-find #"\.\.[\\/]node_modules[\\/]react-dom[\\/]server\.js" (slurp (path/join out "cljs_deps.js")))))))))
(deftest test-preloads
(let [out (path/join (test/tmp-dir) "preloads-test-out")
{:keys [inputs opts]} {:inputs (path/join "src" "test" "cljs")
:opts {:main 'preloads-test.core
:preloads '[preloads-test.preload]
:output-dir out
:optimizations :none
:closure-warnings {:check-types :off}}}
cenv (env/default-compiler-env)]
(test/delete-out-files out)
(build/build
(build/inputs (path/join inputs "preloads_test/core.cljs"))
opts cenv)
(is (fs/existsSync (path/join out "preloads_test/preload.cljs")))
(is (contains? (get-in @cenv [:cljs.analyzer/namespaces 'preloads-test.preload :defs]) 'preload-var))))
(deftest test-libs-cljs-2152
(let [out (path/join (test/tmp-dir) "libs-test-out")
{:keys [inputs opts]} {:inputs (path/join "src" "test" "cljs_build")
:opts {:main 'libs-test.core
:output-dir out
:libs ["src/test/cljs/js_libs"]
:optimizations :none
:closure-warnings {:check-types :off}}}
cenv (env/default-compiler-env)]
(test/delete-out-files out)
(build/build (build/inputs
(path/join inputs "libs_test/core.cljs")
"src/test/cljs/js_libs")
opts cenv)
(is (fs/existsSync (path/join out "tabby.js")))))
(defn collecting-warning-handler [state]
(fn [warning-type env extra]
(when (warning-type ana/*cljs-warnings*)
(when-let [s (ana/error-message warning-type extra)]
(swap! state conj s)))))
(deftest test-emit-node-requires-cljs-2213
(test/delete-node-modules)
(testing "simplest case, require"
(let [ws (atom [])
out (path/join (test/tmp-dir) "emit-node-requires-test-out")
{:keys [inputs opts]} {:inputs (path/join "src" "test" "cljs_build")
:opts {:main 'emit-node-requires-test.core
:output-dir out
:optimizations :none
:target :nodejs
:install-deps true
:npm-deps {:react "15.6.1"
:react-dom "15.6.1"}
:closure-warnings {:check-types :off
:non-standard-jsdoc :off
:parse-error :off}}}
cenv (env/default-compiler-env opts)]
(test/delete-out-files out)
(ana/with-warning-handlers [(collecting-warning-handler ws)]
(build/build (build/inputs (path/join inputs "emit_node_requires_test/core.cljs")) opts cenv))
(is (not (fs/existsSync (path/join out "node_modules/react/react.js"))))
(is (fs/existsSync (path/join out "emit_node_requires_test/core.js")))
(is (true? (boolean (re-find #"emit_node_requires_test\.core\.node\$module\$react_dom\$server = require\('react-dom/server'\);"
(slurp (path/join out "emit_node_requires_test/core.js"))))))
(is (true? (boolean (re-find #"emit_node_requires_test\.core\.node\$module\$react_dom\$server\.renderToString"
(slurp (path/join out "emit_node_requires_test/core.js"))))))
(is (empty? @ws))))
(testing "Node native modules, CLJS-2218"
(let [ws (atom [])
out (path/join (test/tmp-dir) "emit-node-requires-test-out")
{:keys [inputs opts]} {:inputs (path/join "src" "test" "cljs_build")
:opts {:main 'emit-node-requires-test.native-modules
:output-dir out
:optimizations :none
:target :nodejs
:closure-warnings {:check-types :off}}}
cenv (env/default-compiler-env opts)]
(test/delete-out-files out)
(test/delete-node-modules)
(ana/with-warning-handlers [(collecting-warning-handler ws)]
(build/build (build/inputs (path/join inputs "emit_node_requires_test/native_modules.cljs")) opts cenv))
(is (fs/existsSync (path/join out "emit_node_requires_test/native_modules.js")))
(is (true? (boolean (re-find #"emit_node_requires_test\.native_modules\.node\$module\$path\.isAbsolute"
(slurp (path/join out "emit_node_requires_test/native_modules.js"))))))
(is (empty? @ws)))))
(deftest cljs-test-compilation
(testing "success"
(let [out (path/join (test/tmp-dir) "compilation-test-out")
root "src/test/cljs_build"]
(test/delete-out-files out)
(is (build/build
(path/join root "hello" "world.cljs")
{:main 'hello
:optimizations :none
:output-dir out}
(env/default-compiler-env))
"Successful compilation should return")))
(testing "failure"
(let [out (path/join (test/tmp-dir) "compilation-test-out")
root "src/test/cljs_build"]
(test/delete-out-files out)
(try
(build/build
(path/join root "hello" "broken_world.cljs")
{:main 'hello
:optimizations :none
:output-dir out}
(env/default-compiler-env))
(is false)
(catch js/Error e
(is (some? e) "Failed compilation should throw"))))))
( / with - warning - handlers [ ( collecting - warning - handler ws ) ]
( build / build ( build / inputs ( io / file inputs " emit_global_requires_test / core.cljs " ) ) opts ) )
cenv ( env / default - compiler - env ) ]
( build / build ( build / inputs ( io / file inputs " data_readers_test " ) ) opts cenv )
( is ( contains ? ( - > @cenv : : / data - readers ) ' test / custom - identity ) ) ) )
cenv ( env / default - compiler - env ) ]
( build / build ( build / inputs ( io / file inputs " data_readers_test " ) ) opts cenv )
( let [ out ( io / file ( test / tmp - dir ) " cljs-2249 - out " )
(deftest test-node-modules-cljs-2246
(test/delete-node-modules)
(spit "package.json" (js/JSON.stringify (clj->js {:dependencies {:left-pad "1.1.3"}
:devDependencies {"@cljs-oss/module-deps" "*"}})))
(child_process/execSync (string/join " "
(cond->> ["npm" "--no-package-lock" "install"]
util/windows? (into ["cmd" "/c"]))))
(let [ws (atom [])
out (path/join (test/tmp-dir) "node-modules-opt-test-out")
{:keys [inputs opts]} {:inputs (str (path/join "src" "test" "cljs_build"))
:opts {:main 'node-modules-opt-test.core
:output-dir out
:optimizations :none
:closure-warnings {:check-types :off}}}
cenv (env/default-compiler-env opts)]
(test/delete-out-files out)
(ana/with-warning-handlers [(collecting-warning-handler ws)]
(build/build (build/inputs (path/join inputs "node_modules_opt_test/core.cljs")) opts cenv))
(is (fs/existsSync (path/join out "node_modules/left-pad/index.js")))
(is (contains? (:js-module-index @cenv) "left-pad"))
(is (empty? @ws)))
(fs/unlinkSync "package.json")
(test/delete-node-modules))
(deftest test-deps-api-cljs-2255
(let [out (path/join (test/tmp-dir) "cljs-2255-test-out")]
(test/delete-out-files out)
(test/delete-node-modules)
(spit "package.json" "{}")
(build/install-node-deps! {:left-pad "1.1.3"} {:output-dir out})
(is (fs/existsSync (path/join "node_modules" "left-pad" "package.json")))
(test/delete-out-files out)
(test/delete-node-modules)
(spit "package.json" "{}")
(build/install-node-deps!
{:react "15.6.1"
:react-dom "15.6.1"}
{:output-dir out})
(let [modules (build/get-node-deps '[react "react-dom/server"] {:output-dir out})]
(is (true? (some (fn [module]
(= module {:module-type :es6
:file (path/resolve "node_modules/react/react.js")
:provides ["react"
"react/react.js"
"react/react"]}))
modules)))
(is (true? (some (fn [module]
(= module {:module-type :es6
:file (path/resolve "node_modules/react/lib/React.js")
:provides ["react/lib/React.js" "react/lib/React"]}))
modules)))
(is (true? (some (fn [module]
(= module {:module-type :es6
:file (path/resolve "node_modules/react-dom/server.js")
:provides ["react-dom/server.js" "react-dom/server"]}))
modules))))
(test/delete-out-files out)
(test/delete-node-modules)
(fs/unlinkSync "package.json")))
( deftest test - cljs-2296
( let [ out ( .getPath ( io / file ( test / tmp - dir ) " cljs-2296 - test - out " ) )
( is ( .exists ( io / file out " src / test / cljs_build / foreign - libs - dir / vendor / lib.js " ) ) )
( slurp ( io / file out " src / test / cljs_build / foreign - libs - dir / vendor / lib.js " ) ) ) ) ) )
[ { : file ( str ( io / file root " foreign_libs_cljs_2334 " " lib.js " ) )
: provides [ " " ] } ]
( let [ foreign - lib - file ( io / file out ( - > opts : foreign - libs first : file ) )
TODO - when module splitting will be available to JS GCC -
( testing " requires code.split.b "
( is ( test / document - write ? content ' code.split.b ) ) ) ) )
TODO when --package_json_entry_names will be exposed in JS GCC -
: npm - deps { : " 1.2.2 "
( build / build ( build / inputs dir ) opts cenv )
( is ( contains ? (: js - module - index @cenv ) " iterall " ) )
( is ( contains ? (: js - module - index @cenv ) " graphql " ) )
( is ( contains ? (: js - module - index @cenv ) " graphql / execution " ) )
( is ( re - find # " goog\.require\('module\$.*\$node_modules\$iterall\$index'\ ) ; " ( slurp core - js ) ) )
( is ( re - find # " module\$.+\$node_modules\$iterall\$index\[\"default\"\]\.isCollection " ( slurp core - js ) ) )
|
4d311648a197759264c7f84d799e788c97dd6565d47ae1f1ab66febe65e73780 | rufoa/ring-middleware-accept | accept_test.clj | (ns ring.middleware.accept-test
(:require ring.middleware.accept)
(:use midje.sweet))
(tabular
(fact
(get-in ((ring.middleware.accept/wrap-accept identity {?key ?offered}) {:headers ?accept}) [:accept ?key]) => ?expected)
?key ?accept ?offered ?expected
:encoding {"accept-encoding" "a"} ["a"] "a"
:encoding {"accept-encoding" "*"} ["a"] "a"
:encoding {"accept-encoding" "a"} ["b"] nil
:mime {"accept" "a/a"} ["a/a"] "a/a"
:mime {"accept" "a/a"} ["a/b"] nil
:mime {"accept" "a/*"} ["a/a"] "a/a"
:mime {"accept" "a/*"} ["b/b"] nil
:mime {"accept" "*/*"} ["b/b"] "b/b"
:language {"accept-language" "en-gb"} ["en-gb"] "en-gb"
:language {"accept-language" "en"} ["en-gb"] "en-gb"
:language {"accept-language" "en"} ["fr-ca"] nil
:language {"accept-language" "*"} ["en-gb"] "en-gb"
:encoding {"accept-encoding" "a,b;q=0.5"} ["a" "b"] "a"
:encoding {"accept-encoding" "a;q=0.5,b"} ["a" "b"] "b"
:encoding {"accept-encoding" "a;q=0"} ["a"] nil
:mime {"accept" "a/a,a/*;q=0"} ["a/a"] "a/a"
:mime {"accept" "a/*,*/*;q=0"} ["a/a"] "a/a"
:mime {"accept" "a/a,a/*;q=0"} ["a/b"] nil
:mime {"accept" "a/a,*/*"} ["a/a" "b/b"] "a/a"
:mime {"accept" "a/a,*/*"} ["b/b" "a/a"] "a/a"
:language {"accept-language" "en-gb,en"} ["en-gb" "en-us"] "en-gb"
:language {"accept-language" "en-gb,en"} ["en-us" "en-gb"] "en-gb"
:encoding {"accept-encoding" "a"} ["a" :as :a] :a
:encoding {"accept-encoding" "b"} ["a" :as :a] nil
:encoding {"accept-encoding" "a,b;q=0.5"} ["a" :qs 0.1, "b"] "b"
:encoding {"accept-encoding" "a;q=0.5,b"} ["a", "b" :qs 0.1] "a"
:encoding {"accept-encoding" "a"} ["a" :qs 0] nil
:encoding {} ["identity"] "identity"
:encoding {"accept-encoding" "a"} ["identity"] "identity"
:encoding {"accept-encoding" "identity;q=0"} ["identity"] nil
:encoding {"accept-encoding" "*;q=0"} ["identity"] nil
:charset {"accept-charset" "a;q=0.9"} ["iso-8859-1", "a"] "iso-8859-1"
:charset {} ["iso-8859-1"] "iso-8859-1"
:charset {"accept-charset" "iso-8859-1;q=0"} ["iso-8859-1"] nil
:charset {"accept-charset" "*;q=0"} ["iso-8859-1"] nil
:charset {"accept-charset" ""} ["iso-8859-1"] "iso-8859-1"
:language {"accept-language" "en-gb"} ["en"] "en"
:language {"accept-language" "en-gb,en;q=0"} ["en"] nil
:language {"accept-language" "en-gb;q=0"} ["en"] nil
:language {"accept-language" "en-gb,fr;q=0.9"} ["en" "fr"] "fr") | null | https://raw.githubusercontent.com/rufoa/ring-middleware-accept/67e2500db793c487b6bcc151bdfcfb5b8964af46/test/ring/middleware/accept_test.clj | clojure | (ns ring.middleware.accept-test
(:require ring.middleware.accept)
(:use midje.sweet))
(tabular
(fact
(get-in ((ring.middleware.accept/wrap-accept identity {?key ?offered}) {:headers ?accept}) [:accept ?key]) => ?expected)
?key ?accept ?offered ?expected
:encoding {"accept-encoding" "a"} ["a"] "a"
:encoding {"accept-encoding" "*"} ["a"] "a"
:encoding {"accept-encoding" "a"} ["b"] nil
:mime {"accept" "a/a"} ["a/a"] "a/a"
:mime {"accept" "a/a"} ["a/b"] nil
:mime {"accept" "a/*"} ["a/a"] "a/a"
:mime {"accept" "a/*"} ["b/b"] nil
:mime {"accept" "*/*"} ["b/b"] "b/b"
:language {"accept-language" "en-gb"} ["en-gb"] "en-gb"
:language {"accept-language" "en"} ["en-gb"] "en-gb"
:language {"accept-language" "en"} ["fr-ca"] nil
:language {"accept-language" "*"} ["en-gb"] "en-gb"
:encoding {"accept-encoding" "a,b;q=0.5"} ["a" "b"] "a"
:encoding {"accept-encoding" "a;q=0.5,b"} ["a" "b"] "b"
:encoding {"accept-encoding" "a;q=0"} ["a"] nil
:mime {"accept" "a/a,a/*;q=0"} ["a/a"] "a/a"
:mime {"accept" "a/*,*/*;q=0"} ["a/a"] "a/a"
:mime {"accept" "a/a,a/*;q=0"} ["a/b"] nil
:mime {"accept" "a/a,*/*"} ["a/a" "b/b"] "a/a"
:mime {"accept" "a/a,*/*"} ["b/b" "a/a"] "a/a"
:language {"accept-language" "en-gb,en"} ["en-gb" "en-us"] "en-gb"
:language {"accept-language" "en-gb,en"} ["en-us" "en-gb"] "en-gb"
:encoding {"accept-encoding" "a"} ["a" :as :a] :a
:encoding {"accept-encoding" "b"} ["a" :as :a] nil
:encoding {"accept-encoding" "a,b;q=0.5"} ["a" :qs 0.1, "b"] "b"
:encoding {"accept-encoding" "a;q=0.5,b"} ["a", "b" :qs 0.1] "a"
:encoding {"accept-encoding" "a"} ["a" :qs 0] nil
:encoding {} ["identity"] "identity"
:encoding {"accept-encoding" "a"} ["identity"] "identity"
:encoding {"accept-encoding" "identity;q=0"} ["identity"] nil
:encoding {"accept-encoding" "*;q=0"} ["identity"] nil
:charset {"accept-charset" "a;q=0.9"} ["iso-8859-1", "a"] "iso-8859-1"
:charset {} ["iso-8859-1"] "iso-8859-1"
:charset {"accept-charset" "iso-8859-1;q=0"} ["iso-8859-1"] nil
:charset {"accept-charset" "*;q=0"} ["iso-8859-1"] nil
:charset {"accept-charset" ""} ["iso-8859-1"] "iso-8859-1"
:language {"accept-language" "en-gb"} ["en"] "en"
:language {"accept-language" "en-gb,en;q=0"} ["en"] nil
:language {"accept-language" "en-gb;q=0"} ["en"] nil
:language {"accept-language" "en-gb,fr;q=0.9"} ["en" "fr"] "fr") | |
383e552ae205bcc8b960d4ffac340f98009b3cd49fc102da8a0e6446b5c00ab4 | jwiegley/notes | Runner.hs | newtype ByteString64 = ByteString64 { unByteString64 :: ByteString }
deriving (Eq, Read, Show, Data, Typeable,
#ifndef FAY
Ord, Serialize, Generic, Hashable
#endif
)
| null | https://raw.githubusercontent.com/jwiegley/notes/24574b02bfd869845faa1521854f90e4e8bf5e9a/gists/8924109/Runner.hs | haskell | newtype ByteString64 = ByteString64 { unByteString64 :: ByteString }
deriving (Eq, Read, Show, Data, Typeable,
#ifndef FAY
Ord, Serialize, Generic, Hashable
#endif
)
| |
cb55812e2840a5c5fd02ffc69c3702b7a84f900149d94fb606c0c78f460731a0 | bmeurer/ocaml-experimental | graphics.ml | (***********************************************************************)
(* *)
(* 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$
exception Graphic_failure of string
Initializations
let _ =
Callback.register_exception "Graphics.Graphic_failure" (Graphic_failure "")
external raw_open_graph: string -> unit = "caml_gr_open_graph"
external raw_close_graph: unit -> unit = "caml_gr_close_graph"
external sigio_signal: unit -> int = "caml_gr_sigio_signal"
external sigio_handler: int -> unit = "caml_gr_sigio_handler"
let unix_open_graph arg =
Sys.set_signal (sigio_signal()) (Sys.Signal_handle sigio_handler);
raw_open_graph arg
let unix_close_graph () =
Sys.set_signal (sigio_signal()) Sys.Signal_ignore;
raw_close_graph ()
let (open_graph, close_graph) =
match Sys.os_type with
| "Unix" | "Cygwin" -> (unix_open_graph, unix_close_graph)
| "Win32" -> (raw_open_graph, raw_close_graph)
| "MacOS" -> (raw_open_graph, raw_close_graph)
| _ -> invalid_arg ("Graphics: unknown OS type: " ^ Sys.os_type)
external set_window_title : string -> unit = "caml_gr_set_window_title"
external resize_window : int -> int -> unit = "caml_gr_resize_window"
external clear_graph : unit -> unit = "caml_gr_clear_graph"
external size_x : unit -> int = "caml_gr_size_x"
external size_y : unit -> int = "caml_gr_size_y"
(* Double-buffering *)
external display_mode : bool -> unit = "caml_gr_display_mode"
external remember_mode : bool -> unit = "caml_gr_remember_mode"
external synchronize : unit -> unit = "caml_gr_synchronize"
let auto_synchronize = function
| true -> display_mode true; remember_mode true; synchronize ()
| false -> display_mode false; remember_mode true
;;
(* Colors *)
type color = int
let rgb r g b = (r lsl 16) + (g lsl 8) + b
external set_color : color -> unit = "caml_gr_set_color"
let black = 0x000000
and white = 0xFFFFFF
and red = 0xFF0000
and green = 0x00FF00
and blue = 0x0000FF
and yellow = 0xFFFF00
and cyan = 0x00FFFF
and magenta = 0xFF00FF
let background = white
and foreground = black
(* Drawing *)
external plot : int -> int -> unit = "caml_gr_plot"
let plots points =
for i = 0 to Array.length points - 1 do
let (x, y) = points.(i) in
plot x y;
done
;;
external point_color : int -> int -> color = "caml_gr_point_color"
external moveto : int -> int -> unit = "caml_gr_moveto"
external current_x : unit -> int = "caml_gr_current_x"
external current_y : unit -> int = "caml_gr_current_y"
let current_point () = current_x (), current_y ()
external lineto : int -> int -> unit = "caml_gr_lineto"
let rlineto x y = lineto (current_x () + x) (current_y () + y)
let rmoveto x y = moveto (current_x () + x) (current_y () + y)
external raw_draw_rect : int -> int -> int -> int -> unit = "caml_gr_draw_rect"
let draw_rect x y w h =
if w < 0 || h < 0 then raise (Invalid_argument "draw_rect")
else raw_draw_rect x y w h
;;
let draw_poly, draw_poly_line =
let dodraw close_flag points =
if Array.length points > 0 then begin
let (savex, savey) = current_point () in
moveto (fst points.(0)) (snd points.(0));
for i = 1 to Array.length points - 1 do
let (x, y) = points.(i) in
lineto x y;
done;
if close_flag then lineto (fst points.(0)) (snd points.(0));
moveto savex savey;
end;
in dodraw true, dodraw false
;;
let draw_segments segs =
let (savex, savey) = current_point () in
for i = 0 to Array.length segs - 1 do
let (x1, y1, x2, y2) = segs.(i) in
moveto x1 y1;
lineto x2 y2;
done;
moveto savex savey;
;;
external raw_draw_arc : int -> int -> int -> int -> int -> int -> unit
= "caml_gr_draw_arc" "caml_gr_draw_arc_nat"
let draw_arc x y rx ry a1 a2 =
if rx < 0 || ry < 0 then raise (Invalid_argument "draw_arc/ellipse/circle")
else raw_draw_arc x y rx ry a1 a2
;;
let draw_ellipse x y rx ry = draw_arc x y rx ry 0 360
let draw_circle x y r = draw_arc x y r r 0 360
external raw_set_line_width : int -> unit = "caml_gr_set_line_width"
let set_line_width w =
if w < 0 then raise (Invalid_argument "set_line_width")
else raw_set_line_width w
;;
external raw_fill_rect : int -> int -> int -> int -> unit = "caml_gr_fill_rect"
let fill_rect x y w h =
if w < 0 || h < 0 then raise (Invalid_argument "fill_rect")
else raw_fill_rect x y w h
;;
external fill_poly : (int * int) array -> unit = "caml_gr_fill_poly"
external raw_fill_arc : int -> int -> int -> int -> int -> int -> unit
= "caml_gr_fill_arc" "caml_gr_fill_arc_nat"
let fill_arc x y rx ry a1 a2 =
if rx < 0 || ry < 0 then raise (Invalid_argument "fill_arc/ellipse/circle")
else raw_fill_arc x y rx ry a1 a2
;;
let fill_ellipse x y rx ry = fill_arc x y rx ry 0 360
let fill_circle x y r = fill_arc x y r r 0 360
(* Text *)
external draw_char : char -> unit = "caml_gr_draw_char"
external draw_string : string -> unit = "caml_gr_draw_string"
external set_font : string -> unit = "caml_gr_set_font"
external set_text_size : int -> unit = "caml_gr_set_text_size"
external text_size : string -> int * int = "caml_gr_text_size"
(* Images *)
type image
let transp = -1
external make_image : color array array -> image = "caml_gr_make_image"
external dump_image : image -> color array array = "caml_gr_dump_image"
external draw_image : image -> int -> int -> unit = "caml_gr_draw_image"
external create_image : int -> int -> image = "caml_gr_create_image"
external blit_image : image -> int -> int -> unit = "caml_gr_blit_image"
let get_image x y w h =
let image = create_image w h in
blit_image image x y;
image
(* Events *)
type status =
{ mouse_x : int;
mouse_y : int;
button : bool;
keypressed : bool;
key : char }
type event =
Button_down
| Button_up
| Key_pressed
| Mouse_motion
| Poll
external wait_next_event : event list -> status = "caml_gr_wait_event"
let mouse_pos () =
let e = wait_next_event [Poll] in (e.mouse_x, e.mouse_y)
let button_down () =
let e = wait_next_event [Poll] in e.button
let read_key () =
let e = wait_next_event [Key_pressed] in e.key
let key_pressed () =
let e = wait_next_event [Poll] in e.keypressed
(*** Sound *)
external sound : int -> int -> unit = "caml_gr_sound"
(* Splines *)
let add (x1, y1) (x2, y2) = (x1 +. x2, y1 +. y2)
and sub (x1, y1) (x2, y2) = (x1 -. x2, y1 -. y2)
and middle (x1, y1) (x2, y2) = ((x1 +. x2) /. 2.0, (y1 +. y2) /. 2.0)
and area (x1, y1) (x2, y2) = abs_float (x1 *. y2 -. x2 *. y1)
and norm (x1, y1) = sqrt (x1 *. x1 +. y1 *. y1);;
let test a b c d =
let v = sub d a in
let s = norm v in
area v (sub a b) <= s && area v (sub a c) <= s;;
let spline a b c d =
let rec spl accu a b c d =
if test a b c d then d :: accu else
let a' = middle a b
and o = middle b c in
let b' = middle a' o
and d' = middle c d in
let c' = middle o d' in
let i = middle b' c' in
spl (spl accu a a' b' i) i c' d' d in
spl [a] a b c d;;
let curveto b c (x, y as d) =
let float_point (x, y) = (float_of_int x, float_of_int y) in
let round f = int_of_float (f +. 0.5) in
let int_point (x, y) = (round x, round y) in
let points =
spline
(float_point (current_point ()))
(float_point b) (float_point c) (float_point d) in
draw_poly_line
(Array.of_list (List.map int_point points));
moveto x y;;
| null | https://raw.githubusercontent.com/bmeurer/ocaml-experimental/fe5c10cdb0499e43af4b08f35a3248e5c1a8b541/otherlibs/graph/graphics.ml | ocaml | *********************************************************************
Objective Caml
the special exception on linking described in file ../../LICENSE.
*********************************************************************
Double-buffering
Colors
Drawing
Text
Images
Events
** Sound
Splines | , 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$
exception Graphic_failure of string
Initializations
let _ =
Callback.register_exception "Graphics.Graphic_failure" (Graphic_failure "")
external raw_open_graph: string -> unit = "caml_gr_open_graph"
external raw_close_graph: unit -> unit = "caml_gr_close_graph"
external sigio_signal: unit -> int = "caml_gr_sigio_signal"
external sigio_handler: int -> unit = "caml_gr_sigio_handler"
let unix_open_graph arg =
Sys.set_signal (sigio_signal()) (Sys.Signal_handle sigio_handler);
raw_open_graph arg
let unix_close_graph () =
Sys.set_signal (sigio_signal()) Sys.Signal_ignore;
raw_close_graph ()
let (open_graph, close_graph) =
match Sys.os_type with
| "Unix" | "Cygwin" -> (unix_open_graph, unix_close_graph)
| "Win32" -> (raw_open_graph, raw_close_graph)
| "MacOS" -> (raw_open_graph, raw_close_graph)
| _ -> invalid_arg ("Graphics: unknown OS type: " ^ Sys.os_type)
external set_window_title : string -> unit = "caml_gr_set_window_title"
external resize_window : int -> int -> unit = "caml_gr_resize_window"
external clear_graph : unit -> unit = "caml_gr_clear_graph"
external size_x : unit -> int = "caml_gr_size_x"
external size_y : unit -> int = "caml_gr_size_y"
external display_mode : bool -> unit = "caml_gr_display_mode"
external remember_mode : bool -> unit = "caml_gr_remember_mode"
external synchronize : unit -> unit = "caml_gr_synchronize"
let auto_synchronize = function
| true -> display_mode true; remember_mode true; synchronize ()
| false -> display_mode false; remember_mode true
;;
type color = int
let rgb r g b = (r lsl 16) + (g lsl 8) + b
external set_color : color -> unit = "caml_gr_set_color"
let black = 0x000000
and white = 0xFFFFFF
and red = 0xFF0000
and green = 0x00FF00
and blue = 0x0000FF
and yellow = 0xFFFF00
and cyan = 0x00FFFF
and magenta = 0xFF00FF
let background = white
and foreground = black
external plot : int -> int -> unit = "caml_gr_plot"
let plots points =
for i = 0 to Array.length points - 1 do
let (x, y) = points.(i) in
plot x y;
done
;;
external point_color : int -> int -> color = "caml_gr_point_color"
external moveto : int -> int -> unit = "caml_gr_moveto"
external current_x : unit -> int = "caml_gr_current_x"
external current_y : unit -> int = "caml_gr_current_y"
let current_point () = current_x (), current_y ()
external lineto : int -> int -> unit = "caml_gr_lineto"
let rlineto x y = lineto (current_x () + x) (current_y () + y)
let rmoveto x y = moveto (current_x () + x) (current_y () + y)
external raw_draw_rect : int -> int -> int -> int -> unit = "caml_gr_draw_rect"
let draw_rect x y w h =
if w < 0 || h < 0 then raise (Invalid_argument "draw_rect")
else raw_draw_rect x y w h
;;
let draw_poly, draw_poly_line =
let dodraw close_flag points =
if Array.length points > 0 then begin
let (savex, savey) = current_point () in
moveto (fst points.(0)) (snd points.(0));
for i = 1 to Array.length points - 1 do
let (x, y) = points.(i) in
lineto x y;
done;
if close_flag then lineto (fst points.(0)) (snd points.(0));
moveto savex savey;
end;
in dodraw true, dodraw false
;;
let draw_segments segs =
let (savex, savey) = current_point () in
for i = 0 to Array.length segs - 1 do
let (x1, y1, x2, y2) = segs.(i) in
moveto x1 y1;
lineto x2 y2;
done;
moveto savex savey;
;;
external raw_draw_arc : int -> int -> int -> int -> int -> int -> unit
= "caml_gr_draw_arc" "caml_gr_draw_arc_nat"
let draw_arc x y rx ry a1 a2 =
if rx < 0 || ry < 0 then raise (Invalid_argument "draw_arc/ellipse/circle")
else raw_draw_arc x y rx ry a1 a2
;;
let draw_ellipse x y rx ry = draw_arc x y rx ry 0 360
let draw_circle x y r = draw_arc x y r r 0 360
external raw_set_line_width : int -> unit = "caml_gr_set_line_width"
let set_line_width w =
if w < 0 then raise (Invalid_argument "set_line_width")
else raw_set_line_width w
;;
external raw_fill_rect : int -> int -> int -> int -> unit = "caml_gr_fill_rect"
let fill_rect x y w h =
if w < 0 || h < 0 then raise (Invalid_argument "fill_rect")
else raw_fill_rect x y w h
;;
external fill_poly : (int * int) array -> unit = "caml_gr_fill_poly"
external raw_fill_arc : int -> int -> int -> int -> int -> int -> unit
= "caml_gr_fill_arc" "caml_gr_fill_arc_nat"
let fill_arc x y rx ry a1 a2 =
if rx < 0 || ry < 0 then raise (Invalid_argument "fill_arc/ellipse/circle")
else raw_fill_arc x y rx ry a1 a2
;;
let fill_ellipse x y rx ry = fill_arc x y rx ry 0 360
let fill_circle x y r = fill_arc x y r r 0 360
external draw_char : char -> unit = "caml_gr_draw_char"
external draw_string : string -> unit = "caml_gr_draw_string"
external set_font : string -> unit = "caml_gr_set_font"
external set_text_size : int -> unit = "caml_gr_set_text_size"
external text_size : string -> int * int = "caml_gr_text_size"
type image
let transp = -1
external make_image : color array array -> image = "caml_gr_make_image"
external dump_image : image -> color array array = "caml_gr_dump_image"
external draw_image : image -> int -> int -> unit = "caml_gr_draw_image"
external create_image : int -> int -> image = "caml_gr_create_image"
external blit_image : image -> int -> int -> unit = "caml_gr_blit_image"
let get_image x y w h =
let image = create_image w h in
blit_image image x y;
image
type status =
{ mouse_x : int;
mouse_y : int;
button : bool;
keypressed : bool;
key : char }
type event =
Button_down
| Button_up
| Key_pressed
| Mouse_motion
| Poll
external wait_next_event : event list -> status = "caml_gr_wait_event"
let mouse_pos () =
let e = wait_next_event [Poll] in (e.mouse_x, e.mouse_y)
let button_down () =
let e = wait_next_event [Poll] in e.button
let read_key () =
let e = wait_next_event [Key_pressed] in e.key
let key_pressed () =
let e = wait_next_event [Poll] in e.keypressed
external sound : int -> int -> unit = "caml_gr_sound"
let add (x1, y1) (x2, y2) = (x1 +. x2, y1 +. y2)
and sub (x1, y1) (x2, y2) = (x1 -. x2, y1 -. y2)
and middle (x1, y1) (x2, y2) = ((x1 +. x2) /. 2.0, (y1 +. y2) /. 2.0)
and area (x1, y1) (x2, y2) = abs_float (x1 *. y2 -. x2 *. y1)
and norm (x1, y1) = sqrt (x1 *. x1 +. y1 *. y1);;
let test a b c d =
let v = sub d a in
let s = norm v in
area v (sub a b) <= s && area v (sub a c) <= s;;
let spline a b c d =
let rec spl accu a b c d =
if test a b c d then d :: accu else
let a' = middle a b
and o = middle b c in
let b' = middle a' o
and d' = middle c d in
let c' = middle o d' in
let i = middle b' c' in
spl (spl accu a a' b' i) i c' d' d in
spl [a] a b c d;;
let curveto b c (x, y as d) =
let float_point (x, y) = (float_of_int x, float_of_int y) in
let round f = int_of_float (f +. 0.5) in
let int_point (x, y) = (round x, round y) in
let points =
spline
(float_point (current_point ()))
(float_point b) (float_point c) (float_point d) in
draw_poly_line
(Array.of_list (List.map int_point points));
moveto x y;;
|
30f01dc071bf9288451cd85051c0f8429ad2944ec42e6c97be7d505d7c55b344 | vikram/lisplibraries | widget.lisp |
(in-package :weblocks)
(export '(defwidget widget widget-name
widget-propagate-dirty widget-rendered-p widget-continuation
widget-parent widget-prefix-fn widget-suffix-fn
with-widget-header
render-widget-body widget-css-classes render-widget mark-dirty
widget-dirty-p find-widget-by-path* find-widget-by-path
*current-widget*
*override-parent-p*))
(defmacro defwidget (name direct-superclasses &body body)
"A macro used to define new widget classes. Behaves exactly as
defclass, except adds 'widget-class' metaclass specification and
inherits from 'widget' if no direct superclasses are provided."
`(progn
(defclass ,name ,(or direct-superclasses '(widget))
,@body
(:metaclass widget-class))
(defmethod per-class-dependencies append ((obj ,name))
(declare (ignore obj))
(dependencies-by-symbol (quote ,name)))))
(defclass widget (dom-object-mixin)
((propagate-dirty :accessor widget-propagate-dirty
:initform nil
:initarg :propagate-dirty
:documentation "A list of widget paths (see
'find-widget-by-path') or widgets each of which
will be made dirty when this widget is made dirty
via a POST request. This slot allows setting up
dependencies between widgets that will make
multiple widgets update automatically during AJAX
requests.")
(renderedp :accessor widget-rendered-p
:initform nil
:affects-dirty-status-p nil
:documentation "This slot holds a boolean flag
indicating whether the widget has been rendered at least
once. Because marking unrendered widgets as dirty may
cause JS problems, 'mark-dirty' will use this flag to
determine the status of a widget.")
(continuation :accessor widget-continuation
:initform nil
:documentation "Stores the continuation object for
widgets that were invoked via one of the do-*
functions ('do-page', etc.). When 'answer' is called
on a widget, this value is used to resume the
computation.")
(parent :accessor widget-parent
:initform nil
:documentation "Stores the 'parent' of a widget,
i.e. the composite widget in which this widget is
located, if any. This value is automatically set by
composites with the slot 'composite-widgets' is
set. Note, a widget can only have one parent at any
given time.")
(widget-prefix-fn :initform nil
:initarg :widget-prefix-fn
:accessor widget-prefix-fn
:documentation "A function called prior to
rendering the widget body. The function should
expect the widget as well as any additional
arguments passed to the widget.")
(widget-suffix-fn :initform nil
:initarg :widget-suffix-fn
:accessor widget-suffix-fn
:documentation "A function called after rendering
the widget body. The function should expect the
widget as well as any additional arguments passed
to the widget."))
#+lispworks (:optimize-slot-access nil)
(:metaclass widget-class)
(:documentation "Base class for all widget objects."))
;; Process the :name initarg and set the dom-id accordingly. Note that
;; it is possible to pass :name nil, which simply means that objects
;; will render without id in generated HTML.
(defmethod initialize-instance :after ((obj widget) &key name &allow-other-keys)
(when name (setf (dom-id obj) name)))
(defgeneric widget-name (obj)
(:documentation "An interface to the DOM id of a widget. Provides
access to the underlying implementation, can return either a symbol, a
string, or nil.")
(:method ((obj widget)) (ensure-dom-id obj))
(:method ((obj symbol)) obj)
(:method ((obj function)) nil)
(:method ((obj string)) nil))
(defmethod (setf widget-name) (name (obj widget))
(setf (dom-id obj) name))
(defparameter *override-parent-p* nil
"Allow parent overriding in (SETF COMPOSITE-WIDGETS).")
Do n't allow setting a parent for widget that already has one
;;; (unless it's setting parent to nil)
(defmethod (setf widget-parent) (val (obj widget))
(if (and val (widget-parent obj) (not *override-parent-p*))
(error "Widget ~a already has a parent." obj)
(setf (slot-value obj 'parent) val)))
;;; Define widget-rendered-p for objects that don't derive from
;;; 'widget'
(defmethod widget-rendered-p (obj)
nil)
(defmethod (setf widget-rendered-p) (val obj)
nil)
;;; Define widget-parent for objects that don't derive from 'widget'
(defmethod widget-parent (obj)
(declare (ignore obj))
nil)
(defmethod (setf widget-parent) (obj val)
(declare (ignore obj val))
nil)
(defgeneric with-widget-header (obj body-fn &rest args &key
widget-prefix-fn widget-suffix-fn
&allow-other-keys)
(:documentation
"Renders a header and footer for the widget and calls 'body-fn'
within it. Specialize this function to provide customized headers for
different widgets.
'widget-prefix-fn' and 'widget-suffix-fn' allow specifying functions
that will be applied before and after the body is rendered.")
(:method (obj body-fn &rest args
&key widget-prefix-fn widget-suffix-fn
&allow-other-keys)
(with-html
(:div :class (dom-classes obj)
:id (dom-id obj)
(safe-apply widget-prefix-fn obj args)
(apply body-fn obj args)
(safe-apply widget-suffix-fn obj args)))))
(defgeneric render-widget-body (obj &rest args &key &allow-other-keys)
(:documentation
"A generic function that renders a widget in its current state. In
order to actually render the widget, call 'render-widget' instead.
'obj' - widget object to render.
One of the implementations allows \"rendering\" functions. When
'render-widget' is called on a function, the function is simply
called. This allows to easily add functions to composite widgets that
can do custom rendering without much boilerplate. Similarly symbols
that are fbound to functions can be treated as widgets.
Another implementation allows rendering strings."))
(defmethod render-widget-body ((obj symbol) &rest args)
(if (fboundp obj)
(apply obj args)
(error "Cannot render ~A as widget. Symbol not bound to a
function." obj)))
(defmethod render-widget-body ((obj function) &rest args)
(apply obj args))
(defmethod render-widget-body ((obj string) &rest args &key id class &allow-other-keys)
(declare (ignore args))
(with-html
(:p :id id :class class (str obj))))
(defmethod widget-prefix-fn (obj)
nil)
(defmethod widget-suffix-fn (obj)
nil)
(defgeneric render-widget (obj &key inlinep &allow-other-keys)
(:documentation
"Renders a widget ('render-widget-body') wrapped in a
header ('with-widget-header'). If 'inlinep' is true, renders the
widget without a header.
Additionally, calls 'dependencies' and adds the returned items to
*page-dependencies*. This is later used by Weblocks to declare
stylesheets and javascript links in the page header."))
(defmethod render-widget (obj &rest args &key inlinep &allow-other-keys)
(declare (special *page-dependencies*))
(if (ajax-request-p)
(dolist (dep (dependencies obj))
(send-script
(ps* `(,(typecase dep
(stylesheet-dependency 'include_css)
(script-dependency 'include_dom))
,(puri:render-uri (dependency-url dep) nil)))
:before-load))
(setf *page-dependencies*
(append *page-dependencies* (dependencies obj))))
(if inlinep
(apply #'render-widget-body obj args)
(apply #'with-widget-header obj #'render-widget-body
(append
(when (widget-prefix-fn obj)
(list :widget-prefix-fn (widget-prefix-fn obj)))
(when (widget-suffix-fn obj)
(list :widget-suffix-fn (widget-suffix-fn obj)))
args)))
(setf (widget-rendered-p obj) t))
;;; Make all widgets act as composites to simplify development
(defmethod composite-widgets ((obj widget))
nil)
(defmethod composite-widgets ((obj function))
nil)
(defmethod composite-widgets ((obj symbol))
nil)
(defmethod composite-widgets ((obj string))
nil)
(defgeneric mark-dirty (w &key putp)
(:documentation
"Default implementation adds a widget to a list of dirty
widgets. Normally used during an AJAX request. If there are any
widgets in the 'propagate-dirty' slot of 'w' and 'putp' is true, these
widgets are added to the dirty list as well.
Note, this function is automatically called when widget slots are
modified, unless slots are marked with affects-dirty-status-p."))
(defmethod mark-dirty ((w widget) &key putp)
(declare (special *dirty-widgets*))
(when (functionp w)
(error "AJAX is not supported for functions. Convert the function
into a CLOS object derived from 'widget'."))
(ignore-errors
(when (widget-rendered-p w)
(setf *dirty-widgets* (adjoin w *dirty-widgets*)))
(when putp
(mapc #'mark-dirty
(remove nil (loop for i in (widget-propagate-dirty w)
collect (find-widget-by-path i)))))))
(defun widget-dirty-p (w)
"Returns true if the widget 'w' has been marked dirty."
(member w *dirty-widgets*))
;;; When slots of a widget are modified, the widget should be marked
;;; as dirty to service AJAX calls.
(defmethod (setf slot-value-using-class) (new-value (class widget-class) (object widget)
(slot-name widget-effective-slot-definition))
(when (widget-slot-affects-dirty-status-p slot-name)
(mark-dirty object))
(call-next-method new-value class object slot-name))
(defgeneric find-widget-by-path* (path root)
(:documentation
"Returns a widget object located at 'path', where 'path' is a list
of widget names starting from root. For convinience, 'path' can be a
widget object, in which case it is simply returned.
'root' - a widget to start the search from."))
(defmethod find-widget-by-path* ((path (eql nil)) root)
root)
(defmethod find-widget-by-path* ((path widget) root)
path)
(defmethod find-widget-by-path* (path (root (eql nil)))
nil)
(defun find-widget-by-path (path &optional (root (root-composite)))
(find-widget-by-path* path root))
(defmethod print-object ((obj widget) stream)
(print-unreadable-object (obj stream :type t)
(format stream "~s" (ensure-dom-id obj))))
| null | https://raw.githubusercontent.com/vikram/lisplibraries/105e3ef2d165275eb78f36f5090c9e2cdd0754dd/site/weblocks-stable/src/widgets/widget/widget.lisp | lisp | Process the :name initarg and set the dom-id accordingly. Note that
it is possible to pass :name nil, which simply means that objects
will render without id in generated HTML.
(unless it's setting parent to nil)
Define widget-rendered-p for objects that don't derive from
'widget'
Define widget-parent for objects that don't derive from 'widget'
Make all widgets act as composites to simplify development
When slots of a widget are modified, the widget should be marked
as dirty to service AJAX calls. |
(in-package :weblocks)
(export '(defwidget widget widget-name
widget-propagate-dirty widget-rendered-p widget-continuation
widget-parent widget-prefix-fn widget-suffix-fn
with-widget-header
render-widget-body widget-css-classes render-widget mark-dirty
widget-dirty-p find-widget-by-path* find-widget-by-path
*current-widget*
*override-parent-p*))
(defmacro defwidget (name direct-superclasses &body body)
"A macro used to define new widget classes. Behaves exactly as
defclass, except adds 'widget-class' metaclass specification and
inherits from 'widget' if no direct superclasses are provided."
`(progn
(defclass ,name ,(or direct-superclasses '(widget))
,@body
(:metaclass widget-class))
(defmethod per-class-dependencies append ((obj ,name))
(declare (ignore obj))
(dependencies-by-symbol (quote ,name)))))
(defclass widget (dom-object-mixin)
((propagate-dirty :accessor widget-propagate-dirty
:initform nil
:initarg :propagate-dirty
:documentation "A list of widget paths (see
'find-widget-by-path') or widgets each of which
will be made dirty when this widget is made dirty
via a POST request. This slot allows setting up
dependencies between widgets that will make
multiple widgets update automatically during AJAX
requests.")
(renderedp :accessor widget-rendered-p
:initform nil
:affects-dirty-status-p nil
:documentation "This slot holds a boolean flag
indicating whether the widget has been rendered at least
once. Because marking unrendered widgets as dirty may
cause JS problems, 'mark-dirty' will use this flag to
determine the status of a widget.")
(continuation :accessor widget-continuation
:initform nil
:documentation "Stores the continuation object for
widgets that were invoked via one of the do-*
functions ('do-page', etc.). When 'answer' is called
on a widget, this value is used to resume the
computation.")
(parent :accessor widget-parent
:initform nil
:documentation "Stores the 'parent' of a widget,
i.e. the composite widget in which this widget is
located, if any. This value is automatically set by
composites with the slot 'composite-widgets' is
set. Note, a widget can only have one parent at any
given time.")
(widget-prefix-fn :initform nil
:initarg :widget-prefix-fn
:accessor widget-prefix-fn
:documentation "A function called prior to
rendering the widget body. The function should
expect the widget as well as any additional
arguments passed to the widget.")
(widget-suffix-fn :initform nil
:initarg :widget-suffix-fn
:accessor widget-suffix-fn
:documentation "A function called after rendering
the widget body. The function should expect the
widget as well as any additional arguments passed
to the widget."))
#+lispworks (:optimize-slot-access nil)
(:metaclass widget-class)
(:documentation "Base class for all widget objects."))
(defmethod initialize-instance :after ((obj widget) &key name &allow-other-keys)
(when name (setf (dom-id obj) name)))
(defgeneric widget-name (obj)
(:documentation "An interface to the DOM id of a widget. Provides
access to the underlying implementation, can return either a symbol, a
string, or nil.")
(:method ((obj widget)) (ensure-dom-id obj))
(:method ((obj symbol)) obj)
(:method ((obj function)) nil)
(:method ((obj string)) nil))
(defmethod (setf widget-name) (name (obj widget))
(setf (dom-id obj) name))
(defparameter *override-parent-p* nil
"Allow parent overriding in (SETF COMPOSITE-WIDGETS).")
Do n't allow setting a parent for widget that already has one
(defmethod (setf widget-parent) (val (obj widget))
(if (and val (widget-parent obj) (not *override-parent-p*))
(error "Widget ~a already has a parent." obj)
(setf (slot-value obj 'parent) val)))
(defmethod widget-rendered-p (obj)
nil)
(defmethod (setf widget-rendered-p) (val obj)
nil)
(defmethod widget-parent (obj)
(declare (ignore obj))
nil)
(defmethod (setf widget-parent) (obj val)
(declare (ignore obj val))
nil)
(defgeneric with-widget-header (obj body-fn &rest args &key
widget-prefix-fn widget-suffix-fn
&allow-other-keys)
(:documentation
"Renders a header and footer for the widget and calls 'body-fn'
within it. Specialize this function to provide customized headers for
different widgets.
'widget-prefix-fn' and 'widget-suffix-fn' allow specifying functions
that will be applied before and after the body is rendered.")
(:method (obj body-fn &rest args
&key widget-prefix-fn widget-suffix-fn
&allow-other-keys)
(with-html
(:div :class (dom-classes obj)
:id (dom-id obj)
(safe-apply widget-prefix-fn obj args)
(apply body-fn obj args)
(safe-apply widget-suffix-fn obj args)))))
(defgeneric render-widget-body (obj &rest args &key &allow-other-keys)
(:documentation
"A generic function that renders a widget in its current state. In
order to actually render the widget, call 'render-widget' instead.
'obj' - widget object to render.
One of the implementations allows \"rendering\" functions. When
'render-widget' is called on a function, the function is simply
called. This allows to easily add functions to composite widgets that
can do custom rendering without much boilerplate. Similarly symbols
that are fbound to functions can be treated as widgets.
Another implementation allows rendering strings."))
(defmethod render-widget-body ((obj symbol) &rest args)
(if (fboundp obj)
(apply obj args)
(error "Cannot render ~A as widget. Symbol not bound to a
function." obj)))
(defmethod render-widget-body ((obj function) &rest args)
(apply obj args))
(defmethod render-widget-body ((obj string) &rest args &key id class &allow-other-keys)
(declare (ignore args))
(with-html
(:p :id id :class class (str obj))))
(defmethod widget-prefix-fn (obj)
nil)
(defmethod widget-suffix-fn (obj)
nil)
(defgeneric render-widget (obj &key inlinep &allow-other-keys)
(:documentation
"Renders a widget ('render-widget-body') wrapped in a
header ('with-widget-header'). If 'inlinep' is true, renders the
widget without a header.
Additionally, calls 'dependencies' and adds the returned items to
*page-dependencies*. This is later used by Weblocks to declare
stylesheets and javascript links in the page header."))
(defmethod render-widget (obj &rest args &key inlinep &allow-other-keys)
(declare (special *page-dependencies*))
(if (ajax-request-p)
(dolist (dep (dependencies obj))
(send-script
(ps* `(,(typecase dep
(stylesheet-dependency 'include_css)
(script-dependency 'include_dom))
,(puri:render-uri (dependency-url dep) nil)))
:before-load))
(setf *page-dependencies*
(append *page-dependencies* (dependencies obj))))
(if inlinep
(apply #'render-widget-body obj args)
(apply #'with-widget-header obj #'render-widget-body
(append
(when (widget-prefix-fn obj)
(list :widget-prefix-fn (widget-prefix-fn obj)))
(when (widget-suffix-fn obj)
(list :widget-suffix-fn (widget-suffix-fn obj)))
args)))
(setf (widget-rendered-p obj) t))
(defmethod composite-widgets ((obj widget))
nil)
(defmethod composite-widgets ((obj function))
nil)
(defmethod composite-widgets ((obj symbol))
nil)
(defmethod composite-widgets ((obj string))
nil)
(defgeneric mark-dirty (w &key putp)
(:documentation
"Default implementation adds a widget to a list of dirty
widgets. Normally used during an AJAX request. If there are any
widgets in the 'propagate-dirty' slot of 'w' and 'putp' is true, these
widgets are added to the dirty list as well.
Note, this function is automatically called when widget slots are
modified, unless slots are marked with affects-dirty-status-p."))
(defmethod mark-dirty ((w widget) &key putp)
(declare (special *dirty-widgets*))
(when (functionp w)
(error "AJAX is not supported for functions. Convert the function
into a CLOS object derived from 'widget'."))
(ignore-errors
(when (widget-rendered-p w)
(setf *dirty-widgets* (adjoin w *dirty-widgets*)))
(when putp
(mapc #'mark-dirty
(remove nil (loop for i in (widget-propagate-dirty w)
collect (find-widget-by-path i)))))))
(defun widget-dirty-p (w)
"Returns true if the widget 'w' has been marked dirty."
(member w *dirty-widgets*))
(defmethod (setf slot-value-using-class) (new-value (class widget-class) (object widget)
(slot-name widget-effective-slot-definition))
(when (widget-slot-affects-dirty-status-p slot-name)
(mark-dirty object))
(call-next-method new-value class object slot-name))
(defgeneric find-widget-by-path* (path root)
(:documentation
"Returns a widget object located at 'path', where 'path' is a list
of widget names starting from root. For convinience, 'path' can be a
widget object, in which case it is simply returned.
'root' - a widget to start the search from."))
(defmethod find-widget-by-path* ((path (eql nil)) root)
root)
(defmethod find-widget-by-path* ((path widget) root)
path)
(defmethod find-widget-by-path* (path (root (eql nil)))
nil)
(defun find-widget-by-path (path &optional (root (root-composite)))
(find-widget-by-path* path root))
(defmethod print-object ((obj widget) stream)
(print-unreadable-object (obj stream :type t)
(format stream "~s" (ensure-dom-id obj))))
|
b51618d1359b822a24d42ffa31d77e4ac97e7913de943bba9167e351e79d7612 | haskell/text-icu | Properties.hs | -- Tester beware!
--
-- Many of the tests below are "weak", i.e. they ensure that functions
-- return results, without checking whether the results are correct.
-- Weak tests are described as such.
# LANGUAGE CPP #
# LANGUAGE OverloadedStrings , LambdaCase #
# OPTIONS_GHC -fno - warn - missing - signatures #
module Properties (propertyTests, testCases) where
import Control.DeepSeq (NFData(..))
import Data.Function (on)
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import Data.Text.ICU (LocaleName(..), ParseError(..))
import QuickCheckUtils (NonEmptyText(..), LatinSpoofableText(..),
NonSpoofableText(..), Utf8Text(..))
import Data.Text.ICU.Normalize2 (NormalizationMode(..))
import qualified Data.Text.ICU.Normalize2 as I
import Test.Framework (Test, testGroup)
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.Framework.Providers.HUnit (hUnitTestToTests)
import Test.HUnit ((~?=), (@?=), (~:))
import qualified Test.HUnit (Test(..), assertFailure)
import Test.QuickCheck.Monadic (monadicIO, run, assert)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.ICU as I
import qualified Data.Text.ICU.BiDi as BiDi
import qualified Data.Text.ICU.Calendar as Cal
import qualified Data.Text.ICU.Convert as I
import qualified Data.Text.ICU.Char as I
import qualified Data.Text.ICU.CharsetDetection as CD
import qualified Data.Text.ICU.Error as Err
import qualified Data.Text.ICU.Number as N
import qualified Data.Text.ICU.Shape as S
import System.IO.Unsafe (unsafePerformIO)
#if !MIN_VERSION_base(4,11,0)
import Data.Semigroup ((<>))
#endif
# ANN module ( " HLint : use camelCase"::String ) #
t_rnf :: (NFData b) => (a -> b) -> a -> Bool
t_rnf f t = rnf (f t) == ()
t_nonEmpty :: (Text -> Text) -> Text -> Bool
t_nonEmpty f t
| T.null t = T.null ft
| otherwise = T.length ft > 0
where ft = f t
-- Case mapping
-- These tests are all fairly weak.
t_toCaseFold bool = t_nonEmpty $ I.toCaseFold bool
t_toLower locale = t_nonEmpty $ I.toLower locale
t_toUpper locale = t_nonEmpty $ I.toUpper locale
-- Iteration
t_charIterator_String a b = (compare `on` I.fromString) a b == compare a b
t_charIterator_Text a b = (compare `on` I.fromText) a b == compare a b
t_charIterator_Utf8 a b = (compare `on` I.fromUtf8) ba bb == compare ba bb
where ba = T.encodeUtf8 a; bb = T.encodeUtf8 b
-- Normalization
t_quickCheck_isNormalized mode normMode txt
| mode `elem` [NFD, NFKD] = quickCheck == Just isNormalized
| otherwise = fromMaybe isNormalized quickCheck == isNormalized
where quickCheck = I.quickCheck mode normTxt
isNormalized = I.isNormalized mode normTxt
normTxt = I.normalize normMode txt
-- Collation
t_collate a b = c a b == flipOrdering (c b a)
where c = I.collate I.uca
t_collate_emptyRule a b = I.collate cUca a b == I.collate cEmpty a b
where
cUca = I.uca
cEmpty = either (error "Can’t create empty collator") id
$ I.collatorFromRules ""
flipOrdering :: Ordering -> Ordering
flipOrdering = \ case
GT -> LT
LT -> GT
EQ -> EQ
Convert
converter e = unsafePerformIO $ I.open e Nothing
t_convert a = I.toUnicode c (I.fromUnicode c a) == a
where c = converter "UTF-32"
-- Unicode character database
-- These tests are weak.
t_blockCode = t_rnf I.blockCode
t_charFullName c = I.charFromFullName (I.charFullName c) == Just c
t_charName c = maybe True (==c) $ I.charFromName (I.charName c)
t_combiningClass = t_rnf I.combiningClass
t_direction = t_rnf I.direction
t_property p = t_rnf $ I.property p
t_isMirrored = t_rnf $ I.isMirrored
t_mirror = t_rnf $ I.mirror
t_digitToInt = t_rnf $ I.digitToInt
t_numericValue = t_rnf $ I.numericValue
-- Spoofing
t_nonspoofable (NonSpoofableText t) = I.spoofCheck I.spoof t == I.CheckOK
t_spoofable (LatinSpoofableText t) = I.spoofCheck I.spoof t ==
I.CheckFailed [I.RestrictionLevel]
t_confusable (NonEmptyText t) = I.areConfusable I.spoof t t `elem`
[I.CheckFailed [I.MixedScriptConfusable]
,I.CheckFailed [I.SingleScriptConfusable]]
-- Encoding Guessing
t_Utf8IsUtf8 a = monadicIO $ do
val <- run $ CD.detect (utf8Text a) >>= CD.getName
assert $ T.isPrefixOf "UTF-8" val
propertyTests :: Test
propertyTests =
testGroup "Properties" [
testProperty "t_toCaseFold" t_toCaseFold
, testProperty "t_toLower" t_toLower
, testProperty "t_toUpper" t_toUpper
, testProperty "t_charIterator_String" t_charIterator_String
, testProperty "t_charIterator_Text" t_charIterator_Text
, testProperty "t_charIterator_Utf8" t_charIterator_Utf8
, testProperty "t_quickCheck_isNormalized" t_quickCheck_isNormalized
, testProperty "t_collate" t_collate
, testProperty "t_collate_emptyRule" t_collate_emptyRule
, testProperty "t_convert" t_convert
, testProperty "t_blockCode" t_blockCode
, testProperty "t_charFullName" t_charFullName
, testProperty "t_charName" t_charName
, testProperty "t_combiningClass" t_combiningClass
, testProperty "t_direction" $ t_direction
--, testProperty "t_property" t_property
, testProperty "t_isMirrored" t_isMirrored
, testProperty "t_mirror" t_mirror
, testProperty "t_digitToInt" t_digitToInt
, testProperty "t_numericValue" t_numericValue
, testProperty "t_spoofable" t_spoofable
, testProperty "t_nonspoofable" t_nonspoofable
, testProperty "t_confusable" t_confusable
, testProperty "t_Utf8IsUtf8" t_Utf8IsUtf8
]
testCases :: Test
testCases =
testGroup "Test cases" $ hUnitTestToTests $ Test.HUnit.TestList $
[I.normalize NFC "Ame\x0301lie" ~?= "Amélie"
,I.normalize NFC "(⊃。•́︵•̀。)⊃" ~?= "(⊃。•́︵•̀。)⊃"
,map I.brkBreak (I.breaks (I.breakWord (Locale "en_US")) "Hi, Amélie!")
~?= ["Hi",","," ","Amélie","!"]
,map I.brkBreak (I.breaksRight (I.breakLine (Locale "ru")) "Привет, мир!")
~?= ["мир!","Привет, "]
,(I.unfold I.group <$> I.findAll "[abc]+" "xx b yy ac") ~?= [["b"],["ac"]]
,I.toUpper (Locale "de-DE") "ß" ~?= "SS"
,I.toCaseFold False "flag" ~?= "flag"
,I.blockCode '\x1FA50' ~?= I.ChessSymbols
,I.direction '\x2068' ~?= I.FirstStrongIsolate
,I.getSkeleton I.spoof Nothing "\1089\1072t" ~?= "cat"
,S.shapeArabic [S.LettersShape] (nosp "ا ب ت ث") ~?= (nosp "ﺍ ﺑ ﺘ ﺚ")
,BiDi.reorderParagraphs [] (nosp "abc ا ب ت ث def\n123")
~?= ["abc" <> T.reverse (nosp "ا ب ت ث") <> "def\n", "123"]
,N.formatNumber (N.numberFormatter N.NUM_CURRENCY_PLURAL "en_US")
(12.5 :: Double) ~?= "12.50 US dollars"
,do
dfDe <- I.standardDateFormatter I.LongFormatStyle I.LongFormatStyle
(Locale "de_DE") ""
c <- cal "CET" 2000 00 01 02 03 00
return $ I.formatCalendar dfDe (Cal.add c [(Cal.Hour, 25), (Cal.Second, 65)])
`ioEq`
"2. Januar 2000 um 03:04:05 GMT+1"
,do
dfAt <- I.standardDateFormatter I.LongFormatStyle I.LongFormatStyle
(Locale "de_AT") "CET"
return $ I.dateSymbols dfAt I.Months
`ioEq`
["Jänner","Februar","März","April","Mai","Juni"
,"Juli","August","September","Oktober","November","Dezember"]
,do
dfP <- I.patternDateFormatter
"MMMM dd, yyyy GGGG, hh 'o''clock' a, VVVV" (Locale "en_US") ""
c <- cal "America/Los_Angeles" 2000 00 02 03 04 05
return $ I.formatCalendar dfP c
`ioEq`
"January 02, 2000 Anno Domini, 03 o'clock AM, Los Angeles Time"
,(flip Cal.getField Cal.Year =<< cal "UTC" 1999 01 02 03 04 05) `ioEq` 1999
,(elem "en_US" <$> I.availableLocales) `ioEq` True
,(flip I.formatIntegral (12345 :: Int)
<$> I.numberFormatter "precision-integer" (Locale "fr"))
`ioEq` "12\8239\&345"
,(flip I.formatDouble 12345.6789
<$> I.numberFormatter "precision-currency-cash currency/EUR" (Locale "it"))
`ioEq` "12.345,68\160€"
, Test.HUnit.TestLabel "collate" testCases_collate
]
<>
concat
[conv "ISO-2022-CN" "程序設計" "\ESC$)A\SO3LPr\ESC$)G]CSS\SI"
,conv "cp1251" "Привет, мир!" "\207\240\232\226\229\242, \236\232\240!"
]
where conv n f t = [I.fromUnicode c f ~?= t, I.toUnicode c t ~?= f]
where c = converter n
nosp = T.filter (/= ' ')
cal tz y m d h mn s = do
c <- Cal.calendar tz (Locale "en_US") Cal.TraditionalCalendarType
Cal.setDateTime c y m d h mn s
return c
ioEq io a = Test.HUnit.TestCase $ do
x <- io
x @?= a
testCases_collate :: Test.HUnit.Test
testCases_collate = Test.HUnit.TestList $
[ Test.HUnit.TestLabel "invalid format" $
assertParseError (I.collatorFromRules "& a < <") Err.u_INVALID_FORMAT_ERROR (Just 0) (Just 4)
, Test.HUnit.TestLabel "custom collator" $ Test.HUnit.TestCase $ do
let c = either (error "Can’t create b<a collator") id
$ I.collatorFromRules "& b < a"
I.collate c "a" "b" @?= GT
]
where
assertParseError (Left e) err line offset = Test.HUnit.TestList
[ "errError" ~: errError e ~?= err
, "errLine" ~: errLine e ~?= line
, "errOffset" ~: errOffset e ~?= offset
]
assertParseError (Right _) _ _ _ = Test.HUnit.TestCase $ Test.HUnit.assertFailure "Expects a Left"
| null | https://raw.githubusercontent.com/haskell/text-icu/5e0914e8c0cac72eedad05c820d1d700cdf79d39/tests/Properties.hs | haskell | Tester beware!
Many of the tests below are "weak", i.e. they ensure that functions
return results, without checking whether the results are correct.
Weak tests are described as such.
Case mapping
These tests are all fairly weak.
Iteration
Normalization
Collation
Unicode character database
These tests are weak.
Spoofing
Encoding Guessing
, testProperty "t_property" t_property |
# LANGUAGE CPP #
# LANGUAGE OverloadedStrings , LambdaCase #
# OPTIONS_GHC -fno - warn - missing - signatures #
module Properties (propertyTests, testCases) where
import Control.DeepSeq (NFData(..))
import Data.Function (on)
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import Data.Text.ICU (LocaleName(..), ParseError(..))
import QuickCheckUtils (NonEmptyText(..), LatinSpoofableText(..),
NonSpoofableText(..), Utf8Text(..))
import Data.Text.ICU.Normalize2 (NormalizationMode(..))
import qualified Data.Text.ICU.Normalize2 as I
import Test.Framework (Test, testGroup)
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.Framework.Providers.HUnit (hUnitTestToTests)
import Test.HUnit ((~?=), (@?=), (~:))
import qualified Test.HUnit (Test(..), assertFailure)
import Test.QuickCheck.Monadic (monadicIO, run, assert)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.ICU as I
import qualified Data.Text.ICU.BiDi as BiDi
import qualified Data.Text.ICU.Calendar as Cal
import qualified Data.Text.ICU.Convert as I
import qualified Data.Text.ICU.Char as I
import qualified Data.Text.ICU.CharsetDetection as CD
import qualified Data.Text.ICU.Error as Err
import qualified Data.Text.ICU.Number as N
import qualified Data.Text.ICU.Shape as S
import System.IO.Unsafe (unsafePerformIO)
#if !MIN_VERSION_base(4,11,0)
import Data.Semigroup ((<>))
#endif
# ANN module ( " HLint : use camelCase"::String ) #
t_rnf :: (NFData b) => (a -> b) -> a -> Bool
t_rnf f t = rnf (f t) == ()
t_nonEmpty :: (Text -> Text) -> Text -> Bool
t_nonEmpty f t
| T.null t = T.null ft
| otherwise = T.length ft > 0
where ft = f t
t_toCaseFold bool = t_nonEmpty $ I.toCaseFold bool
t_toLower locale = t_nonEmpty $ I.toLower locale
t_toUpper locale = t_nonEmpty $ I.toUpper locale
t_charIterator_String a b = (compare `on` I.fromString) a b == compare a b
t_charIterator_Text a b = (compare `on` I.fromText) a b == compare a b
t_charIterator_Utf8 a b = (compare `on` I.fromUtf8) ba bb == compare ba bb
where ba = T.encodeUtf8 a; bb = T.encodeUtf8 b
t_quickCheck_isNormalized mode normMode txt
| mode `elem` [NFD, NFKD] = quickCheck == Just isNormalized
| otherwise = fromMaybe isNormalized quickCheck == isNormalized
where quickCheck = I.quickCheck mode normTxt
isNormalized = I.isNormalized mode normTxt
normTxt = I.normalize normMode txt
t_collate a b = c a b == flipOrdering (c b a)
where c = I.collate I.uca
t_collate_emptyRule a b = I.collate cUca a b == I.collate cEmpty a b
where
cUca = I.uca
cEmpty = either (error "Can’t create empty collator") id
$ I.collatorFromRules ""
flipOrdering :: Ordering -> Ordering
flipOrdering = \ case
GT -> LT
LT -> GT
EQ -> EQ
Convert
converter e = unsafePerformIO $ I.open e Nothing
t_convert a = I.toUnicode c (I.fromUnicode c a) == a
where c = converter "UTF-32"
t_blockCode = t_rnf I.blockCode
t_charFullName c = I.charFromFullName (I.charFullName c) == Just c
t_charName c = maybe True (==c) $ I.charFromName (I.charName c)
t_combiningClass = t_rnf I.combiningClass
t_direction = t_rnf I.direction
t_property p = t_rnf $ I.property p
t_isMirrored = t_rnf $ I.isMirrored
t_mirror = t_rnf $ I.mirror
t_digitToInt = t_rnf $ I.digitToInt
t_numericValue = t_rnf $ I.numericValue
t_nonspoofable (NonSpoofableText t) = I.spoofCheck I.spoof t == I.CheckOK
t_spoofable (LatinSpoofableText t) = I.spoofCheck I.spoof t ==
I.CheckFailed [I.RestrictionLevel]
t_confusable (NonEmptyText t) = I.areConfusable I.spoof t t `elem`
[I.CheckFailed [I.MixedScriptConfusable]
,I.CheckFailed [I.SingleScriptConfusable]]
t_Utf8IsUtf8 a = monadicIO $ do
val <- run $ CD.detect (utf8Text a) >>= CD.getName
assert $ T.isPrefixOf "UTF-8" val
propertyTests :: Test
propertyTests =
testGroup "Properties" [
testProperty "t_toCaseFold" t_toCaseFold
, testProperty "t_toLower" t_toLower
, testProperty "t_toUpper" t_toUpper
, testProperty "t_charIterator_String" t_charIterator_String
, testProperty "t_charIterator_Text" t_charIterator_Text
, testProperty "t_charIterator_Utf8" t_charIterator_Utf8
, testProperty "t_quickCheck_isNormalized" t_quickCheck_isNormalized
, testProperty "t_collate" t_collate
, testProperty "t_collate_emptyRule" t_collate_emptyRule
, testProperty "t_convert" t_convert
, testProperty "t_blockCode" t_blockCode
, testProperty "t_charFullName" t_charFullName
, testProperty "t_charName" t_charName
, testProperty "t_combiningClass" t_combiningClass
, testProperty "t_direction" $ t_direction
, testProperty "t_isMirrored" t_isMirrored
, testProperty "t_mirror" t_mirror
, testProperty "t_digitToInt" t_digitToInt
, testProperty "t_numericValue" t_numericValue
, testProperty "t_spoofable" t_spoofable
, testProperty "t_nonspoofable" t_nonspoofable
, testProperty "t_confusable" t_confusable
, testProperty "t_Utf8IsUtf8" t_Utf8IsUtf8
]
testCases :: Test
testCases =
testGroup "Test cases" $ hUnitTestToTests $ Test.HUnit.TestList $
[I.normalize NFC "Ame\x0301lie" ~?= "Amélie"
,I.normalize NFC "(⊃。•́︵•̀。)⊃" ~?= "(⊃。•́︵•̀。)⊃"
,map I.brkBreak (I.breaks (I.breakWord (Locale "en_US")) "Hi, Amélie!")
~?= ["Hi",","," ","Amélie","!"]
,map I.brkBreak (I.breaksRight (I.breakLine (Locale "ru")) "Привет, мир!")
~?= ["мир!","Привет, "]
,(I.unfold I.group <$> I.findAll "[abc]+" "xx b yy ac") ~?= [["b"],["ac"]]
,I.toUpper (Locale "de-DE") "ß" ~?= "SS"
,I.toCaseFold False "flag" ~?= "flag"
,I.blockCode '\x1FA50' ~?= I.ChessSymbols
,I.direction '\x2068' ~?= I.FirstStrongIsolate
,I.getSkeleton I.spoof Nothing "\1089\1072t" ~?= "cat"
,S.shapeArabic [S.LettersShape] (nosp "ا ب ت ث") ~?= (nosp "ﺍ ﺑ ﺘ ﺚ")
,BiDi.reorderParagraphs [] (nosp "abc ا ب ت ث def\n123")
~?= ["abc" <> T.reverse (nosp "ا ب ت ث") <> "def\n", "123"]
,N.formatNumber (N.numberFormatter N.NUM_CURRENCY_PLURAL "en_US")
(12.5 :: Double) ~?= "12.50 US dollars"
,do
dfDe <- I.standardDateFormatter I.LongFormatStyle I.LongFormatStyle
(Locale "de_DE") ""
c <- cal "CET" 2000 00 01 02 03 00
return $ I.formatCalendar dfDe (Cal.add c [(Cal.Hour, 25), (Cal.Second, 65)])
`ioEq`
"2. Januar 2000 um 03:04:05 GMT+1"
,do
dfAt <- I.standardDateFormatter I.LongFormatStyle I.LongFormatStyle
(Locale "de_AT") "CET"
return $ I.dateSymbols dfAt I.Months
`ioEq`
["Jänner","Februar","März","April","Mai","Juni"
,"Juli","August","September","Oktober","November","Dezember"]
,do
dfP <- I.patternDateFormatter
"MMMM dd, yyyy GGGG, hh 'o''clock' a, VVVV" (Locale "en_US") ""
c <- cal "America/Los_Angeles" 2000 00 02 03 04 05
return $ I.formatCalendar dfP c
`ioEq`
"January 02, 2000 Anno Domini, 03 o'clock AM, Los Angeles Time"
,(flip Cal.getField Cal.Year =<< cal "UTC" 1999 01 02 03 04 05) `ioEq` 1999
,(elem "en_US" <$> I.availableLocales) `ioEq` True
,(flip I.formatIntegral (12345 :: Int)
<$> I.numberFormatter "precision-integer" (Locale "fr"))
`ioEq` "12\8239\&345"
,(flip I.formatDouble 12345.6789
<$> I.numberFormatter "precision-currency-cash currency/EUR" (Locale "it"))
`ioEq` "12.345,68\160€"
, Test.HUnit.TestLabel "collate" testCases_collate
]
<>
concat
[conv "ISO-2022-CN" "程序設計" "\ESC$)A\SO3LPr\ESC$)G]CSS\SI"
,conv "cp1251" "Привет, мир!" "\207\240\232\226\229\242, \236\232\240!"
]
where conv n f t = [I.fromUnicode c f ~?= t, I.toUnicode c t ~?= f]
where c = converter n
nosp = T.filter (/= ' ')
cal tz y m d h mn s = do
c <- Cal.calendar tz (Locale "en_US") Cal.TraditionalCalendarType
Cal.setDateTime c y m d h mn s
return c
ioEq io a = Test.HUnit.TestCase $ do
x <- io
x @?= a
testCases_collate :: Test.HUnit.Test
testCases_collate = Test.HUnit.TestList $
[ Test.HUnit.TestLabel "invalid format" $
assertParseError (I.collatorFromRules "& a < <") Err.u_INVALID_FORMAT_ERROR (Just 0) (Just 4)
, Test.HUnit.TestLabel "custom collator" $ Test.HUnit.TestCase $ do
let c = either (error "Can’t create b<a collator") id
$ I.collatorFromRules "& b < a"
I.collate c "a" "b" @?= GT
]
where
assertParseError (Left e) err line offset = Test.HUnit.TestList
[ "errError" ~: errError e ~?= err
, "errLine" ~: errLine e ~?= line
, "errOffset" ~: errOffset e ~?= offset
]
assertParseError (Right _) _ _ _ = Test.HUnit.TestCase $ Test.HUnit.assertFailure "Expects a Left"
|
1628a9660b3534d4b666a370c2b4744eb8eb1aa87e9abab23b339af49d68a43c | ktakashi/sagittarius-scheme | json-object.scm | (import (rnrs)
(text json object-builder)
(text json)
(srfi :64 testing))
(test-begin "JSON object")
(define-record-type location
(fields precision latitude longitude address city state zip country))
(test-assert (json:builder? (json-object-builder
(@ list
(make-location
"precision"
"Latitude"
"Longitude"
"Address"
"City"
"State"
"Zip"
"Country")))))
(let* ((json-string "[
{
\"precision\": \"zip\",
\"Latitude\": 37.7668,
\"Longitude\": -122.3959,
\"Address\": \"\",
\"City\": \"SAN FRANCISCO\",
\"State\": \"CA\",
\"Zip\": \"94107\",
\"Country\": \"US\"
},
{
\"precision\": \"zip\",
\"Latitude\": 37.371991,
\"Longitude\": -122.026020,
\"City\": \"SUNNYVALE\",
\"State\": \"CA\",
\"Zip\": \"94085\",
\"Country\": \"US\"
}
]")
(builder (json-object-builder
(@ list
(make-location
"precision"
"Latitude"
"Longitude"
(? "Address" #f)
"City"
"State"
"Zip"
"Country"))))
(serializer (json-object-serializer
(-> (("precision" location-precision)
("Latitude" location-latitude)
("Longitude" location-longitude)
(? "Address" #f location-address)
("City" location-city)
("State" location-state)
("Zip" location-zip)
("Country" location-country)))))
(v (json-string->object json-string builder)))
(define-syntax check-location
(syntax-rules ()
((_ loc precision latitude longitude address city state zip country)
(let ((loc1 loc))
(test-equal precision (location-precision loc1))
(test-equal latitude (location-latitude loc1))
(test-equal longitude (location-longitude loc1))
(test-equal address (location-address loc1))
(test-equal city (location-city loc1))
(test-equal state (location-state loc1))
(test-equal zip (location-zip loc1))
(test-equal country (location-country loc1))))))
(test-assert (list? v))
(test-assert (for-all location? v))
(test-equal 2 (length v))
(check-location (car v) "zip" 37.7668 -122.3959
"" "SAN FRANCISCO" "CA" "94107" "US")
(check-location (cadr v)
"zip" 37.371991 -122.026020 #f "SUNNYVALE"
"CA" "94085" "US")
(test-assert (json:serializer? serializer))
(let ((s (object->json-string v serializer)))
(test-assert (string? s))
(test-equal (json-read (open-string-input-port json-string))
(json-read (open-string-input-port s)))))
(define-record-type image-holder
(fields image))
(define-record-type image
(fields width height title thumbnail animated ids))
(define-record-type thumbnail
(fields url height width))
(let* ((json-string "{
\"Image\": {
\"Width\": 800,
\"Height\": 600,
\"Title\": \"View from 15th Floor\",
\"Thumbnail\": {
\"Url\": \"\",
\"Height\": 125,
\"Width\": 100
},
\"Animated\" : false,
\"IDs\": [116, 943, 234, 38793]
}
}"
)
(builder (json-object-builder
(make-image-holder
("Image"
(make-image
"Width"
"Height"
"Title"
("Thumbnail"
(make-thumbnail
"Url"
"Height"
"Width"))
"Animated"
("IDs" (@ list)))))))
(serializer (json-object-serializer
(("Image" image-holder-image
(("Width" image-width)
("Height" image-height)
("Title" image-title)
("Thumbnail" image-thumbnail
(("Url" thumbnail-url)
("Height" thumbnail-height)
("Width" thumbnail-width)))
("Animated" image-animated)
("IDs" image-ids (->)))))))
(v (json-string->object json-string builder)))
(test-assert (image-holder? v))
(let ((image (image-holder-image v)))
(test-assert (image? image))
(test-equal '(116 943 234 38793) (image-ids image))
(let ((thumbnail (image-thumbnail image)))
(test-assert (thumbnail? thumbnail))
(test-equal ""
(thumbnail-url thumbnail))))
(let ((s (object->json-string v serializer)))
(test-equal (json-read (open-string-input-port json-string))
(json-read (open-string-input-port s)))))
;; other tests
(let ()
(define-record-type foo
(fields bar))
(define serializer
(json-object-serializer
(("bar" foo-bar (@)))))
(test-equal "{\"bar\": [1, 2, 3]}"
(object->json-string (make-foo '#(1 2 3)) serializer)))
(let ()
(define-record-type foo
(fields bar))
(define serializer
(json-object-serializer
(("bar" foo-bar (@ bytevector-u8-ref bytevector-length)))))
(test-equal "{\"bar\": [1, 2, 3]}"
(object->json-string (make-foo '#vu8(1 2 3)) serializer)))
(let ((json-string "{\"bar\": {\"buz\": 1}}"))
(define-record-type foo
(fields bar))
(define-record-type bar
(fields buz))
(define bar-serializer
(json-object-serializer
(("buz" bar-buz))))
(define serializer
(json-object-serializer
(("bar" foo-bar bar-serializer))))
(define bar-builder (json-object-builder (make-bar "buz")))
(define builder (json-object-builder (make-foo ("bar" bar-builder))))
(test-equal json-string
(object->json-string
(json-string->object json-string builder)
serializer)))
(let ()
(define-record-type base (fields base))
(define-record-type sub (fields sub) (parent base))
(define base-builder (json-object-builder (make-base "base")))
(define sub-builder (json-object-builder (make-sub base-builder "sub")))
(define base-serializer (json-object-serializer (("base" base-base))))
(define sub-serializer (json-object-serializer
(base-serializer ("sub" sub-sub))))
(test-equal '#(("base" . "base") ("sub" . "sub"))
(object->json (make-sub "base" "sub") sub-serializer))
(let ((s (json->object '#(("base" . "base") ("sub" . "sub")) sub-builder)))
(test-assert (sub? s))
(test-equal "base" (base-base s))
(test-equal "sub" (sub-sub s)))
)
(test-end)
| null | https://raw.githubusercontent.com/ktakashi/sagittarius-scheme/44e49b4ed45ac3a715bbe93624a068ba13c20b68/test/tests/text/json-object.scm | scheme | other tests | (import (rnrs)
(text json object-builder)
(text json)
(srfi :64 testing))
(test-begin "JSON object")
(define-record-type location
(fields precision latitude longitude address city state zip country))
(test-assert (json:builder? (json-object-builder
(@ list
(make-location
"precision"
"Latitude"
"Longitude"
"Address"
"City"
"State"
"Zip"
"Country")))))
(let* ((json-string "[
{
\"precision\": \"zip\",
\"Latitude\": 37.7668,
\"Longitude\": -122.3959,
\"Address\": \"\",
\"City\": \"SAN FRANCISCO\",
\"State\": \"CA\",
\"Zip\": \"94107\",
\"Country\": \"US\"
},
{
\"precision\": \"zip\",
\"Latitude\": 37.371991,
\"Longitude\": -122.026020,
\"City\": \"SUNNYVALE\",
\"State\": \"CA\",
\"Zip\": \"94085\",
\"Country\": \"US\"
}
]")
(builder (json-object-builder
(@ list
(make-location
"precision"
"Latitude"
"Longitude"
(? "Address" #f)
"City"
"State"
"Zip"
"Country"))))
(serializer (json-object-serializer
(-> (("precision" location-precision)
("Latitude" location-latitude)
("Longitude" location-longitude)
(? "Address" #f location-address)
("City" location-city)
("State" location-state)
("Zip" location-zip)
("Country" location-country)))))
(v (json-string->object json-string builder)))
(define-syntax check-location
(syntax-rules ()
((_ loc precision latitude longitude address city state zip country)
(let ((loc1 loc))
(test-equal precision (location-precision loc1))
(test-equal latitude (location-latitude loc1))
(test-equal longitude (location-longitude loc1))
(test-equal address (location-address loc1))
(test-equal city (location-city loc1))
(test-equal state (location-state loc1))
(test-equal zip (location-zip loc1))
(test-equal country (location-country loc1))))))
(test-assert (list? v))
(test-assert (for-all location? v))
(test-equal 2 (length v))
(check-location (car v) "zip" 37.7668 -122.3959
"" "SAN FRANCISCO" "CA" "94107" "US")
(check-location (cadr v)
"zip" 37.371991 -122.026020 #f "SUNNYVALE"
"CA" "94085" "US")
(test-assert (json:serializer? serializer))
(let ((s (object->json-string v serializer)))
(test-assert (string? s))
(test-equal (json-read (open-string-input-port json-string))
(json-read (open-string-input-port s)))))
(define-record-type image-holder
(fields image))
(define-record-type image
(fields width height title thumbnail animated ids))
(define-record-type thumbnail
(fields url height width))
(let* ((json-string "{
\"Image\": {
\"Width\": 800,
\"Height\": 600,
\"Title\": \"View from 15th Floor\",
\"Thumbnail\": {
\"Url\": \"\",
\"Height\": 125,
\"Width\": 100
},
\"Animated\" : false,
\"IDs\": [116, 943, 234, 38793]
}
}"
)
(builder (json-object-builder
(make-image-holder
("Image"
(make-image
"Width"
"Height"
"Title"
("Thumbnail"
(make-thumbnail
"Url"
"Height"
"Width"))
"Animated"
("IDs" (@ list)))))))
(serializer (json-object-serializer
(("Image" image-holder-image
(("Width" image-width)
("Height" image-height)
("Title" image-title)
("Thumbnail" image-thumbnail
(("Url" thumbnail-url)
("Height" thumbnail-height)
("Width" thumbnail-width)))
("Animated" image-animated)
("IDs" image-ids (->)))))))
(v (json-string->object json-string builder)))
(test-assert (image-holder? v))
(let ((image (image-holder-image v)))
(test-assert (image? image))
(test-equal '(116 943 234 38793) (image-ids image))
(let ((thumbnail (image-thumbnail image)))
(test-assert (thumbnail? thumbnail))
(test-equal ""
(thumbnail-url thumbnail))))
(let ((s (object->json-string v serializer)))
(test-equal (json-read (open-string-input-port json-string))
(json-read (open-string-input-port s)))))
(let ()
(define-record-type foo
(fields bar))
(define serializer
(json-object-serializer
(("bar" foo-bar (@)))))
(test-equal "{\"bar\": [1, 2, 3]}"
(object->json-string (make-foo '#(1 2 3)) serializer)))
(let ()
(define-record-type foo
(fields bar))
(define serializer
(json-object-serializer
(("bar" foo-bar (@ bytevector-u8-ref bytevector-length)))))
(test-equal "{\"bar\": [1, 2, 3]}"
(object->json-string (make-foo '#vu8(1 2 3)) serializer)))
(let ((json-string "{\"bar\": {\"buz\": 1}}"))
(define-record-type foo
(fields bar))
(define-record-type bar
(fields buz))
(define bar-serializer
(json-object-serializer
(("buz" bar-buz))))
(define serializer
(json-object-serializer
(("bar" foo-bar bar-serializer))))
(define bar-builder (json-object-builder (make-bar "buz")))
(define builder (json-object-builder (make-foo ("bar" bar-builder))))
(test-equal json-string
(object->json-string
(json-string->object json-string builder)
serializer)))
(let ()
(define-record-type base (fields base))
(define-record-type sub (fields sub) (parent base))
(define base-builder (json-object-builder (make-base "base")))
(define sub-builder (json-object-builder (make-sub base-builder "sub")))
(define base-serializer (json-object-serializer (("base" base-base))))
(define sub-serializer (json-object-serializer
(base-serializer ("sub" sub-sub))))
(test-equal '#(("base" . "base") ("sub" . "sub"))
(object->json (make-sub "base" "sub") sub-serializer))
(let ((s (json->object '#(("base" . "base") ("sub" . "sub")) sub-builder)))
(test-assert (sub? s))
(test-equal "base" (base-base s))
(test-equal "sub" (sub-sub s)))
)
(test-end)
|
ad9c61d3a6835fc31fc6171654616b31e83193a476d464ee67dd19468c6dd247 | PLTools/GT | test807showT.ml |
let i d x = x
let show_typed_string = Printf.sprintf " \"%s\ " "
module AL : sig
type ( ' a,'b ) alist = Nil | Cons of ' a * ' b
[ @@deriving gt ~options:{show_typed ; } ]
end = struct
type ( ' a,'b ) alist = Nil | Cons of ' a * ' b
[ @@deriving gt ~options:{show_typed ; } ]
end
let ( ) =
let open AL in
let sh xs = show_typed_alist
" string " show_typed_string
" string " show_typed_string xs
in
Printf.printf " % s\n% ! " ( sh @@ Cons ( " aaa " , " bbb " ) ) ;
( )
module L : sig
type ' a list = ( ' a , ' a list ) AL.alist
[ @@deriving gt ~options:{show_typed ; } ]
end = struct
type ' a list = ( ' a , ' a list ) AL.alist
[ @@deriving gt ~options:{show_typed ; } ]
end
let ( ) =
let open L in
let sh x = show_typed_list " string " show_typed_string x in
Printf.printf " % s\n% ! " ( sh @@ Cons ( " aaa " , Cons ( " bbb " , ) ) )
module GT = struct
include GT
let int =
int.gcata ;
plugins = object
method show_typed =
method show =
method gmap = int.plugins#gmap
end
}
end
module : sig
type ' a logic = Var of GT.int | Value of ' a
[ @@deriving gt ~options:{show_typed ; } ]
end = struct
type ' a logic = Var of GT.int | Value of ' a
[ @@deriving gt ~options:{show_typed ; } ]
end
( * enhancing a class to print a type for constructor
let id x = x
let show_typed_string = Printf.sprintf "\"%s\""
module AL : sig
type ('a,'b) alist = Nil | Cons of 'a * 'b
[@@deriving gt ~options:{show_typed;}]
end = struct
type ('a,'b) alist = Nil | Cons of 'a * 'b
[@@deriving gt ~options:{show_typed;}]
end
let () =
let open AL in
let sh xs = show_typed_alist
"string" show_typed_string
"string" show_typed_string xs
in
Printf.printf "%s\n%!" (sh @@ Cons ("aaa", "bbb"));
()
module L : sig
type 'a list = ('a, 'a list) AL.alist
[@@deriving gt ~options:{show_typed;}]
end = struct
type 'a list = ('a, 'a list) AL.alist
[@@deriving gt ~options:{show_typed;}]
end
let () =
let open L in
let sh x = show_typed_list "string" show_typed_string x in
Printf.printf "%s\n%!" (sh @@ Cons ("aaa", Cons ("bbb", Nil)))
module GT = struct
include GT
let int =
{gcata = int.gcata;
plugins = object
method show_typed = int.plugins#show
method show = int.plugins#show
method gmap = int.plugins#gmap
end
}
end
module Lo : sig
type 'a logic = Var of GT.int | Value of 'a
[@@deriving gt ~options:{show_typed;}]
end = struct
type 'a logic = Var of GT.int | Value of 'a
[@@deriving gt ~options:{show_typed;}]
end
(* enhancing a class to print a type for constructor Var *)
class ['a,'extra] show_typed_logic fself typ_a fa = object
inherit ['a, 'extra] Lo.show_typed_logic_t fself typ_a fa
method c_Var () _a =
Format.sprintf "Var(%s : %s)"
((GT.int.GT.plugins)#show_typed _a)
typ_a
end
let rec custom_show_typed_logic typ_a fa subj =
GT.fix0
(fun self -> Lo.gcata_logic ((new show_typed_logic) self typ_a fa) ())
subj
let () =
let open Lo in
let sh x = custom_show_typed_logic "string" show_typed_string x in
Printf.printf "%s\t%s\n%!" (sh @@ Var 5) (sh @@ Value "asdf")
module LList : sig
type 'a llist = ('a, 'a llist) AL.alist Lo.logic
[@@deriving gt ~options:{show_typed;}]
end = struct
type 'a llist = ('a, 'a llist) AL.alist Lo.logic
[@@deriving gt ~options:{show_typed;}]
end
let () =
let sh x = LList.show_typed_llist "string" show_typed_string x in
Printf.printf "%s\n%!" (sh @@ Value (Cons ("aaa", Value (Cons ("bbb", Var 15)))) )
(* Now let's try show_typed for mutal recursion *)
module Mutal : sig
type 'a foo = F1 of 'a | F2 of 'a boo
and 'b boo = B1 of 'b | B2 of 'b foo
[@@deriving gt ~options:{show_typed;}]
end = struct
type 'a foo = F1 of 'a | F2 of 'a boo
and 'b boo = B1 of 'b | B2 of 'b foo
[@@deriving gt ~options:{show_typed;}]
let () =
let sh1 x = show_typed_foo "string" show_typed_string x in
let sh2 x = show_typed_boo "string" show_typed_string x in
Printf.printf "%s\n%!" (sh1 @@ F2 (B2 (F1 "asdf")));
Printf.printf "%s\n%!" (sh1 @@ F2 (B2 (F2 (B1 "z"))));
Printf.printf "%s\n%!" (sh2 @@ B2 (F2 (B2 (F1 "asdf"))) );
Printf.printf "%s\n%!" (sh2 @@ B2 (F2 (B2 (F2 (B1 "z")))) );
()
end
*)
| null | https://raw.githubusercontent.com/PLTools/GT/62d1a424a3336f2317ba67e447a9ff09d179b583/regression/test807showT.ml | ocaml | enhancing a class to print a type for constructor Var
Now let's try show_typed for mutal recursion |
let i d x = x
let show_typed_string = Printf.sprintf " \"%s\ " "
module AL : sig
type ( ' a,'b ) alist = Nil | Cons of ' a * ' b
[ @@deriving gt ~options:{show_typed ; } ]
end = struct
type ( ' a,'b ) alist = Nil | Cons of ' a * ' b
[ @@deriving gt ~options:{show_typed ; } ]
end
let ( ) =
let open AL in
let sh xs = show_typed_alist
" string " show_typed_string
" string " show_typed_string xs
in
Printf.printf " % s\n% ! " ( sh @@ Cons ( " aaa " , " bbb " ) ) ;
( )
module L : sig
type ' a list = ( ' a , ' a list ) AL.alist
[ @@deriving gt ~options:{show_typed ; } ]
end = struct
type ' a list = ( ' a , ' a list ) AL.alist
[ @@deriving gt ~options:{show_typed ; } ]
end
let ( ) =
let open L in
let sh x = show_typed_list " string " show_typed_string x in
Printf.printf " % s\n% ! " ( sh @@ Cons ( " aaa " , Cons ( " bbb " , ) ) )
module GT = struct
include GT
let int =
int.gcata ;
plugins = object
method show_typed =
method show =
method gmap = int.plugins#gmap
end
}
end
module : sig
type ' a logic = Var of GT.int | Value of ' a
[ @@deriving gt ~options:{show_typed ; } ]
end = struct
type ' a logic = Var of GT.int | Value of ' a
[ @@deriving gt ~options:{show_typed ; } ]
end
( * enhancing a class to print a type for constructor
let id x = x
let show_typed_string = Printf.sprintf "\"%s\""
module AL : sig
type ('a,'b) alist = Nil | Cons of 'a * 'b
[@@deriving gt ~options:{show_typed;}]
end = struct
type ('a,'b) alist = Nil | Cons of 'a * 'b
[@@deriving gt ~options:{show_typed;}]
end
let () =
let open AL in
let sh xs = show_typed_alist
"string" show_typed_string
"string" show_typed_string xs
in
Printf.printf "%s\n%!" (sh @@ Cons ("aaa", "bbb"));
()
module L : sig
type 'a list = ('a, 'a list) AL.alist
[@@deriving gt ~options:{show_typed;}]
end = struct
type 'a list = ('a, 'a list) AL.alist
[@@deriving gt ~options:{show_typed;}]
end
let () =
let open L in
let sh x = show_typed_list "string" show_typed_string x in
Printf.printf "%s\n%!" (sh @@ Cons ("aaa", Cons ("bbb", Nil)))
module GT = struct
include GT
let int =
{gcata = int.gcata;
plugins = object
method show_typed = int.plugins#show
method show = int.plugins#show
method gmap = int.plugins#gmap
end
}
end
module Lo : sig
type 'a logic = Var of GT.int | Value of 'a
[@@deriving gt ~options:{show_typed;}]
end = struct
type 'a logic = Var of GT.int | Value of 'a
[@@deriving gt ~options:{show_typed;}]
end
class ['a,'extra] show_typed_logic fself typ_a fa = object
inherit ['a, 'extra] Lo.show_typed_logic_t fself typ_a fa
method c_Var () _a =
Format.sprintf "Var(%s : %s)"
((GT.int.GT.plugins)#show_typed _a)
typ_a
end
let rec custom_show_typed_logic typ_a fa subj =
GT.fix0
(fun self -> Lo.gcata_logic ((new show_typed_logic) self typ_a fa) ())
subj
let () =
let open Lo in
let sh x = custom_show_typed_logic "string" show_typed_string x in
Printf.printf "%s\t%s\n%!" (sh @@ Var 5) (sh @@ Value "asdf")
module LList : sig
type 'a llist = ('a, 'a llist) AL.alist Lo.logic
[@@deriving gt ~options:{show_typed;}]
end = struct
type 'a llist = ('a, 'a llist) AL.alist Lo.logic
[@@deriving gt ~options:{show_typed;}]
end
let () =
let sh x = LList.show_typed_llist "string" show_typed_string x in
Printf.printf "%s\n%!" (sh @@ Value (Cons ("aaa", Value (Cons ("bbb", Var 15)))) )
module Mutal : sig
type 'a foo = F1 of 'a | F2 of 'a boo
and 'b boo = B1 of 'b | B2 of 'b foo
[@@deriving gt ~options:{show_typed;}]
end = struct
type 'a foo = F1 of 'a | F2 of 'a boo
and 'b boo = B1 of 'b | B2 of 'b foo
[@@deriving gt ~options:{show_typed;}]
let () =
let sh1 x = show_typed_foo "string" show_typed_string x in
let sh2 x = show_typed_boo "string" show_typed_string x in
Printf.printf "%s\n%!" (sh1 @@ F2 (B2 (F1 "asdf")));
Printf.printf "%s\n%!" (sh1 @@ F2 (B2 (F2 (B1 "z"))));
Printf.printf "%s\n%!" (sh2 @@ B2 (F2 (B2 (F1 "asdf"))) );
Printf.printf "%s\n%!" (sh2 @@ B2 (F2 (B2 (F2 (B1 "z")))) );
()
end
*)
|
55325defa0290235a2d8aa5fbcfe2deb0f040f0b1aa5a5a5ba7f5122e4a31f25 | contivero/hasmin | BasicShape.hs | # LANGUAGE OverloadedStrings , FlexibleInstances , FlexibleContexts ,
StandaloneDeriving , DeriveFunctor , ,
DeriveTraversable #
StandaloneDeriving, DeriveFunctor, DeriveFoldable,
DeriveTraversable #-}
-----------------------------------------------------------------------------
-- |
Module : Hasmin . Types . BasicShape
Copyright : ( c ) 2017
-- License : BSD3
-- Stability : experimental
-- Portability : unknown
--
-----------------------------------------------------------------------------
module Hasmin.Types.BasicShape
( BasicShape(..)
, ShapeRadius(..)
, AtMost2(..)
, FillRule(..)
) where
import Control.Monad.Reader (Reader)
import Data.Monoid ((<>), mempty)
import Data.Bitraversable (bitraverse)
import Data.Maybe (isJust)
import Data.List.NonEmpty (NonEmpty((:|)))
import qualified Data.List.NonEmpty as NE
import Data.Text.Lazy.Builder (Builder)
import Hasmin.Types.Position
import Hasmin.Types.BorderRadius
import Hasmin.Types.Dimension
import Hasmin.Types.PercentageLength
import Hasmin.Types.Numeric
import Hasmin.Config
import Hasmin.Class
import Hasmin.Utils
type ShapeArg = PercentageLength
-- | CSS <-shapes/#basic-shape-functions \<basic-shape\>> data type.
data BasicShape
-- inset( <shape-arg>{1,4} [round <border-radius>]? )
= Inset (NonEmpty ShapeArg) (Maybe BorderRadius)
-- circle( [<shape-radius>]? [at <position>]? )
| Circle (Maybe ShapeRadius) (Maybe Position)
-- ellipse( [<shape-radius>{2}]? [at <position>]? )
| Ellipse (AtMost2 ShapeRadius) (Maybe Position)
-- polygon( [<fill-rule>,]? [<shape-arg> <shape-arg>]# )
| Polygon (Maybe FillRule) (NonEmpty (ShapeArg, ShapeArg))
deriving Show
instance Eq BasicShape where
Inset sas1 mbr1 == Inset sas2 mbr2 = eqUsing sasEq sas1 sas2 && mbrEq mbr1 mbr2
Circle msr1 mp1 == Circle msr2 mp2 = msrEq msr1 msr2 && mpEq mp1 mp2
Ellipse sr2 mp1 == Ellipse sr2' mp2 = sr2Eq sr2 sr2' && mpEq mp1 mp2
Polygon mfr1 sas1 == Polygon mfr2 sas2 = mfrEq mfr1 mfr2 && eqUsing pairEq sas1 sas2
_ == _ = False
eqUsing :: (a -> a -> Bool) -> NonEmpty a -> NonEmpty a -> Bool
eqUsing f (x:|xs) (y:|ys) = f x y && go xs ys
where go [] [] = True
go (_:_) [] = False
go [] (_:_) = False
go (c:cs) (d:ds) = f c d && go cs ds
pairEq :: (Num a, Eq a) => (Either a Length, Either a Length)
-> (Either a Length, Either a Length) -> Bool
pairEq (a1, a2) (b1, b2) = a1 `sasEq` b1 && a2 `sasEq` b2
sasEq :: (Num a, Eq a) => Either a Length -> Either a Length -> Bool
sasEq a b = isZero a && isZero b || a == b
mfrEq :: Maybe FillRule -> Maybe FillRule -> Bool
mfrEq Nothing (Just NonZero) = True
mfrEq (Just NonZero) Nothing = True
mfrEq x y = x == y
sr2Eq :: AtMost2 ShapeRadius -> AtMost2 ShapeRadius -> Bool
sr2Eq None x =
case x of
One SRClosestSide -> True
Two SRClosestSide SRClosestSide -> True
None -> True
_ -> False
sr2Eq (One SRClosestSide) None = True
sr2Eq (One x) (Two y SRClosestSide) = x == y
sr2Eq (One x) (One y) = x == y
sr2Eq One{} _ = False
sr2Eq (Two x SRClosestSide) (One y) = x == y
sr2Eq (Two SRClosestSide SRClosestSide) None = True
sr2Eq (Two a b) (Two c d) = a == c && b == d
sr2Eq Two{} _ = False
msrEq :: Maybe ShapeRadius -> Maybe ShapeRadius -> Bool
msrEq Nothing (Just SRClosestSide) = True
msrEq (Just SRClosestSide) Nothing = True
msrEq x y = x == y
mbrEq :: Maybe BorderRadius -> Maybe BorderRadius -> Bool
mbrEq Nothing y = maybe True isZeroBR y
mbrEq x Nothing = mbrEq Nothing x
mbrEq x y = x == y
mpEq :: Maybe Position -> Maybe Position -> Bool
mpEq Nothing (Just x) = x == centerpos
mpEq (Just x) Nothing = x == centerpos
mpEq x y = x == y
data ShapeRadius = SRLength Length
| SRPercentage Percentage
| SRClosestSide
| SRFarthestSide
deriving (Show, Eq)
instance ToText ShapeRadius where
toBuilder (SRLength l) = toBuilder l
toBuilder (SRPercentage p) = toBuilder p
toBuilder SRClosestSide = "closest-side"
toBuilder SRFarthestSide = "farthest-side"
minifySR :: ShapeRadius -> Reader Config ShapeRadius
minifySR (SRLength l) = SRLength <$> minify l
minifySR sr = pure sr
data FillRule = NonZero | EvenOdd
deriving (Show, Eq)
data AtMost2 a = None | One a | Two a a
deriving (Functor, Foldable, Traversable)
deriving instance Show a => Show (AtMost2 a)
deriving instance Eq a => Eq (AtMost2 a)
instance ToText FillRule where
toBuilder NonZero = "nonzero"
toBuilder EvenOdd = "evenodd"
instance Minifiable BasicShape where
minify (Inset xs Nothing) = pure $ Inset (reduceTRBL xs) Nothing
minify (Inset xs (Just br)) = Inset (reduceTRBL xs) <$> br'
where br' = do
x <- minify br
pure $ if isZeroBR x
then Nothing
else Just x
minify (Circle msr mp) = do
mp' <- traverse minify mp
let newPos = if mp' == Just centerpos then Nothing else mp'
Circle <$> minifyMSR msr <*> pure newPos
where minifyMSR :: Maybe ShapeRadius -> Reader Config (Maybe ShapeRadius)
minifyMSR Nothing = pure Nothing
minifyMSR (Just sr) =
case sr of
SRLength l -> Just . SRLength <$> minify l
SRClosestSide -> pure Nothing
_ -> pure (Just sr)
minify (Ellipse sr2 mp) = do
sr' <- minifySR2 sr2
mp' <- traverse minify mp
let newPos = if mp' == Just centerpos
then Nothing
else mp'
pure $ Ellipse sr' newPos
where minifySR2 (One x) =
case x of
SRClosestSide -> pure None
SRLength l -> One . SRLength <$> minify l
_ -> pure (One x)
minifySR2 (Two x SRClosestSide) = minifySR2 (One x)
minifySR2 t@Two{} = traverse minifySR t
minifySR2 None = pure None
minify (Polygon mfr mp) =
case mfr of
Just NonZero -> Polygon Nothing <$> mp'
_ -> Polygon mfr <$> mp'
where mp' = traverse (bitraverse minifyPL minifyPL) mp
instance ToText BasicShape where
toBuilder (Inset xs mys) = surround "inset" $ mconcatIntersperse toBuilder " " (NE.toList xs) <> mys'
where mys' = maybe mempty (\x -> " round " <> toBuilder x) mys
toBuilder (Circle msr mp) = surround "circle" $ msr' <> ms <> mp'
where msr' = maybe mempty toBuilder msr
mp' = maybe mempty (\x -> "at " <> toBuilder x) mp
ms = if isJust msr && isJust mp then " " else mempty
toBuilder (Ellipse m2sr mp) = surround "ellipse" $ bsr2 <> ms <> mp'
where ms = if bsr2 == mempty || mp' == mempty then mempty else " "
mp' = maybe mempty (\x -> "at " <> toBuilder x) mp
bsr2 =
case m2sr of
One rx -> toBuilder rx
Two rx ry -> toBuilder rx <> " " <> toBuilder ry
None -> mempty
toBuilder (Polygon mfr xys) = surround "polygon" $ f mfr xys
where f Nothing xys' = mconcatIntersperse g "," (NE.toList xys')
f (Just fr) xys' = toBuilder fr <> "," <> mconcatIntersperse g "," (NE.toList xys')
g (x, y) = toBuilder x <> " " <> toBuilder y
surround :: Builder -> Builder -> Builder
surround func x = func <> "(" <> x <> ")"
| null | https://raw.githubusercontent.com/contivero/hasmin/2a7604159b51e69c5e9c564dce53cb3ab09ae22b/src/Hasmin/Types/BasicShape.hs | haskell | ---------------------------------------------------------------------------
|
License : BSD3
Stability : experimental
Portability : unknown
---------------------------------------------------------------------------
| CSS <-shapes/#basic-shape-functions \<basic-shape\>> data type.
inset( <shape-arg>{1,4} [round <border-radius>]? )
circle( [<shape-radius>]? [at <position>]? )
ellipse( [<shape-radius>{2}]? [at <position>]? )
polygon( [<fill-rule>,]? [<shape-arg> <shape-arg>]# ) | # LANGUAGE OverloadedStrings , FlexibleInstances , FlexibleContexts ,
StandaloneDeriving , DeriveFunctor , ,
DeriveTraversable #
StandaloneDeriving, DeriveFunctor, DeriveFoldable,
DeriveTraversable #-}
Module : Hasmin . Types . BasicShape
Copyright : ( c ) 2017
module Hasmin.Types.BasicShape
( BasicShape(..)
, ShapeRadius(..)
, AtMost2(..)
, FillRule(..)
) where
import Control.Monad.Reader (Reader)
import Data.Monoid ((<>), mempty)
import Data.Bitraversable (bitraverse)
import Data.Maybe (isJust)
import Data.List.NonEmpty (NonEmpty((:|)))
import qualified Data.List.NonEmpty as NE
import Data.Text.Lazy.Builder (Builder)
import Hasmin.Types.Position
import Hasmin.Types.BorderRadius
import Hasmin.Types.Dimension
import Hasmin.Types.PercentageLength
import Hasmin.Types.Numeric
import Hasmin.Config
import Hasmin.Class
import Hasmin.Utils
type ShapeArg = PercentageLength
data BasicShape
= Inset (NonEmpty ShapeArg) (Maybe BorderRadius)
| Circle (Maybe ShapeRadius) (Maybe Position)
| Ellipse (AtMost2 ShapeRadius) (Maybe Position)
| Polygon (Maybe FillRule) (NonEmpty (ShapeArg, ShapeArg))
deriving Show
instance Eq BasicShape where
Inset sas1 mbr1 == Inset sas2 mbr2 = eqUsing sasEq sas1 sas2 && mbrEq mbr1 mbr2
Circle msr1 mp1 == Circle msr2 mp2 = msrEq msr1 msr2 && mpEq mp1 mp2
Ellipse sr2 mp1 == Ellipse sr2' mp2 = sr2Eq sr2 sr2' && mpEq mp1 mp2
Polygon mfr1 sas1 == Polygon mfr2 sas2 = mfrEq mfr1 mfr2 && eqUsing pairEq sas1 sas2
_ == _ = False
eqUsing :: (a -> a -> Bool) -> NonEmpty a -> NonEmpty a -> Bool
eqUsing f (x:|xs) (y:|ys) = f x y && go xs ys
where go [] [] = True
go (_:_) [] = False
go [] (_:_) = False
go (c:cs) (d:ds) = f c d && go cs ds
pairEq :: (Num a, Eq a) => (Either a Length, Either a Length)
-> (Either a Length, Either a Length) -> Bool
pairEq (a1, a2) (b1, b2) = a1 `sasEq` b1 && a2 `sasEq` b2
sasEq :: (Num a, Eq a) => Either a Length -> Either a Length -> Bool
sasEq a b = isZero a && isZero b || a == b
mfrEq :: Maybe FillRule -> Maybe FillRule -> Bool
mfrEq Nothing (Just NonZero) = True
mfrEq (Just NonZero) Nothing = True
mfrEq x y = x == y
sr2Eq :: AtMost2 ShapeRadius -> AtMost2 ShapeRadius -> Bool
sr2Eq None x =
case x of
One SRClosestSide -> True
Two SRClosestSide SRClosestSide -> True
None -> True
_ -> False
sr2Eq (One SRClosestSide) None = True
sr2Eq (One x) (Two y SRClosestSide) = x == y
sr2Eq (One x) (One y) = x == y
sr2Eq One{} _ = False
sr2Eq (Two x SRClosestSide) (One y) = x == y
sr2Eq (Two SRClosestSide SRClosestSide) None = True
sr2Eq (Two a b) (Two c d) = a == c && b == d
sr2Eq Two{} _ = False
msrEq :: Maybe ShapeRadius -> Maybe ShapeRadius -> Bool
msrEq Nothing (Just SRClosestSide) = True
msrEq (Just SRClosestSide) Nothing = True
msrEq x y = x == y
mbrEq :: Maybe BorderRadius -> Maybe BorderRadius -> Bool
mbrEq Nothing y = maybe True isZeroBR y
mbrEq x Nothing = mbrEq Nothing x
mbrEq x y = x == y
mpEq :: Maybe Position -> Maybe Position -> Bool
mpEq Nothing (Just x) = x == centerpos
mpEq (Just x) Nothing = x == centerpos
mpEq x y = x == y
data ShapeRadius = SRLength Length
| SRPercentage Percentage
| SRClosestSide
| SRFarthestSide
deriving (Show, Eq)
instance ToText ShapeRadius where
toBuilder (SRLength l) = toBuilder l
toBuilder (SRPercentage p) = toBuilder p
toBuilder SRClosestSide = "closest-side"
toBuilder SRFarthestSide = "farthest-side"
minifySR :: ShapeRadius -> Reader Config ShapeRadius
minifySR (SRLength l) = SRLength <$> minify l
minifySR sr = pure sr
data FillRule = NonZero | EvenOdd
deriving (Show, Eq)
data AtMost2 a = None | One a | Two a a
deriving (Functor, Foldable, Traversable)
deriving instance Show a => Show (AtMost2 a)
deriving instance Eq a => Eq (AtMost2 a)
instance ToText FillRule where
toBuilder NonZero = "nonzero"
toBuilder EvenOdd = "evenodd"
instance Minifiable BasicShape where
minify (Inset xs Nothing) = pure $ Inset (reduceTRBL xs) Nothing
minify (Inset xs (Just br)) = Inset (reduceTRBL xs) <$> br'
where br' = do
x <- minify br
pure $ if isZeroBR x
then Nothing
else Just x
minify (Circle msr mp) = do
mp' <- traverse minify mp
let newPos = if mp' == Just centerpos then Nothing else mp'
Circle <$> minifyMSR msr <*> pure newPos
where minifyMSR :: Maybe ShapeRadius -> Reader Config (Maybe ShapeRadius)
minifyMSR Nothing = pure Nothing
minifyMSR (Just sr) =
case sr of
SRLength l -> Just . SRLength <$> minify l
SRClosestSide -> pure Nothing
_ -> pure (Just sr)
minify (Ellipse sr2 mp) = do
sr' <- minifySR2 sr2
mp' <- traverse minify mp
let newPos = if mp' == Just centerpos
then Nothing
else mp'
pure $ Ellipse sr' newPos
where minifySR2 (One x) =
case x of
SRClosestSide -> pure None
SRLength l -> One . SRLength <$> minify l
_ -> pure (One x)
minifySR2 (Two x SRClosestSide) = minifySR2 (One x)
minifySR2 t@Two{} = traverse minifySR t
minifySR2 None = pure None
minify (Polygon mfr mp) =
case mfr of
Just NonZero -> Polygon Nothing <$> mp'
_ -> Polygon mfr <$> mp'
where mp' = traverse (bitraverse minifyPL minifyPL) mp
instance ToText BasicShape where
toBuilder (Inset xs mys) = surround "inset" $ mconcatIntersperse toBuilder " " (NE.toList xs) <> mys'
where mys' = maybe mempty (\x -> " round " <> toBuilder x) mys
toBuilder (Circle msr mp) = surround "circle" $ msr' <> ms <> mp'
where msr' = maybe mempty toBuilder msr
mp' = maybe mempty (\x -> "at " <> toBuilder x) mp
ms = if isJust msr && isJust mp then " " else mempty
toBuilder (Ellipse m2sr mp) = surround "ellipse" $ bsr2 <> ms <> mp'
where ms = if bsr2 == mempty || mp' == mempty then mempty else " "
mp' = maybe mempty (\x -> "at " <> toBuilder x) mp
bsr2 =
case m2sr of
One rx -> toBuilder rx
Two rx ry -> toBuilder rx <> " " <> toBuilder ry
None -> mempty
toBuilder (Polygon mfr xys) = surround "polygon" $ f mfr xys
where f Nothing xys' = mconcatIntersperse g "," (NE.toList xys')
f (Just fr) xys' = toBuilder fr <> "," <> mconcatIntersperse g "," (NE.toList xys')
g (x, y) = toBuilder x <> " " <> toBuilder y
surround :: Builder -> Builder -> Builder
surround func x = func <> "(" <> x <> ")"
|
a2f50fd384b465ec52fcfe206118890688561f140128f0bd35f81ed4c51ae1e7 | shaunlebron/t3tr0s-bare | board.cljs | (ns game.board)
;;------------------------------------------------------------
;; Pieces.
;;------------------------------------------------------------
; The available pieces resemble letters I,L,J,S,Z,O,T.
; Each piece structure is stored in :coords as [x y a].
; The "a" component of :coords stands for adjacency,
which is a number with bit flags UP , RIGHT , DOWN , LEFT .
; For example, the coords for the J piece:
;
; ********
; * X=-1 *
; * Y=-1 *
; * *
; **********************
; * X=-1 * X=0 * X=1 *
; * Y=0 * Y=0 * Y=0 *
; * * * *
; **********************
;
; We also need to encode "adjacency" information so we
; can graphically connect tiles of the same piece.
; These codes require explanation:
;
; ********
; * *
; * A=4 *
; * *
; **********************
; * * * *
; * A=3 * A=10 * A=8 *
; * * * *
; **********************
;
Adjacency codes are 4 - bit numbers ( for good reason ) ,
; with each bit indicating adjacency along its respective direction:
;
; UP RIGHT DOWN LEFT -> binary -> CODE (decimal)
; - - - - 0000 0
; X - - - 0001 1
- X - - 0010 2
X X - - 0011 3 < -- shown in above example
; - - X - 0100 4 <-- shown in above example
; X - X - 0101 5
; - X X - 0110 6
; X X X - 0111 7
- - - X 1000 8 < -- shown in above example
X - - X 1001 9
- X - X 1010 10 < -- shown in above example
X X - X 1011 11
- - X X 1100 12
; X - X X 1101 13
- X X 14
; X X X X 1111 15 (not possible in tetris)
;
; The revelation here is that SIMPLE ROTATION of the piece
; is achieved by applying this function over each coordinate:
;
Rotate ( [ X Y A ] ) -- > [ -Y X ( 4 bit rotate of A ) ]
;
(def pieces
{:I {:name :I
:coords [
[-1 0 2] [ 0 0 10] [ 1 0 10] [ 2 0 8]
]}
:L {:name :L
:coords [
[ 1 -1 4]
[-1 0 2] [ 0 0 10] [ 1 0 9]
]}
:J {:name :J
:coords [
[-1 -1 4]
[-1 0 3] [ 0 0 10] [ 1 0 8]
]}
:S {:name :S
:coords [
[ 0 -1 6] [ 1 -1 8]
[-1 0 2] [ 0 0 9]
]}
:Z {:name :Z
:coords [
[-1 -1 2] [ 0 -1 12]
[ 0 0 3] [ 1 0 8]
]}
:O {:name :O
:coords [
[ 0 -1 6] [ 1 -1 12]
[ 0 0 3] [ 1 0 9]
]}
:T {:name :T
:coords [
[ 0 -1 4]
[-1 0 2] [ 0 0 11] [ 1 0 8]
]}})
(defn get-rand-diff-piece
"Return a random piece different from the given one."
[piece]
(pieces (rand-nth (keys (dissoc pieces (:name piece))))))
(defn get-rand-piece
"Return a random piece."
[]
(pieces (rand-nth (keys pieces))))
(defn rotate-piece
"Create a new piece by rotating the given piece clockwise."
[piece]
(if (= :O (:name piece))
piece
(let [br (fn [a] (+ (* 2 (mod a 8)) (/ (bit-and a 8) 8)))
new-coords (map (fn [[x y a]] [(- y) x (br a)]) (:coords piece))]
(assoc piece :coords new-coords))))
(defn piece-value
"Creates a cell value from the given piece type and adjacency."
[t a]
(if (zero? t) 0 (str (name t) a)))
(defn piece-type-adj
"Gets the piece type and adjacency from a cell value string."
[value]
(let [t (if (zero? value) 0 (keyword (first value))) ; get the value key (piece type)
a (if (zero? value) 0 (int (subs value 1)))] ; get the adjacency code
[t a]))
(defn update-adj
"Updates the adjacency of the given cell value."
[value f]
(let [[t a] (piece-type-adj value)
new-a (f a)]
(piece-value t new-a)))
;;------------------------------------------------------------
;; Board.
;;------------------------------------------------------------
; conventions for standard board size
(def n-rows 22)
(def n-cols 10)
(def rows-cutoff 1.5)
(def empty-row (vec (repeat n-cols 0)))
(def highlighted-row (vec (concat ["H2"] (repeat (- n-cols 2) "H10") ["H8"])))
(defn game-over-row
"Creates a vector of random tiles with no adjacency."
[]
(vec
(for [x (range n-cols)]
(str (name (nth (keys pieces) (rand-int 7))) 0))))
(def empty-board (vec (repeat n-rows empty-row)))
; The starting position of all pieces.
(def start-position [4 2])
(defn coord-inside?
"Determines if the coordinate is inside the board."
[x y]
(and (<= 0 x (dec n-cols))
(<= 0 y (dec n-rows))))
(def cell-filled? (complement zero?))
;;------------------------------------------------------------
;; Pure Functions operating on a board.
;;------------------------------------------------------------
(defn board-size
"Get the size of the given board as [w h]."
[board]
(let [w (count (first board))
h (count board)]
[w h]))
(defn read-board
"Get the current value from the given board position."
[x y board]
(get-in board [y x]))
(defn write-to-board
"Returns a new board with a value written to the given position."
[x y value board]
(if (coord-inside? x y)
(assoc-in board [y x] value)
board))
(defn write-coord-to-board
"Returns a new board with a value written to the given relative coordinate and position."
[[cx cy ca] x y value board]
(write-to-board (+ cx x) (+ cy y) (piece-value value ca) board))
(defn write-coords-to-board
"Returns a new board with a value written to the given relative coordinates and position."
[coords x y value board]
(if (zero? (count coords))
board
(let [coord (first coords)
rest-coords (rest coords)
new-board (write-coord-to-board coord x y value board)]
(recur rest-coords x y value new-board))))
(defn write-piece-to-board
"Returns a new board with a the given piece written to the coordinate on the board."
[piece x y board]
(let [value (:name piece)
coords (:coords piece)]
(write-coords-to-board coords x y value board)))
(defn write-piece-behind-board
"Like write-piece-to-board, but only draws to empty cells, to make it look like it's drawing behind."
[piece x y board]
(let [value (:name piece)
can-write? (fn [[cx cy]] (zero? (read-board (+ x cx) (+ y cy) board)))
coords (filter can-write? (:coords piece))]
(write-coords-to-board coords x y value board)))
(defn highlight-rows
"Returns a new board with the given rows highlighted."
[active-rows board]
(vec (map-indexed
(fn [i row]
(if (active-rows i) highlighted-row row)) board)))
(defn collapse-rows
"Returns a new board with the given row indices collapsed."
[rows board]
(let [cleared-board (->> board
(map-indexed vector)
(remove #(rows (first %)))
(map second))
n (count rows)
new-board (into (vec (repeat n empty-row)) cleared-board)]
new-board))
(defn sever-row
"Return a new row, severing its adjacency across the given boundary."
[row dir]
(let [adj (if (= dir :up) (+ 2 4 8) (+ 1 2 8))
new-row (vec (map #(update-adj % (fn [a] (bit-and a adj))) row))]
new-row))
(defn sever-row-neighbors
"Return a new board, disconnecting the adjacency of the rows neighboring the given row index."
[i board]
(let [row-up (get board (dec i))
board1 (if row-up
(assoc board (dec i) (sever-row row-up :down))
board)
row-down (get board (inc i))
board2 (if row-down
(assoc board1 (inc i) (sever-row row-down :up))
board1)]
board2))
(defn clear-rows
"Return a new board with the given row indices cleared."
[rows board]
(if (zero? (count rows))
board
(let [next-rows (rest rows)
i (first rows)
severed-board (sever-row-neighbors i board)
next-board (assoc severed-board i empty-row)]
(recur next-rows next-board))))
(defn get-filled-row-indices
"Get the indices of the filled rows for the given board."
[board]
indexed rows [ [ 0 r ] [ 1 r ] ]
choose filled [ 1 r ]
(map first) ; select index only
(apply hash-set))) ; convert to a set
(defn coord-empty?
"Determines if the given coordinate on the board is empty."
[x y board]
(zero? (read-board x y board)))
(defn coord-fits?
"Determines if the given relative coordinate fits at the position on the board."
[[cx cy] x y board]
(let [abs-x (+ x cx)
abs-y (+ y cy)]
(and (coord-inside? abs-x abs-y)
(coord-empty? abs-x abs-y board))))
(defn piece-fits?
"Determines if the given piece will collide with anything in the current board."
[piece x y board]
(every? #(coord-fits? % x y board) (:coords piece)))
(defn get-drop-pos
"Get the future drop position of the given piece."
[piece x y board]
(let [collide? (fn [cy] (not (piece-fits? piece x cy board)))
cy (first (filter collide? (iterate inc y)))]
(max y (dec cy))))
(defn create-drawable-board
"Creates a new drawable board, by combining the current piece with the current board."
[piece x y board]
(if piece
(let [ghost (assoc piece :name :G)
gy (get-drop-pos piece x y board)
board1 (write-piece-to-board ghost x gy board)
board2 (write-piece-to-board piece x y board1)]
board2)
board))
(defn highest-nonempty-row
[board]
(first (keep-indexed #(if (not= empty-row %2) %1) board)))
(defn tower-height
[board]
(let [h (count board)]
(if-let [y (highest-nonempty-row board)]
(- h y)
0)))
;;------------------------------------------------------------
Next piece board generator .
;;------------------------------------------------------------
(defn next-piece-board
"Returns a small board for drawing the next piece."
([] (next-piece-board nil))
([piece]
(let [board [[0 0 0 0]
[0 0 0 0]
[0 0 0 0]
[0 0 0 0]]]
(if piece
(write-piece-to-board piece 1 2 board)
board))))
| null | https://raw.githubusercontent.com/shaunlebron/t3tr0s-bare/b11628da985101b4fdaaf987c615d50e2808338d/src/game/board.cljs | clojure | ------------------------------------------------------------
Pieces.
------------------------------------------------------------
The available pieces resemble letters I,L,J,S,Z,O,T.
Each piece structure is stored in :coords as [x y a].
The "a" component of :coords stands for adjacency,
For example, the coords for the J piece:
********
* X=-1 *
* Y=-1 *
* *
**********************
* X=-1 * X=0 * X=1 *
* Y=0 * Y=0 * Y=0 *
* * * *
**********************
We also need to encode "adjacency" information so we
can graphically connect tiles of the same piece.
These codes require explanation:
********
* *
* A=4 *
* *
**********************
* * * *
* A=3 * A=10 * A=8 *
* * * *
**********************
with each bit indicating adjacency along its respective direction:
UP RIGHT DOWN LEFT -> binary -> CODE (decimal)
- - - - 0000 0
X - - - 0001 1
- - X - 0100 4 <-- shown in above example
X - X - 0101 5
- X X - 0110 6
X X X - 0111 7
X - X X 1101 13
X X X X 1111 15 (not possible in tetris)
The revelation here is that SIMPLE ROTATION of the piece
is achieved by applying this function over each coordinate:
get the value key (piece type)
get the adjacency code
------------------------------------------------------------
Board.
------------------------------------------------------------
conventions for standard board size
The starting position of all pieces.
------------------------------------------------------------
Pure Functions operating on a board.
------------------------------------------------------------
select index only
convert to a set
------------------------------------------------------------
------------------------------------------------------------ | (ns game.board)
which is a number with bit flags UP , RIGHT , DOWN , LEFT .
Adjacency codes are 4 - bit numbers ( for good reason ) ,
- X - - 0010 2
X X - - 0011 3 < -- shown in above example
- - - X 1000 8 < -- shown in above example
X - - X 1001 9
- X - X 1010 10 < -- shown in above example
X X - X 1011 11
- - X X 1100 12
- X X 14
Rotate ( [ X Y A ] ) -- > [ -Y X ( 4 bit rotate of A ) ]
(def pieces
{:I {:name :I
:coords [
[-1 0 2] [ 0 0 10] [ 1 0 10] [ 2 0 8]
]}
:L {:name :L
:coords [
[ 1 -1 4]
[-1 0 2] [ 0 0 10] [ 1 0 9]
]}
:J {:name :J
:coords [
[-1 -1 4]
[-1 0 3] [ 0 0 10] [ 1 0 8]
]}
:S {:name :S
:coords [
[ 0 -1 6] [ 1 -1 8]
[-1 0 2] [ 0 0 9]
]}
:Z {:name :Z
:coords [
[-1 -1 2] [ 0 -1 12]
[ 0 0 3] [ 1 0 8]
]}
:O {:name :O
:coords [
[ 0 -1 6] [ 1 -1 12]
[ 0 0 3] [ 1 0 9]
]}
:T {:name :T
:coords [
[ 0 -1 4]
[-1 0 2] [ 0 0 11] [ 1 0 8]
]}})
(defn get-rand-diff-piece
"Return a random piece different from the given one."
[piece]
(pieces (rand-nth (keys (dissoc pieces (:name piece))))))
(defn get-rand-piece
"Return a random piece."
[]
(pieces (rand-nth (keys pieces))))
(defn rotate-piece
"Create a new piece by rotating the given piece clockwise."
[piece]
(if (= :O (:name piece))
piece
(let [br (fn [a] (+ (* 2 (mod a 8)) (/ (bit-and a 8) 8)))
new-coords (map (fn [[x y a]] [(- y) x (br a)]) (:coords piece))]
(assoc piece :coords new-coords))))
(defn piece-value
"Creates a cell value from the given piece type and adjacency."
[t a]
(if (zero? t) 0 (str (name t) a)))
(defn piece-type-adj
"Gets the piece type and adjacency from a cell value string."
[value]
[t a]))
(defn update-adj
"Updates the adjacency of the given cell value."
[value f]
(let [[t a] (piece-type-adj value)
new-a (f a)]
(piece-value t new-a)))
(def n-rows 22)
(def n-cols 10)
(def rows-cutoff 1.5)
(def empty-row (vec (repeat n-cols 0)))
(def highlighted-row (vec (concat ["H2"] (repeat (- n-cols 2) "H10") ["H8"])))
(defn game-over-row
"Creates a vector of random tiles with no adjacency."
[]
(vec
(for [x (range n-cols)]
(str (name (nth (keys pieces) (rand-int 7))) 0))))
(def empty-board (vec (repeat n-rows empty-row)))
(def start-position [4 2])
(defn coord-inside?
"Determines if the coordinate is inside the board."
[x y]
(and (<= 0 x (dec n-cols))
(<= 0 y (dec n-rows))))
(def cell-filled? (complement zero?))
(defn board-size
"Get the size of the given board as [w h]."
[board]
(let [w (count (first board))
h (count board)]
[w h]))
(defn read-board
"Get the current value from the given board position."
[x y board]
(get-in board [y x]))
(defn write-to-board
"Returns a new board with a value written to the given position."
[x y value board]
(if (coord-inside? x y)
(assoc-in board [y x] value)
board))
(defn write-coord-to-board
"Returns a new board with a value written to the given relative coordinate and position."
[[cx cy ca] x y value board]
(write-to-board (+ cx x) (+ cy y) (piece-value value ca) board))
(defn write-coords-to-board
"Returns a new board with a value written to the given relative coordinates and position."
[coords x y value board]
(if (zero? (count coords))
board
(let [coord (first coords)
rest-coords (rest coords)
new-board (write-coord-to-board coord x y value board)]
(recur rest-coords x y value new-board))))
(defn write-piece-to-board
"Returns a new board with a the given piece written to the coordinate on the board."
[piece x y board]
(let [value (:name piece)
coords (:coords piece)]
(write-coords-to-board coords x y value board)))
(defn write-piece-behind-board
"Like write-piece-to-board, but only draws to empty cells, to make it look like it's drawing behind."
[piece x y board]
(let [value (:name piece)
can-write? (fn [[cx cy]] (zero? (read-board (+ x cx) (+ y cy) board)))
coords (filter can-write? (:coords piece))]
(write-coords-to-board coords x y value board)))
(defn highlight-rows
"Returns a new board with the given rows highlighted."
[active-rows board]
(vec (map-indexed
(fn [i row]
(if (active-rows i) highlighted-row row)) board)))
(defn collapse-rows
"Returns a new board with the given row indices collapsed."
[rows board]
(let [cleared-board (->> board
(map-indexed vector)
(remove #(rows (first %)))
(map second))
n (count rows)
new-board (into (vec (repeat n empty-row)) cleared-board)]
new-board))
(defn sever-row
"Return a new row, severing its adjacency across the given boundary."
[row dir]
(let [adj (if (= dir :up) (+ 2 4 8) (+ 1 2 8))
new-row (vec (map #(update-adj % (fn [a] (bit-and a adj))) row))]
new-row))
(defn sever-row-neighbors
"Return a new board, disconnecting the adjacency of the rows neighboring the given row index."
[i board]
(let [row-up (get board (dec i))
board1 (if row-up
(assoc board (dec i) (sever-row row-up :down))
board)
row-down (get board (inc i))
board2 (if row-down
(assoc board1 (inc i) (sever-row row-down :up))
board1)]
board2))
(defn clear-rows
"Return a new board with the given row indices cleared."
[rows board]
(if (zero? (count rows))
board
(let [next-rows (rest rows)
i (first rows)
severed-board (sever-row-neighbors i board)
next-board (assoc severed-board i empty-row)]
(recur next-rows next-board))))
(defn get-filled-row-indices
"Get the indices of the filled rows for the given board."
[board]
indexed rows [ [ 0 r ] [ 1 r ] ]
choose filled [ 1 r ]
(defn coord-empty?
"Determines if the given coordinate on the board is empty."
[x y board]
(zero? (read-board x y board)))
(defn coord-fits?
"Determines if the given relative coordinate fits at the position on the board."
[[cx cy] x y board]
(let [abs-x (+ x cx)
abs-y (+ y cy)]
(and (coord-inside? abs-x abs-y)
(coord-empty? abs-x abs-y board))))
(defn piece-fits?
"Determines if the given piece will collide with anything in the current board."
[piece x y board]
(every? #(coord-fits? % x y board) (:coords piece)))
(defn get-drop-pos
"Get the future drop position of the given piece."
[piece x y board]
(let [collide? (fn [cy] (not (piece-fits? piece x cy board)))
cy (first (filter collide? (iterate inc y)))]
(max y (dec cy))))
(defn create-drawable-board
"Creates a new drawable board, by combining the current piece with the current board."
[piece x y board]
(if piece
(let [ghost (assoc piece :name :G)
gy (get-drop-pos piece x y board)
board1 (write-piece-to-board ghost x gy board)
board2 (write-piece-to-board piece x y board1)]
board2)
board))
(defn highest-nonempty-row
[board]
(first (keep-indexed #(if (not= empty-row %2) %1) board)))
(defn tower-height
[board]
(let [h (count board)]
(if-let [y (highest-nonempty-row board)]
(- h y)
0)))
Next piece board generator .
(defn next-piece-board
"Returns a small board for drawing the next piece."
([] (next-piece-board nil))
([piece]
(let [board [[0 0 0 0]
[0 0 0 0]
[0 0 0 0]
[0 0 0 0]]]
(if piece
(write-piece-to-board piece 1 2 board)
board))))
|
e0f605e71d82dbe70ab00c3d45dec0a27830e483e1b702f878497740cc361651 | ktakashi/sagittarius-scheme | cipher.scm | -*- mode : scheme ; coding : utf-8 -*-
;;;
;;; cipher.scm Cryptographic library
;;;
#!deprecated
#!nounbound
(library (crypto cipher)
(export crypto-object?
cipher-keysize
cipher-blocksize
cipher-iv
cipher-update-aad!
cipher-tag! cipher-tag
cipher-max-tag-size
(rename (legacy-cipher? cipher?))
make-cipher
cipher-encrypt
cipher-decrypt
cipher-signature
cipher-verify
key-check-value
cipher-encrypt/tag
cipher-decrypt/tag
cipher-decrypt/verify
;; parameters
define-mode-parameter
(rename (make-cipher-parameter make-composite-parameter)
(cipher-parameter? mode-parameter?))
(rename (mode-name-parameter <mode-name-parameter>))
make-mode-name-parameter mode-name-parameter?
parameter-mode-name
<iv-parameter> make-iv-parameter iv-parameter?
(rename (cipher-parameter-iv parameter-iv))
<ctr-parameter> make-ctr-parameter ctr-parameter?
parameter-ctr-mode
<rfc3686-parameter> make-rfc3686-parameter rfc3686-parameter?
(rename (padding-parameter <padding-parameter>))
make-padding-parameter padding-parameter?
parameter-padder
<round-parameter> make-round-parameter round-parameter?
(rename (cipher-parameter-rounds parameter-rounds))
;; signing
;; supported algorithms
(rename (*scheme:blowfish* Blowfish)
(*scheme:x-tea* X-Tea)
(*scheme:rc2* RC2)
(*scheme:rc5* RC5-32/12/b)
(*scheme:rc6* RC6-32/20/b)
(*scheme:safer+* SAFER+)
(*scheme:safer-k64* SAFER-K64)
(*scheme:safer-sk64* SAFER-SK64)
(*scheme:safer-k128* SAFER-K128)
(*scheme:safer-sk128* SAFER-SK128)
(*scheme:aes* AES)
(*scheme:aes-128* AES-128)
(*scheme:aes-192* AES-192)
(*scheme:aes-256* AES-256)
(*scheme:twofish* Twofish)
(*scheme:des* DES)
(*scheme:des3* DES3)
(*scheme:desede* DESede)
(*scheme:cast5* CAST5)
(*scheme:cast-128* CAST-128)
(*scheme:noekeon* Noekeon)
(*scheme:skipjack* Skipjack)
(*scheme:khazad* Khazad)
(*scheme:seed* SEED)
(*scheme:kasumi* KASUMI)
(*scheme:camellia* Camellia))
;; supported modes
(rename (*mode:ecb* MODE_ECB)
(*mode:cbc* MODE_CBC)
(*mode:cfb* MODE_CFB)
(*mode:ofb* MODE_OFB)
(*mode:ctr* MODE_CTR)
(*mode:lrw* MODE_LRW)
(*mode:f8* MODE_F8)
(*mode:eax* MODE_EAX)
(*mode:ocb* MODE_OCB)
(*mode:ocb3* MODE_OCB3)
(*mode:gcm* MODE_GCM))
ctr conter mode
(rename (*ctr-mode:little-endian* CTR_COUNTER_LITTLE_ENDIAN)
(*ctr-mode:big-endian* CTR_COUNTER_BIG_ENDIAN)
(*ctr-mode:rfc3686* LTC_CTR_RFC3686))
(rename (<legacy-crypto> <crypto>)
(<legacy-cipher> <cipher>)
(<legacy-cipher-spi> <cipher-spi>))
<key>
<symmetric-key>
<asymmetric-key>
;; for backward compatibility
cipher
(rename (cipher-encrypt encrypt)
(cipher-decrypt decrypt)
(cipher-signature sign)
(cipher-verify verify))
)
(import (rnrs)
(sagittarius)
(sagittarius crypto parameters)
(sagittarius crypto ciphers symmetric)
(clos core)
(crypto spi)
(crypto key)
(crypto pkcs))
(define-syntax define-mode-parameter (make-define-cipher-parameter))
(define-mode-parameter mode-name-parameter
make-mode-name-parameter mode-name-parameter?
(mode-name parameter-mode-name))
(define-mode-parameter padding-parameter
make-padding-parameter padding-parameter?
(padder parameter-padder))
(define-mode-parameter (<ctr-parameter> <iv-parameter>)
(make-ctr-parameter (lambda (p)
(lambda (iv :optional (mode *ctr-mode:big-endian*))
((p iv) mode))))
ctr-parameter?
(mode parameter-ctr-mode))
(define-mode-parameter (<rfc3686-parameter> <ctr-parameter>)
(make-rfc3686-parameter
(lambda (p)
(lambda (iv nonce :optional (mode *ctr-mode:big-endian*))
(let ((v (make-bytevector 16 0))
(nlen (bytevector-length nonce))
(ivlen (bytevector-length iv)))
(if (= mode *ctr-mode:big-endian*)
NONCE || IV || ONE = 16
(begin
(bytevector-copy! nonce 0 v 0 nlen)
(bytevector-copy! iv 0 v nlen ivlen))
ONE || IV || NONCE ( i guess )
(begin
(bytevector-copy! iv 0 v 4 ivlen)
(bytevector-copy! nonce 0 v (+ 4 ivlen) nlen)))
let it do libtomcrypt
((p v (+ mode *ctr-mode:rfc3686*)))))))
rfc3686-parameter?)
(define (crypto-object? o)
(or (key? o)
(is-a? o <legacy-crypto>)))
;; This is why we want to replace lagacy library...
(define (cipher-verify cipher M S . opts)
(let ((spi (cipher-spi cipher)))
(or (apply (cipher-spi-verifier spi) M S (cipher-spi-key spi) opts)
(error 'cipher-verify "Inconsistent"))))
(define (cipher-signature cipher M . opts)
(let ((spi (cipher-spi cipher)))
(apply (cipher-spi-signer spi) M (cipher-spi-key spi) opts)))
(define (cipher-decrypt cipher ct :optional (len 0))
(let ((spi (cipher-spi cipher)))
(if (legacy-builtin-cipher-spi? spi)
((cipher-spi-decrypt spi) ct len (cipher-spi-key spi))
((cipher-spi-decrypt spi) ct (cipher-spi-key spi)))))
(define (cipher-encrypt cipher pt :optional (len 0))
(let ((spi (cipher-spi cipher)))
(if (legacy-builtin-cipher-spi? spi)
((cipher-spi-encrypt spi) pt len (cipher-spi-key spi))
((cipher-spi-encrypt spi) pt (cipher-spi-key spi)))))
(define (cipher-max-tag-size cipher)
(let ((spi (cipher-spi cipher)))
(cipher-spi-tagsize spi)))
(define (cipher-update-aad! cipher aad . opts)
(let ((spi (cipher-spi cipher)))
(cond ((cipher-spi-update-aad spi) => (lambda (proc) (apply proc aad opts)))
(else #f))))
(define (cipher-iv cipher :optional (iv #f))
(let ((spi (cipher-spi cipher)))
(if (bytevector? iv)
(slot-set! spi 'iv iv)
(cipher-spi-iv spi))))
(define (cipher-keysize cipher test)
(let ((spi (cipher-spi cipher)))
((cipher-spi-keysize spi) test)))
(define (cipher type key
:key (mode *mode:ecb*)
(iv #f)
(padder pkcs5-padder)
(rounds 0)
(ctr-mode *ctr-mode:big-endian*)
:allow-other-keys
:rest rest)
(define (rfc3686?)
(not (zero? (bitwise-and ctr-mode *ctr-mode:rfc3686*))))
(apply make-cipher type key
:mode-parameter
(apply make-cipher-parameter
(filter values
(list
(make-mode-name-parameter mode)
(make-padding-parameter padder)
(make-round-parameter rounds)
(and iv
(if (rfc3686?)
;; should we add nonce?
(make-rfc3686-parameter iv
#vu8(0 0 0 0)
ctr-mode)
(make-ctr-parameter iv ctr-mode))))))
rest))
(define (make-cipher type key
:key (mode-parameter #f)
:allow-other-keys
:rest rest)
(define parameter mode-parameter)
;; kinda silly but for now
(let ((mode (or (and parameter (parameter-mode-name parameter *mode:ecb*))
*mode:ecb*))
(iv (and parameter (cipher-parameter-iv parameter #f)))
these 2 does n't have to be there but
;; make-builtin-cipher-spi requires it.
;; TODO better construction
(rounds (or (and parameter (cipher-parameter-rounds parameter 0)) 0))
(ctr-mode (or (and parameter
(parameter-ctr-mode parameter *ctr-mode:big-endian*))
*ctr-mode:big-endian*))
(padder (or (and parameter (parameter-padder parameter #f))
no-padding)))
(unless (or (eq? mode *mode:ecb*) (bytevector? iv))
(assertion-violation 'cipher "the given mode iv is required"))
(let ((spi (cond ((cipher-descriptor? type)
(make-builtin-cipher-spi
type mode key iv rounds padder ctr-mode))
((lookup-cipher-spi type) =>
(lambda (spi)
(apply make spi key :mode-parameter parameter
rest)))
((legacy-cipher-spi? type) type) ;; reuse
(else
(assertion-violation 'cipher
"unknown cipher type" type)))))
(make <legacy-cipher> :spi spi))))
(define-constant +check-value+ (make-bytevector 8 0))
(define (key-check-value type key :optional (size 3))
(unless (<= 3 size 8)
(assertion-violation 'key-check-value "size must be between 3 to 8"
size))
(let ((c (make-cipher type key)))
(bytevector-copy (cipher-encrypt c +check-value+) 0 size)))
;; with authentication
(define (cipher-tag! cipher out)
(let ((spi (cipher-spi cipher)))
(cond ((cipher-spi-tag spi) => (lambda (proc) (proc out)))
(else 0))))
(define (cipher-tag cipher :key (tag #f))
(let ((out (if tag tag (make-bytevector (cipher-max-tag-size cipher)))))
(cipher-tag! cipher out)
out))
(define (cipher-encrypt/tag cipher data
:key (tag-size (cipher-max-tag-size cipher)))
(let ((encrypted (cipher-encrypt cipher data)))
(values encrypted (cipher-tag cipher :tag (make-bytevector tag-size)))))
(define (cipher-decrypt/tag cipher data tag)
(let ((pt (cipher-decrypt cipher data)))
(values pt (cipher-tag cipher :tag tag))))
(define (cipher-decrypt/verify cipher encrypted tag)
(let-values (((pt target)
(cipher-decrypt/tag cipher encrypted
:tag-size (bytevector-length tag))))
(unless (bytevector=? tag target)
(error (slot-ref cipher 'name) 'cipher-decrypt/verify
"invalid tag is given"))
pt))
)
| null | https://raw.githubusercontent.com/ktakashi/sagittarius-scheme/ed1d5e34e3df5e6f1c1240b190ab959de5041455/ext/crypto/crypto/cipher.scm | scheme | coding : utf-8 -*-
cipher.scm Cryptographic library
parameters
signing
supported algorithms
supported modes
for backward compatibility
This is why we want to replace lagacy library...
should we add nonce?
kinda silly but for now
make-builtin-cipher-spi requires it.
TODO better construction
reuse
with authentication | #!deprecated
#!nounbound
(library (crypto cipher)
(export crypto-object?
cipher-keysize
cipher-blocksize
cipher-iv
cipher-update-aad!
cipher-tag! cipher-tag
cipher-max-tag-size
(rename (legacy-cipher? cipher?))
make-cipher
cipher-encrypt
cipher-decrypt
cipher-signature
cipher-verify
key-check-value
cipher-encrypt/tag
cipher-decrypt/tag
cipher-decrypt/verify
define-mode-parameter
(rename (make-cipher-parameter make-composite-parameter)
(cipher-parameter? mode-parameter?))
(rename (mode-name-parameter <mode-name-parameter>))
make-mode-name-parameter mode-name-parameter?
parameter-mode-name
<iv-parameter> make-iv-parameter iv-parameter?
(rename (cipher-parameter-iv parameter-iv))
<ctr-parameter> make-ctr-parameter ctr-parameter?
parameter-ctr-mode
<rfc3686-parameter> make-rfc3686-parameter rfc3686-parameter?
(rename (padding-parameter <padding-parameter>))
make-padding-parameter padding-parameter?
parameter-padder
<round-parameter> make-round-parameter round-parameter?
(rename (cipher-parameter-rounds parameter-rounds))
(rename (*scheme:blowfish* Blowfish)
(*scheme:x-tea* X-Tea)
(*scheme:rc2* RC2)
(*scheme:rc5* RC5-32/12/b)
(*scheme:rc6* RC6-32/20/b)
(*scheme:safer+* SAFER+)
(*scheme:safer-k64* SAFER-K64)
(*scheme:safer-sk64* SAFER-SK64)
(*scheme:safer-k128* SAFER-K128)
(*scheme:safer-sk128* SAFER-SK128)
(*scheme:aes* AES)
(*scheme:aes-128* AES-128)
(*scheme:aes-192* AES-192)
(*scheme:aes-256* AES-256)
(*scheme:twofish* Twofish)
(*scheme:des* DES)
(*scheme:des3* DES3)
(*scheme:desede* DESede)
(*scheme:cast5* CAST5)
(*scheme:cast-128* CAST-128)
(*scheme:noekeon* Noekeon)
(*scheme:skipjack* Skipjack)
(*scheme:khazad* Khazad)
(*scheme:seed* SEED)
(*scheme:kasumi* KASUMI)
(*scheme:camellia* Camellia))
(rename (*mode:ecb* MODE_ECB)
(*mode:cbc* MODE_CBC)
(*mode:cfb* MODE_CFB)
(*mode:ofb* MODE_OFB)
(*mode:ctr* MODE_CTR)
(*mode:lrw* MODE_LRW)
(*mode:f8* MODE_F8)
(*mode:eax* MODE_EAX)
(*mode:ocb* MODE_OCB)
(*mode:ocb3* MODE_OCB3)
(*mode:gcm* MODE_GCM))
ctr conter mode
(rename (*ctr-mode:little-endian* CTR_COUNTER_LITTLE_ENDIAN)
(*ctr-mode:big-endian* CTR_COUNTER_BIG_ENDIAN)
(*ctr-mode:rfc3686* LTC_CTR_RFC3686))
(rename (<legacy-crypto> <crypto>)
(<legacy-cipher> <cipher>)
(<legacy-cipher-spi> <cipher-spi>))
<key>
<symmetric-key>
<asymmetric-key>
cipher
(rename (cipher-encrypt encrypt)
(cipher-decrypt decrypt)
(cipher-signature sign)
(cipher-verify verify))
)
(import (rnrs)
(sagittarius)
(sagittarius crypto parameters)
(sagittarius crypto ciphers symmetric)
(clos core)
(crypto spi)
(crypto key)
(crypto pkcs))
(define-syntax define-mode-parameter (make-define-cipher-parameter))
(define-mode-parameter mode-name-parameter
make-mode-name-parameter mode-name-parameter?
(mode-name parameter-mode-name))
(define-mode-parameter padding-parameter
make-padding-parameter padding-parameter?
(padder parameter-padder))
(define-mode-parameter (<ctr-parameter> <iv-parameter>)
(make-ctr-parameter (lambda (p)
(lambda (iv :optional (mode *ctr-mode:big-endian*))
((p iv) mode))))
ctr-parameter?
(mode parameter-ctr-mode))
(define-mode-parameter (<rfc3686-parameter> <ctr-parameter>)
(make-rfc3686-parameter
(lambda (p)
(lambda (iv nonce :optional (mode *ctr-mode:big-endian*))
(let ((v (make-bytevector 16 0))
(nlen (bytevector-length nonce))
(ivlen (bytevector-length iv)))
(if (= mode *ctr-mode:big-endian*)
NONCE || IV || ONE = 16
(begin
(bytevector-copy! nonce 0 v 0 nlen)
(bytevector-copy! iv 0 v nlen ivlen))
ONE || IV || NONCE ( i guess )
(begin
(bytevector-copy! iv 0 v 4 ivlen)
(bytevector-copy! nonce 0 v (+ 4 ivlen) nlen)))
let it do libtomcrypt
((p v (+ mode *ctr-mode:rfc3686*)))))))
rfc3686-parameter?)
(define (crypto-object? o)
(or (key? o)
(is-a? o <legacy-crypto>)))
(define (cipher-verify cipher M S . opts)
(let ((spi (cipher-spi cipher)))
(or (apply (cipher-spi-verifier spi) M S (cipher-spi-key spi) opts)
(error 'cipher-verify "Inconsistent"))))
(define (cipher-signature cipher M . opts)
(let ((spi (cipher-spi cipher)))
(apply (cipher-spi-signer spi) M (cipher-spi-key spi) opts)))
(define (cipher-decrypt cipher ct :optional (len 0))
(let ((spi (cipher-spi cipher)))
(if (legacy-builtin-cipher-spi? spi)
((cipher-spi-decrypt spi) ct len (cipher-spi-key spi))
((cipher-spi-decrypt spi) ct (cipher-spi-key spi)))))
(define (cipher-encrypt cipher pt :optional (len 0))
(let ((spi (cipher-spi cipher)))
(if (legacy-builtin-cipher-spi? spi)
((cipher-spi-encrypt spi) pt len (cipher-spi-key spi))
((cipher-spi-encrypt spi) pt (cipher-spi-key spi)))))
(define (cipher-max-tag-size cipher)
(let ((spi (cipher-spi cipher)))
(cipher-spi-tagsize spi)))
(define (cipher-update-aad! cipher aad . opts)
(let ((spi (cipher-spi cipher)))
(cond ((cipher-spi-update-aad spi) => (lambda (proc) (apply proc aad opts)))
(else #f))))
(define (cipher-iv cipher :optional (iv #f))
(let ((spi (cipher-spi cipher)))
(if (bytevector? iv)
(slot-set! spi 'iv iv)
(cipher-spi-iv spi))))
(define (cipher-keysize cipher test)
(let ((spi (cipher-spi cipher)))
((cipher-spi-keysize spi) test)))
(define (cipher type key
:key (mode *mode:ecb*)
(iv #f)
(padder pkcs5-padder)
(rounds 0)
(ctr-mode *ctr-mode:big-endian*)
:allow-other-keys
:rest rest)
(define (rfc3686?)
(not (zero? (bitwise-and ctr-mode *ctr-mode:rfc3686*))))
(apply make-cipher type key
:mode-parameter
(apply make-cipher-parameter
(filter values
(list
(make-mode-name-parameter mode)
(make-padding-parameter padder)
(make-round-parameter rounds)
(and iv
(if (rfc3686?)
(make-rfc3686-parameter iv
#vu8(0 0 0 0)
ctr-mode)
(make-ctr-parameter iv ctr-mode))))))
rest))
(define (make-cipher type key
:key (mode-parameter #f)
:allow-other-keys
:rest rest)
(define parameter mode-parameter)
(let ((mode (or (and parameter (parameter-mode-name parameter *mode:ecb*))
*mode:ecb*))
(iv (and parameter (cipher-parameter-iv parameter #f)))
these 2 does n't have to be there but
(rounds (or (and parameter (cipher-parameter-rounds parameter 0)) 0))
(ctr-mode (or (and parameter
(parameter-ctr-mode parameter *ctr-mode:big-endian*))
*ctr-mode:big-endian*))
(padder (or (and parameter (parameter-padder parameter #f))
no-padding)))
(unless (or (eq? mode *mode:ecb*) (bytevector? iv))
(assertion-violation 'cipher "the given mode iv is required"))
(let ((spi (cond ((cipher-descriptor? type)
(make-builtin-cipher-spi
type mode key iv rounds padder ctr-mode))
((lookup-cipher-spi type) =>
(lambda (spi)
(apply make spi key :mode-parameter parameter
rest)))
(else
(assertion-violation 'cipher
"unknown cipher type" type)))))
(make <legacy-cipher> :spi spi))))
(define-constant +check-value+ (make-bytevector 8 0))
(define (key-check-value type key :optional (size 3))
(unless (<= 3 size 8)
(assertion-violation 'key-check-value "size must be between 3 to 8"
size))
(let ((c (make-cipher type key)))
(bytevector-copy (cipher-encrypt c +check-value+) 0 size)))
(define (cipher-tag! cipher out)
(let ((spi (cipher-spi cipher)))
(cond ((cipher-spi-tag spi) => (lambda (proc) (proc out)))
(else 0))))
(define (cipher-tag cipher :key (tag #f))
(let ((out (if tag tag (make-bytevector (cipher-max-tag-size cipher)))))
(cipher-tag! cipher out)
out))
(define (cipher-encrypt/tag cipher data
:key (tag-size (cipher-max-tag-size cipher)))
(let ((encrypted (cipher-encrypt cipher data)))
(values encrypted (cipher-tag cipher :tag (make-bytevector tag-size)))))
(define (cipher-decrypt/tag cipher data tag)
(let ((pt (cipher-decrypt cipher data)))
(values pt (cipher-tag cipher :tag tag))))
(define (cipher-decrypt/verify cipher encrypted tag)
(let-values (((pt target)
(cipher-decrypt/tag cipher encrypted
:tag-size (bytevector-length tag))))
(unless (bytevector=? tag target)
(error (slot-ref cipher 'name) 'cipher-decrypt/verify
"invalid tag is given"))
pt))
)
|
0cea48db483308a0cd4f47a062f6bb54c6c27651ee333ff2aa61116839a3d87e | esmolanka/sexp-grammar | Generic.hs | {-# LANGUAGE Safe #-}
module Language.SexpGrammar.Generic
( -- * GHC.Generics helpers
with
, match
, Coproduct (..)
) where
import Data.InvertibleGrammar.Generic
| null | https://raw.githubusercontent.com/esmolanka/sexp-grammar/ec5a2af94ebe403a5fab882af36ee9bbd12b3783/sexp-grammar/src/Language/SexpGrammar/Generic.hs | haskell | # LANGUAGE Safe #
* GHC.Generics helpers |
module Language.SexpGrammar.Generic
with
, match
, Coproduct (..)
) where
import Data.InvertibleGrammar.Generic
|
30c48652689c611e092a73c031020850dc388bcf82ad4916f7c180db76aeaa9f | juxt/jig | shared.clj | Copyright © 2013 , JUXT LTD . 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.
(ns jig.cljs.shared
(:require
[clojure.tools.namespace.find :as ns-find]
[clojure.tools.namespace.file :as ns-file]))
(def ^:dynamic *shared-metadata* :shared)
(defn ns-marked-as-shared?
"Is the namespace of the given file marked as shared?"
([jar file-name]
(when-let [ns-decl (ns-find/read-ns-decl-from-jarfile-entry jar file-name)]
(*shared-metadata* (meta (second ns-decl)))))
([file-name]
(when-let [ns-decl (ns-file/read-file-ns-decl file-name)]
(*shared-metadata* (meta (second ns-decl))))))
(defn rename-to-js
"Rename any Clojure-based file to a JavaScript file."
[file-str]
(clojure.string/replace file-str #".clj\w*$" ".js"))
(defn relative-path
"Given a directory and a file, return the relative path to the file
from within this directory."
[dir file]
(.substring (.getAbsolutePath file)
(inc (.length (.getAbsolutePath dir)))))
(defn js-file-name
"Given a directory and file, return the relative path to the
JavaScript file."
[dir file]
(rename-to-js (relative-path dir file)))
(defn cljs-file?
"Is the given file a ClojureScript file?"
[f]
(and (.isFile f)
(.endsWith (.getName f) ".cljs")))
| null | https://raw.githubusercontent.com/juxt/jig/3997887e5a56faadb1b48eccecbc7034b3d31e41/extensions/cljs-builder/src/jig/cljs/shared.clj | clojure |
The use and distribution terms for this software are covered by the
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. | Copyright © 2013 , JUXT LTD . All Rights Reserved .
Eclipse Public License 1.0 ( -1.0.php )
(ns jig.cljs.shared
(:require
[clojure.tools.namespace.find :as ns-find]
[clojure.tools.namespace.file :as ns-file]))
(def ^:dynamic *shared-metadata* :shared)
(defn ns-marked-as-shared?
"Is the namespace of the given file marked as shared?"
([jar file-name]
(when-let [ns-decl (ns-find/read-ns-decl-from-jarfile-entry jar file-name)]
(*shared-metadata* (meta (second ns-decl)))))
([file-name]
(when-let [ns-decl (ns-file/read-file-ns-decl file-name)]
(*shared-metadata* (meta (second ns-decl))))))
(defn rename-to-js
"Rename any Clojure-based file to a JavaScript file."
[file-str]
(clojure.string/replace file-str #".clj\w*$" ".js"))
(defn relative-path
"Given a directory and a file, return the relative path to the file
from within this directory."
[dir file]
(.substring (.getAbsolutePath file)
(inc (.length (.getAbsolutePath dir)))))
(defn js-file-name
"Given a directory and file, return the relative path to the
JavaScript file."
[dir file]
(rename-to-js (relative-path dir file)))
(defn cljs-file?
"Is the given file a ClojureScript file?"
[f]
(and (.isFile f)
(.endsWith (.getName f) ".cljs")))
|
0549916a2c147445705e95dba77046764805e984ab8be4ceb86a41e4ed7a374d | rickeyski/slack-api | Id.hs | # LANGUAGE DataKinds , KindSignatures , TemplateHaskell , DeriveGeneric #
module Web.Slack.Types.Id
( UserId,
BotId,
ChannelId,
FileId,
CommentId,
IMId,
TeamId,
SubteamId,
Id(..),
getId
) where
import Data.Aeson
import Data.Text (Text)
import Control.Lens.TH
import Data.Hashable
import GHC.Generics
data FieldType = TUser | TBot | TChannel | TFile | TComment | TIM | TTeam | TSubteam deriving (Eq, Show)
newtype Id (a :: FieldType) = Id { _getId :: Text } deriving (Show, Eq, Ord, Generic)
instance ToJSON (Id a) where
toJSON (Id uid) = String uid
instance FromJSON (Id a) where
parseJSON = withText "Id" (return . Id)
instance Hashable (Id a)
type UserId = Id 'TUser
type BotId = Id 'TBot
type ChannelId = Id 'TChannel
type FileId = Id 'TFile
type CommentId = Id 'TComment
type IMId = Id 'TIM
type TeamId = Id 'TTeam
type SubteamId = Id 'TSubteam
makeLenses ''Id
| null | https://raw.githubusercontent.com/rickeyski/slack-api/5f6659e09bce19fe0ca9dfce8743bec7de518d77/src/Web/Slack/Types/Id.hs | haskell | # LANGUAGE DataKinds , KindSignatures , TemplateHaskell , DeriveGeneric #
module Web.Slack.Types.Id
( UserId,
BotId,
ChannelId,
FileId,
CommentId,
IMId,
TeamId,
SubteamId,
Id(..),
getId
) where
import Data.Aeson
import Data.Text (Text)
import Control.Lens.TH
import Data.Hashable
import GHC.Generics
data FieldType = TUser | TBot | TChannel | TFile | TComment | TIM | TTeam | TSubteam deriving (Eq, Show)
newtype Id (a :: FieldType) = Id { _getId :: Text } deriving (Show, Eq, Ord, Generic)
instance ToJSON (Id a) where
toJSON (Id uid) = String uid
instance FromJSON (Id a) where
parseJSON = withText "Id" (return . Id)
instance Hashable (Id a)
type UserId = Id 'TUser
type BotId = Id 'TBot
type ChannelId = Id 'TChannel
type FileId = Id 'TFile
type CommentId = Id 'TComment
type IMId = Id 'TIM
type TeamId = Id 'TTeam
type SubteamId = Id 'TSubteam
makeLenses ''Id
| |
28eb111a6b57d5bec8e4d5fcd180cfbe7b61c63617962ccfc316dbb688862761 | Reisen/pixel | HKD.hs | module Pixel.HKD ( HKD ) where
import Protolude
--------------------------------------------------------------------------------
Higher - Kinded Data ( HKD ) , or Functor Functors is a way of modeling data as a
-- collection of Functor data:
--
-- ```
-- data Example' f = Example
-- { _exampleField1 :: HKD f Text
-- , _exampleField2 :: HKD f Int
-- }
-- ```
--
This allows defining ad - hoc structures on the fly by substituting the ` f `
-- for specific purposes, a validatable Example:
--
-- ```
type UnvalidatedExample = Example ' Maybe
-- type Example = Example' Identity
--
validateExample : : UnvalidatedExample - > Example
-- ```
--
-- In order to not have to constantly unwrap/re-wrap Identity when we want to
work with just normal data , we use a type - family called which erases the
-- Identity case, giving us our original data back.
type family HKD (f :: * -> *) a where
HKD Identity a = a
HKD f a = f a
| null | https://raw.githubusercontent.com/Reisen/pixel/9096cc2c5b909049cdca6d14856ffc1fc99d81b5/src/lib/Pixel/HKD.hs | haskell | ------------------------------------------------------------------------------
collection of Functor data:
```
data Example' f = Example
{ _exampleField1 :: HKD f Text
, _exampleField2 :: HKD f Int
}
```
for specific purposes, a validatable Example:
```
type Example = Example' Identity
```
In order to not have to constantly unwrap/re-wrap Identity when we want to
Identity case, giving us our original data back. | module Pixel.HKD ( HKD ) where
import Protolude
Higher - Kinded Data ( HKD ) , or Functor Functors is a way of modeling data as a
This allows defining ad - hoc structures on the fly by substituting the ` f `
type UnvalidatedExample = Example ' Maybe
validateExample : : UnvalidatedExample - > Example
work with just normal data , we use a type - family called which erases the
type family HKD (f :: * -> *) a where
HKD Identity a = a
HKD f a = f a
|
537bdf9fad2fcd00980a185167ec2513991252bfad57dbaf8934d0ba42ba3176 | AndrasKovacs/ELTE-func-lang | Lesson11_pre.hs | module Lesson11 where
import Control.Monad
import Control.Applicative
import Data.Char
import Debug.Trace
PARSER LIBRARY
--------------------------------------------------------------------------------
newtype Parser a = Parser { runParser :: String -> Maybe (a, String) }
instance Functor Parser where
fmap :: (a -> b) -> Parser a -> Parser b
-- g :: String -> Maybe (a, String)
fmap f (Parser g) = Parser $ \str -> case g str of
Nothing -> Nothing
Just (a, str') -> Just (f a, str')
instance Applicative Parser where
pure :: a -> Parser a
pure a = Parser $ \str -> Just (a, str)
(<*>) :: Parser (a -> b) -> Parser a -> Parser b
-- f :: String -> Maybe (a -> b, String)
-- g :: String -> Maybe (a, String)
(Parser f) <*> (Parser g) = Parser $ \str -> case f str of
Nothing -> Nothing
Just (aToB, str') -> case g str' of
Nothing -> Nothing
Just (a, str'') -> Just (aToB a, str'')
instance Monad Parser where
(>>=) :: Parser a -> (a -> Parser b) -> Parser b
(Parser f) >>= g = Parser $ \str -> case f str of
Nothing -> Nothing
Just (a,str') -> runParser (g a) str'
pontosan az üres inputot olvassuk
eof :: Parser ()
eof = Parser $ \str -> case str of
[] -> Just ((),[])
_ -> Nothing
olvassunk egy input , feltétel
satisfy :: (Char -> Bool) -> Parser Char
satisfy p = Parser $ \str -> case str of
(x:xs) | p x -> Just (x,xs)
_ -> Nothing
-- olvassunk egy tetszőleges karaktert
anyChar :: Parser Char
anyChar = satisfy (const True)
olvassunk egy konkrét karaktert
char :: Char -> Parser ()
char c = void (satisfy (== c))
-- char c = () <$ satisfy (== c)
-- olvassunk egy konkrét String-et
String ~ [ ]
string [] = pure ()
string (x:xs) = do
char x
string xs
instance Alternative Parser where
empty :: Parser a
empty = Parser $ const Nothing
(<|>) :: Parser a -> Parser a -> Parser a
(Parser f) <|> (Parser g) = Parser $ \str -> case f str of
Nothing -> g str
x -> x
-- Control.Applicative-ból:
many : : a - > Parser [ a ] -- 0 - szor vagy többször futtatja
some : : a - > Parser [ a ] -- 1 - szer vagy többször futtatja
many' :: Parser a -> Parser [a]
many' pa = some' pa <|> pure []
some' :: Parser a -> Parser [a]
some' pa = do
a <- pa
as <- many' pa
pure (a:as)
many_ :: Parser a -> Parser ()
many_ pa = () <$ many pa
some_ :: Parser a -> Parser ()
some_ pa = () <$ some pa
-- Control.Applicative-ból:
optional : : a - > Parser ( Maybe a ) -- ( soha )
-- optional pa = (Just <$> pa) <|> pure Nothing
optional_ :: Parser a -> Parser ()
optional_ pa = () <$ optional pa
általában ezt úgy szokás megtalálni , hogy ` between : : open - > Parser close - > Parser a - > Parser a
between :: Parser open -> Parser a -> Parser close -> Parser a
between pOpen pa pClose = do
pOpen
a <- pa
pClose
pure a
is meg lehet írni .
between' :: Parser open -> Parser a -> Parser close -> Parser a
between' pOpen pa pClose = pOpen *> pa <* pClose
debug :: String -> Parser a -> Parser a
debug msg pa = Parser $ \s -> trace (msg ++ " : " ++ s) (runParser pa s)
inList :: [Char] -> Parser Char
inList [] = empty
inList (x:xs) = (x <$ char x) <|> inList xs
inList_ :: [Char] -> Parser ()
inList_ = void . inList
-- std függvény:
choice :: [Parser a] -> Parser a
choice [] = empty
choice (p:ps) = p <|> choice ps
lowercase :: Parser ()
lowercase = inList_ ['a'..'z']
digit_ :: Parser ()
digit_ = inList_ ['0'..'9']
digit :: Parser Integer
digit = fmap (\c -> fromIntegral (fromEnum c - fromEnum '0')) $ inList ['0'..'9']
-- Functor/Applicative operátorok
( < $ ) kicseréli parser értékre
-- (<$>) fmap
( < * ) két parser - t futtat , az első
( * > ) két parser - t futtat , a második értékét visszaadja
integer :: Parser Integer
integer = do
a <- optional $ char '-'
digits <- some digit
let summa = foldl (\acc x -> 10 * acc + x) 0 digits
pure $ case a of
Nothing -> summa
Just _ -> -summa
ws :: Parser ()
ws = many_ (satisfy isSpace)
olvassunk 1 vagy több pa - t , psep -
pa ....
sepBy1 :: Parser a -> Parser sep -> Parser [a]
sepBy1 pa psep = do
a <- pa
as <- many $ psep *> pa
pure $ a:as
olvassunk 0 vagy több pa - t , psep -
sepBy :: Parser a -> Parser sep -> Parser [a]
sepBy pa psep = sepBy1 pa psep <|> pure []
data Exp = Lit Integer | Plus Exp Exp | Mul Exp Exp deriving Show
evalExp :: Exp -> Integer
evalExp (Lit n) = n
evalExp (Plus e1 e2) = evalExp e1 + evalExp e2
evalExp (Mul e1 e2) = evalExp e1 * evalExp e2
12 * 12 + 9
satisfy' :: (Char -> Bool) -> Parser Char
satisfy' f = satisfy f <* ws
char' :: Char -> Parser ()
char' c = char c <* ws
string' :: String -> Parser ()
string' s = string s <* ws
tokenize :: Parser a -> Parser a
tokenize pa = pa <* ws
topLevel :: Parser a -> Parser a
topLevel pa = ws *> pa <* eof
-- operátor segédfüggvények
rightAssoc :: (a -> a -> a) -> Parser a -> Parser sep -> Parser a
rightAssoc f pa psep = foldr1 f <$> sepBy1 pa psep
leftAssoc :: (a -> a -> a) -> Parser a -> Parser sep -> Parser a
leftAssoc f pa psep = foldl1 f <$> sepBy1 pa psep
nonAssoc :: (a -> a -> a) -> Parser a -> Parser sep -> Parser a
nonAssoc f pa psep = do
exps <- sepBy1 pa psep
case exps of
[e] -> pure e
[e1,e2] -> pure (f e1 e2)
_ -> empty
-----------------------------------------------------------------------
pExp :: Parser Exp
pExp = undefined | null | https://raw.githubusercontent.com/AndrasKovacs/ELTE-func-lang/b459dc8e50900bfc4474a1864819da3d50915f6c/2021-22-2/gyak_2/Lesson11_pre.hs | haskell | ------------------------------------------------------------------------------
g :: String -> Maybe (a, String)
f :: String -> Maybe (a -> b, String)
g :: String -> Maybe (a, String)
olvassunk egy tetszőleges karaktert
char c = () <$ satisfy (== c)
olvassunk egy konkrét String-et
Control.Applicative-ból:
0 - szor vagy többször futtatja
1 - szer vagy többször futtatja
Control.Applicative-ból:
( soha )
optional pa = (Just <$> pa) <|> pure Nothing
std függvény:
Functor/Applicative operátorok
(<$>) fmap
operátor segédfüggvények
--------------------------------------------------------------------- | module Lesson11 where
import Control.Monad
import Control.Applicative
import Data.Char
import Debug.Trace
PARSER LIBRARY
newtype Parser a = Parser { runParser :: String -> Maybe (a, String) }
instance Functor Parser where
fmap :: (a -> b) -> Parser a -> Parser b
fmap f (Parser g) = Parser $ \str -> case g str of
Nothing -> Nothing
Just (a, str') -> Just (f a, str')
instance Applicative Parser where
pure :: a -> Parser a
pure a = Parser $ \str -> Just (a, str)
(<*>) :: Parser (a -> b) -> Parser a -> Parser b
(Parser f) <*> (Parser g) = Parser $ \str -> case f str of
Nothing -> Nothing
Just (aToB, str') -> case g str' of
Nothing -> Nothing
Just (a, str'') -> Just (aToB a, str'')
instance Monad Parser where
(>>=) :: Parser a -> (a -> Parser b) -> Parser b
(Parser f) >>= g = Parser $ \str -> case f str of
Nothing -> Nothing
Just (a,str') -> runParser (g a) str'
pontosan az üres inputot olvassuk
eof :: Parser ()
eof = Parser $ \str -> case str of
[] -> Just ((),[])
_ -> Nothing
olvassunk egy input , feltétel
satisfy :: (Char -> Bool) -> Parser Char
satisfy p = Parser $ \str -> case str of
(x:xs) | p x -> Just (x,xs)
_ -> Nothing
anyChar :: Parser Char
anyChar = satisfy (const True)
olvassunk egy konkrét karaktert
char :: Char -> Parser ()
char c = void (satisfy (== c))
String ~ [ ]
string [] = pure ()
string (x:xs) = do
char x
string xs
instance Alternative Parser where
empty :: Parser a
empty = Parser $ const Nothing
(<|>) :: Parser a -> Parser a -> Parser a
(Parser f) <|> (Parser g) = Parser $ \str -> case f str of
Nothing -> g str
x -> x
many' :: Parser a -> Parser [a]
many' pa = some' pa <|> pure []
some' :: Parser a -> Parser [a]
some' pa = do
a <- pa
as <- many' pa
pure (a:as)
many_ :: Parser a -> Parser ()
many_ pa = () <$ many pa
some_ :: Parser a -> Parser ()
some_ pa = () <$ some pa
optional_ :: Parser a -> Parser ()
optional_ pa = () <$ optional pa
általában ezt úgy szokás megtalálni , hogy ` between : : open - > Parser close - > Parser a - > Parser a
between :: Parser open -> Parser a -> Parser close -> Parser a
between pOpen pa pClose = do
pOpen
a <- pa
pClose
pure a
is meg lehet írni .
between' :: Parser open -> Parser a -> Parser close -> Parser a
between' pOpen pa pClose = pOpen *> pa <* pClose
debug :: String -> Parser a -> Parser a
debug msg pa = Parser $ \s -> trace (msg ++ " : " ++ s) (runParser pa s)
inList :: [Char] -> Parser Char
inList [] = empty
inList (x:xs) = (x <$ char x) <|> inList xs
inList_ :: [Char] -> Parser ()
inList_ = void . inList
choice :: [Parser a] -> Parser a
choice [] = empty
choice (p:ps) = p <|> choice ps
lowercase :: Parser ()
lowercase = inList_ ['a'..'z']
digit_ :: Parser ()
digit_ = inList_ ['0'..'9']
digit :: Parser Integer
digit = fmap (\c -> fromIntegral (fromEnum c - fromEnum '0')) $ inList ['0'..'9']
( < $ ) kicseréli parser értékre
( < * ) két parser - t futtat , az első
( * > ) két parser - t futtat , a második értékét visszaadja
integer :: Parser Integer
integer = do
a <- optional $ char '-'
digits <- some digit
let summa = foldl (\acc x -> 10 * acc + x) 0 digits
pure $ case a of
Nothing -> summa
Just _ -> -summa
ws :: Parser ()
ws = many_ (satisfy isSpace)
olvassunk 1 vagy több pa - t , psep -
pa ....
sepBy1 :: Parser a -> Parser sep -> Parser [a]
sepBy1 pa psep = do
a <- pa
as <- many $ psep *> pa
pure $ a:as
olvassunk 0 vagy több pa - t , psep -
sepBy :: Parser a -> Parser sep -> Parser [a]
sepBy pa psep = sepBy1 pa psep <|> pure []
data Exp = Lit Integer | Plus Exp Exp | Mul Exp Exp deriving Show
evalExp :: Exp -> Integer
evalExp (Lit n) = n
evalExp (Plus e1 e2) = evalExp e1 + evalExp e2
evalExp (Mul e1 e2) = evalExp e1 * evalExp e2
12 * 12 + 9
satisfy' :: (Char -> Bool) -> Parser Char
satisfy' f = satisfy f <* ws
char' :: Char -> Parser ()
char' c = char c <* ws
string' :: String -> Parser ()
string' s = string s <* ws
tokenize :: Parser a -> Parser a
tokenize pa = pa <* ws
topLevel :: Parser a -> Parser a
topLevel pa = ws *> pa <* eof
rightAssoc :: (a -> a -> a) -> Parser a -> Parser sep -> Parser a
rightAssoc f pa psep = foldr1 f <$> sepBy1 pa psep
leftAssoc :: (a -> a -> a) -> Parser a -> Parser sep -> Parser a
leftAssoc f pa psep = foldl1 f <$> sepBy1 pa psep
nonAssoc :: (a -> a -> a) -> Parser a -> Parser sep -> Parser a
nonAssoc f pa psep = do
exps <- sepBy1 pa psep
case exps of
[e] -> pure e
[e1,e2] -> pure (f e1 e2)
_ -> empty
pExp :: Parser Exp
pExp = undefined |
a80f6f703d54be4807abae00221340ec568785b87fc8497958a62dcadbd18d62 | alpacaaa/quad-ci | Github.hs | module Github where
import Core
import Data.Aeson ((.:))
import qualified Data.Aeson as Aeson
import qualified Data.Aeson.Types as Aeson.Types
import qualified Data.Yaml as Yaml
import qualified Docker
import qualified JobHandler
import qualified Network.HTTP.Simple as HTTP
import RIO
import qualified RIO.NonEmpty.Partial as NonEmpty.Partial
import qualified RIO.Text as Text
createCloneStep :: JobHandler.CommitInfo -> Step
createCloneStep info =
Step
{ name = StepName "clone",
commands =
NonEmpty.Partial.fromList
[ "git clone -q /" <> info.repo <> " .",
"git checkout -qf " <> info.sha
],
image = Docker.Image "alpine/git" "v2.26.2"
}
fetchRemotePipeline :: JobHandler.CommitInfo -> IO Pipeline
fetchRemotePipeline info = do
endpoint <- HTTP.parseRequest ""
let path = "/repos/" <> info.repo <> "/contents/.quad.yml"
let req =
endpoint
& HTTP.setRequestPath (encodeUtf8 path)
& HTTP.addToRequestQueryString [("ref", Just $ encodeUtf8 info.sha)]
& HTTP.addRequestHeader "User-Agent" "quad-ci"
& HTTP.addRequestHeader "Accept" "application/vnd.github.v3.raw"
res <- HTTP.httpBS req
Yaml.decodeThrow $ HTTP.getResponseBody res
parsePushEvent :: ByteString -> IO JobHandler.CommitInfo
parsePushEvent body = do
let parser = Aeson.withObject "github-webhook" $ \event -> do
branch <-
event .: "ref" <&> \ref ->
Text.dropPrefix "refs/heads/" ref
commit <- event .: "head_commit"
sha <- commit .: "id"
message <- commit .: "message"
author <- commit .: "author" >>= \a -> a .: "username"
repo <- event .: "repository" >>= \r -> r .: "full_name"
pure
JobHandler.CommitInfo
{ sha = sha,
branch = branch,
message = message,
author = author,
repo = repo
}
let result = do
value <- Aeson.eitherDecodeStrict body
Aeson.Types.parseEither parser value
case result of
Left e -> throwString e
Right info -> pure info | null | https://raw.githubusercontent.com/alpacaaa/quad-ci/99175d3d0da5c03de22e3b20ae3b6ded79e40b57/src/Github.hs | haskell | module Github where
import Core
import Data.Aeson ((.:))
import qualified Data.Aeson as Aeson
import qualified Data.Aeson.Types as Aeson.Types
import qualified Data.Yaml as Yaml
import qualified Docker
import qualified JobHandler
import qualified Network.HTTP.Simple as HTTP
import RIO
import qualified RIO.NonEmpty.Partial as NonEmpty.Partial
import qualified RIO.Text as Text
createCloneStep :: JobHandler.CommitInfo -> Step
createCloneStep info =
Step
{ name = StepName "clone",
commands =
NonEmpty.Partial.fromList
[ "git clone -q /" <> info.repo <> " .",
"git checkout -qf " <> info.sha
],
image = Docker.Image "alpine/git" "v2.26.2"
}
fetchRemotePipeline :: JobHandler.CommitInfo -> IO Pipeline
fetchRemotePipeline info = do
endpoint <- HTTP.parseRequest ""
let path = "/repos/" <> info.repo <> "/contents/.quad.yml"
let req =
endpoint
& HTTP.setRequestPath (encodeUtf8 path)
& HTTP.addToRequestQueryString [("ref", Just $ encodeUtf8 info.sha)]
& HTTP.addRequestHeader "User-Agent" "quad-ci"
& HTTP.addRequestHeader "Accept" "application/vnd.github.v3.raw"
res <- HTTP.httpBS req
Yaml.decodeThrow $ HTTP.getResponseBody res
parsePushEvent :: ByteString -> IO JobHandler.CommitInfo
parsePushEvent body = do
let parser = Aeson.withObject "github-webhook" $ \event -> do
branch <-
event .: "ref" <&> \ref ->
Text.dropPrefix "refs/heads/" ref
commit <- event .: "head_commit"
sha <- commit .: "id"
message <- commit .: "message"
author <- commit .: "author" >>= \a -> a .: "username"
repo <- event .: "repository" >>= \r -> r .: "full_name"
pure
JobHandler.CommitInfo
{ sha = sha,
branch = branch,
message = message,
author = author,
repo = repo
}
let result = do
value <- Aeson.eitherDecodeStrict body
Aeson.Types.parseEither parser value
case result of
Left e -> throwString e
Right info -> pure info | |
51b1233658bbc6a0c12d9a6fc03b66f73515f29ba9a4e1f66c44cde1a12831ec | zlatozar/study-paip | exercises.lisp | -*- Mode : LISP ; Syntax : COMMON - LISP ; Package : CH12 - EXERCISES ; Base : 10 -*-
;;;; File exercises.lisp
(in-package #:ch12-exercises)
;;; ____________________________________________________________________________
(def-prolog-compiler-macro and (goal body cont bindings)
(compile-body (append (args goal) body) cont bindings))
(def-prolog-compiler-macro or (goal body cont bindings)
(let ((disjuncts (args goal)))
(case (length disjuncts)
(0 fail)
(1 (compile-body (cons (first disjuncts) body) cont bindings))
(t (let ((fn (gensym "F")))
`(flet ((,fn () ,(compile-body body cont bindings)))
.,(maybe-add-undo-bindings
(loop for g in disjuncts collect
(compile-body (list g) `#',fn
bindings)))))))))
;; when a goal succeeds, we call the continuation
(defun true=/0 (cont)
(funcall cont))
;; when a goal fails, we ignore the continuation
(defun fail=/0 (cont)
(declare (ignore cont))
nil)
Prolog trace
(defvar *prolog-trace-indent* 0)
(defun prolog-trace (kind predicate &rest args)
(if
(member kind '(call redo))
(incf *prolog-trace-indent* 3))
(format t "~&~VT~a ~a:~{ ~a~}"
*prolog-trace-indent* kind predicate args)
(if
(member kind '(fail exit))
(decf *prolog-trace-indent* 3)))
(defun >/2 (x y cont)
(if
(and (numberp (deref x)) (numberp (deref y)) (> χ y))
(funcall cont)))
(defun numberp=/1 (x cont)
(if
(numberp (deref x ) )
(funcall cont)))
| null | https://raw.githubusercontent.com/zlatozar/study-paip/dfa1ca6118f718f5d47d8c63cbb7b4cad23671e1/ch12/exercises.lisp | lisp | Syntax : COMMON - LISP ; Package : CH12 - EXERCISES ; Base : 10 -*-
File exercises.lisp
____________________________________________________________________________
when a goal succeeds, we call the continuation
when a goal fails, we ignore the continuation |
(in-package #:ch12-exercises)
(def-prolog-compiler-macro and (goal body cont bindings)
(compile-body (append (args goal) body) cont bindings))
(def-prolog-compiler-macro or (goal body cont bindings)
(let ((disjuncts (args goal)))
(case (length disjuncts)
(0 fail)
(1 (compile-body (cons (first disjuncts) body) cont bindings))
(t (let ((fn (gensym "F")))
`(flet ((,fn () ,(compile-body body cont bindings)))
.,(maybe-add-undo-bindings
(loop for g in disjuncts collect
(compile-body (list g) `#',fn
bindings)))))))))
(defun true=/0 (cont)
(funcall cont))
(defun fail=/0 (cont)
(declare (ignore cont))
nil)
Prolog trace
(defvar *prolog-trace-indent* 0)
(defun prolog-trace (kind predicate &rest args)
(if
(member kind '(call redo))
(incf *prolog-trace-indent* 3))
(format t "~&~VT~a ~a:~{ ~a~}"
*prolog-trace-indent* kind predicate args)
(if
(member kind '(fail exit))
(decf *prolog-trace-indent* 3)))
(defun >/2 (x y cont)
(if
(and (numberp (deref x)) (numberp (deref y)) (> χ y))
(funcall cont)))
(defun numberp=/1 (x cont)
(if
(numberp (deref x ) )
(funcall cont)))
|
e132c06f86397de7a42a24076d0854eedcc7c8897207415cab8b6d03e6cd8a1b | yurug/ocaml-crontab | io.ml | open Cron
let _announce =
Random.self_init ();
let out = Printf.sprintf "crontab.backup-%d" (Random.bits ()) in
Printf.printf "Saving the local crontab in %s.\n" out;
Sys.command (Printf.sprintf "crontab -l > %s" out)
let saved = crontab_get ()
let entry1 = make_entry "true"
let entry2 = make_entry ~minute:(List [single valid_minute 33]) "false"
let table = make [entry1; entry2]
let _put = crontab_install table
let loaded = crontab_get ()
let _restore = crontab_install saved
let check what desc =
Printf.printf "[%s] %s\n%!" (if what then "OK" else "KO") desc;
exit (if what then 0 else 1)
let check () =
check (loaded = table) "Input/Output of crontab"
| null | https://raw.githubusercontent.com/yurug/ocaml-crontab/59b0d84bfe3d7f2a9ee1e00c6f6733dba2765c55/tests/io.ml | ocaml | open Cron
let _announce =
Random.self_init ();
let out = Printf.sprintf "crontab.backup-%d" (Random.bits ()) in
Printf.printf "Saving the local crontab in %s.\n" out;
Sys.command (Printf.sprintf "crontab -l > %s" out)
let saved = crontab_get ()
let entry1 = make_entry "true"
let entry2 = make_entry ~minute:(List [single valid_minute 33]) "false"
let table = make [entry1; entry2]
let _put = crontab_install table
let loaded = crontab_get ()
let _restore = crontab_install saved
let check what desc =
Printf.printf "[%s] %s\n%!" (if what then "OK" else "KO") desc;
exit (if what then 0 else 1)
let check () =
check (loaded = table) "Input/Output of crontab"
| |
a944a2d8d84f8e669c7d0912a07e2f7b9cdf05af224197adccce9774f5a0fc23 | ocaml/oasis | OASISFormat.ml | (******************************************************************************)
OASIS : architecture for building OCaml libraries and applications
(* *)
Copyright ( C ) 2011 - 2016 ,
Copyright ( C ) 2008 - 2011 , OCamlCore SARL
(* *)
(* 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 OCaml static compilation *)
(* exception. *)
(* *)
(* 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 file COPYING 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. , 51 Franklin St , Fifth Floor , Boston , MA 02110 - 1301 USA
(******************************************************************************)
open OASISTypes
open Format
open FormatExt
* Pretty printing of OASIS files
*)
let pp_print_fields fmt (schm, _, data) =
let fake_data =
PropList.Data.create ()
in
let key_value =
List.rev
(PropList.Schema.fold
(fun acc key _ _ ->
try
let str =
PropList.Schema.get
schm
data
key
in
let is_default =
try
let default =
PropList.Schema.get
schm
fake_data
key
in
str = default
with
| OASISValues.Not_printable
| PropList.Not_set _ ->
(* Unable to compare so this is not default *)
false
in
if not is_default then
(key, str) :: acc
else
acc
with
| OASISValues.Not_printable ->
acc
| PropList.Not_set _ ->
(* TODO: is it really necessary *)
(* when extra. <> None ->*)
acc)
[]
schm)
in
let max_key_length =
(* ":" *)
1
+
(* Maximum length of a key *)
(List.fold_left
max
0
(* Only consider length of key *)
(List.rev_map
fst
(* Remove key/value that exceed line length *)
(List.filter
(fun (k, v) -> k + v < pp_get_margin fmt ())
(* Consider only length of key/value *)
(List.rev_map
(fun (k, v) -> String.length k, String.length v)
key_value))))
in
let pp_print_field fmt k v =
pp_open_box fmt 2;
pp_print_string fmt k;
pp_print_string fmt ":";
pp_print_break fmt (max 0 (max_key_length - String.length k)) 0;
pp_print_string_spaced fmt v;
pp_close_box fmt ()
in
let _b : bool =
pp_open_vbox fmt 0;
List.fold_left
(fun first (k, v) ->
if not first then begin
pp_print_cut fmt ()
end;
pp_print_field fmt k v;
false)
true
key_value
in
pp_close_box fmt ()
let pp_print_section plugins fmt sct =
let pp_print_section' schm t =
let (schm, _, _) as sct_data =
OASISSchema_intern.to_proplist schm plugins t
in
let {cs_name = nm; _} =
OASISSection.section_common sct
in
let pp_id_or_string fmt str =
(* A string is an id if varname_of_string doesn't change it *)
if OASISUtils.is_varname str then
fprintf fmt "%s" str
else
fprintf fmt "%S" str
in
fprintf fmt "@[<v 2>%s %a@,%a@]@,"
(PropList.Schema.name schm)
pp_id_or_string nm
pp_print_fields sct_data
in
match sct with
| Library (cs, bs, lib) ->
pp_print_section' OASISLibrary.schema (cs, bs, lib)
| Object (cs, bs, obj) ->
pp_print_section' OASISObject.schema (cs, bs, obj)
| Executable (cs, bs, exec) ->
pp_print_section' OASISExecutable.schema (cs, bs, exec)
| SrcRepo (cs, src_repo) ->
pp_print_section' OASISSourceRepository.schema (cs, src_repo)
| Test (cs, test) ->
pp_print_section' OASISTest.schema (cs, test)
| Flag (cs, flag) ->
pp_print_section' OASISFlag.schema (cs, flag)
| Doc (cs, doc) ->
pp_print_section' OASISDocument.schema (cs, doc)
let pp_print_package fmt pkg =
let (_, plugins, _) as pkg_data =
OASISSchema_intern.to_proplist OASISPackage.schema [] pkg
in
pp_open_vbox fmt 0;
pp_print_fields fmt pkg_data;
pp_print_cut fmt ();
List.iter (pp_print_section plugins fmt) pkg.sections;
pp_close_box fmt ()
| null | https://raw.githubusercontent.com/ocaml/oasis/3d1a9421db92a0882ebc58c5df219b18c1e5681d/src/oasis/OASISFormat.ml | ocaml | ****************************************************************************
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
your option) any later version, with the OCaml static compilation
exception.
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 file COPYING for more
details.
****************************************************************************
Unable to compare so this is not default
TODO: is it really necessary
when extra. <> None ->
":"
Maximum length of a key
Only consider length of key
Remove key/value that exceed line length
Consider only length of key/value
A string is an id if varname_of_string doesn't change it | OASIS : architecture for building OCaml libraries and applications
Copyright ( C ) 2011 - 2016 ,
Copyright ( C ) 2008 - 2011 , OCamlCore SARL
the Free Software Foundation ; either version 2.1 of the License , or ( at
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. , 51 Franklin St , Fifth Floor , Boston , MA 02110 - 1301 USA
open OASISTypes
open Format
open FormatExt
* Pretty printing of OASIS files
*)
let pp_print_fields fmt (schm, _, data) =
let fake_data =
PropList.Data.create ()
in
let key_value =
List.rev
(PropList.Schema.fold
(fun acc key _ _ ->
try
let str =
PropList.Schema.get
schm
data
key
in
let is_default =
try
let default =
PropList.Schema.get
schm
fake_data
key
in
str = default
with
| OASISValues.Not_printable
| PropList.Not_set _ ->
false
in
if not is_default then
(key, str) :: acc
else
acc
with
| OASISValues.Not_printable ->
acc
| PropList.Not_set _ ->
acc)
[]
schm)
in
let max_key_length =
1
+
(List.fold_left
max
0
(List.rev_map
fst
(List.filter
(fun (k, v) -> k + v < pp_get_margin fmt ())
(List.rev_map
(fun (k, v) -> String.length k, String.length v)
key_value))))
in
let pp_print_field fmt k v =
pp_open_box fmt 2;
pp_print_string fmt k;
pp_print_string fmt ":";
pp_print_break fmt (max 0 (max_key_length - String.length k)) 0;
pp_print_string_spaced fmt v;
pp_close_box fmt ()
in
let _b : bool =
pp_open_vbox fmt 0;
List.fold_left
(fun first (k, v) ->
if not first then begin
pp_print_cut fmt ()
end;
pp_print_field fmt k v;
false)
true
key_value
in
pp_close_box fmt ()
let pp_print_section plugins fmt sct =
let pp_print_section' schm t =
let (schm, _, _) as sct_data =
OASISSchema_intern.to_proplist schm plugins t
in
let {cs_name = nm; _} =
OASISSection.section_common sct
in
let pp_id_or_string fmt str =
if OASISUtils.is_varname str then
fprintf fmt "%s" str
else
fprintf fmt "%S" str
in
fprintf fmt "@[<v 2>%s %a@,%a@]@,"
(PropList.Schema.name schm)
pp_id_or_string nm
pp_print_fields sct_data
in
match sct with
| Library (cs, bs, lib) ->
pp_print_section' OASISLibrary.schema (cs, bs, lib)
| Object (cs, bs, obj) ->
pp_print_section' OASISObject.schema (cs, bs, obj)
| Executable (cs, bs, exec) ->
pp_print_section' OASISExecutable.schema (cs, bs, exec)
| SrcRepo (cs, src_repo) ->
pp_print_section' OASISSourceRepository.schema (cs, src_repo)
| Test (cs, test) ->
pp_print_section' OASISTest.schema (cs, test)
| Flag (cs, flag) ->
pp_print_section' OASISFlag.schema (cs, flag)
| Doc (cs, doc) ->
pp_print_section' OASISDocument.schema (cs, doc)
let pp_print_package fmt pkg =
let (_, plugins, _) as pkg_data =
OASISSchema_intern.to_proplist OASISPackage.schema [] pkg
in
pp_open_vbox fmt 0;
pp_print_fields fmt pkg_data;
pp_print_cut fmt ();
List.iter (pp_print_section plugins fmt) pkg.sections;
pp_close_box fmt ()
|
1940843e7dd6a18a64e0f892aa165bfa2022caa26cb0d7243205c8738624a008 | well-typed/optics | Passthrough.hs | module Optics.Passthrough where
import Optics.Internal.Optic
import Optics.AffineTraversal
import Optics.Lens
import Optics.Prism
import Optics.Traversal
import Optics.View
class (Is k A_Traversal, ViewableOptic k r) => PermeableOptic k r where
| Modify the target of an ' Optic ' returning extra information of type ' r ' .
passthrough
:: Optic k is s t a b
-> (a -> (r, b))
-> s
-> (ViewResult k r, t)
instance PermeableOptic An_Iso r where
passthrough o = toLensVL o
# INLINE passthrough #
instance PermeableOptic A_Lens r where
passthrough o = toLensVL o
# INLINE passthrough #
instance PermeableOptic A_Prism r where
passthrough o f s = withPrism o $ \bt sta -> case sta s of
Left t -> (Nothing, t)
Right a -> case f a of
(r, b) -> (Just r, bt b)
# INLINE passthrough #
instance PermeableOptic An_AffineTraversal r where
passthrough o f s = withAffineTraversal o $ \sta sbt -> case sta s of
Left t -> (Nothing, t)
Right a -> case f a of
(r, b) -> (Just r, sbt s b)
# INLINE passthrough #
instance Monoid r => PermeableOptic A_Traversal r where
passthrough = traverseOf
# INLINE passthrough #
| null | https://raw.githubusercontent.com/well-typed/optics/7cc3f9c334cdf69feaf10f58b11d3dbe2f98812c/optics-extra/src/Optics/Passthrough.hs | haskell | module Optics.Passthrough where
import Optics.Internal.Optic
import Optics.AffineTraversal
import Optics.Lens
import Optics.Prism
import Optics.Traversal
import Optics.View
class (Is k A_Traversal, ViewableOptic k r) => PermeableOptic k r where
| Modify the target of an ' Optic ' returning extra information of type ' r ' .
passthrough
:: Optic k is s t a b
-> (a -> (r, b))
-> s
-> (ViewResult k r, t)
instance PermeableOptic An_Iso r where
passthrough o = toLensVL o
# INLINE passthrough #
instance PermeableOptic A_Lens r where
passthrough o = toLensVL o
# INLINE passthrough #
instance PermeableOptic A_Prism r where
passthrough o f s = withPrism o $ \bt sta -> case sta s of
Left t -> (Nothing, t)
Right a -> case f a of
(r, b) -> (Just r, bt b)
# INLINE passthrough #
instance PermeableOptic An_AffineTraversal r where
passthrough o f s = withAffineTraversal o $ \sta sbt -> case sta s of
Left t -> (Nothing, t)
Right a -> case f a of
(r, b) -> (Just r, sbt s b)
# INLINE passthrough #
instance Monoid r => PermeableOptic A_Traversal r where
passthrough = traverseOf
# INLINE passthrough #
| |
4dd4f84e5740e68a43ea6596dbb13ee4d26af35695cbdca22810e89b501e1f5d | Beluga-lang/Beluga | fun.mli | include module type of Stdlib.Fun
(** [f ++ g] is the function composition of [f] and [g], such that
[(f ++ g) x] is [f (g x)]. *)
val ( ++ ) : ('b -> 'c) -> ('a -> 'b) -> 'a -> 'c
(** [f >> g] is the function composition of [f] and [g], such that
[x |> (f >> g)] is [g (f x)]. *)
val ( >> ) : ('a -> 'b) -> ('b -> 'c) -> 'a -> 'c
(** [apply x f] is [f x]. This is useful when a function pipeline ends in a
call to the generated function. *)
val apply : 'a -> ('a -> 'b) -> 'b
(** [flip f x y] is [f y x]. *)
val flip : ('a -> 'b -> 'c) -> 'b -> 'a -> 'c
(** [until f] repeatedly calls the effectful function [f] until [f ()] is
[false]. If [f] always returns [true], then [until f] does not terminate. *)
val until : (unit -> bool) -> unit
(** [through f x] applies the effectful function [f] on [x] and returns [x].
@example [... |> through (fun x -> print_string x) |> ...]
*)
val through : ('a -> unit) -> 'a -> 'a
(** [after f x] calls the effectful function [f] and returns [x].
This effectively calls [f] after executing a function pipeline.
@example [... |> through (fun x -> print_string "Success") |> ...]
*)
val after : (unit -> unit) -> 'a -> 'a
(** Converts an uncurried function to a curried function. *)
val curry : ('a * 'b -> 'c) -> 'a -> 'b -> 'c
(** Converts a curried function to a function on pairs. *)
val uncurry : ('a -> 'b -> 'c) -> 'a * 'b -> 'c
(** The fixpoint combinator. *)
val fix : (('a -> 'b) -> 'a -> 'b) -> 'a -> 'b
| null | https://raw.githubusercontent.com/Beluga-lang/Beluga/0b27be6d78ab917fdb7a18dd8e3b74c90e979950/src/support/fun.mli | ocaml | * [f ++ g] is the function composition of [f] and [g], such that
[(f ++ g) x] is [f (g x)].
* [f >> g] is the function composition of [f] and [g], such that
[x |> (f >> g)] is [g (f x)].
* [apply x f] is [f x]. This is useful when a function pipeline ends in a
call to the generated function.
* [flip f x y] is [f y x].
* [until f] repeatedly calls the effectful function [f] until [f ()] is
[false]. If [f] always returns [true], then [until f] does not terminate.
* [through f x] applies the effectful function [f] on [x] and returns [x].
@example [... |> through (fun x -> print_string x) |> ...]
* [after f x] calls the effectful function [f] and returns [x].
This effectively calls [f] after executing a function pipeline.
@example [... |> through (fun x -> print_string "Success") |> ...]
* Converts an uncurried function to a curried function.
* Converts a curried function to a function on pairs.
* The fixpoint combinator. | include module type of Stdlib.Fun
val ( ++ ) : ('b -> 'c) -> ('a -> 'b) -> 'a -> 'c
val ( >> ) : ('a -> 'b) -> ('b -> 'c) -> 'a -> 'c
val apply : 'a -> ('a -> 'b) -> 'b
val flip : ('a -> 'b -> 'c) -> 'b -> 'a -> 'c
val until : (unit -> bool) -> unit
val through : ('a -> unit) -> 'a -> 'a
val after : (unit -> unit) -> 'a -> 'a
val curry : ('a * 'b -> 'c) -> 'a -> 'b -> 'c
val uncurry : ('a -> 'b -> 'c) -> 'a * 'b -> 'c
val fix : (('a -> 'b) -> 'a -> 'b) -> 'a -> 'b
|
7c4a093dcb27accb70b1d217a675761b5b9db1025a9c7a5a946a3663e8ecf13b | docker-in-aws/docker-in-aws | form_ports.cljs | (ns swarmpit.component.service.form-ports
(:require [material.component :as comp]
[material.component.form :as form]
[material.component.list-table-form :as list]
[swarmpit.component.state :as state]
[swarmpit.component.parser :refer [parse-int]]
[swarmpit.ajax :as ajax]
[swarmpit.routes :as routes]
[sablono.core :refer-macros [html]]
[rum.core :as rum]))
(enable-console-print!)
(def form-value-cursor (conj state/form-value-cursor :ports))
(defn- not-suggested?
[port]
(not
(some #(= (:containerPort port)
(:containerPort %)) (state/get-value form-value-cursor))))
(defn load-suggestable-ports
[repository]
(ajax/get
(routes/path-for-backend :repository-ports)
{:params {:repository (:name repository)
:repositoryTag (:tag repository)}
:on-success (fn [{:keys [response]}]
(doseq [port response]
(if (not-suggested? port)
(state/add-item (merge port
{:mode "ingress"}) form-value-cursor))))
:on-error (fn [_])}))
(def headers [{:name "Container port"
:width "100px"}
{:name "Protocol"
:width "100px"}
{:name "Mode"
:width "150px"}
{:name "Host port"
:width "100px"}])
(defn- form-container [value index]
(list/textfield
{:name (str "form-container-text-" index)
:key (str "form-container-text-" index)
:type "number"
:min 1
:max 65535
:value value
:onChange (fn [_ v]
(state/update-item index :containerPort (parse-int v) form-value-cursor))}))
(defn- form-protocol [value index]
(list/selectfield
{:name (str "form-protocol-select-" index)
:key (str "form-protocol-select-" index)
:value value
:onChange (fn [_ _ v]
(state/update-item index :protocol v form-value-cursor))}
(comp/menu-item
{:name (str "form-protocol-tcp-" index)
:key (str "form-protocol-tcp-" index)
:value "tcp"
:primaryText "TCP"})
(comp/menu-item
{:name (str "form-protocol-udp-" index)
:key (str "form-protocol-udp-" index)
:value "udp"
:primaryText "UDP"})))
(defn- form-mode [value index]
(list/selectfield
{:name (str "form-mode-select-" index)
:key (str "form-mode-select-" index)
:value value
:onChange (fn [_ _ v]
(state/update-item index :mode v form-value-cursor))}
(comp/menu-item
{:name (str "form-mode-ingress-" index)
:key (str "form-mode-ingress-" index)
:value "ingress"
:primaryText "ingress"})
(comp/menu-item
{:name (str "form-mode-host-" index)
:key (str "form-mode-host-" index)
:value "host"
:primaryText "host"})))
(defn- form-host [value index]
(list/textfield
{:name (str "form-host-text-" index)
:key (str "form-host-text-" index)
:type "number"
:min 1
:max 65535
:value value
:onChange (fn [_ v]
(state/update-item index :hostPort (parse-int v) form-value-cursor))}))
(defn- render-ports
[item index _]
(let [{:keys [containerPort
protocol
mode
hostPort]} item]
[(form-container containerPort index)
(form-protocol protocol index)
(form-mode mode index)
(form-host hostPort index)]))
(defn- form-table
[ports]
(form/form
{}
(list/table-raw headers
ports
nil
render-ports
(fn [index] (state/remove-item index form-value-cursor)))))
(defn- add-item
[]
(state/add-item {:containerPort 0
:protocol "tcp"
:mode "ingress"
:hostPort 0} form-value-cursor))
(rum/defc form < rum/reactive []
(let [ports (state/react form-value-cursor)]
(if (empty? ports)
(form/value "Service has no published ports.")
(form-table ports)))) | null | https://raw.githubusercontent.com/docker-in-aws/docker-in-aws/bfc7e82ac82ea158bfb03445da6aec167b1a14a3/ch16/swarmpit/src/cljs/swarmpit/component/service/form_ports.cljs | clojure | (ns swarmpit.component.service.form-ports
(:require [material.component :as comp]
[material.component.form :as form]
[material.component.list-table-form :as list]
[swarmpit.component.state :as state]
[swarmpit.component.parser :refer [parse-int]]
[swarmpit.ajax :as ajax]
[swarmpit.routes :as routes]
[sablono.core :refer-macros [html]]
[rum.core :as rum]))
(enable-console-print!)
(def form-value-cursor (conj state/form-value-cursor :ports))
(defn- not-suggested?
[port]
(not
(some #(= (:containerPort port)
(:containerPort %)) (state/get-value form-value-cursor))))
(defn load-suggestable-ports
[repository]
(ajax/get
(routes/path-for-backend :repository-ports)
{:params {:repository (:name repository)
:repositoryTag (:tag repository)}
:on-success (fn [{:keys [response]}]
(doseq [port response]
(if (not-suggested? port)
(state/add-item (merge port
{:mode "ingress"}) form-value-cursor))))
:on-error (fn [_])}))
(def headers [{:name "Container port"
:width "100px"}
{:name "Protocol"
:width "100px"}
{:name "Mode"
:width "150px"}
{:name "Host port"
:width "100px"}])
(defn- form-container [value index]
(list/textfield
{:name (str "form-container-text-" index)
:key (str "form-container-text-" index)
:type "number"
:min 1
:max 65535
:value value
:onChange (fn [_ v]
(state/update-item index :containerPort (parse-int v) form-value-cursor))}))
(defn- form-protocol [value index]
(list/selectfield
{:name (str "form-protocol-select-" index)
:key (str "form-protocol-select-" index)
:value value
:onChange (fn [_ _ v]
(state/update-item index :protocol v form-value-cursor))}
(comp/menu-item
{:name (str "form-protocol-tcp-" index)
:key (str "form-protocol-tcp-" index)
:value "tcp"
:primaryText "TCP"})
(comp/menu-item
{:name (str "form-protocol-udp-" index)
:key (str "form-protocol-udp-" index)
:value "udp"
:primaryText "UDP"})))
(defn- form-mode [value index]
(list/selectfield
{:name (str "form-mode-select-" index)
:key (str "form-mode-select-" index)
:value value
:onChange (fn [_ _ v]
(state/update-item index :mode v form-value-cursor))}
(comp/menu-item
{:name (str "form-mode-ingress-" index)
:key (str "form-mode-ingress-" index)
:value "ingress"
:primaryText "ingress"})
(comp/menu-item
{:name (str "form-mode-host-" index)
:key (str "form-mode-host-" index)
:value "host"
:primaryText "host"})))
(defn- form-host [value index]
(list/textfield
{:name (str "form-host-text-" index)
:key (str "form-host-text-" index)
:type "number"
:min 1
:max 65535
:value value
:onChange (fn [_ v]
(state/update-item index :hostPort (parse-int v) form-value-cursor))}))
(defn- render-ports
[item index _]
(let [{:keys [containerPort
protocol
mode
hostPort]} item]
[(form-container containerPort index)
(form-protocol protocol index)
(form-mode mode index)
(form-host hostPort index)]))
(defn- form-table
[ports]
(form/form
{}
(list/table-raw headers
ports
nil
render-ports
(fn [index] (state/remove-item index form-value-cursor)))))
(defn- add-item
[]
(state/add-item {:containerPort 0
:protocol "tcp"
:mode "ingress"
:hostPort 0} form-value-cursor))
(rum/defc form < rum/reactive []
(let [ports (state/react form-value-cursor)]
(if (empty? ports)
(form/value "Service has no published ports.")
(form-table ports)))) | |
6a98fa74992effd3165119864ed06ef79e32365764a8591845214e40335677cd | hidaris/thinking-dumps | 06_cond.rkt | #lang racket
;; (provide (all-defined-out))
(define (sum3 xs)
(cond [(null? xs) 0]
[(number? (car xs)) (+ (car xs) (sum3 (cdr xs)))]
[(list? (car xs)) (+ (sum3 (car xs)) (sum3 (cdr xs)))]
[#t (sum3 (cdr xs))]))
(sum3 '("hi"))
(define (count-falses xs)
(cond [(null? xs) 0]
[(car xs) (count-falses (cdr xs))]
[#t (+ 1 (count-falses (cdr xs)))]))
(count-falses '(#f 2 3 4 #f #t #f))
| null | https://raw.githubusercontent.com/hidaris/thinking-dumps/3fceaf9e6195ab99c8315749814a7377ef8baf86/cse341/racket/06_cond.rkt | racket | (provide (all-defined-out)) | #lang racket
(define (sum3 xs)
(cond [(null? xs) 0]
[(number? (car xs)) (+ (car xs) (sum3 (cdr xs)))]
[(list? (car xs)) (+ (sum3 (car xs)) (sum3 (cdr xs)))]
[#t (sum3 (cdr xs))]))
(sum3 '("hi"))
(define (count-falses xs)
(cond [(null? xs) 0]
[(car xs) (count-falses (cdr xs))]
[#t (+ 1 (count-falses (cdr xs)))]))
(count-falses '(#f 2 3 4 #f #t #f))
|
f435a5352ade12b66e673c7d5ca21a78b62bff9bfe38fbe506f5e949723bc53e | roburio/caldav | webdav_api.mli | type tree = Webdav_xml.tree
type content_type = string
open Webdav_config
module type S =
sig
type state
val mkcol : state -> config -> path:string -> user:string -> Cohttp.Code.meth -> Ptime.t -> data:string ->
(unit, [ `Bad_request | `Conflict | `Forbidden of string ]) result Lwt.t
val propfind : state -> config -> path:string -> user:string -> depth:string option -> data:string ->
(string, [> `Bad_request | `Forbidden of string | `Property_not_found ]) result Lwt.t
val proppatch : state -> config -> path:string -> user:string -> data:string ->
(string, [> `Bad_request ]) result Lwt.t
val report : state -> config -> path:string -> user:string -> data:string ->
(string, [> `Bad_request ]) result Lwt.t
val write_component : state -> config -> path:string -> Ptime.t -> content_type:content_type -> data:string ->
(string, [> `Bad_request | `Conflict | `Forbidden | `Internal_server_error ]) result Lwt.t
val delete : state -> path:string -> Ptime.t -> bool Lwt.t
val read : state -> path:string -> is_mozilla:bool -> (string * content_type, [> `Not_found ]) result Lwt.t
val access_granted_for_acl : state -> config -> Cohttp.Code.meth -> path:string -> user:string -> bool Lwt.t
val last_modified : state -> path:string -> string option Lwt.t
val compute_etag : state -> path:string -> string option Lwt.t
val verify_auth_header : state -> config -> string -> (string, [> `Msg of string | `Unknown_user of string * string ]) result Lwt.t
val make_user : ?props:(Webdav_xml.fqname * Properties.property) list -> state -> Ptime.t -> config -> name:string -> password:string -> salt:Cstruct.t ->
(Uri.t, [> `Conflict | `Internal_server_error ]) result Lwt.t
val change_user_password : state -> config -> name:string -> password:string -> salt:Cstruct.t -> (unit, [> `Internal_server_error ]) result Lwt.t
val delete_user : state -> config -> string -> (unit, [> `Internal_server_error | `Not_found | `Conflict ]) result Lwt.t
val make_group : state -> Ptime.t -> config -> string -> string list -> (Uri.t, [> `Conflict | `Internal_server_error ]) result Lwt.t
val enroll : state -> config -> member:string -> group:string -> (unit, [> `Conflict | `Internal_server_error ]) result Lwt.t
val resign : state -> config -> member:string -> group:string -> (unit, [> `Conflict | `Internal_server_error ]) result Lwt.t
val replace_group_members : state -> config -> string -> string list -> (unit, [> `Conflict | `Internal_server_error ]) result Lwt.t
val delete_group : state -> config -> string -> (unit, [> `Internal_server_error | `Not_found | `Conflict ]) result Lwt.t
val initialize_fs : state -> Ptime.t -> config -> unit Lwt.t
val initialize_fs_for_apple_testsuite : state -> Ptime.t -> config -> unit Lwt.t
val generate_salt : unit -> Cstruct.t
val connect : state -> config -> string option -> state Lwt.t
end
module Make(R : Mirage_random.S)(Clock : Mirage_clock.PCLOCK)(Fs: Webdav_fs.S) : S with type state = Fs.t
| null | https://raw.githubusercontent.com/roburio/caldav/3914aef28175f22983772b67be3d366a9d2d9e4e/src/webdav_api.mli | ocaml | type tree = Webdav_xml.tree
type content_type = string
open Webdav_config
module type S =
sig
type state
val mkcol : state -> config -> path:string -> user:string -> Cohttp.Code.meth -> Ptime.t -> data:string ->
(unit, [ `Bad_request | `Conflict | `Forbidden of string ]) result Lwt.t
val propfind : state -> config -> path:string -> user:string -> depth:string option -> data:string ->
(string, [> `Bad_request | `Forbidden of string | `Property_not_found ]) result Lwt.t
val proppatch : state -> config -> path:string -> user:string -> data:string ->
(string, [> `Bad_request ]) result Lwt.t
val report : state -> config -> path:string -> user:string -> data:string ->
(string, [> `Bad_request ]) result Lwt.t
val write_component : state -> config -> path:string -> Ptime.t -> content_type:content_type -> data:string ->
(string, [> `Bad_request | `Conflict | `Forbidden | `Internal_server_error ]) result Lwt.t
val delete : state -> path:string -> Ptime.t -> bool Lwt.t
val read : state -> path:string -> is_mozilla:bool -> (string * content_type, [> `Not_found ]) result Lwt.t
val access_granted_for_acl : state -> config -> Cohttp.Code.meth -> path:string -> user:string -> bool Lwt.t
val last_modified : state -> path:string -> string option Lwt.t
val compute_etag : state -> path:string -> string option Lwt.t
val verify_auth_header : state -> config -> string -> (string, [> `Msg of string | `Unknown_user of string * string ]) result Lwt.t
val make_user : ?props:(Webdav_xml.fqname * Properties.property) list -> state -> Ptime.t -> config -> name:string -> password:string -> salt:Cstruct.t ->
(Uri.t, [> `Conflict | `Internal_server_error ]) result Lwt.t
val change_user_password : state -> config -> name:string -> password:string -> salt:Cstruct.t -> (unit, [> `Internal_server_error ]) result Lwt.t
val delete_user : state -> config -> string -> (unit, [> `Internal_server_error | `Not_found | `Conflict ]) result Lwt.t
val make_group : state -> Ptime.t -> config -> string -> string list -> (Uri.t, [> `Conflict | `Internal_server_error ]) result Lwt.t
val enroll : state -> config -> member:string -> group:string -> (unit, [> `Conflict | `Internal_server_error ]) result Lwt.t
val resign : state -> config -> member:string -> group:string -> (unit, [> `Conflict | `Internal_server_error ]) result Lwt.t
val replace_group_members : state -> config -> string -> string list -> (unit, [> `Conflict | `Internal_server_error ]) result Lwt.t
val delete_group : state -> config -> string -> (unit, [> `Internal_server_error | `Not_found | `Conflict ]) result Lwt.t
val initialize_fs : state -> Ptime.t -> config -> unit Lwt.t
val initialize_fs_for_apple_testsuite : state -> Ptime.t -> config -> unit Lwt.t
val generate_salt : unit -> Cstruct.t
val connect : state -> config -> string option -> state Lwt.t
end
module Make(R : Mirage_random.S)(Clock : Mirage_clock.PCLOCK)(Fs: Webdav_fs.S) : S with type state = Fs.t
| |
d7ca13d1db5155f3dab3a2e344c0f288a59e70962421a9b54a7d18450b245c71 | buildsome/buildsome | par_exec.hs | import Control.Concurrent.Async (asyncOn, wait)
threadHandler n = readFile $ "after_sleep." ++ show n
main = do
-- To get actual concurrency we need to use different POSIX threads,
because otherwise the user - threads share the same buildsome
-- client, which will re-serialize them
a <- asyncOn 0 $ threadHandler 1
b <- asyncOn 1 $ threadHandler 2
wait a
wait b
| null | https://raw.githubusercontent.com/buildsome/buildsome/479b92bb74a474a5f0c3292b79202cc850bd8653/test/overpar/par_exec.hs | haskell | To get actual concurrency we need to use different POSIX threads,
client, which will re-serialize them | import Control.Concurrent.Async (asyncOn, wait)
threadHandler n = readFile $ "after_sleep." ++ show n
main = do
because otherwise the user - threads share the same buildsome
a <- asyncOn 0 $ threadHandler 1
b <- asyncOn 1 $ threadHandler 2
wait a
wait b
|
9feed6c1bcbce6376fae98ca9bf9bdd41f27a37bfe0cb471d8c06f53e519aef1 | LightTable/Clojure | light_nrepl_test.clj | (ns leiningen.light-nrepl-test
(:require [leiningen.light-nrepl :as repl]
[clojure.test :refer [is deftest testing]]))
(deftest at-least-version-test
(testing "Smaller versions return false"
(is (false? (repl/at-least-version? "1.4.1" {:major 1 :minor 5 :patch 1})))
(is (false? (repl/at-least-version? "0.7.5" {:major 1 :minor 5 :patch 1}))))
(testing "Larger or equal to versions return true"
(is (repl/at-least-version? "1.6.1" {:major 1 :minor 6 :patch 1}))
(is (repl/at-least-version? "1.8.0" {:major 1 :minor 6 :patch 1}))
(is (repl/at-least-version? "2.1.0" {:major 1 :minor 6 :patch 1}))))
(deftest maintained-clojure-version-test
(is (repl/maintained-clojure-version? "1.8.0-alpha4"))
(is (repl/maintained-clojure-version? nil)
"nil is maintained since the user is given the clojure version of the middleware")
(is (false? (repl/maintained-clojure-version? "1.7.0-RC1"))
"1.7.0-* versions aren't maintained because they conflict with the new middleware"))
(deftest parse-version-test
(testing "Extra versioning after patch is ignored"
(is (= {:major 1 :minor 7 :patch 0} (repl/parse-version "1.7.0-RC1"))))
(testing "Fail fast if nil version"
(is (thrown? AssertionError (repl/parse-version nil))))
(testing "Fail fast if invalid version format"
(is (thrown? AssertionError (repl/parse-version "1.1")))))
| null | https://raw.githubusercontent.com/LightTable/Clojure/6f335ff3bec841b24a0b8ad7ca0dc126b3352a15/runner/test/leiningen/light_nrepl_test.clj | clojure | (ns leiningen.light-nrepl-test
(:require [leiningen.light-nrepl :as repl]
[clojure.test :refer [is deftest testing]]))
(deftest at-least-version-test
(testing "Smaller versions return false"
(is (false? (repl/at-least-version? "1.4.1" {:major 1 :minor 5 :patch 1})))
(is (false? (repl/at-least-version? "0.7.5" {:major 1 :minor 5 :patch 1}))))
(testing "Larger or equal to versions return true"
(is (repl/at-least-version? "1.6.1" {:major 1 :minor 6 :patch 1}))
(is (repl/at-least-version? "1.8.0" {:major 1 :minor 6 :patch 1}))
(is (repl/at-least-version? "2.1.0" {:major 1 :minor 6 :patch 1}))))
(deftest maintained-clojure-version-test
(is (repl/maintained-clojure-version? "1.8.0-alpha4"))
(is (repl/maintained-clojure-version? nil)
"nil is maintained since the user is given the clojure version of the middleware")
(is (false? (repl/maintained-clojure-version? "1.7.0-RC1"))
"1.7.0-* versions aren't maintained because they conflict with the new middleware"))
(deftest parse-version-test
(testing "Extra versioning after patch is ignored"
(is (= {:major 1 :minor 7 :patch 0} (repl/parse-version "1.7.0-RC1"))))
(testing "Fail fast if nil version"
(is (thrown? AssertionError (repl/parse-version nil))))
(testing "Fail fast if invalid version format"
(is (thrown? AssertionError (repl/parse-version "1.1")))))
| |
841b3111a34fe11e7dc7e2fd5edc98741610eec6efab1673894637e9afcc0159 | dalvescb/LearningHaskell_Exercises | Spec.hs | # LANGUAGE ExistentialQuantification #
|
Module : HaskellExercises07.Spec
Copyright : ( c ) 2020
License : GPL ( see the LICENSE file )
Maintainer : none
Stability : experimental
Portability : portable
Description :
Contains Quickcheck tests for Exercises07 and a main function that runs each tests and prints the results
Module : HaskellExercises07.Spec
Copyright : (c) Curtis D'Alves 2020
License : GPL (see the LICENSE file)
Maintainer : none
Stability : experimental
Portability : portable
Description:
Contains Quickcheck tests for Exercises07 and a main function that runs each tests and prints the results
-}
module Main where
import qualified Exercises07 as E7
import Test.QuickCheck (quickCheck
,quickCheckResult
,quickCheckWithResult
,stdArgs
,maxSuccess
,Result(Success)
,within
,Testable, Arbitrary (arbitrary), Positive (..))
import Test.Hspec
import Test.QuickCheck.Property (property)
import Test.QuickCheck.Gen (sized)
-------------------------------------------------------------------------------------------
-- * QuickCheck Tests
| Existential type wrapper for QuickCheck propositions , allows @propList@ to essentially
act as a heterogeneous list that can hold any quickcheck propositions of any type
data QuickProp = forall prop . Testable prop =>
QuickProp { quickPropName :: String
, quickPropMark :: Int
, quickPropFunc :: prop
}
-- | Arbitrary instance for Tree
instance Arbitrary a => Arbitrary (E7.Tree a) where
arbitrary =
let
genTree n
| n <= 0 = do v <- arbitrary
return $ E7.TNode v []
-- NOTE always generates a binary tree
| otherwise = do (Positive n0) <- arbitrary
t0 <- genTree (n `div` (n0+1)) -- generate an arbitrary sized left tree
(Positive n1) <- arbitrary
t1 <- genTree (n `div` (n1+1)) -- generate an arbitrary sized right tree
v <- arbitrary
return $ E7.TNode v [t0, t1]
in sized genTree
-- | Arbitrary instance for Tree
instance Arbitrary E7.FamilyTree where
arbitrary =
let
genTree n
| n <= 0 = do n <- arbitrary
return $ E7.Person n Nothing Nothing
-- NOTE always generates a binary tree
| otherwise = do (Positive n0) <- arbitrary
t0 <- genTree (n `div` (n0+1)) -- generate an arbitrary sized left tree
(Positive n1) <- arbitrary
t1 <- genTree (n `div` (n1+1)) -- generate an arbitrary sized right tree
n <- arbitrary
return $ E7.Person n (Just t0 ) (Just t1)
in sized genTree
-- | Boolean implication
(==>) :: Bool -> Bool -> Bool
x ==> y = (not x) || y
infixr 4 ==>
-- | QuickCheck proposition for testing Exercises07.iter
iterProp0 :: Int -> Bool
iterProp0 n
| n <= 0 = True
| otherwise = (E7.iter n (+1) 0) == n
iterProp1 :: Int -> Bool
iterProp1 n
| n <= 0 = True
| otherwise = (E7.iter n (*2) 1) == 2^n
| QuickCheck proposition for testing Exercises07.mapMaybe
mapMaybeProp :: Maybe Int -> Bool
mapMaybeProp maybe = (E7.mapMaybe (+1) maybe) == fmap (+1) maybe
-- | QuickCheck proposition for testing Exercises07.concatMapMaybe
concatMapMaybeProp0 :: [Int] -> Bool
concatMapMaybeProp0 xs = E7.concatMapMaybe Just xs == xs
concatMapMaybeProp1 :: [Int] -> Bool
concatMapMaybeProp1 xs = E7.concatMapMaybe (\_ -> Nothing) xs == []
-- | QuickCheck proposition for testing Exercises07.curry
curryProp0 :: Int -> Int -> Bool
curryProp0 x y = E7.curry snd x y == y
curryProp1 :: Int -> Int -> Bool
curryProp1 x y = E7.curry fst x y == x
| QuickCheck proposition for testing
foldtProp0 :: E7.Tree Int -> Bool
foldtProp0 tree =
let
sumT (E7.TNode x ts ) = sum (x : (map sumT ts))
in sumT tree == E7.foldt (+) 0 tree
foldtProp1 :: E7.Tree Int -> Bool
foldtProp1 tree =
let
prodT (E7.TNode x ts ) = product (x : (map prodT ts))
in prodT tree == E7.foldt (*) 1 tree
| QuickCheck proposition for testing
familyTree2TreeProp :: E7.FamilyTree -> Bool
familyTree2TreeProp famTree =
let
cmpTrees (E7.Person name (Just m) (Just f)) (E7.TNode x ts) = (name == x)
&& ( or (map (cmpTrees m) ts) )
&& ( or (map (cmpTrees f) ts) )
cmpTrees (E7.Person name Nothing (Just f)) (E7.TNode x [t]) = (name == x)
&& ( cmpTrees f t )
cmpTrees (E7.Person name (Just m) Nothing) (E7.TNode x [t]) = (name == x)
&& ( cmpTrees m t )
cmpTrees (E7.Person name Nothing Nothing) (E7.TNode x []) = (name == x)
cmpTrees _ _ = False
in cmpTrees famTree (E7.familyTree2Tree famTree)
| QuickCheck proposition for testing Exercises07.allFamily
allFamilyProp :: E7.FamilyTree -> Bool
allFamilyProp famTree =
let
famToList :: E7.FamilyTree -> [String]
famToList (E7.Person n m f) = n : ((concat $ E7.maybeToList $ fmap famToList m)
++ (concat $ E7.maybeToList $ fmap famToList f))
in and [ p `elem` famToList famTree | p <- E7.allFamily famTree ]
&& and [ p `elem` E7.allFamily famTree | p <- famToList famTree ]
-------------------------------------------------------------------------------------------
-- * Run Tests
main :: IO ()
main = hspec $ do
describe "iter" $ do
it "iter n (+1) 0 should be n" $ property $ iterProp0
it "iter n (*2) 1 should be n" $ property $ iterProp1
describe "mapMaybe" $ do
it "mapMaybe (+1) should correspond to fmap (+1)" $ property $ mapMaybeProp
describe "concatMapMaybe" $ do
it "concatMapMaybe Just xs should be xs" $ property $ concatMapMaybeProp0
it "concatMapMaybe (\\x -> Nothing) xs should be []" $ property $ concatMapMaybeProp1
describe "curry" $ do
it "curry snd x y should be y" $ property $ curryProp0
it "curry fst x y should be x" $ property $ curryProp1
describe "foldt" $ do
it "foldt (+) 0 tree should sum all elements in tree" $ property $ foldtProp0
it "foldt (*) 1 tree should multiply all elements in tree" $ property $ foldtProp1
describe "familyTree2Tree" $ do
it "every node in each tree should have the same parents" $ property $ familyTree2TreeProp
describe "allFamily" $ do
it "every name in the tree should appear in the list and vice versa" $ property $ allFamilyProp
| null | https://raw.githubusercontent.com/dalvescb/LearningHaskell_Exercises/7ee9f651c897b4c6a70d1fc180eb1a5060d0e6b0/HaskellExercises07/test/Spec.hs | haskell | -----------------------------------------------------------------------------------------
* QuickCheck Tests
| Arbitrary instance for Tree
NOTE always generates a binary tree
generate an arbitrary sized left tree
generate an arbitrary sized right tree
| Arbitrary instance for Tree
NOTE always generates a binary tree
generate an arbitrary sized left tree
generate an arbitrary sized right tree
| Boolean implication
| QuickCheck proposition for testing Exercises07.iter
| QuickCheck proposition for testing Exercises07.concatMapMaybe
| QuickCheck proposition for testing Exercises07.curry
-----------------------------------------------------------------------------------------
* Run Tests | # LANGUAGE ExistentialQuantification #
|
Module : HaskellExercises07.Spec
Copyright : ( c ) 2020
License : GPL ( see the LICENSE file )
Maintainer : none
Stability : experimental
Portability : portable
Description :
Contains Quickcheck tests for Exercises07 and a main function that runs each tests and prints the results
Module : HaskellExercises07.Spec
Copyright : (c) Curtis D'Alves 2020
License : GPL (see the LICENSE file)
Maintainer : none
Stability : experimental
Portability : portable
Description:
Contains Quickcheck tests for Exercises07 and a main function that runs each tests and prints the results
-}
module Main where
import qualified Exercises07 as E7
import Test.QuickCheck (quickCheck
,quickCheckResult
,quickCheckWithResult
,stdArgs
,maxSuccess
,Result(Success)
,within
,Testable, Arbitrary (arbitrary), Positive (..))
import Test.Hspec
import Test.QuickCheck.Property (property)
import Test.QuickCheck.Gen (sized)
| Existential type wrapper for QuickCheck propositions , allows @propList@ to essentially
act as a heterogeneous list that can hold any quickcheck propositions of any type
data QuickProp = forall prop . Testable prop =>
QuickProp { quickPropName :: String
, quickPropMark :: Int
, quickPropFunc :: prop
}
instance Arbitrary a => Arbitrary (E7.Tree a) where
arbitrary =
let
genTree n
| n <= 0 = do v <- arbitrary
return $ E7.TNode v []
| otherwise = do (Positive n0) <- arbitrary
(Positive n1) <- arbitrary
v <- arbitrary
return $ E7.TNode v [t0, t1]
in sized genTree
instance Arbitrary E7.FamilyTree where
arbitrary =
let
genTree n
| n <= 0 = do n <- arbitrary
return $ E7.Person n Nothing Nothing
| otherwise = do (Positive n0) <- arbitrary
(Positive n1) <- arbitrary
n <- arbitrary
return $ E7.Person n (Just t0 ) (Just t1)
in sized genTree
(==>) :: Bool -> Bool -> Bool
x ==> y = (not x) || y
infixr 4 ==>
iterProp0 :: Int -> Bool
iterProp0 n
| n <= 0 = True
| otherwise = (E7.iter n (+1) 0) == n
iterProp1 :: Int -> Bool
iterProp1 n
| n <= 0 = True
| otherwise = (E7.iter n (*2) 1) == 2^n
| QuickCheck proposition for testing Exercises07.mapMaybe
mapMaybeProp :: Maybe Int -> Bool
mapMaybeProp maybe = (E7.mapMaybe (+1) maybe) == fmap (+1) maybe
concatMapMaybeProp0 :: [Int] -> Bool
concatMapMaybeProp0 xs = E7.concatMapMaybe Just xs == xs
concatMapMaybeProp1 :: [Int] -> Bool
concatMapMaybeProp1 xs = E7.concatMapMaybe (\_ -> Nothing) xs == []
curryProp0 :: Int -> Int -> Bool
curryProp0 x y = E7.curry snd x y == y
curryProp1 :: Int -> Int -> Bool
curryProp1 x y = E7.curry fst x y == x
| QuickCheck proposition for testing
foldtProp0 :: E7.Tree Int -> Bool
foldtProp0 tree =
let
sumT (E7.TNode x ts ) = sum (x : (map sumT ts))
in sumT tree == E7.foldt (+) 0 tree
foldtProp1 :: E7.Tree Int -> Bool
foldtProp1 tree =
let
prodT (E7.TNode x ts ) = product (x : (map prodT ts))
in prodT tree == E7.foldt (*) 1 tree
| QuickCheck proposition for testing
familyTree2TreeProp :: E7.FamilyTree -> Bool
familyTree2TreeProp famTree =
let
cmpTrees (E7.Person name (Just m) (Just f)) (E7.TNode x ts) = (name == x)
&& ( or (map (cmpTrees m) ts) )
&& ( or (map (cmpTrees f) ts) )
cmpTrees (E7.Person name Nothing (Just f)) (E7.TNode x [t]) = (name == x)
&& ( cmpTrees f t )
cmpTrees (E7.Person name (Just m) Nothing) (E7.TNode x [t]) = (name == x)
&& ( cmpTrees m t )
cmpTrees (E7.Person name Nothing Nothing) (E7.TNode x []) = (name == x)
cmpTrees _ _ = False
in cmpTrees famTree (E7.familyTree2Tree famTree)
| QuickCheck proposition for testing Exercises07.allFamily
allFamilyProp :: E7.FamilyTree -> Bool
allFamilyProp famTree =
let
famToList :: E7.FamilyTree -> [String]
famToList (E7.Person n m f) = n : ((concat $ E7.maybeToList $ fmap famToList m)
++ (concat $ E7.maybeToList $ fmap famToList f))
in and [ p `elem` famToList famTree | p <- E7.allFamily famTree ]
&& and [ p `elem` E7.allFamily famTree | p <- famToList famTree ]
main :: IO ()
main = hspec $ do
describe "iter" $ do
it "iter n (+1) 0 should be n" $ property $ iterProp0
it "iter n (*2) 1 should be n" $ property $ iterProp1
describe "mapMaybe" $ do
it "mapMaybe (+1) should correspond to fmap (+1)" $ property $ mapMaybeProp
describe "concatMapMaybe" $ do
it "concatMapMaybe Just xs should be xs" $ property $ concatMapMaybeProp0
it "concatMapMaybe (\\x -> Nothing) xs should be []" $ property $ concatMapMaybeProp1
describe "curry" $ do
it "curry snd x y should be y" $ property $ curryProp0
it "curry fst x y should be x" $ property $ curryProp1
describe "foldt" $ do
it "foldt (+) 0 tree should sum all elements in tree" $ property $ foldtProp0
it "foldt (*) 1 tree should multiply all elements in tree" $ property $ foldtProp1
describe "familyTree2Tree" $ do
it "every node in each tree should have the same parents" $ property $ familyTree2TreeProp
describe "allFamily" $ do
it "every name in the tree should appear in the list and vice versa" $ property $ allFamilyProp
|
439c838adb00114394f46ac440733301fc7957ee131283cfe62c1088c601d59e | LonoCloud/step.async | step_schedule.clj | (ns lonocloud.step.async.step-schedule
"Algorithms for scheduling what to run next in a step machine"
(:require [lonocloud.step.async.pschema :as s]
[lonocloud.step.async.step-model :refer [ThreadId ChannelId PendingPutChoices]])
(:import [java.util Random]))
(def ^:private max-seed 100000000)
(s/defn stm-rand [initial-seed :- s/Int]
(let [seed (ref initial-seed)]
(fn [n]
(let [r (Random. @seed)
result (.nextInt r n)
new-seed (.nextInt r max-seed)]
(ref-set seed new-seed)
result))))
(s/defn- random-pick [choices
rand-source :- s/Fn]
(let [n (count choices)]
(when (pos? n)
((-> choices
sort
vec)
(rand-source n)))))
(s/defn random-scheduler
"Randomly select the next step to take in a step machine (if the rand-source is STM compatible,
then the 'random' choices are actually repeatable with the same seed)."
[rand-source :- s/Fn
pending-threads :- #{ThreadId}
parked-threads :- #{ThreadId}
available-pending-puts :- PendingPutChoices
available-takes :- #{ChannelId}
channel-waiters :- {ChannelId #{ThreadId}}
available-puts :- {ThreadId ChannelId}]
(let [verb-choices (->> [(when (not (empty? pending-threads))
:run-pending)
(when (not (empty? parked-threads))
:run-parked)
(when (not (empty? available-pending-puts))
:do-pending-put)
(when (not (empty? available-takes))
:take)
(when (not (empty? available-puts))
:put)]
(remove nil?))]
(condp = (random-pick verb-choices rand-source)
:run-pending [:run-pending (-> pending-threads
(random-pick rand-source))]
:run-parked [:run-parked (-> parked-threads
(random-pick rand-source))]
:do-pending-put [:do-pending-put (-> (->> available-pending-puts
(map first))
(random-pick rand-source))]
:take (let [channel-id (-> available-takes
(random-pick rand-source))
thread-id (-> (channel-waiters channel-id)
(random-pick rand-source))]
[:take thread-id channel-id])
:put [:put (-> available-puts
keys
(random-pick rand-source))])))
(s/defn deterministic-scheduler
"Deterministically select the next step to take in a step machine"
[pending-threads :- #{ThreadId}
parked-threads :- #{ThreadId}
available-pending-puts :- PendingPutChoices
available-takes :- #{ChannelId}
channel-waiters :- {ChannelId #{ThreadId}}
available-puts :- {ThreadId ChannelId}]
(if (not (empty? pending-threads))
(let [pending-id-to-run (-> pending-threads
sort
first)]
[:run-pending pending-id-to-run])
(if (not (empty? parked-threads))
(let [parked-id-to-run (-> parked-threads
sort
first)]
[:run-parked parked-id-to-run])
(if (not (empty? available-pending-puts))
(let [pending-put-to-run (->> available-pending-puts
(map first)
sort
first)]
[:do-pending-put pending-put-to-run])
(if (not (empty? available-takes))
(let [take-channel-id (->> available-takes
sort
first)
take-thread-id (->> (channel-waiters take-channel-id)
sort
first)]
[:take take-thread-id take-channel-id])
(if (not (empty? available-puts))
[:put (->> available-puts
keys
sort
first)]))))))
| null | https://raw.githubusercontent.com/LonoCloud/step.async/31dc58f72cb9719a11a97dc36992c67cf3efb766/src/lonocloud/step/async/step_schedule.clj | clojure | (ns lonocloud.step.async.step-schedule
"Algorithms for scheduling what to run next in a step machine"
(:require [lonocloud.step.async.pschema :as s]
[lonocloud.step.async.step-model :refer [ThreadId ChannelId PendingPutChoices]])
(:import [java.util Random]))
(def ^:private max-seed 100000000)
(s/defn stm-rand [initial-seed :- s/Int]
(let [seed (ref initial-seed)]
(fn [n]
(let [r (Random. @seed)
result (.nextInt r n)
new-seed (.nextInt r max-seed)]
(ref-set seed new-seed)
result))))
(s/defn- random-pick [choices
rand-source :- s/Fn]
(let [n (count choices)]
(when (pos? n)
((-> choices
sort
vec)
(rand-source n)))))
(s/defn random-scheduler
"Randomly select the next step to take in a step machine (if the rand-source is STM compatible,
then the 'random' choices are actually repeatable with the same seed)."
[rand-source :- s/Fn
pending-threads :- #{ThreadId}
parked-threads :- #{ThreadId}
available-pending-puts :- PendingPutChoices
available-takes :- #{ChannelId}
channel-waiters :- {ChannelId #{ThreadId}}
available-puts :- {ThreadId ChannelId}]
(let [verb-choices (->> [(when (not (empty? pending-threads))
:run-pending)
(when (not (empty? parked-threads))
:run-parked)
(when (not (empty? available-pending-puts))
:do-pending-put)
(when (not (empty? available-takes))
:take)
(when (not (empty? available-puts))
:put)]
(remove nil?))]
(condp = (random-pick verb-choices rand-source)
:run-pending [:run-pending (-> pending-threads
(random-pick rand-source))]
:run-parked [:run-parked (-> parked-threads
(random-pick rand-source))]
:do-pending-put [:do-pending-put (-> (->> available-pending-puts
(map first))
(random-pick rand-source))]
:take (let [channel-id (-> available-takes
(random-pick rand-source))
thread-id (-> (channel-waiters channel-id)
(random-pick rand-source))]
[:take thread-id channel-id])
:put [:put (-> available-puts
keys
(random-pick rand-source))])))
(s/defn deterministic-scheduler
"Deterministically select the next step to take in a step machine"
[pending-threads :- #{ThreadId}
parked-threads :- #{ThreadId}
available-pending-puts :- PendingPutChoices
available-takes :- #{ChannelId}
channel-waiters :- {ChannelId #{ThreadId}}
available-puts :- {ThreadId ChannelId}]
(if (not (empty? pending-threads))
(let [pending-id-to-run (-> pending-threads
sort
first)]
[:run-pending pending-id-to-run])
(if (not (empty? parked-threads))
(let [parked-id-to-run (-> parked-threads
sort
first)]
[:run-parked parked-id-to-run])
(if (not (empty? available-pending-puts))
(let [pending-put-to-run (->> available-pending-puts
(map first)
sort
first)]
[:do-pending-put pending-put-to-run])
(if (not (empty? available-takes))
(let [take-channel-id (->> available-takes
sort
first)
take-thread-id (->> (channel-waiters take-channel-id)
sort
first)]
[:take take-thread-id take-channel-id])
(if (not (empty? available-puts))
[:put (->> available-puts
keys
sort
first)]))))))
| |
e7e32aca5a6d2c87d4022562101ae68123d5332f93c22fcd10b37a9e9b5e2800 | sdiehl/elliptic-curve | SECP256K1.hs | module Data.Curve.Weierstrass.SECP256K1
( module Data.Curve.Weierstrass
, Point(..)
-- * SECP256K1 curve
, module Data.Curve.Weierstrass.SECP256K1
) where
import Protolude
import Data.Field.Galois
import GHC.Natural (Natural)
import Data.Curve.Weierstrass
-------------------------------------------------------------------------------
-- Types
-------------------------------------------------------------------------------
-- | SECP256K1 curve.
data SECP256K1
-- | Field of points of SECP256K1 curve.
type Fq = Prime Q
type Q = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f
-- | Field of coefficients of SECP256K1 curve.
type Fr = Prime R
type R = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141
SECP256K1 curve is a Weierstrass curve .
instance Curve 'Weierstrass c SECP256K1 Fq Fr => WCurve c SECP256K1 Fq Fr where
a_ = const _a
{-# INLINABLE a_ #-}
b_ = const _b
# INLINABLE b _ #
h_ = const _h
{-# INLINABLE h_ #-}
q_ = const _q
# INLINABLE q _ #
r_ = const _r
# INLINABLE r _ #
-- | Affine SECP256K1 curve point.
type PA = WAPoint SECP256K1 Fq Fr
Affine SECP256K1 curve is a Weierstrass affine curve .
instance WACurve SECP256K1 Fq Fr where
gA_ = gA
# INLINABLE gA _ #
-- | Jacobian SECP256K1 point.
type PJ = WJPoint SECP256K1 Fq Fr
Jacobian SECP256K1 curve is a Weierstrass Jacobian curve .
instance WJCurve SECP256K1 Fq Fr where
gJ_ = gJ
# INLINABLE gJ _ #
-- | Projective SECP256K1 point.
type PP = WPPoint SECP256K1 Fq Fr
Projective SECP256K1 curve is a Weierstrass projective curve .
instance WPCurve SECP256K1 Fq Fr where
gP_ = gP
# INLINABLE gP _ #
-------------------------------------------------------------------------------
-- Parameters
-------------------------------------------------------------------------------
-- | Coefficient @A@ of SECP256K1 curve.
_a :: Fq
_a = 0x0
# INLINABLE _ a #
-- | Coefficient @B@ of SECP256K1 curve.
_b :: Fq
_b = 0x7
{-# INLINABLE _b #-}
-- | Cofactor of SECP256K1 curve.
_h :: Natural
_h = 0x1
# INLINABLE _ h #
-- | Characteristic of SECP256K1 curve.
_q :: Natural
_q = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f
{-# INLINABLE _q #-}
-- | Order of SECP256K1 curve.
_r :: Natural
_r = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141
{-# INLINABLE _r #-}
-- | Coordinate @X@ of SECP256K1 curve.
_x :: Fq
_x = 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798
{-# INLINABLE _x #-}
-- | Coordinate @Y@ of SECP256K1 curve.
_y :: Fq
_y = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8
{-# INLINABLE _y #-}
-- | Generator of affine SECP256K1 curve.
gA :: PA
gA = A _x _y
# INLINABLE gA #
| Generator of Jacobian SECP256K1 curve .
gJ :: PJ
gJ = J _x _y 1
# INLINABLE gJ #
-- | Generator of projective SECP256K1 curve.
gP :: PP
gP = P _x _y 1
# INLINABLE gP #
| null | https://raw.githubusercontent.com/sdiehl/elliptic-curve/445e196a550e36e0f25bd4d9d6a38676b4cf2be8/src/Data/Curve/Weierstrass/SECP256K1.hs | haskell | * SECP256K1 curve
-----------------------------------------------------------------------------
Types
-----------------------------------------------------------------------------
| SECP256K1 curve.
| Field of points of SECP256K1 curve.
| Field of coefficients of SECP256K1 curve.
# INLINABLE a_ #
# INLINABLE h_ #
| Affine SECP256K1 curve point.
| Jacobian SECP256K1 point.
| Projective SECP256K1 point.
-----------------------------------------------------------------------------
Parameters
-----------------------------------------------------------------------------
| Coefficient @A@ of SECP256K1 curve.
| Coefficient @B@ of SECP256K1 curve.
# INLINABLE _b #
| Cofactor of SECP256K1 curve.
| Characteristic of SECP256K1 curve.
# INLINABLE _q #
| Order of SECP256K1 curve.
# INLINABLE _r #
| Coordinate @X@ of SECP256K1 curve.
# INLINABLE _x #
| Coordinate @Y@ of SECP256K1 curve.
# INLINABLE _y #
| Generator of affine SECP256K1 curve.
| Generator of projective SECP256K1 curve. | module Data.Curve.Weierstrass.SECP256K1
( module Data.Curve.Weierstrass
, Point(..)
, module Data.Curve.Weierstrass.SECP256K1
) where
import Protolude
import Data.Field.Galois
import GHC.Natural (Natural)
import Data.Curve.Weierstrass
data SECP256K1
type Fq = Prime Q
type Q = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f
type Fr = Prime R
type R = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141
SECP256K1 curve is a Weierstrass curve .
instance Curve 'Weierstrass c SECP256K1 Fq Fr => WCurve c SECP256K1 Fq Fr where
a_ = const _a
b_ = const _b
# INLINABLE b _ #
h_ = const _h
q_ = const _q
# INLINABLE q _ #
r_ = const _r
# INLINABLE r _ #
type PA = WAPoint SECP256K1 Fq Fr
Affine SECP256K1 curve is a Weierstrass affine curve .
instance WACurve SECP256K1 Fq Fr where
gA_ = gA
# INLINABLE gA _ #
type PJ = WJPoint SECP256K1 Fq Fr
Jacobian SECP256K1 curve is a Weierstrass Jacobian curve .
instance WJCurve SECP256K1 Fq Fr where
gJ_ = gJ
# INLINABLE gJ _ #
type PP = WPPoint SECP256K1 Fq Fr
Projective SECP256K1 curve is a Weierstrass projective curve .
instance WPCurve SECP256K1 Fq Fr where
gP_ = gP
# INLINABLE gP _ #
_a :: Fq
_a = 0x0
# INLINABLE _ a #
_b :: Fq
_b = 0x7
_h :: Natural
_h = 0x1
# INLINABLE _ h #
_q :: Natural
_q = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f
_r :: Natural
_r = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141
_x :: Fq
_x = 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798
_y :: Fq
_y = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8
gA :: PA
gA = A _x _y
# INLINABLE gA #
| Generator of Jacobian SECP256K1 curve .
gJ :: PJ
gJ = J _x _y 1
# INLINABLE gJ #
gP :: PP
gP = P _x _y 1
# INLINABLE gP #
|
da1d05a490bc842ee0be958a6b8bf288c31c7e10c5ff0ea824124da1e19b9e63 | agda/agda | Warnings.hs |
module Agda.Interaction.Options.Warnings
(
WarningMode (..)
, warningSet
, warn2Error
, defaultWarningSet
, allWarnings
, usualWarnings
, noWarnings
, unsolvedWarnings
, incompleteMatchWarnings
, errorWarnings
, defaultWarningMode
, WarningModeError(..)
, prettyWarningModeError
, warningModeUpdate
, warningSets
, WarningName (..)
, warningName2String
, string2WarningName
, usageWarning
)
where
import Control.Arrow ( (&&&) )
import Control.DeepSeq
import Control.Monad ( guard, when )
import Text.Read ( readMaybe )
import Data.Set (Set)
import qualified Data.Set as Set
import qualified Data.HashMap.Strict as HMap
import Data.List ( stripPrefix, intercalate )
import GHC.Generics (Generic)
import Agda.Utils.Either ( maybeToEither )
import Agda.Utils.Lens
import Agda.Utils.List
import Agda.Utils.Maybe
import Agda.Utils.Impossible
import Agda.Utils.Functor
| A @WarningMode@ has two components : a set of warnings to be displayed
-- and a flag stating whether warnings should be turned into fatal errors.
data WarningMode = WarningMode
{ _warningSet :: Set WarningName
, _warn2Error :: Bool
} deriving (Eq, Show, Generic)
instance NFData WarningMode
warningSet :: Lens' (Set WarningName) WarningMode
warningSet f o = (\ ws -> o { _warningSet = ws }) <$> f (_warningSet o)
warn2Error :: Lens' Bool WarningMode
warn2Error f o = (\ ws -> o { _warn2Error = ws }) <$> f (_warn2Error o)
-- | The @defaultWarningMode@ is a curated set of warnings covering non-fatal
-- errors and disabling style-related ones
defaultWarningSet :: String
defaultWarningSet = "warn"
defaultWarningMode :: WarningMode
defaultWarningMode = WarningMode ws False where
ws = fst $ fromMaybe __IMPOSSIBLE__ $ lookup defaultWarningSet warningSets
-- | Some warnings are errors and cannot be turned off.
data WarningModeError = Unknown String | NoNoError String
prettyWarningModeError :: WarningModeError -> String
prettyWarningModeError = \case
Unknown str -> concat [ "Unknown warning flag: ", str, "." ]
NoNoError str -> concat [ "You may only turn off benign warnings. The warning "
, str
," is a non-fatal error and thus cannot be ignored." ]
| From user - given directives we compute updates
type WarningModeUpdate = WarningMode -> WarningMode
-- | @warningModeUpdate str@ computes the action of @str@ over the current
-- @WarningMode@: it may reset the set of warnings, add or remove a specific
-- flag or demand that any warning be turned into an error
warningModeUpdate :: String -> Either WarningModeError WarningModeUpdate
warningModeUpdate str = case str of
"error" -> pure $ set warn2Error True
"noerror" -> pure $ set warn2Error False
_ | Just ws <- fst <$> lookup str warningSets
-> pure $ set warningSet ws
_ -> case stripPrefix "no" str of
Nothing -> do
wname :: WarningName <- maybeToEither (Unknown str) $ string2WarningName str
pure (over warningSet $ Set.insert wname)
Just str' -> do
wname :: WarningName <- maybeToEither (Unknown str') $ string2WarningName str'
when (wname `elem` errorWarnings) (Left (NoNoError str'))
pure (over warningSet $ Set.delete wname)
-- | Common sets of warnings
warningSets :: [(String, (Set WarningName, String))]
warningSets = [ ("all" , (allWarnings, "All of the existing warnings"))
, ("warn" , (usualWarnings, "Default warning level"))
, ("ignore", (errorWarnings, "Ignore all the benign warnings"))
]
noWarnings :: Set WarningName
noWarnings = Set.empty
unsolvedWarnings :: Set WarningName
unsolvedWarnings = Set.fromList
[ UnsolvedMetaVariables_
, UnsolvedInteractionMetas_
, UnsolvedConstraints_
]
incompleteMatchWarnings :: Set WarningName
incompleteMatchWarnings = Set.fromList [ CoverageIssue_ ]
errorWarnings :: Set WarningName
errorWarnings = Set.fromList
[ CoverageIssue_
, GenericNonFatalError_
, MissingDefinitions_
, MissingDeclarations_
, NotAllowedInMutual_
, NotStrictlyPositive_
, OverlappingTokensWarning_
, PragmaCompiled_
, SafeFlagPostulate_
, SafeFlagPragma_
, SafeFlagNonTerminating_
, SafeFlagTerminating_
, SafeFlagWithoutKFlagPrimEraseEquality_
, SafeFlagNoPositivityCheck_
, SafeFlagPolarity_
, SafeFlagNoUniverseCheck_
, SafeFlagEta_
, SafeFlagInjective_
, SafeFlagNoCoverageCheck_
, TerminationIssue_
, UnsolvedMetaVariables_
, UnsolvedInteractionMetas_
, UnsolvedConstraints_
, InfectiveImport_
, CoInfectiveImport_
, RewriteNonConfluent_
, RewriteMaybeNonConfluent_
, RewriteAmbiguousRules_
, RewriteMissingRule_
]
allWarnings :: Set WarningName
allWarnings = Set.fromList [minBound..maxBound]
usualWarnings :: Set WarningName
usualWarnings = allWarnings Set.\\ Set.fromList
[ UnknownFixityInMixfixDecl_
, CoverageNoExactSplit_
, ShadowingInTelescope_
]
| The @WarningName@ data enumeration is meant to have a one - to - one correspondance
-- to existing warnings in the codebase.
data WarningName
-- Option Warnings
= OptionRenamed_
Parser Warnings
| OverlappingTokensWarning_
| UnsupportedAttribute_
| MultipleAttributes_
-- Library Warnings
| LibUnknownField_
-- Nicifer Warnings
| EmptyAbstract_
| EmptyConstructor_
| EmptyField_
| EmptyGeneralize_
| EmptyInstance_
| EmptyMacro_
| EmptyMutual_
| EmptyPostulate_
| EmptyPrimitive_
| EmptyPrivate_
| EmptyRewritePragma_
| EmptyWhere_
| HiddenGeneralize_
| InvalidCatchallPragma_
| InvalidConstructor_
| InvalidConstructorBlock_
| InvalidCoverageCheckPragma_
| InvalidNoPositivityCheckPragma_
| InvalidNoUniverseCheckPragma_
| InvalidRecordDirective_
| InvalidTerminationCheckPragma_
| MissingDeclarations_
| MissingDefinitions_
| NotAllowedInMutual_
| OpenPublicAbstract_
| OpenPublicPrivate_
| PolarityPragmasButNotPostulates_
| PragmaCompiled_
| PragmaNoTerminationCheck_
| ShadowingInTelescope_
| UnknownFixityInMixfixDecl_
| UnknownNamesInFixityDecl_
| UnknownNamesInPolarityPragmas_
| UselessAbstract_
| UselessInstance_
| UselessPrivate_
-- Scope and Type Checking Warnings
| AbsurdPatternRequiresNoRHS_
| AsPatternShadowsConstructorOrPatternSynonym_
| CantGeneralizeOverSorts_
issue # 4154
| CoverageIssue_
| CoverageNoExactSplit_
| DeprecationWarning_
| DuplicateUsing_
| FixityInRenamingModule_
| GenericNonFatalError_
| GenericUseless_
| GenericWarning_
| IllformedAsClause_
| InstanceArgWithExplicitArg_
| InstanceWithExplicitArg_
| InstanceNoOutputTypeName_
| InversionDepthReached_
| ModuleDoesntExport_
| NoGuardednessFlag_
| NotInScope_
| NotStrictlyPositive_
| UnsupportedIndexedMatch_
| OldBuiltin_
| PlentyInHardCompileTimeMode_
| PragmaCompileErased_
| RewriteMaybeNonConfluent_
| RewriteNonConfluent_
| RewriteAmbiguousRules_
| RewriteMissingRule_
| SafeFlagEta_
| SafeFlagInjective_
| SafeFlagNoCoverageCheck_
| SafeFlagNonTerminating_
| SafeFlagNoPositivityCheck_
| SafeFlagNoUniverseCheck_
| SafeFlagPolarity_
| SafeFlagPostulate_
| SafeFlagPragma_
| SafeFlagTerminating_
| SafeFlagWithoutKFlagPrimEraseEquality_
| TerminationIssue_
| UnreachableClauses_
| UnsolvedConstraints_
| UnsolvedInteractionMetas_
| UnsolvedMetaVariables_
| UselessHiding_
| UselessInline_
| UselessPatternDeclarationForRecord_
| UselessPublic_
| UserWarning_
| WithoutKFlagPrimEraseEquality_
| WrongInstanceDeclaration_
-- Checking consistency of options
| CoInfectiveImport_
| InfectiveImport_
-- Record field warnings
| DuplicateFieldsWarning_
| TooManyFieldsWarning_
deriving (Eq, Ord, Show, Read, Enum, Bounded, Generic)
instance NFData WarningName
-- | The flag corresponding to a warning is precisely the name of the constructor
-- minus the trailing underscore.
string2WarningName :: String -> Maybe WarningName
string2WarningName = (`HMap.lookup` warnings) where
warnings = HMap.fromList $ map (\x -> (warningName2String x, x)) [minBound..maxBound]
warningName2String :: WarningName -> String
warningName2String = initWithDefault __IMPOSSIBLE__ . show
-- | @warningUsage@ generated using @warningNameDescription@
usageWarning :: String
usageWarning = intercalate "\n"
[ "The -W or --warning option can be used to disable or enable\
\ different warnings. The flag -W error (or --warning=error)\
\ can be used to turn all warnings into errors, while -W noerror\
\ turns this off again."
, ""
, "A group of warnings can be enabled by -W group, where group is\
\ one of the following:"
, ""
, untable (fmap (fst &&& snd . snd) warningSets)
, "Individual benign warnings can be turned on and off by -W Name and\
\ -W noName, respectively, where Name comes from the following\
\ list (warnings marked with 'd' are turned on by default, and 'b'\
\ stands for \"benign warning\"):"
, ""
, untable $ forMaybe [minBound..maxBound] $ \ w ->
let wnd = warningNameDescription w in
( warningName2String w
, (if w `Set.member` usualWarnings then "d" else " ") ++
(if not (w `Set.member` errorWarnings) then "b" else " ") ++
" " ++
wnd
) <$ guard (not $ null wnd)
]
where
untable :: [(String, String)] -> String
untable rows =
let len = maximum (map (length . fst) rows) in
unlines $ for rows $ \ (hdr, cnt) ->
concat [ hdr, replicate (1 + len - length hdr) ' ', cnt ]
-- | @WarningName@ descriptions used for generating usage information
-- Leave String empty to skip that name.
warningNameDescription :: WarningName -> String
warningNameDescription = \case
-- Option Warnings
OptionRenamed_ -> "Renamed options."
Parser Warnings
OverlappingTokensWarning_ -> "Multi-line comments spanning one or more literate text blocks."
UnsupportedAttribute_ -> "Unsupported attributes."
MultipleAttributes_ -> "Multiple attributes."
-- Library Warnings
LibUnknownField_ -> "Unknown field in library file."
-- Nicifer Warnings
EmptyAbstract_ -> "Empty `abstract' blocks."
EmptyConstructor_ -> "Empty `constructor' blocks."
EmptyField_ -> "Empty `field` blocks."
EmptyGeneralize_ -> "Empty `variable' blocks."
EmptyInstance_ -> "Empty `instance' blocks."
EmptyMacro_ -> "Empty `macro' blocks."
EmptyMutual_ -> "Empty `mutual' blocks."
EmptyPostulate_ -> "Empty `postulate' blocks."
EmptyPrimitive_ -> "Empty `primitive' blocks."
EmptyPrivate_ -> "Empty `private' blocks."
EmptyRewritePragma_ -> "Empty `REWRITE' pragmas."
EmptyWhere_ -> "Empty `where' blocks."
HiddenGeneralize_ -> "Hidden identifiers in variable blocks."
InvalidCatchallPragma_ -> "`CATCHALL' pragmas before a non-function clause."
InvalidConstructor_ -> "`constructor' blocks may only contain type signatures for constructors."
InvalidConstructorBlock_ -> "No `constructor' blocks outside of `interleaved mutual' blocks."
InvalidCoverageCheckPragma_ -> "Coverage checking pragmas before non-function or `mutual' blocks."
InvalidNoPositivityCheckPragma_ -> "No positivity checking pragmas before non-`data', `record' or `mutual' blocks."
InvalidNoUniverseCheckPragma_ -> "No universe checking pragmas before non-`data' or `record' declaration."
InvalidRecordDirective_ -> "No record directive outside of record definition / below field declarations."
InvalidTerminationCheckPragma_ -> "Termination checking pragmas before non-function or `mutual' blocks."
MissingDeclarations_ -> "Definitions not associated to a declaration."
MissingDefinitions_ -> "Declarations not associated to a definition."
NotAllowedInMutual_ -> "Declarations not allowed in a mutual block."
OpenPublicAbstract_ -> "'open public' directive in an 'abstract' block."
OpenPublicPrivate_ -> "'open public' directive in a 'private' block."
PolarityPragmasButNotPostulates_ -> "Polarity pragmas for non-postulates."
PragmaCompiled_ -> "'COMPILE' pragmas not allowed in safe mode."
PragmaNoTerminationCheck_ -> "`NO_TERMINATION_CHECK' pragmas are deprecated"
ShadowingInTelescope_ -> "Repeated variable name in telescope."
UnknownFixityInMixfixDecl_ -> "Mixfix names without an associated fixity declaration."
UnknownNamesInFixityDecl_ -> "Names not declared in the same scope as their syntax or fixity declaration."
UnknownNamesInPolarityPragmas_ -> "Names not declared in the same scope as their polarity pragmas."
UselessAbstract_ -> "`abstract' blocks where they have no effect."
UselessHiding_ -> "Names in `hiding' directive that are anyway not imported."
UselessInline_ -> "`INLINE' pragmas where they have no effect."
UselessInstance_ -> "`instance' blocks where they have no effect."
UselessPrivate_ -> "`private' blocks where they have no effect."
UselessPublic_ -> "`public' blocks where they have no effect."
UselessPatternDeclarationForRecord_ -> "`pattern' attributes where they have no effect."
-- Scope and Type Checking Warnings
AbsurdPatternRequiresNoRHS_ -> "A clause with an absurd pattern does not need a Right Hand Side."
AsPatternShadowsConstructorOrPatternSynonym_ -> "@-patterns that shadow constructors or pattern synonyms."
CantGeneralizeOverSorts_ -> "Attempt to generalize over sort metas in 'variable' declaration."
issue # 4154
CoverageIssue_ -> "Failed coverage checks."
CoverageNoExactSplit_ -> "Failed exact split checks."
DeprecationWarning_ -> "Feature deprecation."
GenericNonFatalError_ -> ""
GenericUseless_ -> "Useless code."
GenericWarning_ -> ""
IllformedAsClause_ -> "Illformed `as'-clauses in `import' statements."
InstanceNoOutputTypeName_ -> "instance arguments whose type does not end in a named or variable type are never considered by instance search."
InstanceArgWithExplicitArg_ -> "instance arguments with explicit arguments are never considered by instance search."
InstanceWithExplicitArg_ -> "`instance` declarations with explicit arguments are never considered by instance search."
InversionDepthReached_ -> "Inversions of pattern-matching failed due to exhausted inversion depth."
NoGuardednessFlag_ -> "Coinductive record but no --guardedness flag."
ModuleDoesntExport_ -> "Imported name is not actually exported."
DuplicateUsing_ -> "Repeated names in using directive."
FixityInRenamingModule_ -> "Found fixity annotation in renaming directive for module."
NotInScope_ -> "Out of scope name."
NotStrictlyPositive_ -> "Failed strict positivity checks."
UnsupportedIndexedMatch_ -> "Failed to compute full equivalence when splitting on indexed family."
OldBuiltin_ -> "Deprecated `BUILTIN' pragmas."
PlentyInHardCompileTimeMode_ -> "Use of @ω or @plenty in hard compile-time mode."
PragmaCompileErased_ -> "`COMPILE' pragma targeting an erased symbol."
RewriteMaybeNonConfluent_ -> "Failed local confluence check while computing overlap."
RewriteNonConfluent_ -> "Failed local confluence check while joining critical pairs."
RewriteAmbiguousRules_ -> "Failed global confluence check because of overlapping rules."
RewriteMissingRule_ -> "Failed global confluence check because of missing rule."
SafeFlagEta_ -> "`ETA' pragmas with the safe flag."
SafeFlagInjective_ -> "`INJECTIVE' pragmas with the safe flag."
SafeFlagNoCoverageCheck_ -> "`NON_COVERING` pragmas with the safe flag."
SafeFlagNonTerminating_ -> "`NON_TERMINATING' pragmas with the safe flag."
SafeFlagNoPositivityCheck_ -> "`NO_POSITIVITY_CHECK' pragmas with the safe flag."
SafeFlagNoUniverseCheck_ -> "`NO_UNIVERSE_CHECK' pragmas with the safe flag."
SafeFlagPolarity_ -> "`POLARITY' pragmas with the safe flag."
SafeFlagPostulate_ -> "`postulate' blocks with the safe flag."
SafeFlagPragma_ -> "Unsafe `OPTIONS' pragmas with the safe flag."
SafeFlagTerminating_ -> "`TERMINATING' pragmas with the safe flag."
SafeFlagWithoutKFlagPrimEraseEquality_ -> "`primEraseEquality' used with the safe and without-K flags."
TerminationIssue_ -> "Failed termination checks."
UnreachableClauses_ -> "Unreachable function clauses."
UnsolvedConstraints_ -> "Unsolved constraints."
UnsolvedInteractionMetas_ -> "Unsolved interaction meta variables."
UnsolvedMetaVariables_ -> "Unsolved meta variables."
UserWarning_ -> "User-defined warning added using one of the 'WARNING_ON_*' pragmas."
WithoutKFlagPrimEraseEquality_ -> "`primEraseEquality' usages with the without-K flags."
WrongInstanceDeclaration_ -> "Instances that do not adhere to the required format."
-- Checking consistency of options
CoInfectiveImport_ -> "Importing a file not using e.g. `--safe' from one which does."
InfectiveImport_ -> "Importing a file using e.g. `--cubical' into one which doesn't."
-- Record field warnings
DuplicateFieldsWarning_ -> "Record expression with duplicate field names."
TooManyFieldsWarning_ -> "Record expression with invalid field names."
| null | https://raw.githubusercontent.com/agda/agda/db92582d2ea632d25c1fc2cb2179a8aabe2d5205/src/full/Agda/Interaction/Options/Warnings.hs | haskell | and a flag stating whether warnings should be turned into fatal errors.
| The @defaultWarningMode@ is a curated set of warnings covering non-fatal
errors and disabling style-related ones
| Some warnings are errors and cannot be turned off.
| @warningModeUpdate str@ computes the action of @str@ over the current
@WarningMode@: it may reset the set of warnings, add or remove a specific
flag or demand that any warning be turned into an error
| Common sets of warnings
to existing warnings in the codebase.
Option Warnings
Library Warnings
Nicifer Warnings
Scope and Type Checking Warnings
Checking consistency of options
Record field warnings
| The flag corresponding to a warning is precisely the name of the constructor
minus the trailing underscore.
| @warningUsage@ generated using @warningNameDescription@
warning option can be used to disable or enable\
warning=error)\
| @WarningName@ descriptions used for generating usage information
Leave String empty to skip that name.
Option Warnings
Library Warnings
Nicifer Warnings
Scope and Type Checking Warnings
Checking consistency of options
Record field warnings |
module Agda.Interaction.Options.Warnings
(
WarningMode (..)
, warningSet
, warn2Error
, defaultWarningSet
, allWarnings
, usualWarnings
, noWarnings
, unsolvedWarnings
, incompleteMatchWarnings
, errorWarnings
, defaultWarningMode
, WarningModeError(..)
, prettyWarningModeError
, warningModeUpdate
, warningSets
, WarningName (..)
, warningName2String
, string2WarningName
, usageWarning
)
where
import Control.Arrow ( (&&&) )
import Control.DeepSeq
import Control.Monad ( guard, when )
import Text.Read ( readMaybe )
import Data.Set (Set)
import qualified Data.Set as Set
import qualified Data.HashMap.Strict as HMap
import Data.List ( stripPrefix, intercalate )
import GHC.Generics (Generic)
import Agda.Utils.Either ( maybeToEither )
import Agda.Utils.Lens
import Agda.Utils.List
import Agda.Utils.Maybe
import Agda.Utils.Impossible
import Agda.Utils.Functor
| A @WarningMode@ has two components : a set of warnings to be displayed
data WarningMode = WarningMode
{ _warningSet :: Set WarningName
, _warn2Error :: Bool
} deriving (Eq, Show, Generic)
instance NFData WarningMode
warningSet :: Lens' (Set WarningName) WarningMode
warningSet f o = (\ ws -> o { _warningSet = ws }) <$> f (_warningSet o)
warn2Error :: Lens' Bool WarningMode
warn2Error f o = (\ ws -> o { _warn2Error = ws }) <$> f (_warn2Error o)
defaultWarningSet :: String
defaultWarningSet = "warn"
defaultWarningMode :: WarningMode
defaultWarningMode = WarningMode ws False where
ws = fst $ fromMaybe __IMPOSSIBLE__ $ lookup defaultWarningSet warningSets
data WarningModeError = Unknown String | NoNoError String
prettyWarningModeError :: WarningModeError -> String
prettyWarningModeError = \case
Unknown str -> concat [ "Unknown warning flag: ", str, "." ]
NoNoError str -> concat [ "You may only turn off benign warnings. The warning "
, str
," is a non-fatal error and thus cannot be ignored." ]
| From user - given directives we compute updates
type WarningModeUpdate = WarningMode -> WarningMode
warningModeUpdate :: String -> Either WarningModeError WarningModeUpdate
warningModeUpdate str = case str of
"error" -> pure $ set warn2Error True
"noerror" -> pure $ set warn2Error False
_ | Just ws <- fst <$> lookup str warningSets
-> pure $ set warningSet ws
_ -> case stripPrefix "no" str of
Nothing -> do
wname :: WarningName <- maybeToEither (Unknown str) $ string2WarningName str
pure (over warningSet $ Set.insert wname)
Just str' -> do
wname :: WarningName <- maybeToEither (Unknown str') $ string2WarningName str'
when (wname `elem` errorWarnings) (Left (NoNoError str'))
pure (over warningSet $ Set.delete wname)
warningSets :: [(String, (Set WarningName, String))]
warningSets = [ ("all" , (allWarnings, "All of the existing warnings"))
, ("warn" , (usualWarnings, "Default warning level"))
, ("ignore", (errorWarnings, "Ignore all the benign warnings"))
]
noWarnings :: Set WarningName
noWarnings = Set.empty
unsolvedWarnings :: Set WarningName
unsolvedWarnings = Set.fromList
[ UnsolvedMetaVariables_
, UnsolvedInteractionMetas_
, UnsolvedConstraints_
]
incompleteMatchWarnings :: Set WarningName
incompleteMatchWarnings = Set.fromList [ CoverageIssue_ ]
errorWarnings :: Set WarningName
errorWarnings = Set.fromList
[ CoverageIssue_
, GenericNonFatalError_
, MissingDefinitions_
, MissingDeclarations_
, NotAllowedInMutual_
, NotStrictlyPositive_
, OverlappingTokensWarning_
, PragmaCompiled_
, SafeFlagPostulate_
, SafeFlagPragma_
, SafeFlagNonTerminating_
, SafeFlagTerminating_
, SafeFlagWithoutKFlagPrimEraseEquality_
, SafeFlagNoPositivityCheck_
, SafeFlagPolarity_
, SafeFlagNoUniverseCheck_
, SafeFlagEta_
, SafeFlagInjective_
, SafeFlagNoCoverageCheck_
, TerminationIssue_
, UnsolvedMetaVariables_
, UnsolvedInteractionMetas_
, UnsolvedConstraints_
, InfectiveImport_
, CoInfectiveImport_
, RewriteNonConfluent_
, RewriteMaybeNonConfluent_
, RewriteAmbiguousRules_
, RewriteMissingRule_
]
allWarnings :: Set WarningName
allWarnings = Set.fromList [minBound..maxBound]
usualWarnings :: Set WarningName
usualWarnings = allWarnings Set.\\ Set.fromList
[ UnknownFixityInMixfixDecl_
, CoverageNoExactSplit_
, ShadowingInTelescope_
]
| The @WarningName@ data enumeration is meant to have a one - to - one correspondance
data WarningName
= OptionRenamed_
Parser Warnings
| OverlappingTokensWarning_
| UnsupportedAttribute_
| MultipleAttributes_
| LibUnknownField_
| EmptyAbstract_
| EmptyConstructor_
| EmptyField_
| EmptyGeneralize_
| EmptyInstance_
| EmptyMacro_
| EmptyMutual_
| EmptyPostulate_
| EmptyPrimitive_
| EmptyPrivate_
| EmptyRewritePragma_
| EmptyWhere_
| HiddenGeneralize_
| InvalidCatchallPragma_
| InvalidConstructor_
| InvalidConstructorBlock_
| InvalidCoverageCheckPragma_
| InvalidNoPositivityCheckPragma_
| InvalidNoUniverseCheckPragma_
| InvalidRecordDirective_
| InvalidTerminationCheckPragma_
| MissingDeclarations_
| MissingDefinitions_
| NotAllowedInMutual_
| OpenPublicAbstract_
| OpenPublicPrivate_
| PolarityPragmasButNotPostulates_
| PragmaCompiled_
| PragmaNoTerminationCheck_
| ShadowingInTelescope_
| UnknownFixityInMixfixDecl_
| UnknownNamesInFixityDecl_
| UnknownNamesInPolarityPragmas_
| UselessAbstract_
| UselessInstance_
| UselessPrivate_
| AbsurdPatternRequiresNoRHS_
| AsPatternShadowsConstructorOrPatternSynonym_
| CantGeneralizeOverSorts_
issue # 4154
| CoverageIssue_
| CoverageNoExactSplit_
| DeprecationWarning_
| DuplicateUsing_
| FixityInRenamingModule_
| GenericNonFatalError_
| GenericUseless_
| GenericWarning_
| IllformedAsClause_
| InstanceArgWithExplicitArg_
| InstanceWithExplicitArg_
| InstanceNoOutputTypeName_
| InversionDepthReached_
| ModuleDoesntExport_
| NoGuardednessFlag_
| NotInScope_
| NotStrictlyPositive_
| UnsupportedIndexedMatch_
| OldBuiltin_
| PlentyInHardCompileTimeMode_
| PragmaCompileErased_
| RewriteMaybeNonConfluent_
| RewriteNonConfluent_
| RewriteAmbiguousRules_
| RewriteMissingRule_
| SafeFlagEta_
| SafeFlagInjective_
| SafeFlagNoCoverageCheck_
| SafeFlagNonTerminating_
| SafeFlagNoPositivityCheck_
| SafeFlagNoUniverseCheck_
| SafeFlagPolarity_
| SafeFlagPostulate_
| SafeFlagPragma_
| SafeFlagTerminating_
| SafeFlagWithoutKFlagPrimEraseEquality_
| TerminationIssue_
| UnreachableClauses_
| UnsolvedConstraints_
| UnsolvedInteractionMetas_
| UnsolvedMetaVariables_
| UselessHiding_
| UselessInline_
| UselessPatternDeclarationForRecord_
| UselessPublic_
| UserWarning_
| WithoutKFlagPrimEraseEquality_
| WrongInstanceDeclaration_
| CoInfectiveImport_
| InfectiveImport_
| DuplicateFieldsWarning_
| TooManyFieldsWarning_
deriving (Eq, Ord, Show, Read, Enum, Bounded, Generic)
instance NFData WarningName
string2WarningName :: String -> Maybe WarningName
string2WarningName = (`HMap.lookup` warnings) where
warnings = HMap.fromList $ map (\x -> (warningName2String x, x)) [minBound..maxBound]
warningName2String :: WarningName -> String
warningName2String = initWithDefault __IMPOSSIBLE__ . show
usageWarning :: String
usageWarning = intercalate "\n"
\ can be used to turn all warnings into errors, while -W noerror\
\ turns this off again."
, ""
, "A group of warnings can be enabled by -W group, where group is\
\ one of the following:"
, ""
, untable (fmap (fst &&& snd . snd) warningSets)
, "Individual benign warnings can be turned on and off by -W Name and\
\ -W noName, respectively, where Name comes from the following\
\ list (warnings marked with 'd' are turned on by default, and 'b'\
\ stands for \"benign warning\"):"
, ""
, untable $ forMaybe [minBound..maxBound] $ \ w ->
let wnd = warningNameDescription w in
( warningName2String w
, (if w `Set.member` usualWarnings then "d" else " ") ++
(if not (w `Set.member` errorWarnings) then "b" else " ") ++
" " ++
wnd
) <$ guard (not $ null wnd)
]
where
untable :: [(String, String)] -> String
untable rows =
let len = maximum (map (length . fst) rows) in
unlines $ for rows $ \ (hdr, cnt) ->
concat [ hdr, replicate (1 + len - length hdr) ' ', cnt ]
warningNameDescription :: WarningName -> String
warningNameDescription = \case
OptionRenamed_ -> "Renamed options."
Parser Warnings
OverlappingTokensWarning_ -> "Multi-line comments spanning one or more literate text blocks."
UnsupportedAttribute_ -> "Unsupported attributes."
MultipleAttributes_ -> "Multiple attributes."
LibUnknownField_ -> "Unknown field in library file."
EmptyAbstract_ -> "Empty `abstract' blocks."
EmptyConstructor_ -> "Empty `constructor' blocks."
EmptyField_ -> "Empty `field` blocks."
EmptyGeneralize_ -> "Empty `variable' blocks."
EmptyInstance_ -> "Empty `instance' blocks."
EmptyMacro_ -> "Empty `macro' blocks."
EmptyMutual_ -> "Empty `mutual' blocks."
EmptyPostulate_ -> "Empty `postulate' blocks."
EmptyPrimitive_ -> "Empty `primitive' blocks."
EmptyPrivate_ -> "Empty `private' blocks."
EmptyRewritePragma_ -> "Empty `REWRITE' pragmas."
EmptyWhere_ -> "Empty `where' blocks."
HiddenGeneralize_ -> "Hidden identifiers in variable blocks."
InvalidCatchallPragma_ -> "`CATCHALL' pragmas before a non-function clause."
InvalidConstructor_ -> "`constructor' blocks may only contain type signatures for constructors."
InvalidConstructorBlock_ -> "No `constructor' blocks outside of `interleaved mutual' blocks."
InvalidCoverageCheckPragma_ -> "Coverage checking pragmas before non-function or `mutual' blocks."
InvalidNoPositivityCheckPragma_ -> "No positivity checking pragmas before non-`data', `record' or `mutual' blocks."
InvalidNoUniverseCheckPragma_ -> "No universe checking pragmas before non-`data' or `record' declaration."
InvalidRecordDirective_ -> "No record directive outside of record definition / below field declarations."
InvalidTerminationCheckPragma_ -> "Termination checking pragmas before non-function or `mutual' blocks."
MissingDeclarations_ -> "Definitions not associated to a declaration."
MissingDefinitions_ -> "Declarations not associated to a definition."
NotAllowedInMutual_ -> "Declarations not allowed in a mutual block."
OpenPublicAbstract_ -> "'open public' directive in an 'abstract' block."
OpenPublicPrivate_ -> "'open public' directive in a 'private' block."
PolarityPragmasButNotPostulates_ -> "Polarity pragmas for non-postulates."
PragmaCompiled_ -> "'COMPILE' pragmas not allowed in safe mode."
PragmaNoTerminationCheck_ -> "`NO_TERMINATION_CHECK' pragmas are deprecated"
ShadowingInTelescope_ -> "Repeated variable name in telescope."
UnknownFixityInMixfixDecl_ -> "Mixfix names without an associated fixity declaration."
UnknownNamesInFixityDecl_ -> "Names not declared in the same scope as their syntax or fixity declaration."
UnknownNamesInPolarityPragmas_ -> "Names not declared in the same scope as their polarity pragmas."
UselessAbstract_ -> "`abstract' blocks where they have no effect."
UselessHiding_ -> "Names in `hiding' directive that are anyway not imported."
UselessInline_ -> "`INLINE' pragmas where they have no effect."
UselessInstance_ -> "`instance' blocks where they have no effect."
UselessPrivate_ -> "`private' blocks where they have no effect."
UselessPublic_ -> "`public' blocks where they have no effect."
UselessPatternDeclarationForRecord_ -> "`pattern' attributes where they have no effect."
AbsurdPatternRequiresNoRHS_ -> "A clause with an absurd pattern does not need a Right Hand Side."
AsPatternShadowsConstructorOrPatternSynonym_ -> "@-patterns that shadow constructors or pattern synonyms."
CantGeneralizeOverSorts_ -> "Attempt to generalize over sort metas in 'variable' declaration."
issue # 4154
CoverageIssue_ -> "Failed coverage checks."
CoverageNoExactSplit_ -> "Failed exact split checks."
DeprecationWarning_ -> "Feature deprecation."
GenericNonFatalError_ -> ""
GenericUseless_ -> "Useless code."
GenericWarning_ -> ""
IllformedAsClause_ -> "Illformed `as'-clauses in `import' statements."
InstanceNoOutputTypeName_ -> "instance arguments whose type does not end in a named or variable type are never considered by instance search."
InstanceArgWithExplicitArg_ -> "instance arguments with explicit arguments are never considered by instance search."
InstanceWithExplicitArg_ -> "`instance` declarations with explicit arguments are never considered by instance search."
InversionDepthReached_ -> "Inversions of pattern-matching failed due to exhausted inversion depth."
NoGuardednessFlag_ -> "Coinductive record but no --guardedness flag."
ModuleDoesntExport_ -> "Imported name is not actually exported."
DuplicateUsing_ -> "Repeated names in using directive."
FixityInRenamingModule_ -> "Found fixity annotation in renaming directive for module."
NotInScope_ -> "Out of scope name."
NotStrictlyPositive_ -> "Failed strict positivity checks."
UnsupportedIndexedMatch_ -> "Failed to compute full equivalence when splitting on indexed family."
OldBuiltin_ -> "Deprecated `BUILTIN' pragmas."
PlentyInHardCompileTimeMode_ -> "Use of @ω or @plenty in hard compile-time mode."
PragmaCompileErased_ -> "`COMPILE' pragma targeting an erased symbol."
RewriteMaybeNonConfluent_ -> "Failed local confluence check while computing overlap."
RewriteNonConfluent_ -> "Failed local confluence check while joining critical pairs."
RewriteAmbiguousRules_ -> "Failed global confluence check because of overlapping rules."
RewriteMissingRule_ -> "Failed global confluence check because of missing rule."
SafeFlagEta_ -> "`ETA' pragmas with the safe flag."
SafeFlagInjective_ -> "`INJECTIVE' pragmas with the safe flag."
SafeFlagNoCoverageCheck_ -> "`NON_COVERING` pragmas with the safe flag."
SafeFlagNonTerminating_ -> "`NON_TERMINATING' pragmas with the safe flag."
SafeFlagNoPositivityCheck_ -> "`NO_POSITIVITY_CHECK' pragmas with the safe flag."
SafeFlagNoUniverseCheck_ -> "`NO_UNIVERSE_CHECK' pragmas with the safe flag."
SafeFlagPolarity_ -> "`POLARITY' pragmas with the safe flag."
SafeFlagPostulate_ -> "`postulate' blocks with the safe flag."
SafeFlagPragma_ -> "Unsafe `OPTIONS' pragmas with the safe flag."
SafeFlagTerminating_ -> "`TERMINATING' pragmas with the safe flag."
SafeFlagWithoutKFlagPrimEraseEquality_ -> "`primEraseEquality' used with the safe and without-K flags."
TerminationIssue_ -> "Failed termination checks."
UnreachableClauses_ -> "Unreachable function clauses."
UnsolvedConstraints_ -> "Unsolved constraints."
UnsolvedInteractionMetas_ -> "Unsolved interaction meta variables."
UnsolvedMetaVariables_ -> "Unsolved meta variables."
UserWarning_ -> "User-defined warning added using one of the 'WARNING_ON_*' pragmas."
WithoutKFlagPrimEraseEquality_ -> "`primEraseEquality' usages with the without-K flags."
WrongInstanceDeclaration_ -> "Instances that do not adhere to the required format."
CoInfectiveImport_ -> "Importing a file not using e.g. `--safe' from one which does."
InfectiveImport_ -> "Importing a file using e.g. `--cubical' into one which doesn't."
DuplicateFieldsWarning_ -> "Record expression with duplicate field names."
TooManyFieldsWarning_ -> "Record expression with invalid field names."
|
bb59774c18a17cd8abb283a421fb629ee9e1b4ae607f4954ee66c34c8fcc781a | ssor/erlangDemos | ti_app.erl | -module(ti_app).
-behaviour(application).
-export([start/2, stop/1]).
-define(DEFAULT_PORT, 1155).
start(_StartType, _StartArgs) ->
Port = case application:get_env(tcp_interface, port) of
{ok, P} -> P;
undefined -> ?DEFAULT_PORT
end,
{ok, LSock} = gen_tcp:listen(Port, [{active, true}]),
case ti_sup:start_link(LSock) of
{ok, Pid} ->
ti_sup:start_child(),
{ok, Pid};
Other ->
{error, Other}
end.
stop(_State) ->
ok.
| null | https://raw.githubusercontent.com/ssor/erlangDemos/632cd905be2c4f275f1c1ae15238e711d7bb9147/erlware-Erlang-and-OTP-in-Action-Source/chapter_11/tcp_interface/src/ti_app.erl | erlang | -module(ti_app).
-behaviour(application).
-export([start/2, stop/1]).
-define(DEFAULT_PORT, 1155).
start(_StartType, _StartArgs) ->
Port = case application:get_env(tcp_interface, port) of
{ok, P} -> P;
undefined -> ?DEFAULT_PORT
end,
{ok, LSock} = gen_tcp:listen(Port, [{active, true}]),
case ti_sup:start_link(LSock) of
{ok, Pid} ->
ti_sup:start_child(),
{ok, Pid};
Other ->
{error, Other}
end.
stop(_State) ->
ok.
| |
0aee2a378eacbdd24d34d7952569c8212644c46efaef2d49999520a8639fdb69 | collaborativetrust/WikiTrust | read_robots.ml |
Copyright ( c ) 2009 .
All rights reserved .
Authors :
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 names of the contributors may not 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 OWNER 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) 2009 Luca de Alfaro.
All rights reserved.
Authors: Luca de Alfaro
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 names of the contributors may not 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 OWNER 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.
*)
This file contains functions to read a robots file , returning a
hashtable that permits fast checking of whether a user is a robot .
The hashtable maps usernames to unit ; if a username is found in the
hashtable , the user is a robot .
The format of the robot file is one line per robot , with the robot
name encoded as an Ocaml string , as in ( " " included :)
" a funny\trobot name "
hashtable that permits fast checking of whether a user is a robot.
The hashtable maps usernames to unit; if a username is found in the
hashtable, the user is a robot.
The format of the robot file is one line per robot, with the robot
name encoded as an Ocaml string, as in ("" included:)
"a funny\trobot name"
*)
type robot_set_t = (string, unit) Hashtbl.t
let empty_robot_set : robot_set_t = Hashtbl.create 100
let read_robot_file (file_name: string) : robot_set_t =
let robots : robot_set_t = empty_robot_set in
let in_file = open_in file_name in
begin
try (* Until we get an End_of_file. *)
while true do begin
let line = input_line in_file in
(* Extracts the robot name *)
let get_robot s = Hashtbl.add robots s () in
try
Scanf.sscanf line "%S" get_robot
with Scanf.Scan_failure _ -> begin
output_string stderr ("Error reading line: " ^ line)
end
end done
with End_of_file -> close_in in_file
end;
robots
| null | https://raw.githubusercontent.com/collaborativetrust/WikiTrust/9dd056e65c37a22f67d600dd1e87753aa0ec9e2c/analysis/read_robots.ml | ocaml | Until we get an End_of_file.
Extracts the robot name |
Copyright ( c ) 2009 .
All rights reserved .
Authors :
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 names of the contributors may not 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 OWNER 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) 2009 Luca de Alfaro.
All rights reserved.
Authors: Luca de Alfaro
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 names of the contributors may not 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 OWNER 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.
*)
This file contains functions to read a robots file , returning a
hashtable that permits fast checking of whether a user is a robot .
The hashtable maps usernames to unit ; if a username is found in the
hashtable , the user is a robot .
The format of the robot file is one line per robot , with the robot
name encoded as an Ocaml string , as in ( " " included :)
" a funny\trobot name "
hashtable that permits fast checking of whether a user is a robot.
The hashtable maps usernames to unit; if a username is found in the
hashtable, the user is a robot.
The format of the robot file is one line per robot, with the robot
name encoded as an Ocaml string, as in ("" included:)
"a funny\trobot name"
*)
type robot_set_t = (string, unit) Hashtbl.t
let empty_robot_set : robot_set_t = Hashtbl.create 100
let read_robot_file (file_name: string) : robot_set_t =
let robots : robot_set_t = empty_robot_set in
let in_file = open_in file_name in
begin
while true do begin
let line = input_line in_file in
let get_robot s = Hashtbl.add robots s () in
try
Scanf.sscanf line "%S" get_robot
with Scanf.Scan_failure _ -> begin
output_string stderr ("Error reading line: " ^ line)
end
end done
with End_of_file -> close_in in_file
end;
robots
|
91ee9b47f5b00c9649d6a41b394fcd59d52b235032fae65be1ffd433b9ff72dc | mokus0/junkbox | M1M2.hs | module M1M2 where
{-# NOINLINE m1 #-}
m1 = ((filter odd [1..]) !!)
{-# NOINLINE m2 #-}
m2 n = ((filter odd [1..]) !! n)
{-# NOINLINE m3 #-}
m3 :: Int -> Integer
m3 n = ((filter odd [1..]) !! n)
| null | https://raw.githubusercontent.com/mokus0/junkbox/151014bbef9db2b9205209df66c418d6d58b0d9e/Haskell/Benchmarks/M1M2.hs | haskell | # NOINLINE m1 #
# NOINLINE m2 #
# NOINLINE m3 # | module M1M2 where
m1 = ((filter odd [1..]) !!)
m2 n = ((filter odd [1..]) !! n)
m3 :: Int -> Integer
m3 n = ((filter odd [1..]) !! n)
|
ab1dfe8ee5919bb26a8f6ecec6fb0f81134a4cb1dd1f472d0a2a491b2b3a331b | exercism/haskell | SumOfMultiples.hs | module SumOfMultiples (sumOfMultiples) where
sumOfMultiples :: [Int] -> Int -> Int
sumOfMultiples targets upperBound = sum (filter f [1..upperBound-1])
where f n = any ((==0) . mod n) (filter (/= 0) targets)
| null | https://raw.githubusercontent.com/exercism/haskell/ae17e9fc5ca736a228db6dda5e3f3b057fa6f3d0/exercises/practice/sum-of-multiples/.meta/examples/success-standard/src/SumOfMultiples.hs | haskell | module SumOfMultiples (sumOfMultiples) where
sumOfMultiples :: [Int] -> Int -> Int
sumOfMultiples targets upperBound = sum (filter f [1..upperBound-1])
where f n = any ((==0) . mod n) (filter (/= 0) targets)
| |
33543f6ba98f6da4cd96395f534596fe45619bc7df38ef1975468a6c0097f528 | tud-fop/vanda-haskell | FastNub.hs | -------------------------------------------------------------------------------
-- |
Copyright : ( c ) 2010
-- License : BSD-style
Maintainer : < >
--
-- Stability : unknown
-- Portability : portable
-------------------------------------------------------------------------------
module Vanda.Algorithms.Earley.FastNub(nub) where
import qualified Data.Set as Set
| Removes duplicate elements from a list by exploiting the ' ' relation .
In particular , it keeps only the first occurrence of each element .
nub :: (Ord a) => [a] -> [a]
nub xs = f xs Set.empty
where
f (y:ys) s = if Set.member y s
then f ys s
else y : f ys (Set.insert y s)
f [] _ = []
-- this would not be lazy
nub xs = Set.toList $ Set.fromList xs
| null | https://raw.githubusercontent.com/tud-fop/vanda-haskell/3214966361b6dbf178155950c94423eee7f9453e/library/Vanda/Algorithms/Earley/FastNub.hs | haskell | -----------------------------------------------------------------------------
|
License : BSD-style
Stability : unknown
Portability : portable
-----------------------------------------------------------------------------
this would not be lazy | Copyright : ( c ) 2010
Maintainer : < >
module Vanda.Algorithms.Earley.FastNub(nub) where
import qualified Data.Set as Set
| Removes duplicate elements from a list by exploiting the ' ' relation .
In particular , it keeps only the first occurrence of each element .
nub :: (Ord a) => [a] -> [a]
nub xs = f xs Set.empty
where
f (y:ys) s = if Set.member y s
then f ys s
else y : f ys (Set.insert y s)
f [] _ = []
nub xs = Set.toList $ Set.fromList xs
|
bd855bd73b694f071ee47cce0f806987f9b9dcf0df226ac284a0f22befbaa40d | input-output-hk/plutus-apps | API.hs | # LANGUAGE AllowAmbiguousTypes #
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE GADTs #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
# OPTIONS_GHC -Wno - orphans #
# OPTIONS_GHC -fno - omit - interface - pragmas #
# OPTIONS_GHC -fno - ignore - interface - pragmas #
{-|
Mock wallet implementation
-}
module Wallet.API(
WalletEffect,
submitTxn,
ownPaymentPubKeyHash,
ownPaymentPubKeyHashes,
ownFirstPaymentPubKeyHash,
ownAddresses,
balanceTx,
yieldUnbalancedTx,
NodeClientEffect,
publishTx,
getClientSlot,
getClientParams,
PubKey(..),
PubKeyHash(..),
signTxAndSubmit,
signTxAndSubmit_,
payToAddress,
payToAddress_,
payToPaymentPublicKeyHash,
payToPaymentPublicKeyHash_,
Params(..),
-- * Slot ranges
Interval(..),
Slot,
SlotRange,
width,
defaultSlotRange,
interval,
singleton,
isEmpty,
always,
member,
before,
after,
contains,
-- * Error handling
Wallet.Error.WalletAPIError(..),
Wallet.Error.throwInsufficientFundsError,
Wallet.Error.throwOtherError,
) where
import Cardano.Node.Emulator.Params (Params (..))
import Control.Monad (unless, void)
import Control.Monad.Freer (Eff, Member)
import Control.Monad.Freer.Error (Error, throwError)
import Control.Monad.Freer.Extras.Log (LogMsg, logDebug, logWarn)
import Data.List.NonEmpty qualified as NonEmpty
import Data.Maybe (mapMaybe)
import Data.Text (Text)
import Data.Void (Void)
import Ledger (Address, CardanoTx, Interval (Interval, ivFrom, ivTo), PaymentPubKeyHash (PaymentPubKeyHash),
PubKey (PubKey, getPubKey), PubKeyHash (PubKeyHash, getPubKeyHash), Slot, SlotRange, after, always,
before, cardanoPubKeyHash, contains, interval, isEmpty, member, pubKeyHashAddress, singleton, width)
import Ledger.Tx.Constraints qualified as Constraints
import Ledger.Tx.Constraints.OffChain (adjustUnbalancedTx)
import Ledger.Tx.Constraints.ValidityInterval qualified as Interval
import Plutus.V1.Ledger.Value (Value)
import Wallet.Effects (NodeClientEffect, WalletEffect, balanceTx, getClientParams, getClientSlot, ownAddresses,
publishTx, submitTxn, walletAddSignature, yieldUnbalancedTx)
import Wallet.Emulator.LogMessages (RequestHandlerLogMsg (AdjustingUnbalancedTx))
import Wallet.Error (WalletAPIError (NoPaymentPubKeyHashError, PaymentMkTxError, ToCardanoError))
import Wallet.Error qualified
# DEPRECATED ownPaymentPubKeyHash " Use ownFirstPaymentPubKeyHash , ownPaymentPubKeyHashes or ownAddresses instead " #
ownPaymentPubKeyHash ::
( Member WalletEffect effs
, Member (Error WalletAPIError) effs
)
=> Eff effs PaymentPubKeyHash
ownPaymentPubKeyHash = ownFirstPaymentPubKeyHash
ownPaymentPubKeyHashes ::
( Member WalletEffect effs
)
=> Eff effs [PaymentPubKeyHash]
ownPaymentPubKeyHashes = do
addrs <- ownAddresses
pure $ fmap PaymentPubKeyHash $ mapMaybe cardanoPubKeyHash $ NonEmpty.toList addrs
ownFirstPaymentPubKeyHash ::
( Member WalletEffect effs
, Member (Error WalletAPIError) effs
)
=> Eff effs PaymentPubKeyHash
ownFirstPaymentPubKeyHash = do
pkhs <- ownPaymentPubKeyHashes
case pkhs of
[] -> throwError NoPaymentPubKeyHashError
(pkh:_) -> pure pkh
-- | Transfer some funds to an address, returning the transaction that was submitted.
--
Note : Due to a constraint in the Cardano ledger , each tx output must have a
minimum amount of . Therefore , the funds to transfer will be adjusted
-- to satisfy that constraint. See 'adjustUnbalancedTx'.
payToAddress ::
( Member WalletEffect effs
, Member (Error WalletAPIError) effs
, Member (LogMsg Text) effs
, Member (LogMsg RequestHandlerLogMsg) effs
)
=> Params -> SlotRange -> Value -> Address -> Eff effs CardanoTx
payToAddress params range v addr = do
pkh <- ownFirstPaymentPubKeyHash
let constraints = Constraints.mustPayToAddress addr v
<> Constraints.mustValidateInSlotRange (Interval.fromPlutusInterval range)
<> Constraints.mustBeSignedBy pkh
utx <- either (throwError . PaymentMkTxError)
pure
(Constraints.mkTxWithParams @Void params mempty constraints)
(missingAdaCosts, adjustedUtx) <- either (throwError . ToCardanoError) pure
(adjustUnbalancedTx (emulatorPParams params) utx)
logDebug $ AdjustingUnbalancedTx missingAdaCosts
unless (utx == adjustedUtx) $
logWarn @Text $ "Wallet.API.payToPublicKeyHash: "
<> "Adjusted a transaction output value which has less than the minimum amount of Ada."
balancedTx <- balanceTx adjustedUtx
either throwError signTxAndSubmit balancedTx
-- | Transfer some funds to an address.
payToAddress_ ::
( Member WalletEffect effs
, Member (Error WalletAPIError) effs
, Member (LogMsg Text) effs
, Member (LogMsg RequestHandlerLogMsg) effs
)
=> Params -> SlotRange -> Value -> Address -> Eff effs ()
payToAddress_ params range v addr = void $ payToAddress params range v addr
-- | Transfer some funds to an address locked by a public key, returning the
-- transaction that was submitted.
--
Note : Due to a constraint in the Cardano ledger , each tx output must have a
minimum amount of . Therefore , the funds to transfer will be adjusted
-- to satisfy that constraint. See 'adjustUnbalancedTx'.
payToPaymentPublicKeyHash ::
( Member WalletEffect effs
, Member (Error WalletAPIError) effs
, Member (LogMsg Text) effs
, Member (LogMsg RequestHandlerLogMsg) effs
)
=> Params -> SlotRange -> Value -> PaymentPubKeyHash -> Eff effs CardanoTx
payToPaymentPublicKeyHash params range v pkh = payToAddress params range v (pubKeyHashAddress pkh Nothing)
-- | Transfer some funds to an address locked by a public key.
payToPaymentPublicKeyHash_ ::
( Member WalletEffect effs
, Member (Error WalletAPIError) effs
, Member (LogMsg Text) effs
, Member (LogMsg RequestHandlerLogMsg) effs
)
=> Params -> SlotRange -> Value -> PaymentPubKeyHash -> Eff effs ()
payToPaymentPublicKeyHash_ params r v = void . payToPaymentPublicKeyHash params r v
-- | Add the wallet's signature to the transaction and submit it. Returns
-- the transaction with the wallet's signature.
signTxAndSubmit ::
( Member WalletEffect effs
)
=> CardanoTx -> Eff effs CardanoTx
signTxAndSubmit t = do
tx' <- walletAddSignature t
submitTxn tx'
pure tx'
-- | A version of 'signTxAndSubmit' that discards the result.
signTxAndSubmit_ ::
( Member WalletEffect effs
)
=> CardanoTx -> Eff effs ()
signTxAndSubmit_ = void . signTxAndSubmit
-- | The default slot validity range for transactions.
defaultSlotRange :: SlotRange
defaultSlotRange = always
| null | https://raw.githubusercontent.com/input-output-hk/plutus-apps/006f4ae4461094d3e9405a445b0c9cf48727fa81/plutus-contract/src/Wallet/API.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE DataKinds #
# LANGUAGE DerivingStrategies #
# LANGUAGE FlexibleContexts #
# LANGUAGE OverloadedStrings #
# LANGUAGE RankNTypes #
|
Mock wallet implementation
* Slot ranges
* Error handling
| Transfer some funds to an address, returning the transaction that was submitted.
to satisfy that constraint. See 'adjustUnbalancedTx'.
| Transfer some funds to an address.
| Transfer some funds to an address locked by a public key, returning the
transaction that was submitted.
to satisfy that constraint. See 'adjustUnbalancedTx'.
| Transfer some funds to an address locked by a public key.
| Add the wallet's signature to the transaction and submit it. Returns
the transaction with the wallet's signature.
| A version of 'signTxAndSubmit' that discards the result.
| The default slot validity range for transactions. | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE FlexibleInstances #
# LANGUAGE GADTs #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
# OPTIONS_GHC -Wno - orphans #
# OPTIONS_GHC -fno - omit - interface - pragmas #
# OPTIONS_GHC -fno - ignore - interface - pragmas #
module Wallet.API(
WalletEffect,
submitTxn,
ownPaymentPubKeyHash,
ownPaymentPubKeyHashes,
ownFirstPaymentPubKeyHash,
ownAddresses,
balanceTx,
yieldUnbalancedTx,
NodeClientEffect,
publishTx,
getClientSlot,
getClientParams,
PubKey(..),
PubKeyHash(..),
signTxAndSubmit,
signTxAndSubmit_,
payToAddress,
payToAddress_,
payToPaymentPublicKeyHash,
payToPaymentPublicKeyHash_,
Params(..),
Interval(..),
Slot,
SlotRange,
width,
defaultSlotRange,
interval,
singleton,
isEmpty,
always,
member,
before,
after,
contains,
Wallet.Error.WalletAPIError(..),
Wallet.Error.throwInsufficientFundsError,
Wallet.Error.throwOtherError,
) where
import Cardano.Node.Emulator.Params (Params (..))
import Control.Monad (unless, void)
import Control.Monad.Freer (Eff, Member)
import Control.Monad.Freer.Error (Error, throwError)
import Control.Monad.Freer.Extras.Log (LogMsg, logDebug, logWarn)
import Data.List.NonEmpty qualified as NonEmpty
import Data.Maybe (mapMaybe)
import Data.Text (Text)
import Data.Void (Void)
import Ledger (Address, CardanoTx, Interval (Interval, ivFrom, ivTo), PaymentPubKeyHash (PaymentPubKeyHash),
PubKey (PubKey, getPubKey), PubKeyHash (PubKeyHash, getPubKeyHash), Slot, SlotRange, after, always,
before, cardanoPubKeyHash, contains, interval, isEmpty, member, pubKeyHashAddress, singleton, width)
import Ledger.Tx.Constraints qualified as Constraints
import Ledger.Tx.Constraints.OffChain (adjustUnbalancedTx)
import Ledger.Tx.Constraints.ValidityInterval qualified as Interval
import Plutus.V1.Ledger.Value (Value)
import Wallet.Effects (NodeClientEffect, WalletEffect, balanceTx, getClientParams, getClientSlot, ownAddresses,
publishTx, submitTxn, walletAddSignature, yieldUnbalancedTx)
import Wallet.Emulator.LogMessages (RequestHandlerLogMsg (AdjustingUnbalancedTx))
import Wallet.Error (WalletAPIError (NoPaymentPubKeyHashError, PaymentMkTxError, ToCardanoError))
import Wallet.Error qualified
# DEPRECATED ownPaymentPubKeyHash " Use ownFirstPaymentPubKeyHash , ownPaymentPubKeyHashes or ownAddresses instead " #
ownPaymentPubKeyHash ::
( Member WalletEffect effs
, Member (Error WalletAPIError) effs
)
=> Eff effs PaymentPubKeyHash
ownPaymentPubKeyHash = ownFirstPaymentPubKeyHash
ownPaymentPubKeyHashes ::
( Member WalletEffect effs
)
=> Eff effs [PaymentPubKeyHash]
ownPaymentPubKeyHashes = do
addrs <- ownAddresses
pure $ fmap PaymentPubKeyHash $ mapMaybe cardanoPubKeyHash $ NonEmpty.toList addrs
ownFirstPaymentPubKeyHash ::
( Member WalletEffect effs
, Member (Error WalletAPIError) effs
)
=> Eff effs PaymentPubKeyHash
ownFirstPaymentPubKeyHash = do
pkhs <- ownPaymentPubKeyHashes
case pkhs of
[] -> throwError NoPaymentPubKeyHashError
(pkh:_) -> pure pkh
Note : Due to a constraint in the Cardano ledger , each tx output must have a
minimum amount of . Therefore , the funds to transfer will be adjusted
payToAddress ::
( Member WalletEffect effs
, Member (Error WalletAPIError) effs
, Member (LogMsg Text) effs
, Member (LogMsg RequestHandlerLogMsg) effs
)
=> Params -> SlotRange -> Value -> Address -> Eff effs CardanoTx
payToAddress params range v addr = do
pkh <- ownFirstPaymentPubKeyHash
let constraints = Constraints.mustPayToAddress addr v
<> Constraints.mustValidateInSlotRange (Interval.fromPlutusInterval range)
<> Constraints.mustBeSignedBy pkh
utx <- either (throwError . PaymentMkTxError)
pure
(Constraints.mkTxWithParams @Void params mempty constraints)
(missingAdaCosts, adjustedUtx) <- either (throwError . ToCardanoError) pure
(adjustUnbalancedTx (emulatorPParams params) utx)
logDebug $ AdjustingUnbalancedTx missingAdaCosts
unless (utx == adjustedUtx) $
logWarn @Text $ "Wallet.API.payToPublicKeyHash: "
<> "Adjusted a transaction output value which has less than the minimum amount of Ada."
balancedTx <- balanceTx adjustedUtx
either throwError signTxAndSubmit balancedTx
payToAddress_ ::
( Member WalletEffect effs
, Member (Error WalletAPIError) effs
, Member (LogMsg Text) effs
, Member (LogMsg RequestHandlerLogMsg) effs
)
=> Params -> SlotRange -> Value -> Address -> Eff effs ()
payToAddress_ params range v addr = void $ payToAddress params range v addr
Note : Due to a constraint in the Cardano ledger , each tx output must have a
minimum amount of . Therefore , the funds to transfer will be adjusted
payToPaymentPublicKeyHash ::
( Member WalletEffect effs
, Member (Error WalletAPIError) effs
, Member (LogMsg Text) effs
, Member (LogMsg RequestHandlerLogMsg) effs
)
=> Params -> SlotRange -> Value -> PaymentPubKeyHash -> Eff effs CardanoTx
payToPaymentPublicKeyHash params range v pkh = payToAddress params range v (pubKeyHashAddress pkh Nothing)
payToPaymentPublicKeyHash_ ::
( Member WalletEffect effs
, Member (Error WalletAPIError) effs
, Member (LogMsg Text) effs
, Member (LogMsg RequestHandlerLogMsg) effs
)
=> Params -> SlotRange -> Value -> PaymentPubKeyHash -> Eff effs ()
payToPaymentPublicKeyHash_ params r v = void . payToPaymentPublicKeyHash params r v
signTxAndSubmit ::
( Member WalletEffect effs
)
=> CardanoTx -> Eff effs CardanoTx
signTxAndSubmit t = do
tx' <- walletAddSignature t
submitTxn tx'
pure tx'
signTxAndSubmit_ ::
( Member WalletEffect effs
)
=> CardanoTx -> Eff effs ()
signTxAndSubmit_ = void . signTxAndSubmit
defaultSlotRange :: SlotRange
defaultSlotRange = always
|
087e1282c87d9c33e8fbd72d5d11227cb9d2e018c034419d6f29b056aa78ad1d | haroldcarr/learn-haskell-coq-ml-etc | FP01RecFunTest.hs |
Created : 2013 Sep 28 ( Sat ) 09:01:51 by .
Last Modified : 2014 Mar 05 ( We d ) 12:59:38 by .
Created : 2013 Sep 28 (Sat) 09:01:51 by carr.
Last Modified : 2014 Mar 05 (Wed) 12:59:38 by Harold Carr.
-}
import FP01RecFun
import Test.HUnit
import Test.HUnit.Util
tests :: Test
tests = TestList
[
-- BALANCE
teq "balance: '(if (zero? x) max (/ 1 x))' is balanced" (balance "(if (zero? x) max (/ 1 x))") True
,teq "balance: 'I told him ...' is balanced" (balance "I told him (that it's not (yet) done).\n(But he wasn't listening)")
True
,teq "balance: ':-)' is unbalanced" (balance ":-)") False
,teq "balance: counting is not enough" (balance "())(") False
-- COUNT CHANGE
,teq "countChange: example given in instructions" (countChange 4 [1,2]) 3
,teq "countChange: sorted CHF" (countChange 300 [5,10,20,50,100,200,500]) 1022
,teq "countChange: no pennies" (countChange 301 [5,10,20,50,100,200,500]) 0
,teq "countChange: unsorted CHF" (countChange 300 [500,5,50,100,20,200,10]) 1022
PASCAL
,teq "pascal: col=0,row=2" (pascal 0 2) 1
,teq "pascal: col=1,row=2" (pascal 1 2) 2
,teq "pascal: col=1,row=3" (pascal 1 3) 3
,teq "pascal: col=3,row=10" (pascal 3 10) 120
,ter "pascal: col=-1,row=0 throws exception" (pascal (-1) 0)
"IllegalArgumentException: not a legal position: c:-1, r:0"
,ter "pascal: col=0,row=-1 throws exception" (pascal 0 (-1))
"IllegalArgumentException: not a legal position: c:0, r:-1"
,ter "pascal: col=4,row=3 throws exception" (pascal 4 3)
"IllegalArgumentException: not a legal position: c:4, r:3"
]
main :: IO Counts
main = runTestTT tests
-- End of file.
| null | https://raw.githubusercontent.com/haroldcarr/learn-haskell-coq-ml-etc/b4e83ec7c7af730de688b7376497b9f49dc24a0e/haskell/course/2013-11-coursera-fp-odersky-but-in-haskell/FP01RecFunTest.hs | haskell | BALANCE
COUNT CHANGE
End of file. |
Created : 2013 Sep 28 ( Sat ) 09:01:51 by .
Last Modified : 2014 Mar 05 ( We d ) 12:59:38 by .
Created : 2013 Sep 28 (Sat) 09:01:51 by carr.
Last Modified : 2014 Mar 05 (Wed) 12:59:38 by Harold Carr.
-}
import FP01RecFun
import Test.HUnit
import Test.HUnit.Util
tests :: Test
tests = TestList
[
teq "balance: '(if (zero? x) max (/ 1 x))' is balanced" (balance "(if (zero? x) max (/ 1 x))") True
,teq "balance: 'I told him ...' is balanced" (balance "I told him (that it's not (yet) done).\n(But he wasn't listening)")
True
,teq "balance: ':-)' is unbalanced" (balance ":-)") False
,teq "balance: counting is not enough" (balance "())(") False
,teq "countChange: example given in instructions" (countChange 4 [1,2]) 3
,teq "countChange: sorted CHF" (countChange 300 [5,10,20,50,100,200,500]) 1022
,teq "countChange: no pennies" (countChange 301 [5,10,20,50,100,200,500]) 0
,teq "countChange: unsorted CHF" (countChange 300 [500,5,50,100,20,200,10]) 1022
PASCAL
,teq "pascal: col=0,row=2" (pascal 0 2) 1
,teq "pascal: col=1,row=2" (pascal 1 2) 2
,teq "pascal: col=1,row=3" (pascal 1 3) 3
,teq "pascal: col=3,row=10" (pascal 3 10) 120
,ter "pascal: col=-1,row=0 throws exception" (pascal (-1) 0)
"IllegalArgumentException: not a legal position: c:-1, r:0"
,ter "pascal: col=0,row=-1 throws exception" (pascal 0 (-1))
"IllegalArgumentException: not a legal position: c:0, r:-1"
,ter "pascal: col=4,row=3 throws exception" (pascal 4 3)
"IllegalArgumentException: not a legal position: c:4, r:3"
]
main :: IO Counts
main = runTestTT tests
|
d6d6b858b9eb2a74f7f3971b6ab533b1ef84299b7e402a5321e6ae72979d6956 | input-output-hk/plutus-apps | Graph.hs | {-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE DeriveGeneric #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
# OPTIONS_GHC -fno - warn - incomplete - uni - patterns #
-- | Support for visualisation of a blockchain as a graph.
module Wallet.Graph
( txnFlows
, graph
, FlowGraph
, FlowLink
, TxRef
, UtxOwner
, UtxoLocation
) where
import Data.Aeson.Types (ToJSON, toJSON)
import Data.List (nub)
import Data.Map qualified as Map
import Data.Maybe (catMaybes)
import Data.Set qualified as Set
import Data.Text qualified as Text
import GHC.Generics (Generic)
import Cardano.Api qualified as C
import Ledger.Address
import Ledger.Blockchain
import Ledger.Credential (Credential (..))
import Ledger.Crypto
import Ledger.Tx
-- | The owner of an unspent transaction output.
data UtxOwner
= PubKeyOwner PubKey
-- ^ Funds owned by a known public key.
| ScriptOwner
-- ^ Funds locked by script.
| OtherOwner
-- ^ All other funds (that is, funds owned by a public key we are not interested in).
deriving (Eq, Ord, Show, Generic, ToJSON)
-- | Given a set of known public keys, compute the owner of a given transaction output.
owner :: Set.Set PubKey -> TxOut -> UtxOwner
owner keys tx =
let hashMap = foldMap (\pk -> Map.singleton (pubKeyHash pk) pk) keys
in case cardanoAddressCredential (txOutAddress tx) of
ScriptCredential{} -> ScriptOwner
PubKeyCredential pkh | Just pk <- Map.lookup pkh hashMap -> PubKeyOwner pk
_ -> OtherOwner
| A wrapper around the first 8 digits of a ' TxId ' .
newtype TxRef =
TxRef Text.Text
deriving (Eq, Ord, Show, Generic)
instance ToJSON TxRef where
toJSON (TxRef t) = toJSON t
mkRef :: TxId -> TxRef
mkRef = TxRef . Text.pack . take 8 . show . getTxId
| The location of a transaction in a blockchain specified by two indices : the index of the containing
-- block in the chain, and the index of the transaction within the block.
data UtxoLocation = UtxoLocation
{ utxoLocBlock :: Integer
, utxoLocBlockIdx :: Integer
} deriving (Eq, Ord, Show, Generic, ToJSON)
-- | A link in the flow graph.
data FlowLink = FlowLink
{ flowLinkSource :: TxRef -- ^ The source transaction.
, flowLinkTarget :: TxRef -- ^ The target transaction.
^ The value of along this edge .
, flowLinkOwner :: UtxOwner -- ^ The owner of this edge.
, flowLinkSourceLoc :: UtxoLocation -- ^ The location of the source transaction.
, flowLinkTargetLoc :: Maybe UtxoLocation -- ^ The location of the target transaction, if 'Nothing' then it is unspent.
} deriving (Show, Generic, ToJSON)
-- | The flow graph, consisting of a set of nodes ('TxRef's) and edges ('FlowLink's).
data FlowGraph = FlowGraph
{ flowGraphLinks :: [FlowLink]
, flowGraphNodes :: [TxRef]
} deriving (Show, Generic, ToJSON)
-- | Construct a graph from a list of 'FlowLink's.
graph :: [FlowLink] -> FlowGraph
graph lnks = FlowGraph {..}
where
flowGraphLinks = lnks
flowGraphNodes = nub $ fmap flowLinkSource lnks ++ fmap flowLinkTarget lnks
| Compute the ' FlowLink 's for a ' Blockchain ' given a set of known ' PubKey 's .
txnFlows :: [PubKey] -> Blockchain -> [FlowLink]
txnFlows keys bc = catMaybes (utxoLinks ++ foldMap extract bc')
where
bc' = foldMap (\(blockNum, txns) -> fmap (\(blockIdx, txn) -> (UtxoLocation blockNum blockIdx, txn)) txns) $ zipWithIndex $ zipWithIndex <$> reverse bc
sourceLocations :: Map.Map TxOutRef UtxoLocation
sourceLocations = Map.fromList $ foldMap (uncurry outRefsWithLoc) bc'
knownKeys :: Set.Set PubKey
knownKeys = Set.fromList keys
utxos = fmap fst $ Map.toList $ unspentOutputs bc
utxoLinks = uncurry (flow Nothing) <$> zip (utxoTargets <$> utxos) utxos
extract :: (UtxoLocation, OnChainTx) -> [Maybe FlowLink]
extract (loc, tx) =
let targetRef = mkRef $ getCardanoTxId $ unOnChain tx in
fmap (flow (Just loc) targetRef . txInRef) (consumableInputs tx)
-- make a flow for a TxOutRef
flow :: Maybe UtxoLocation -> TxRef -> TxOutRef -> Maybe FlowLink
flow tgtLoc tgtRef rf = do
src <- out bc rf
sourceLoc <- Map.lookup rf sourceLocations
let sourceRef = mkRef $ txOutRefId rf
pure FlowLink
{ flowLinkSource = sourceRef
, flowLinkTarget = tgtRef
, flowLinkValue = fromIntegral $ C.selectLovelace $ txOutValue src
, flowLinkOwner = owner knownKeys src
, flowLinkSourceLoc = sourceLoc
, flowLinkTargetLoc = tgtLoc
}
zipWithIndex = zip [1..]
| Annotate the ' TxOutRef 's produced by a transaction with the location of the transaction .
outRefsWithLoc :: UtxoLocation -> OnChainTx -> [(TxOutRef, UtxoLocation)]
outRefsWithLoc loc (Valid tx) = (\txo -> (snd txo, loc)) <$> getCardanoTxOutRefs tx
outRefsWithLoc _ (Invalid _) = []
-- | Create a 'TxRef' from a 'TxOutRef'.
utxoTargets :: TxOutRef -> TxRef
utxoTargets (TxOutRef rf idx) = TxRef $ Text.unwords ["utxo", Text.pack $ take 8 $ show $ getTxId rf, Text.pack $ show idx]
| null | https://raw.githubusercontent.com/input-output-hk/plutus-apps/e8688b8f86a92b285e7d93eb418ccc314ad41bf9/plutus-contract/src/Wallet/Graph.hs | haskell | # LANGUAGE DeriveAnyClass #
# LANGUAGE OverloadedStrings #
| Support for visualisation of a blockchain as a graph.
| The owner of an unspent transaction output.
^ Funds owned by a known public key.
^ Funds locked by script.
^ All other funds (that is, funds owned by a public key we are not interested in).
| Given a set of known public keys, compute the owner of a given transaction output.
block in the chain, and the index of the transaction within the block.
| A link in the flow graph.
^ The source transaction.
^ The target transaction.
^ The owner of this edge.
^ The location of the source transaction.
^ The location of the target transaction, if 'Nothing' then it is unspent.
| The flow graph, consisting of a set of nodes ('TxRef's) and edges ('FlowLink's).
| Construct a graph from a list of 'FlowLink's.
make a flow for a TxOutRef
| Create a 'TxRef' from a 'TxOutRef'. | # LANGUAGE DeriveGeneric #
# LANGUAGE RecordWildCards #
# OPTIONS_GHC -fno - warn - incomplete - uni - patterns #
module Wallet.Graph
( txnFlows
, graph
, FlowGraph
, FlowLink
, TxRef
, UtxOwner
, UtxoLocation
) where
import Data.Aeson.Types (ToJSON, toJSON)
import Data.List (nub)
import Data.Map qualified as Map
import Data.Maybe (catMaybes)
import Data.Set qualified as Set
import Data.Text qualified as Text
import GHC.Generics (Generic)
import Cardano.Api qualified as C
import Ledger.Address
import Ledger.Blockchain
import Ledger.Credential (Credential (..))
import Ledger.Crypto
import Ledger.Tx
data UtxOwner
= PubKeyOwner PubKey
| ScriptOwner
| OtherOwner
deriving (Eq, Ord, Show, Generic, ToJSON)
owner :: Set.Set PubKey -> TxOut -> UtxOwner
owner keys tx =
let hashMap = foldMap (\pk -> Map.singleton (pubKeyHash pk) pk) keys
in case cardanoAddressCredential (txOutAddress tx) of
ScriptCredential{} -> ScriptOwner
PubKeyCredential pkh | Just pk <- Map.lookup pkh hashMap -> PubKeyOwner pk
_ -> OtherOwner
| A wrapper around the first 8 digits of a ' TxId ' .
newtype TxRef =
TxRef Text.Text
deriving (Eq, Ord, Show, Generic)
instance ToJSON TxRef where
toJSON (TxRef t) = toJSON t
mkRef :: TxId -> TxRef
mkRef = TxRef . Text.pack . take 8 . show . getTxId
| The location of a transaction in a blockchain specified by two indices : the index of the containing
data UtxoLocation = UtxoLocation
{ utxoLocBlock :: Integer
, utxoLocBlockIdx :: Integer
} deriving (Eq, Ord, Show, Generic, ToJSON)
data FlowLink = FlowLink
^ The value of along this edge .
} deriving (Show, Generic, ToJSON)
data FlowGraph = FlowGraph
{ flowGraphLinks :: [FlowLink]
, flowGraphNodes :: [TxRef]
} deriving (Show, Generic, ToJSON)
graph :: [FlowLink] -> FlowGraph
graph lnks = FlowGraph {..}
where
flowGraphLinks = lnks
flowGraphNodes = nub $ fmap flowLinkSource lnks ++ fmap flowLinkTarget lnks
| Compute the ' FlowLink 's for a ' Blockchain ' given a set of known ' PubKey 's .
txnFlows :: [PubKey] -> Blockchain -> [FlowLink]
txnFlows keys bc = catMaybes (utxoLinks ++ foldMap extract bc')
where
bc' = foldMap (\(blockNum, txns) -> fmap (\(blockIdx, txn) -> (UtxoLocation blockNum blockIdx, txn)) txns) $ zipWithIndex $ zipWithIndex <$> reverse bc
sourceLocations :: Map.Map TxOutRef UtxoLocation
sourceLocations = Map.fromList $ foldMap (uncurry outRefsWithLoc) bc'
knownKeys :: Set.Set PubKey
knownKeys = Set.fromList keys
utxos = fmap fst $ Map.toList $ unspentOutputs bc
utxoLinks = uncurry (flow Nothing) <$> zip (utxoTargets <$> utxos) utxos
extract :: (UtxoLocation, OnChainTx) -> [Maybe FlowLink]
extract (loc, tx) =
let targetRef = mkRef $ getCardanoTxId $ unOnChain tx in
fmap (flow (Just loc) targetRef . txInRef) (consumableInputs tx)
flow :: Maybe UtxoLocation -> TxRef -> TxOutRef -> Maybe FlowLink
flow tgtLoc tgtRef rf = do
src <- out bc rf
sourceLoc <- Map.lookup rf sourceLocations
let sourceRef = mkRef $ txOutRefId rf
pure FlowLink
{ flowLinkSource = sourceRef
, flowLinkTarget = tgtRef
, flowLinkValue = fromIntegral $ C.selectLovelace $ txOutValue src
, flowLinkOwner = owner knownKeys src
, flowLinkSourceLoc = sourceLoc
, flowLinkTargetLoc = tgtLoc
}
zipWithIndex = zip [1..]
| Annotate the ' TxOutRef 's produced by a transaction with the location of the transaction .
outRefsWithLoc :: UtxoLocation -> OnChainTx -> [(TxOutRef, UtxoLocation)]
outRefsWithLoc loc (Valid tx) = (\txo -> (snd txo, loc)) <$> getCardanoTxOutRefs tx
outRefsWithLoc _ (Invalid _) = []
utxoTargets :: TxOutRef -> TxRef
utxoTargets (TxOutRef rf idx) = TxRef $ Text.unwords ["utxo", Text.pack $ take 8 $ show $ getTxId rf, Text.pack $ show idx]
|
5c65617ea816ec4d80d74a4ac0c58ffd0be876f87883ad9033c32f13bd4111b9 | fyquah/hardcaml_zprize | ark_bls12_377_g1.ml | open Core
open Ctypes
open Foreign
let sexp_of_z z = Sexp.Atom ("0x" ^ Z.format "x" z)
module External = struct
let potential_dl_filenames =
(* The more principled thing to do is to figure out the build-target and
* use .so or .dylib.. but this works well enough.
* *)
let%bind.List extension = [ "so"; "dylib" ] in
let%bind.List dir =
CR - someday : This is getting out of hand ! refactor to keep
* looking until root and terminate dynamically .
* looking until root and terminate dynamically.
*)
[ "."
; "../"
; "../../"
; "../../../"
; "../../../.."
; "../../../../.."
; "../../../../../../"
; "../../../../../../../"
; "../../../../../../../../"
; "../../../../../../../../../"
]
in
[ dir ^/ "libs/rust/ark_bls12_377_g1/target/debug/libark_bls12_377_g1." ^ extension ]
;;
let () =
Unfortunately , We ca n't install Core_unix on M1 Macs , so we are stuck
* with . , rather than Sys_unix , for the time - being .
* with Caml.Sys, rather than Sys_unix, for the time-being.
*)
let filename =
match List.find potential_dl_filenames ~f:Caml.Sys.file_exists with
| Some filename -> filename
| None ->
failwith
"Cannot find Rust ark_bls12_377_g1 - did you build it? Run `cargo build` in \
rust/ark_bls12_377_g1 first."
in
ignore (Dl.dlopen ~filename ~flags:[ RTLD_LAZY; RTLD_GLOBAL ] : Dl.library)
;;
type affine = unit ptr
let affine : affine typ = ptr void
let free = foreign "ark_bls12_377_g1_free" (ptr affine @-> returning void)
let new_ =
foreign
"ark_bls12_377_g1_new"
(ptr int64_t @-> ptr int64_t @-> bool @-> returning (ptr affine))
;;
let add =
foreign "ark_bls12_377_add" (ptr affine @-> ptr affine @-> returning (ptr affine))
;;
let neg = foreign "ark_bls12_377_g1_neg" (ptr affine @-> returning (ptr affine))
let mul = foreign "ark_bls12_377_mul" (ptr affine @-> int64_t @-> returning (ptr affine))
let subgroup_generator =
foreign "ark_bls12_377_g1_subgroup_generator" (void @-> returning (ptr affine))
;;
let coeff_a = foreign "ark_bls12_377_g1_coeff_a" (ptr int64_t @-> returning void)
let coeff_b = foreign "ark_bls12_377_g1_coeff_b" (ptr int64_t @-> returning void)
let modulus = foreign "ark_bls12_377_g1_modulus" (ptr int64_t @-> returning void)
let get_x =
foreign "ark_bls12_377_g1_get_x" (ptr affine @-> ptr int64_t @-> returning void)
;;
let get_y =
foreign "ark_bls12_377_g1_get_y" (ptr affine @-> ptr int64_t @-> returning void)
;;
let get_infinity =
foreign "ark_bls12_377_g1_get_infinity" (ptr affine @-> returning bool)
;;
let is_on_curve = foreign "ark_bls12_377_g1_is_on_curve" (ptr affine @-> returning bool)
let equal =
foreign "ark_bls12_377_g1_equal" (ptr affine @-> ptr affine @-> returning bool)
;;
end
type affine = External.affine ptr
let bits_of_z z =
let arr = CArray.of_list int64_t [ 0L; 0L; 0L; 0L; 0L; 0L ] in
let z = Z.to_bits z in
let get_word i =
let b o =
let pos = (i * 8) + o in
if pos >= String.length z
then 0L
else (
let shift = o * 8 in
Int64.(of_int (Char.to_int z.[pos]) lsl shift))
in
Int64.O.(b 0 lor b 1 lor b 2 lor b 3 lor b 4 lor b 5 lor b 6 lor b 7)
in
for i = 0 to 5 do
CArray.unsafe_set arr i (get_word i)
done;
arr
;;
let create ~x ~y ~infinity =
let x = bits_of_z x in
let y = bits_of_z y in
let ptr = External.new_ (CArray.start x) (CArray.start y) infinity in
Caml.Gc.finalise External.free ptr;
ptr
;;
let subgroup_generator () =
let ptr = External.subgroup_generator () in
Caml.Gc.finalise External.free ptr;
ptr
;;
let add (a : affine) (b : affine) =
let ptr = External.add a b in
Caml.Gc.finalise External.free ptr;
ptr
;;
let neg (a : affine) =
let ptr = External.neg a in
Caml.Gc.finalise External.free ptr;
ptr
;;
let mul (a : affine) ~by =
assert (Int.is_non_negative by);
let ptr = External.mul a (Int64.of_int by) in
Caml.Gc.finalise External.free ptr;
ptr
;;
let buffer_to_z arr =
String.init (8 * 6) ~f:(fun i ->
let word = i / 8 in
let shift = i % 8 * 8 in
Int64.O.((CArray.get arr word lsr shift) land 0xFFL)
|> Int64.to_int_trunc
|> Char.of_int_exn)
|> Z.of_bits
;;
let create_buffer () = CArray.of_list int64_t [ 0L; 0L; 0L; 0L; 0L; 0L ]
let x (t : affine) =
let buffer = create_buffer () in
External.get_x t (CArray.start buffer);
buffer_to_z buffer
;;
let y (t : affine) =
let buffer = create_buffer () in
External.get_y t (CArray.start buffer);
buffer_to_z buffer
;;
let is_on_curve t = External.is_on_curve t
let infinity t = External.get_infinity t
let equal_affine a b = External.equal a b
let sexp_of_affine affine =
let x = x affine in
let y = y affine in
let infinity = infinity affine in
[%message (x : z) (y : z) (infinity : bool)]
;;
let create_coeff f =
let l =
lazy
(let buffer = create_buffer () in
f (CArray.start buffer);
buffer_to_z buffer)
in
fun () -> Lazy.force l
;;
let coeff_a = create_coeff External.coeff_a
let coeff_b = create_coeff External.coeff_b
let modulus = create_coeff External.modulus
let mul_wide ~part_width a ~by:b =
let open Hardcaml in
let scale = 1 lsl part_width in
let b =
Bits.split_lsb ~part_width ~exact:false b |> List.map ~f:Bits.to_int |> List.rev
in
let rec f acc b =
match b with
| [] -> Option.value_exn acc
| b :: tl ->
let a_by_b = mul a ~by:b in
(match acc with
| None -> f (Some a_by_b) tl
| Some acc ->
let acc = mul acc ~by:scale in
f (Some (add acc a_by_b)) tl)
in
f None b
;;
module For_testing = struct
let sexp_of_z = sexp_of_z
end
| null | https://raw.githubusercontent.com/fyquah/hardcaml_zprize/553b1be10ae9b977decbca850df6ee2d0595e7ff/libs/ark_bls12_377_g1/src/ark_bls12_377_g1.ml | ocaml | The more principled thing to do is to figure out the build-target and
* use .so or .dylib.. but this works well enough.
* | open Core
open Ctypes
open Foreign
let sexp_of_z z = Sexp.Atom ("0x" ^ Z.format "x" z)
module External = struct
let potential_dl_filenames =
let%bind.List extension = [ "so"; "dylib" ] in
let%bind.List dir =
CR - someday : This is getting out of hand ! refactor to keep
* looking until root and terminate dynamically .
* looking until root and terminate dynamically.
*)
[ "."
; "../"
; "../../"
; "../../../"
; "../../../.."
; "../../../../.."
; "../../../../../../"
; "../../../../../../../"
; "../../../../../../../../"
; "../../../../../../../../../"
]
in
[ dir ^/ "libs/rust/ark_bls12_377_g1/target/debug/libark_bls12_377_g1." ^ extension ]
;;
let () =
Unfortunately , We ca n't install Core_unix on M1 Macs , so we are stuck
* with . , rather than Sys_unix , for the time - being .
* with Caml.Sys, rather than Sys_unix, for the time-being.
*)
let filename =
match List.find potential_dl_filenames ~f:Caml.Sys.file_exists with
| Some filename -> filename
| None ->
failwith
"Cannot find Rust ark_bls12_377_g1 - did you build it? Run `cargo build` in \
rust/ark_bls12_377_g1 first."
in
ignore (Dl.dlopen ~filename ~flags:[ RTLD_LAZY; RTLD_GLOBAL ] : Dl.library)
;;
type affine = unit ptr
let affine : affine typ = ptr void
let free = foreign "ark_bls12_377_g1_free" (ptr affine @-> returning void)
let new_ =
foreign
"ark_bls12_377_g1_new"
(ptr int64_t @-> ptr int64_t @-> bool @-> returning (ptr affine))
;;
let add =
foreign "ark_bls12_377_add" (ptr affine @-> ptr affine @-> returning (ptr affine))
;;
let neg = foreign "ark_bls12_377_g1_neg" (ptr affine @-> returning (ptr affine))
let mul = foreign "ark_bls12_377_mul" (ptr affine @-> int64_t @-> returning (ptr affine))
let subgroup_generator =
foreign "ark_bls12_377_g1_subgroup_generator" (void @-> returning (ptr affine))
;;
let coeff_a = foreign "ark_bls12_377_g1_coeff_a" (ptr int64_t @-> returning void)
let coeff_b = foreign "ark_bls12_377_g1_coeff_b" (ptr int64_t @-> returning void)
let modulus = foreign "ark_bls12_377_g1_modulus" (ptr int64_t @-> returning void)
let get_x =
foreign "ark_bls12_377_g1_get_x" (ptr affine @-> ptr int64_t @-> returning void)
;;
let get_y =
foreign "ark_bls12_377_g1_get_y" (ptr affine @-> ptr int64_t @-> returning void)
;;
let get_infinity =
foreign "ark_bls12_377_g1_get_infinity" (ptr affine @-> returning bool)
;;
let is_on_curve = foreign "ark_bls12_377_g1_is_on_curve" (ptr affine @-> returning bool)
let equal =
foreign "ark_bls12_377_g1_equal" (ptr affine @-> ptr affine @-> returning bool)
;;
end
type affine = External.affine ptr
let bits_of_z z =
let arr = CArray.of_list int64_t [ 0L; 0L; 0L; 0L; 0L; 0L ] in
let z = Z.to_bits z in
let get_word i =
let b o =
let pos = (i * 8) + o in
if pos >= String.length z
then 0L
else (
let shift = o * 8 in
Int64.(of_int (Char.to_int z.[pos]) lsl shift))
in
Int64.O.(b 0 lor b 1 lor b 2 lor b 3 lor b 4 lor b 5 lor b 6 lor b 7)
in
for i = 0 to 5 do
CArray.unsafe_set arr i (get_word i)
done;
arr
;;
let create ~x ~y ~infinity =
let x = bits_of_z x in
let y = bits_of_z y in
let ptr = External.new_ (CArray.start x) (CArray.start y) infinity in
Caml.Gc.finalise External.free ptr;
ptr
;;
let subgroup_generator () =
let ptr = External.subgroup_generator () in
Caml.Gc.finalise External.free ptr;
ptr
;;
let add (a : affine) (b : affine) =
let ptr = External.add a b in
Caml.Gc.finalise External.free ptr;
ptr
;;
let neg (a : affine) =
let ptr = External.neg a in
Caml.Gc.finalise External.free ptr;
ptr
;;
let mul (a : affine) ~by =
assert (Int.is_non_negative by);
let ptr = External.mul a (Int64.of_int by) in
Caml.Gc.finalise External.free ptr;
ptr
;;
let buffer_to_z arr =
String.init (8 * 6) ~f:(fun i ->
let word = i / 8 in
let shift = i % 8 * 8 in
Int64.O.((CArray.get arr word lsr shift) land 0xFFL)
|> Int64.to_int_trunc
|> Char.of_int_exn)
|> Z.of_bits
;;
let create_buffer () = CArray.of_list int64_t [ 0L; 0L; 0L; 0L; 0L; 0L ]
let x (t : affine) =
let buffer = create_buffer () in
External.get_x t (CArray.start buffer);
buffer_to_z buffer
;;
let y (t : affine) =
let buffer = create_buffer () in
External.get_y t (CArray.start buffer);
buffer_to_z buffer
;;
let is_on_curve t = External.is_on_curve t
let infinity t = External.get_infinity t
let equal_affine a b = External.equal a b
let sexp_of_affine affine =
let x = x affine in
let y = y affine in
let infinity = infinity affine in
[%message (x : z) (y : z) (infinity : bool)]
;;
let create_coeff f =
let l =
lazy
(let buffer = create_buffer () in
f (CArray.start buffer);
buffer_to_z buffer)
in
fun () -> Lazy.force l
;;
let coeff_a = create_coeff External.coeff_a
let coeff_b = create_coeff External.coeff_b
let modulus = create_coeff External.modulus
let mul_wide ~part_width a ~by:b =
let open Hardcaml in
let scale = 1 lsl part_width in
let b =
Bits.split_lsb ~part_width ~exact:false b |> List.map ~f:Bits.to_int |> List.rev
in
let rec f acc b =
match b with
| [] -> Option.value_exn acc
| b :: tl ->
let a_by_b = mul a ~by:b in
(match acc with
| None -> f (Some a_by_b) tl
| Some acc ->
let acc = mul acc ~by:scale in
f (Some (add acc a_by_b)) tl)
in
f None b
;;
module For_testing = struct
let sexp_of_z = sexp_of_z
end
|
fc824c4746d1d3d9b3ded0e3bc36f4d8f558fe65386fac13d5eb32e74cc38cd9 | tmfg/mmtis-national-access-point | detection_test_days.clj | (ns ote.transit-changes.detection-test-days
(:require [ote.transit-changes.detection :as detection]
[clojure.test :as t :refer [deftest testing is]]
[clojure.spec.test.alpha :as spec-test]
[ote.transit-changes :as transit-changes]
[ote.transit-changes.detection-test-utilities :as tu]
[ote.time :as time]))
TESTS for analysing changes in traffic between specific days
Day hash data for changes for a default week with ONE kind of day hashes
(def data-wk-hash-one-kind ["A" "A" "A" "A" "A" "A" "A"])
(def data-wk-hash-one-kind-change-one ["A" "A" "3" "3" "3" "3" "3"])
(def data-wk-hash-one-kind-change-two ["A" "A" "3" "3" "3" "3" "7"])
Day hash data for changes for a default week with TWO kind of day hashes
(def data-wk-hash-two-kind ["A" "A" "A" "A" "A" "B" "B" ])
(def data-wk-hash-two-kind-one-nil ["A" "A" "A" nil "A" "B" "B" ])
(def data-wk-hash-two-kind-change-one ["A" "A" "A" "A" "A" "5" "5" ])
(def data-wk-hash-two-kind-change-two ["1" "1" "1" "1" "1" "5" "5" ])
(def data-wk-hash-two-kind-holiday [:holiday1 "A" "A" "A" "A" "B" "B" ])
(def data-wk-hash-traffic-weekdays-nil-weekend-traffic [nil nil nil nil nil "C5" "C6"])
(def data-wk-hash-traffic-nil [nil nil nil nil nil nil nil])
(def data-wk-hash-two-kind-on-weekend ["A" "A" "A" "A" "A" "D" "E" ])
(def data-wk-hash-traffic-weekdays-nil-weekend-nil [nil nil nil nil nil "D2" "E2"])
Day hash data for changes for a default week with FIVE kind of day hashes
(def data-wk-hash-five-kind ["A" "B" "B" "B" "F" "G" "H"])
(def data-wk-hash-five-kind-change-four ["A" "2" "5" "5" "5" "6" "7"])
(def data-wk-hash-seven-kind ["A" "C" "D" "E" "F" "G" "H"])
(def data-wk-hash-five-kind-change-seven ["1" "2" "3" "4" "5" "6" "7"])
(def data-wk-hash-two-kind-nil ["A" "A" "A" "A" nil "B" "B" ])
(def data-wk-hash-two-kind-nil-and-holiday ["A" "A" "A" "A" :some-holiday nil "B" ])
(def data-wk-hash-two-kind-nil-and-holiday-changed ["A" "A" "A" "A" "4" "5" "6" ])
(def data-wk-hash-two-kind-nil-changed-and-holiday ["B" "B" :some-holiday "B" "B" "B" "B" ])
(deftest test-changed-days-of-week
(testing "One kind of traffic, changes: 0"
(is (= [] (transit-changes/changed-days-of-week data-wk-hash-one-kind data-wk-hash-one-kind))))
(testing "One kind of traffic, changes: 1"
(is (= [2] (transit-changes/changed-days-of-week data-wk-hash-one-kind data-wk-hash-one-kind-change-one))))
(testing "One kind of traffic, changes: 3"
(is (= [2 6] (transit-changes/changed-days-of-week data-wk-hash-one-kind data-wk-hash-one-kind-change-two))))
(testing "Two kinds of traffic, changes: 1 (weekend)"
(is (= [5] (transit-changes/changed-days-of-week data-wk-hash-two-kind data-wk-hash-two-kind-change-one))))
(testing "Two kinds of traffic, changes: 2 (weekend+week)"
(is (= [0 5] (transit-changes/changed-days-of-week data-wk-hash-two-kind data-wk-hash-two-kind-change-two))))
(testing "Two kinds of traffic, changes to nil on weekdays, different on weekend"
(is (= [0 5 6] (transit-changes/changed-days-of-week data-wk-hash-two-kind data-wk-hash-traffic-weekdays-nil-weekend-traffic))))
(testing "Two kinds of traffic, changes to all nil"
(is (= [0 5] (transit-changes/changed-days-of-week data-wk-hash-two-kind data-wk-hash-traffic-nil))))
(testing "Two kinds of traffic, changes to one nil"
(is (= [3] (transit-changes/changed-days-of-week data-wk-hash-two-kind data-wk-hash-two-kind-one-nil))))
(testing "Five kinds of traffic, changes: 0"
(is (= [] (transit-changes/changed-days-of-week data-wk-hash-five-kind data-wk-hash-five-kind))))
(testing "Five kinds of traffic, changes: 5"
(is (= [1 2 4 5 6] (transit-changes/changed-days-of-week data-wk-hash-five-kind data-wk-hash-five-kind-change-four))))
(testing "Seven kinds of traffic, changes: 7"
(is (= [0 1 2 3 4 5 6] (transit-changes/changed-days-of-week data-wk-hash-seven-kind data-wk-hash-five-kind-change-seven))))
(testing "Two kinds of traffic, changes to nil on weekdays, different on weekend2"
(is (= [0 5 6] (transit-changes/changed-days-of-week data-wk-hash-two-kind-on-weekend data-wk-hash-traffic-weekdays-nil-weekend-nil)))))
(deftest test-changed-days-holidays
(testing "Two kinds of traffic with nil, changes to one kind with holiday"
(is (= [0 4] (transit-changes/changed-days-of-week data-wk-hash-two-kind-nil data-wk-hash-two-kind-nil-changed-and-holiday))))
(testing "Two kinds of traffic with holiday on baseline, ensure no change is detected"
(is (= [] (transit-changes/changed-days-of-week data-wk-hash-two-kind-holiday data-wk-hash-two-kind-holiday))))
(testing "Two kinds of traffic with holiday on new week, ensure no change is detected"
(is (= [] (transit-changes/changed-days-of-week data-wk-hash-two-kind-holiday data-wk-hash-two-kind-holiday))))
(testing "Two kinds of traffic with holiday on baseline, ensure change is detected"
(is (= [1 5] (transit-changes/changed-days-of-week data-wk-hash-two-kind-holiday data-wk-hash-two-kind-change-two))))
(testing "Two kinds of traffic with holiday and nil on baseline, ensure change is detected"
(is (= [5 6] (transit-changes/changed-days-of-week data-wk-hash-two-kind-nil-and-holiday data-wk-hash-two-kind-nil-and-holiday-changed)))))
| null | https://raw.githubusercontent.com/tmfg/mmtis-national-access-point/a86cc890ffa1fe4f773083be5d2556e87a93d975/ote/test/clj/ote/transit_changes/detection_test_days.clj | clojure | (ns ote.transit-changes.detection-test-days
(:require [ote.transit-changes.detection :as detection]
[clojure.test :as t :refer [deftest testing is]]
[clojure.spec.test.alpha :as spec-test]
[ote.transit-changes :as transit-changes]
[ote.transit-changes.detection-test-utilities :as tu]
[ote.time :as time]))
TESTS for analysing changes in traffic between specific days
Day hash data for changes for a default week with ONE kind of day hashes
(def data-wk-hash-one-kind ["A" "A" "A" "A" "A" "A" "A"])
(def data-wk-hash-one-kind-change-one ["A" "A" "3" "3" "3" "3" "3"])
(def data-wk-hash-one-kind-change-two ["A" "A" "3" "3" "3" "3" "7"])
Day hash data for changes for a default week with TWO kind of day hashes
(def data-wk-hash-two-kind ["A" "A" "A" "A" "A" "B" "B" ])
(def data-wk-hash-two-kind-one-nil ["A" "A" "A" nil "A" "B" "B" ])
(def data-wk-hash-two-kind-change-one ["A" "A" "A" "A" "A" "5" "5" ])
(def data-wk-hash-two-kind-change-two ["1" "1" "1" "1" "1" "5" "5" ])
(def data-wk-hash-two-kind-holiday [:holiday1 "A" "A" "A" "A" "B" "B" ])
(def data-wk-hash-traffic-weekdays-nil-weekend-traffic [nil nil nil nil nil "C5" "C6"])
(def data-wk-hash-traffic-nil [nil nil nil nil nil nil nil])
(def data-wk-hash-two-kind-on-weekend ["A" "A" "A" "A" "A" "D" "E" ])
(def data-wk-hash-traffic-weekdays-nil-weekend-nil [nil nil nil nil nil "D2" "E2"])
Day hash data for changes for a default week with FIVE kind of day hashes
(def data-wk-hash-five-kind ["A" "B" "B" "B" "F" "G" "H"])
(def data-wk-hash-five-kind-change-four ["A" "2" "5" "5" "5" "6" "7"])
(def data-wk-hash-seven-kind ["A" "C" "D" "E" "F" "G" "H"])
(def data-wk-hash-five-kind-change-seven ["1" "2" "3" "4" "5" "6" "7"])
(def data-wk-hash-two-kind-nil ["A" "A" "A" "A" nil "B" "B" ])
(def data-wk-hash-two-kind-nil-and-holiday ["A" "A" "A" "A" :some-holiday nil "B" ])
(def data-wk-hash-two-kind-nil-and-holiday-changed ["A" "A" "A" "A" "4" "5" "6" ])
(def data-wk-hash-two-kind-nil-changed-and-holiday ["B" "B" :some-holiday "B" "B" "B" "B" ])
(deftest test-changed-days-of-week
(testing "One kind of traffic, changes: 0"
(is (= [] (transit-changes/changed-days-of-week data-wk-hash-one-kind data-wk-hash-one-kind))))
(testing "One kind of traffic, changes: 1"
(is (= [2] (transit-changes/changed-days-of-week data-wk-hash-one-kind data-wk-hash-one-kind-change-one))))
(testing "One kind of traffic, changes: 3"
(is (= [2 6] (transit-changes/changed-days-of-week data-wk-hash-one-kind data-wk-hash-one-kind-change-two))))
(testing "Two kinds of traffic, changes: 1 (weekend)"
(is (= [5] (transit-changes/changed-days-of-week data-wk-hash-two-kind data-wk-hash-two-kind-change-one))))
(testing "Two kinds of traffic, changes: 2 (weekend+week)"
(is (= [0 5] (transit-changes/changed-days-of-week data-wk-hash-two-kind data-wk-hash-two-kind-change-two))))
(testing "Two kinds of traffic, changes to nil on weekdays, different on weekend"
(is (= [0 5 6] (transit-changes/changed-days-of-week data-wk-hash-two-kind data-wk-hash-traffic-weekdays-nil-weekend-traffic))))
(testing "Two kinds of traffic, changes to all nil"
(is (= [0 5] (transit-changes/changed-days-of-week data-wk-hash-two-kind data-wk-hash-traffic-nil))))
(testing "Two kinds of traffic, changes to one nil"
(is (= [3] (transit-changes/changed-days-of-week data-wk-hash-two-kind data-wk-hash-two-kind-one-nil))))
(testing "Five kinds of traffic, changes: 0"
(is (= [] (transit-changes/changed-days-of-week data-wk-hash-five-kind data-wk-hash-five-kind))))
(testing "Five kinds of traffic, changes: 5"
(is (= [1 2 4 5 6] (transit-changes/changed-days-of-week data-wk-hash-five-kind data-wk-hash-five-kind-change-four))))
(testing "Seven kinds of traffic, changes: 7"
(is (= [0 1 2 3 4 5 6] (transit-changes/changed-days-of-week data-wk-hash-seven-kind data-wk-hash-five-kind-change-seven))))
(testing "Two kinds of traffic, changes to nil on weekdays, different on weekend2"
(is (= [0 5 6] (transit-changes/changed-days-of-week data-wk-hash-two-kind-on-weekend data-wk-hash-traffic-weekdays-nil-weekend-nil)))))
(deftest test-changed-days-holidays
(testing "Two kinds of traffic with nil, changes to one kind with holiday"
(is (= [0 4] (transit-changes/changed-days-of-week data-wk-hash-two-kind-nil data-wk-hash-two-kind-nil-changed-and-holiday))))
(testing "Two kinds of traffic with holiday on baseline, ensure no change is detected"
(is (= [] (transit-changes/changed-days-of-week data-wk-hash-two-kind-holiday data-wk-hash-two-kind-holiday))))
(testing "Two kinds of traffic with holiday on new week, ensure no change is detected"
(is (= [] (transit-changes/changed-days-of-week data-wk-hash-two-kind-holiday data-wk-hash-two-kind-holiday))))
(testing "Two kinds of traffic with holiday on baseline, ensure change is detected"
(is (= [1 5] (transit-changes/changed-days-of-week data-wk-hash-two-kind-holiday data-wk-hash-two-kind-change-two))))
(testing "Two kinds of traffic with holiday and nil on baseline, ensure change is detected"
(is (= [5 6] (transit-changes/changed-days-of-week data-wk-hash-two-kind-nil-and-holiday data-wk-hash-two-kind-nil-and-holiday-changed)))))
| |
4ec72a08c4fe52d54a7e34f882839c67b68301cf8e90a24fd15681d3d07c433e | nikivazou/verified_string_matching | shiftNewIndices.hs | #ifdef IncludedmakeNewIndicesNullLeft
#else
#include "../AutoProofs/makeNewIndicesNullLeft.hs"
#endif
#ifdef IncludedmakeNewIndicesNullRight
#else
#include "../AutoProofs/makeNewIndicesNullRight.hs"
#endif
#ifdef IncludedmapShiftZero
#else
#include "../AutoProofs/mapShiftZero.hs"
#endif
#ifdef IncludedmakeIndicesNull
#else
#include "../AutoProofs/makeIndicesNull.hs"
#endif
#ifdef IncludedcatIndices
#else
#include "../AutoProofs/catIndices.hs"
#endif
#ifdef IncludedmergeIndices
#else
#include "../AutoProofs/mergeIndices.hs"
#endif
#ifdef IncludedmapCastId
#else
#include "../AutoProofs/mapCastId.hs"
#endif
-------------------------------------------------------------------------------
-------- Lemmata on Shifting Indices ---------------------------------------
-------------------------------------------------------------------------------
@ shiftNewIndices
: : xi : RString
- > yi : RString
- > zi : RString
- > tg:{RString | stringLen yi < stringLen tg }
- > { append ( makeNewIndices xi ( yi < + > zi ) tg ) ( map ( shiftStringRight tg xi ( yi < + > zi ) ) ( makeNewIndices tg ) )
= = append ( map ( castGoodIndexRight tg ( xi < + > yi ) ) ( makeNewIndices xi yi tg ) ) ( makeNewIndices ( xi < + > yi ) tg )
}
@
:: xi:RString
-> yi:RString
-> zi:RString
-> tg:{RString | stringLen yi < stringLen tg }
-> { append (makeNewIndices xi (yi <+> zi) tg) (map (shiftStringRight tg xi (yi <+> zi)) (makeNewIndices yi zi tg))
== append (map (castGoodIndexRight tg (xi <+> yi) zi) (makeNewIndices xi yi tg)) (makeNewIndices (xi <+> yi) zi tg)
}
@-}
shiftNewIndices :: RString -> RString -> RString -> RString -> Proof
shiftNewIndices xi yi zi tg
| stringLen tg < 2
= append (makeNewIndices xi yzi tg) (map (shiftStringRight tg xi yzi) (makeNewIndices yi zi tg))
==. append N (map (shiftStringRight tg xi yzi) N)
==. map (shiftStringRight tg xi yzi) N
==. N
==. append N N
==. append (makeNewIndices xi yi tg) (makeNewIndices xyi zi tg)
==. append (map (castGoodIndexRight tg xyi zi) (makeNewIndices xi yi tg)) (makeNewIndices xyi zi tg)
? mapCastId tg xyi zi (makeNewIndices xi yi tg)
*** QED
where
yzi = yi <+> zi
xyi = xi <+> yi
xyziL = xyi <+> zi
shiftNewIndices xi yi zi tg
| stringLen xi == 0
= append (makeNewIndices xi yzi tg)
(map (shiftStringRight tg xi yzi) (makeNewIndices yi zi tg))
==. append (makeNewIndices stringEmp yzi tg)
(map (shiftStringRight tg xi yzi) (makeNewIndices yi zi tg))
? stringEmpProp xi
==. append (makeNewIndices stringEmp yzi tg)
(map (shiftStringRight tg xi yzi) (makeNewIndices yi zi tg))
? makeNewIndicesNullRight yzi tg
==. append N
(map (shiftStringRight tg xi yzi) (makeNewIndices yi zi tg))
==. map (shiftStringRight tg xi yzi) (makeNewIndices yi zi tg)
? stringEmpProp xi
==. map (shiftStringRight tg stringEmp yzi) (makeNewIndices yi zi tg)
? mapShiftZero tg yzi (makeNewIndices yi zi tg)
==. makeNewIndices yi zi tg
==. makeNewIndices xyi zi tg
? concatEmpLeft xi yi
==. append N (makeNewIndices xyi zi tg)
==. append (makeNewIndices stringEmp yi tg) (makeNewIndices xyi zi tg)
? makeNewIndicesNullRight yi tg
==. append (makeNewIndices xi yi tg) (makeNewIndices xyi zi tg)
? stringEmpProp xi
==. append (map (castGoodIndexRight tg xyi zi) (makeNewIndices xi yi tg)) (makeNewIndices xyi zi tg)
? mapCastId tg xyi zi (makeNewIndices xi yi tg)
*** QED
| stringLen yi == 0
= append (makeNewIndices xi yzi tg)
(map (shiftStringRight tg xi yzi) (makeNewIndices yi zi tg))
==. append (makeNewIndices xi zi tg)
(map (shiftStringRight tg xi yzi) (makeNewIndices yi zi tg))
?(stringEmpProp yi &&& concatEmpLeft yi zi)
==. append (makeNewIndices xi zi tg)
(map (shiftStringRight tg xi zi) (makeNewIndices stringEmp zi tg))
==. append (makeNewIndices xi zi tg)
(map (shiftStringRight tg xi (stringEmp <+> zi)) N)
?makeNewIndicesNullRight zi tg
==. append (makeNewIndices xi zi tg) N
==. makeNewIndices xi zi tg
?listLeftId (makeNewIndices xi zi tg)
==. makeNewIndices xyi zi tg
?concatEmpRight xi yi
==. append N (makeNewIndices xyi zi tg)
==. append (makeNewIndices xi stringEmp tg) (makeNewIndices xyi zi tg)
?makeNewIndicesNullLeft xi tg
==. append (makeNewIndices xi yi tg) (makeNewIndices xyi zi tg)
==. append (map (castGoodIndexRight tg xyi zi) (makeNewIndices xi yi tg)) (makeNewIndices xyi zi tg)
? (stringEmpProp yi &&& mapCastId tg xyi zi (makeNewIndices xi yi tg))
*** QED
| stringLen yi - stringLen tg == - 1
= append (makeNewIndices xi yzi tg)
(map (shiftStringRight tg xi yzi) (makeNewIndices yi zi tg))
==. append (makeIndices xyziR tg loxi hixi)
(map (shiftStringRight tg xi yzi) (makeIndices yzi tg loyi hiyi))
==. append (makeIndices xyziR tg loxi hixi)
(makeIndices xyziR tg midxyi hixyi)
?shiftIndicesRight loyi hiyi xi yzi tg
==. append (makeIndices xyziL tg loxi hixi)
(makeIndices xyziL tg midxyi hixyi)
?concatStringAssoc xi yi zi
==. append (append (makeIndices xyziR tg loxi midxi)
(makeIndices xyziR tg (midxi+1) hixi))
(makeIndices xyziR tg midxyi hixyi)
?mergeIndices xyziL tg loxi midxi hixi
==. append (append (makeIndices xyziR tg loxi midxi) N)
(makeIndices xyziR tg midxyi hixyi)
==. append (makeIndices xyziR tg loxi midxi)
(makeIndices xyziR tg midxyi hixyi)
?listLeftId (makeIndices xyziR tg loxi midxi)
==. append (makeIndices xyi tg loxi hixi)
(makeIndices xyziR tg midxyi hixyi)
?catIndices xyi zi tg loxi hixi
==. append (makeIndices xyi tg loxi hixi)
(makeIndices xyziL tg loxyi hixyi)
==. append (makeNewIndices xi yi tg) (makeNewIndices xyi zi tg)
==. append (map (castGoodIndexRight tg xyi zi) (makeNewIndices xi yi tg)) (makeNewIndices xyi zi tg)
?mapCastId tg xyi zi (makeNewIndices xi yi tg)
*** QED
| 0 <= stringLen xi + stringLen yi - stringLen tg
= append (makeNewIndices xi yzi tg)
(map (shiftStringRight tg xi yzi) (makeNewIndices yi zi tg))
==. append (makeIndices xyziR tg loxi hixi)
(map (shiftStringRight tg xi yzi) (makeIndices yzi tg loyi hiyi))
==. append (makeIndices xyziR tg loxi hixi)
(makeIndices xyziR tg midxyi hixyi)
?shiftIndicesRight loyi hiyi xi yzi tg
==. append (makeIndices xyziL tg loxi hixi)
(makeIndices xyziL tg midxyi hixyi)
?concatStringAssoc xi yi zi
==. append (append (makeIndices xyziR tg loxi midxi)
(makeIndices xyziR tg (midxi+1) hixi))
(makeIndices xyziR tg midxyi hixyi)
?mergeIndices xyziL tg loxi midxi hixi
==. append (makeIndices xyziL tg loxi midxi)
(append (makeIndices xyziL tg (midxi+1) hixi)
(makeIndices xyziL tg midxyi hixyi))
?listAssoc (makeIndices xyziR tg loxi midxi) (makeIndices xyziR tg (midxi+1) hixi) (makeIndices xyziR tg midxyi hixyi)
==. append (makeIndices xyziL tg loxi midxi)
(makeIndices xyziL tg (midxi+1) hixyi)
?mergeIndices xyziL tg (midxi+1) hixi hixyi
==. append (makeIndices xyi tg loxi hixi)
(makeIndices xyziL tg (midxi+1) hixyi)
?catIndices xyi zi tg loxi hixi
==. append (makeIndices xyi tg loxi hixi)
(makeIndices xyziL tg loxyi hixyi)
==. append (makeNewIndices xi yi tg) (makeNewIndices xyi zi tg)
==. append (map (castGoodIndexRight tg xyi zi) (makeNewIndices xi yi tg)) (makeNewIndices xyi zi tg)
?mapCastId tg xyi zi (makeNewIndices xi yi tg)
*** QED
| stringLen xi + stringLen yi < stringLen tg
= append (makeNewIndices xi yzi tg)
(map (shiftStringRight tg xi yzi) (makeNewIndices yi zi tg))
==. append (makeIndices xyziR tg loxi hixi)
(map (shiftStringRight tg xi yzi) (makeIndices yzi tg loyi hiyi))
==. append (makeIndices xyziR tg loxi hixi)
(makeIndices xyziR tg midxyi hixyi)
?shiftIndicesRight loyi hiyi xi yzi tg
==. append (makeIndices xyziL tg loxi hixi)
(makeIndices xyziL tg midxyi hixyi)
?concatStringAssoc xi yi zi
==. makeIndices xyziL tg 0 (stringLen xyi - 1)
?mergeIndices xyziL tg loxi hixi hixyi
==. append N (makeIndices xyziL tg 0 hixyi)
==. append (makeIndices xyi tg loxi hixi)
(makeIndices xyziL tg loxyi hixyi)
? makeIndicesNull xyi tg 0 (stringLen xi -1)
==. append (makeNewIndices xi yi tg) (makeNewIndices xyi zi tg)
==. append (map (castGoodIndexRight tg xyi zi) (makeNewIndices xi yi tg)) (makeNewIndices xyi zi tg)
? mapCastId tg xyi zi (makeNewIndices xi yi tg)
*** QED
where
xyziR = xi <+> (yi <+> zi)
xyziL = xyi <+> zi
yzi = yi <+> zi
xyi = xi <+> yi
midxyi = maxInt (stringLen xi + stringLen yi - stringLen tg + 1) (stringLen xi)
midxi = stringLen xi + stringLen yi - stringLen tg
loyi = maxInt (stringLen yi - stringLen tg + 1) 0
loxi = maxInt (stringLen xi - stringLen tg + 1) 0
loxyi = maxInt (stringLen xyi - stringLen tg + 1) 0
hiyi = stringLen yi - 1
hixi = stringLen xi - 1
hixyi = stringLen xi + hiyi
| null | https://raw.githubusercontent.com/nikivazou/verified_string_matching/abdd611a0758467f776c59c3d6c9e4705d36a3a0/src/AutoProofs/shiftNewIndices.hs | haskell | -----------------------------------------------------------------------------
------ Lemmata on Shifting Indices ---------------------------------------
----------------------------------------------------------------------------- | #ifdef IncludedmakeNewIndicesNullLeft
#else
#include "../AutoProofs/makeNewIndicesNullLeft.hs"
#endif
#ifdef IncludedmakeNewIndicesNullRight
#else
#include "../AutoProofs/makeNewIndicesNullRight.hs"
#endif
#ifdef IncludedmapShiftZero
#else
#include "../AutoProofs/mapShiftZero.hs"
#endif
#ifdef IncludedmakeIndicesNull
#else
#include "../AutoProofs/makeIndicesNull.hs"
#endif
#ifdef IncludedcatIndices
#else
#include "../AutoProofs/catIndices.hs"
#endif
#ifdef IncludedmergeIndices
#else
#include "../AutoProofs/mergeIndices.hs"
#endif
#ifdef IncludedmapCastId
#else
#include "../AutoProofs/mapCastId.hs"
#endif
@ shiftNewIndices
: : xi : RString
- > yi : RString
- > zi : RString
- > tg:{RString | stringLen yi < stringLen tg }
- > { append ( makeNewIndices xi ( yi < + > zi ) tg ) ( map ( shiftStringRight tg xi ( yi < + > zi ) ) ( makeNewIndices tg ) )
= = append ( map ( castGoodIndexRight tg ( xi < + > yi ) ) ( makeNewIndices xi yi tg ) ) ( makeNewIndices ( xi < + > yi ) tg )
}
@
:: xi:RString
-> yi:RString
-> zi:RString
-> tg:{RString | stringLen yi < stringLen tg }
-> { append (makeNewIndices xi (yi <+> zi) tg) (map (shiftStringRight tg xi (yi <+> zi)) (makeNewIndices yi zi tg))
== append (map (castGoodIndexRight tg (xi <+> yi) zi) (makeNewIndices xi yi tg)) (makeNewIndices (xi <+> yi) zi tg)
}
@-}
shiftNewIndices :: RString -> RString -> RString -> RString -> Proof
shiftNewIndices xi yi zi tg
| stringLen tg < 2
= append (makeNewIndices xi yzi tg) (map (shiftStringRight tg xi yzi) (makeNewIndices yi zi tg))
==. append N (map (shiftStringRight tg xi yzi) N)
==. map (shiftStringRight tg xi yzi) N
==. N
==. append N N
==. append (makeNewIndices xi yi tg) (makeNewIndices xyi zi tg)
==. append (map (castGoodIndexRight tg xyi zi) (makeNewIndices xi yi tg)) (makeNewIndices xyi zi tg)
? mapCastId tg xyi zi (makeNewIndices xi yi tg)
*** QED
where
yzi = yi <+> zi
xyi = xi <+> yi
xyziL = xyi <+> zi
shiftNewIndices xi yi zi tg
| stringLen xi == 0
= append (makeNewIndices xi yzi tg)
(map (shiftStringRight tg xi yzi) (makeNewIndices yi zi tg))
==. append (makeNewIndices stringEmp yzi tg)
(map (shiftStringRight tg xi yzi) (makeNewIndices yi zi tg))
? stringEmpProp xi
==. append (makeNewIndices stringEmp yzi tg)
(map (shiftStringRight tg xi yzi) (makeNewIndices yi zi tg))
? makeNewIndicesNullRight yzi tg
==. append N
(map (shiftStringRight tg xi yzi) (makeNewIndices yi zi tg))
==. map (shiftStringRight tg xi yzi) (makeNewIndices yi zi tg)
? stringEmpProp xi
==. map (shiftStringRight tg stringEmp yzi) (makeNewIndices yi zi tg)
? mapShiftZero tg yzi (makeNewIndices yi zi tg)
==. makeNewIndices yi zi tg
==. makeNewIndices xyi zi tg
? concatEmpLeft xi yi
==. append N (makeNewIndices xyi zi tg)
==. append (makeNewIndices stringEmp yi tg) (makeNewIndices xyi zi tg)
? makeNewIndicesNullRight yi tg
==. append (makeNewIndices xi yi tg) (makeNewIndices xyi zi tg)
? stringEmpProp xi
==. append (map (castGoodIndexRight tg xyi zi) (makeNewIndices xi yi tg)) (makeNewIndices xyi zi tg)
? mapCastId tg xyi zi (makeNewIndices xi yi tg)
*** QED
| stringLen yi == 0
= append (makeNewIndices xi yzi tg)
(map (shiftStringRight tg xi yzi) (makeNewIndices yi zi tg))
==. append (makeNewIndices xi zi tg)
(map (shiftStringRight tg xi yzi) (makeNewIndices yi zi tg))
?(stringEmpProp yi &&& concatEmpLeft yi zi)
==. append (makeNewIndices xi zi tg)
(map (shiftStringRight tg xi zi) (makeNewIndices stringEmp zi tg))
==. append (makeNewIndices xi zi tg)
(map (shiftStringRight tg xi (stringEmp <+> zi)) N)
?makeNewIndicesNullRight zi tg
==. append (makeNewIndices xi zi tg) N
==. makeNewIndices xi zi tg
?listLeftId (makeNewIndices xi zi tg)
==. makeNewIndices xyi zi tg
?concatEmpRight xi yi
==. append N (makeNewIndices xyi zi tg)
==. append (makeNewIndices xi stringEmp tg) (makeNewIndices xyi zi tg)
?makeNewIndicesNullLeft xi tg
==. append (makeNewIndices xi yi tg) (makeNewIndices xyi zi tg)
==. append (map (castGoodIndexRight tg xyi zi) (makeNewIndices xi yi tg)) (makeNewIndices xyi zi tg)
? (stringEmpProp yi &&& mapCastId tg xyi zi (makeNewIndices xi yi tg))
*** QED
| stringLen yi - stringLen tg == - 1
= append (makeNewIndices xi yzi tg)
(map (shiftStringRight tg xi yzi) (makeNewIndices yi zi tg))
==. append (makeIndices xyziR tg loxi hixi)
(map (shiftStringRight tg xi yzi) (makeIndices yzi tg loyi hiyi))
==. append (makeIndices xyziR tg loxi hixi)
(makeIndices xyziR tg midxyi hixyi)
?shiftIndicesRight loyi hiyi xi yzi tg
==. append (makeIndices xyziL tg loxi hixi)
(makeIndices xyziL tg midxyi hixyi)
?concatStringAssoc xi yi zi
==. append (append (makeIndices xyziR tg loxi midxi)
(makeIndices xyziR tg (midxi+1) hixi))
(makeIndices xyziR tg midxyi hixyi)
?mergeIndices xyziL tg loxi midxi hixi
==. append (append (makeIndices xyziR tg loxi midxi) N)
(makeIndices xyziR tg midxyi hixyi)
==. append (makeIndices xyziR tg loxi midxi)
(makeIndices xyziR tg midxyi hixyi)
?listLeftId (makeIndices xyziR tg loxi midxi)
==. append (makeIndices xyi tg loxi hixi)
(makeIndices xyziR tg midxyi hixyi)
?catIndices xyi zi tg loxi hixi
==. append (makeIndices xyi tg loxi hixi)
(makeIndices xyziL tg loxyi hixyi)
==. append (makeNewIndices xi yi tg) (makeNewIndices xyi zi tg)
==. append (map (castGoodIndexRight tg xyi zi) (makeNewIndices xi yi tg)) (makeNewIndices xyi zi tg)
?mapCastId tg xyi zi (makeNewIndices xi yi tg)
*** QED
| 0 <= stringLen xi + stringLen yi - stringLen tg
= append (makeNewIndices xi yzi tg)
(map (shiftStringRight tg xi yzi) (makeNewIndices yi zi tg))
==. append (makeIndices xyziR tg loxi hixi)
(map (shiftStringRight tg xi yzi) (makeIndices yzi tg loyi hiyi))
==. append (makeIndices xyziR tg loxi hixi)
(makeIndices xyziR tg midxyi hixyi)
?shiftIndicesRight loyi hiyi xi yzi tg
==. append (makeIndices xyziL tg loxi hixi)
(makeIndices xyziL tg midxyi hixyi)
?concatStringAssoc xi yi zi
==. append (append (makeIndices xyziR tg loxi midxi)
(makeIndices xyziR tg (midxi+1) hixi))
(makeIndices xyziR tg midxyi hixyi)
?mergeIndices xyziL tg loxi midxi hixi
==. append (makeIndices xyziL tg loxi midxi)
(append (makeIndices xyziL tg (midxi+1) hixi)
(makeIndices xyziL tg midxyi hixyi))
?listAssoc (makeIndices xyziR tg loxi midxi) (makeIndices xyziR tg (midxi+1) hixi) (makeIndices xyziR tg midxyi hixyi)
==. append (makeIndices xyziL tg loxi midxi)
(makeIndices xyziL tg (midxi+1) hixyi)
?mergeIndices xyziL tg (midxi+1) hixi hixyi
==. append (makeIndices xyi tg loxi hixi)
(makeIndices xyziL tg (midxi+1) hixyi)
?catIndices xyi zi tg loxi hixi
==. append (makeIndices xyi tg loxi hixi)
(makeIndices xyziL tg loxyi hixyi)
==. append (makeNewIndices xi yi tg) (makeNewIndices xyi zi tg)
==. append (map (castGoodIndexRight tg xyi zi) (makeNewIndices xi yi tg)) (makeNewIndices xyi zi tg)
?mapCastId tg xyi zi (makeNewIndices xi yi tg)
*** QED
| stringLen xi + stringLen yi < stringLen tg
= append (makeNewIndices xi yzi tg)
(map (shiftStringRight tg xi yzi) (makeNewIndices yi zi tg))
==. append (makeIndices xyziR tg loxi hixi)
(map (shiftStringRight tg xi yzi) (makeIndices yzi tg loyi hiyi))
==. append (makeIndices xyziR tg loxi hixi)
(makeIndices xyziR tg midxyi hixyi)
?shiftIndicesRight loyi hiyi xi yzi tg
==. append (makeIndices xyziL tg loxi hixi)
(makeIndices xyziL tg midxyi hixyi)
?concatStringAssoc xi yi zi
==. makeIndices xyziL tg 0 (stringLen xyi - 1)
?mergeIndices xyziL tg loxi hixi hixyi
==. append N (makeIndices xyziL tg 0 hixyi)
==. append (makeIndices xyi tg loxi hixi)
(makeIndices xyziL tg loxyi hixyi)
? makeIndicesNull xyi tg 0 (stringLen xi -1)
==. append (makeNewIndices xi yi tg) (makeNewIndices xyi zi tg)
==. append (map (castGoodIndexRight tg xyi zi) (makeNewIndices xi yi tg)) (makeNewIndices xyi zi tg)
? mapCastId tg xyi zi (makeNewIndices xi yi tg)
*** QED
where
xyziR = xi <+> (yi <+> zi)
xyziL = xyi <+> zi
yzi = yi <+> zi
xyi = xi <+> yi
midxyi = maxInt (stringLen xi + stringLen yi - stringLen tg + 1) (stringLen xi)
midxi = stringLen xi + stringLen yi - stringLen tg
loyi = maxInt (stringLen yi - stringLen tg + 1) 0
loxi = maxInt (stringLen xi - stringLen tg + 1) 0
loxyi = maxInt (stringLen xyi - stringLen tg + 1) 0
hiyi = stringLen yi - 1
hixi = stringLen xi - 1
hixyi = stringLen xi + hiyi
|
518f325936ad7054f2edd3ab8273ef47aec33d869b00daea98c124dbcd0aa256 | Nibre/BlamScript-Research | floodzone_mission.lisp | ;========== GLOBALS ==========================================================================
(global boolean debug 1)
(global boolean dialogue 1)
(global boolean g_play_cinematics 1)
(global boolean g_fact_ent_sen_spawn 0)
(global short g_fact_ent_sen_count 0)
(global short g_fact_ent_sen_index 10)
(global short g_fact_ent_enf_count 0)
(global short g_fact_ent_enf_index 3)
(script stub void x07 (print "x07"))
(script stub void c06_intra1 (print "c06_intra1"))
(script stub void c06_intra2 (print "c06_intra2"))
(script command_script cs_invulnerable
(cs_enable_moving 1)
(object_cannot_take_damage (ai_get_object ai_current_actor))
(sleep_until (>= (ai_combat_status ai_current_actor) ai_combat_status_certain))
(sleep (* 30 1))
(object_can_take_damage (ai_get_object ai_current_actor))
)
(script command_script cs_invul_8
(cs_enable_moving 1)
(object_cannot_take_damage (ai_get_object ai_current_actor))
(sleep (* 30 8))
(object_can_take_damage (ai_get_object ai_current_actor))
)
(script command_script cs_kill
(ai_kill_silent ai_current_actor)
)
(script static void no_death
(object_cannot_take_damage (ai_actors covenant))
)
(script dormant ice_cream_superman
(object_create ice_cream_head)
(sleep_until
(or
(unit_has_weapon (unit (player0)) "objects\weapons\multiplayer\ball\head_sp.weapon")
(unit_has_weapon (unit (player1)) "objects\weapons\multiplayer\ball\head_sp.weapon")
)
5)
(if debug (print "you're going to get fat!!!!! or dead..."))
(if debug (print "because now everyone is superman!!!!"))
(ice_cream_flavor_stock 10)
)
; ===== !!!! MUSIC !!!! ===========================================================================
(global boolean g_music_06b_01 1)
(global boolean g_music_06b_02 0)
(global boolean g_music_06b_03 0)
(global boolean g_music_06b_04 0)
(global boolean g_music_06b_05 0)
(global boolean g_music_06b_06 0)
(global boolean g_music_06b_07 0)
(script dormant music_06b_01
(sleep_until g_music_06b_01)
(if debug (print "start music 06b_01"))
(sound_looping_start scenarios\solo\06b_floodzone\06b_music\06b_01 none 1)
; (sleep_until (not g_music_06b_01))
( if debug ( print " stop music 06b_01 " ) )
4 ( sound_looping_stop scenarios\solo\06b_floodzone\06b_music\06b_01 )
)
(script dormant music_06b_02
(sleep_until g_music_06b_02)
(if debug (print "start music 06b_02"))
(sound_looping_start scenarios\solo\06b_floodzone\06b_music\06b_02 none 1)
(sleep_until (not g_music_06b_02))
(if debug (print "stop music 06b_02"))
(sound_looping_stop scenarios\solo\06b_floodzone\06b_music\06b_02)
)
(script dormant music_06b_03
(sleep_until g_music_06b_03)
(if debug (print "start music 06b_03"))
(sound_looping_start scenarios\solo\06b_floodzone\06b_music\06b_03 none 1)
(sleep_until (not g_music_06b_03))
(if debug (print "stop music 06b_03"))
(sound_looping_stop scenarios\solo\06b_floodzone\06b_music\06b_03)
)
(script dormant music_06b_04
(sleep_until g_music_06b_04)
(if debug (print "start music 06b_04"))
(sound_looping_start scenarios\solo\06b_floodzone\06b_music\06b_04 none 1)
; (sleep_until (not g_music_06b_04))
( if debug ( print " stop music 06b_04 " ) )
; (sound_looping_stop scenarios\solo\06b_floodzone\06b_music\06b_04)
)
(script dormant music_06b_05
(sleep_until (volume_test_objects tv_e20_dock_entrance (players)))
(set g_music_06b_05 1)
(if debug (print "start music 06b_05"))
(sound_looping_start scenarios\solo\06b_floodzone\06b_music\06b_05 none 1)
(sleep_until (not g_music_06b_05))
(if debug (print "stop music 06b_05"))
(sound_looping_stop scenarios\solo\06b_floodzone\06b_music\06b_05)
)
(script dormant music_06b_06
(sleep_until g_music_06b_06)
(if debug (print "start music 06b_06"))
(sound_looping_start scenarios\solo\06b_floodzone\06b_music\06b_06 none 1)
; (sleep_until (not g_music_06b_06))
; (if debug (print "stop music 06b_06"))
; (sound_looping_stop scenarios\solo\06b_floodzone\06b_music\06b_06)
)
(script dormant music_06b_07
(sleep_until (volume_test_objects tv_music_06b_07 (players)))
(if debug (print "start music 06b_07"))
(sound_looping_start scenarios\solo\06b_floodzone\06b_music\06b_07 none 1)
)
;= CHAPTER TITLES ========================================================================
(script dormant chapter_mirror
(sleep 30)
(cinematic_set_title title_1)
(sleep 150)
(hud_cinematic_fade 1 0.5)
(cinematic_show_letterbox false)
)
(script dormant chapter_competition
(sleep 30)
(hud_cinematic_fade 0 0.5)
(cinematic_show_letterbox true)
(sleep 30)
(cinematic_set_title title_2)
(sleep 150)
(hud_cinematic_fade 1 0.5)
(cinematic_show_letterbox false)
)
(script dormant chapter_gallery
(hud_cinematic_fade 0 0.5)
(cinematic_show_letterbox true)
(sleep 30)
(cinematic_set_title title_3)
(sleep 150)
(hud_cinematic_fade 1 0.5)
(cinematic_show_letterbox false)
)
(script dormant chapter_familiar
(hud_cinematic_fade 0 0.5)
(cinematic_show_letterbox true)
(sleep 30)
(cinematic_set_title title_4)
(sleep 150)
(hud_cinematic_fade 1 0.5)
(cinematic_show_letterbox false)
)
;= OBJECTIVES ============================================================================
(script dormant objective_push_set
(sleep 30)
(print "new objective set:")
(print "Push through the Quarantine-Zone toward The Library.")
(objectives_show_up_to 0)
)
(script dormant objective_push_clear
(print "objective complete:")
(print "Push through the Quarantine-Zone toward The Library.")
(objectives_finish_up_to 0)
)
(script dormant objective_link_set
(sleep 30)
(print "new objective set:")
(print "Link-up with the Spec-Ops Leader, and break through the Flood barricade.")
(objectives_show_up_to 1)
)
(script dormant objective_link_clear
(print "objective complete:")
(print "Link-up with the Spec-Ops Leader, and break through the Flood barricade.")
(objectives_finish_up_to 1)
)
(script dormant objective_retrieve_set
(sleep 30)
(print "new objective set:")
(print "Retrieve the Sacred Icon before the Humans.")
(objectives_show_up_to 2)
)
(script dormant objective_retrieve_clear
(print "objective complete:")
(print "Retrieve the Sacred Icon before the Humans.")
(objectives_finish_up_to 2)
)
; ===== DIALOGUE SCENES ===========================================================================
(global short dialogue_pause 7)
(global boolean g_qz_cov_def_progress 0)
; plays right after the insertion cinematic
(script dormant sc_cov_charge
for , because he bitches a lot
(if dialogue (print "COMMANDER: Forward, warriors! And fear not pain or death!"))
(sleep (ai_play_line_on_object none 0220))
(sleep (* dialogue_pause 2))
; (if dialogue (print "SPEC-OPS: For those who fell before us!"))
; (sleep (ai_play_line_on_object none 0230))
; (sleep dialogue_pause)
(if dialogue (print "COMMANDER: Go, Arbiter! I'll follow when our reinforcements arrive!"))
(sleep (ai_play_line_on_object none 0240))
(sleep dialogue_pause)
(sleep_until g_qz_cov_def_progress)
(if (<= (ai_living_count cov_def_enf) 0) (sleep 180) (sleep 30))
if the enforcers are not alive then sleep 180 , if they are then sleep 30
; if there are no enforcers alive when it tries to play this line skip it
(if (> (ai_living_count cov_def_enf) 0)
(begin
(if dialogue (print "SPEC-OPS: Go, Enforcers!"))
(sleep (ai_play_line covenant 0590))
(sleep dialogue_pause)
)
)
(if dialogue (print "SPEC-OPS: To the vehicles! We'll need their heavy-guns!"))
(sleep (ai_play_line covenant 0600))
(sleep dialogue_pause)
(if dialogue (print "SPEC-OPS: Onward! To the Sacred Icon!"))
(sleep (ai_play_line covenant 0610))
(sleep dialogue_pause)
)
* this was removed because it was blocking the AI from getting into their vehicles
|(script dormant sc_cov_charge
| ( sleep_until ( cs_sc_cov_charge covenant ) )
;|)
;*;
(script command_script cs_sc_qz_veh_int
(if dialogue (print "SPEC-OPS: What?! The Parasite controls our vehicles?!"))
(sleep (ai_play_line covenant 0620))
(sleep dialogue_pause)
(if dialogue (print "SPEC-OPS: Impossible! It's never done that before!"))
(sleep (ai_play_line covenant 0640))
(sleep dialogue_pause)
(if dialogue (print "SPEC-OPS: No matter. It will die all the same!"))
(sleep (ai_play_line covenant 0650))
(sleep dialogue_pause)
)
; plays when the covenant see the flood driving ghosts
(script dormant sc_qz_veh_int
(sleep 180)
(sleep_until (ai_scene sc_qz_veh_int cs_sc_qz_veh_int covenant))
)
; plays when you get to the bottom of the dam
(script dormant sc_ext_a
(if dialogue (print "COMMANDER: I'm sending you a squad of my most experienced Warriors, Arbiter."))
(sleep (ai_play_line_on_object none 0650))
(sleep dialogue_pause)
(if dialogue (print "COMMANDER: Do not squander their talents!"))
(sleep (ai_play_line_on_object none 0660))
(sleep dialogue_pause)
)
; plays halfway through the vehicle interior space (unlike what the title would suggest)
(script dormant sc_factory_approach
(if dialogue (print "COMMANDER: Commander! We've found a human vehicle!"))
(sleep (ai_play_line covenant 0250))
(sleep dialogue_pause)
(if dialogue (print "SPEC-OPS: Keep moving. I'm on my way."))
(sleep (ai_play_line_on_object none 0260))
(sleep dialogue_pause)
)
; plays in the gateway to the final vehicle space (right after the crashed factory exit)
(script dormant sc_factory_exit
(sleep 60)
(if dialogue (print "SPEC-OPS: Humans and parasites!"))
(if dialogue (print "This ring has been befouled, but we will wipe it clean!"))
(sleep (ai_play_line covenant 0270))
(sleep dialogue_pause)
(if dialogue (print "SPEC-OPS: Honoring those who built it!"))
(sleep (ai_play_line covenant 0280))
(sleep dialogue_pause)
)
; plays at the exit from the crashed sentinel factory
(script dormant sc_human_fools
(if dialogue (print "COMMANDER: Human fools. I almost feel sorry for them."))
(sleep (ai_play_line_on_object none 0290))
(sleep dialogue_pause)
)
; plays when the exterior b covenant reinforcements get dropped off
(script dormant sc_ext_b
(if dialogue (print "SPEC-OPS: Forward to the Icon!"))
(sleep (ai_play_line covenant 0700))
(sleep dialogue_pause)
(if dialogue (print "SPEC-OPS: The Parasite's ranks swell as we draw nearer to the Library!"))
(sleep (ai_play_line covenant 0710))
(sleep dialogue_pause)
(if dialogue (print "SPEC-OPS: Steel your nerves. We are not turning back!"))
(sleep (ai_play_line covenant 0720))
(sleep dialogue_pause)
)
; joe plays this line in his cinematic
(script dormant sc_chasm
(if dialogue (print "TARTARUS: I see that coward didn't join you."))
(sleep (ai_play_line_on_object none 0300))
(sleep dialogue_pause)
(if dialogue (print "TARTARUS: I'll do what I can to keep the Flood off your back."))
(sleep (ai_play_line_on_object none 0310))
(sleep dialogue_pause)
)
; plays right after the key cinematic
(script dormant sc_outer_wall
(if dialogue (print "TARTARUS: We cannot let the humans capture the Icon!"))
(sleep (ai_play_line_on_object none 0320))
(sleep dialogue_pause)
(if dialogue (print "TARTARUS: The Hierarchs do not look kindly on failure."))
(sleep (ai_play_line_on_object none 0330))
(sleep dialogue_pause)
)
; plays when the key docs in its final position
(script dormant sc_dock
(if dialogue (print "TARTARUS: Hurry, Arbiter! Get the Icon!"))
(sleep (ai_play_line_on_object none 0340))
(sleep dialogue_pause)
)
;====== COVENANT VEHICLE MIGRATION =======================================================
(script static boolean driver_seat_test
(if
(or
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_cov_def_spectre/spectre) "spectre_d" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_cov_def_ghosts/a) "ghost_d" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_cov_def_ghosts/b) "ghost_d" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location veh_int_flood_ghosts_ini/a) "ghost_d" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location veh_int_flood_ghosts_ini/b) "ghost_d" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location veh_int_hog_ab/hog) "warthog_d" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location veh_int_ghost_ab/a) "ghost_d" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location veh_int_ghost_ab/b) "ghost_d" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location veh_int_scorpion/scorpion) "ghost_d" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location veh_int_flood_hog_bk/warthog) "ghost_d" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location veh_int_flood_ghosts_bk/a) "ghost_d" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location veh_int_flood_ghosts_bk/b) "ghost_d" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_ext_a_ghosts/a) "ghost_d" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_ext_a_ghosts/b) "ghost_d" (players))
)
true false)
)
(script static boolean passenger_seat_test
(if
(or
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_cov_def_spectre/spectre) "spectre_p_l" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_cov_def_spectre/spectre) "spectre_p_r" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_cov_def_spectre/spectre) "spectre_g" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location veh_int_hog_ab/hog) "warthog_p" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location veh_int_hog_ab/hog) "warthog_g" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location veh_int_flood_hog_bk/warthog) "warthog_p" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location veh_int_flood_hog_bk/warthog) "warthog_g" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_ext_b_fact_warthog/warthog) "warthog_p" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_ext_b_fact_warthog/warthog) "warthog_g" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_ext_b_warthog/warthog) "warthog_p" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_ext_b_warthog/warthog) "warthog_g" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_ext_b_warthog_gauss/warthog) "warthog_p" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_ext_b_warthog_gauss/warthog) "warthog_g" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_ext_b_cov_spectre/spectre) "spectre_p_l" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_ext_b_cov_spectre/spectre) "spectre_p_r" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_ext_b_cov_spectre/spectre) "spectre_g" (players))
)
true false)
)
(global short g_order_delay 150)
(script command_script cov_def_spec_tele_a
(cs_teleport bsp_swap_teleport/a bsp_swap_teleport/face)
)
(script command_script cov_def_spec_tele_b
(cs_teleport bsp_swap_teleport/b bsp_swap_teleport/face)
)
(script command_script cov_def_spec_tele_c
(cs_teleport bsp_swap_teleport/c bsp_swap_teleport/face)
)
(script command_script cov_def_spec_tele_d
(cs_teleport bsp_swap_teleport/d bsp_swap_teleport/face)
)
(script command_script cs_fact_ent_exit_veh
(cs_enable_pathfinding_failsafe true)
(cs_go_to_nearest crashed_fact_ent)
9/22
9/22
(ai_set_orders covenant cov_follow_factory1)
(sleep 30)
(ai_vehicle_exit covenant)
)
(global boolean g_veh_int_migrate_a 0)
(global boolean g_veh_int_migrate_b 0)
(global boolean g_veh_int_migrate_c 0)
(global boolean g_veh_int_migrate_d 0)
(global boolean g_veh_int_migrate_e 0)
(global boolean g_ext_a_dam_migrate_a 0)
(global boolean g_ext_a_dam_migrate_b 0)
(global boolean g_ext_a_migrate_a 0)
(global boolean g_ext_a_migrate_b 0)
(global boolean g_ext_a_migrate_c 0)
(global boolean g_ext_a_migrate_d 0)
(global boolean g_ext_a_migrate_e 0)
(global boolean g_ext_a_migrate_f 0)
(global boolean g_ext_a_fact_ent_migrate 0)
(script dormant ext_a_vehicle_orders
(sleep g_order_delay)
; == covenant defense ==
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(ai_set_orders covenant cov_drive_cov_def))
)
(true (ai_set_orders covenant cov_follow_cov_def))
)
(= (structure_bsp_index) 1))
)
;*
| ; = = BSP SWAP BULLSHIT = = = = = = = = = = = =
;| (if (not (volume_test_object tv_bsp_swap_bullshit (ai_get_object qz_cov_def_spec_ops/a)))
| ( cs_run_command_script qz_cov_def_spec_ops / a cov_def_spec_tele_a )
;| )
;| (if (not (volume_test_object tv_bsp_swap_bullshit (ai_get_object qz_cov_def_spec_ops/b)))
;| (cs_run_command_script qz_cov_def_spec_ops/b cov_def_spec_tele_b)
;| )
;| (if (not (volume_test_object tv_bsp_swap_bullshit (ai_get_object qz_cov_def_spec_ops/c)))
;| (cs_run_command_script qz_cov_def_spec_ops/c cov_def_spec_tele_c)
;| )
;| (if (not (volume_test_object tv_bsp_swap_bullshit (ai_get_object qz_cov_def_spec_ops/d)))
;| (cs_run_command_script qz_cov_def_spec_ops/d cov_def_spec_tele_d)
;| )
| ; = = BSP SWAP BULLSHIT = = = = = = = = = = = =
;*;
; VEHICLE INTERIOR START =======================================================================================
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(cond
((= (structure_bsp_index) 0) (begin
(ai_set_orders covenant_infantry cov_follow_cov_def)
(ai_set_orders covenant_vehicles cov_drive_cov_def)
)
)
((= (structure_bsp_index) 1) (begin
(ai_set_orders covenant_infantry cov_follow_veh_int)
(ai_set_orders covenant_vehicles cov_drive_veh_int_a)
)
)
)
)
)
(true
(cond
((= (structure_bsp_index) 0) (ai_set_orders covenant cov_follow_cov_def))
((= (structure_bsp_index) 1) (ai_set_orders covenant cov_follow_veh_int))
)
)
)
(or ; exit conditions
(and
(volume_test_objects tv_veh_int_a (players))
(ai_trigger_test "done_fighting" covenant)
)
(and
(volume_test_objects tv_veh_int_a (players))
(<= (ai_living_count veh_int_sen_a) 0)
)
g_veh_int_migrate_b
))
)
(sleep g_order_delay)
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(cond
((= (structure_bsp_index) 0) (begin
(ai_set_orders covenant_infantry cov_follow_cov_def)
(ai_set_orders covenant_vehicles cov_drive_cov_def)
)
)
((= (structure_bsp_index) 1) (begin
(ai_set_orders covenant_infantry cov_follow_veh_int)
(ai_set_orders covenant_vehicles cov_drive_veh_int_b)
)
)
)
)
)
(true
(cond
((= (structure_bsp_index) 0) (ai_set_orders covenant cov_follow_cov_def))
((= (structure_bsp_index) 1) (ai_set_orders covenant cov_follow_veh_int))
)
)
)
(or ; exit conditions
(and
(volume_test_objects tv_veh_int_b (players))
(ai_trigger_test "done_fighting" covenant)
)
(and
(volume_test_objects tv_veh_int_b (players))
(<= (ai_living_count veh_int_sen_b) 0)
(<= (ai_living_count veh_int_flood_b) 0)
)
g_veh_int_migrate_c
))
)
(sleep g_order_delay)
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(ai_set_orders covenant_infantry cov_follow_veh_int)
(ai_set_orders covenant_vehicles cov_drive_veh_int_c)
)
)
(true (ai_set_orders covenant cov_follow_veh_int))
)
(or ; exit conditions
(and
(volume_test_objects tv_veh_int_c (players))
(ai_trigger_test "done_fighting" covenant)
)
(and
(volume_test_objects tv_veh_int_c (players))
(<= (ai_living_count veh_int_sen_c) 0)
(<= (ai_living_count veh_int_flood_c) 0)
)
g_veh_int_migrate_d
))
)
(sleep g_order_delay)
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(ai_set_orders covenant_infantry cov_follow_veh_int)
(ai_set_orders covenant_vehicles cov_drive_veh_int_d)
)
)
(true (ai_set_orders covenant cov_follow_veh_int))
)
(or ; exit conditions
(and
(volume_test_objects tv_veh_int_d (players))
(ai_trigger_test "done_fighting" covenant)
)
(and
(volume_test_objects tv_veh_int_d (players))
(<= (ai_living_count veh_int_sen_d) 0)
(<= (ai_living_count veh_int_flood_d) 0)
)
g_veh_int_migrate_e
))
)
(sleep g_order_delay)
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(ai_set_orders covenant_infantry cov_follow_veh_int)
(ai_set_orders covenant_vehicles cov_drive_veh_int_e)
)
)
(true (ai_set_orders covenant cov_follow_veh_int))
)
(or ; exit conditions
(volume_test_objects tv_qz_ext_a (players))
g_ext_a_dam_migrate_a
))
)
(sleep g_order_delay)
; EXTERIOR A START =======================================================================================
; == upper dam ==
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(ai_set_orders covenant_infantry cov_follow_ext_a_dam)
(ai_set_orders covenant_vehicles cov_drive_ext_a_dam_a)
)
)
(true (ai_set_orders covenant cov_follow_ext_a_dam))
)
(or ; exit conditions
(and
(volume_test_objects tv_ext_a_dam_a (players))
(ai_trigger_test "done_fighting" covenant)
)
(and
(volume_test_objects tv_ext_a_dam_a (players))
(<= (ai_living_count ext_a_sen_dam_a) 0)
(<= (ai_living_count ext_a_flood_dam_a) 0)
)
g_ext_a_dam_migrate_b
)
)
)
(sleep g_order_delay)
; == lower dam ==
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(ai_set_orders covenant_infantry cov_follow_ext_a_dam)
(ai_set_orders covenant_vehicles cov_drive_ext_a_dam_b)
)
)
(true (ai_set_orders covenant cov_follow_ext_a_dam))
)
(or ; exit conditions
(and
(volume_test_objects qz_ext_a_dam_b (players))
(ai_trigger_test "done_fighting" covenant)
)
(and
(volume_test_objects qz_ext_a_dam_b (players))
(<= (ai_living_count ext_a_sen_dam_b) 0)
(<= (ai_living_count ext_a_flood_dam_b) 0)
)
g_ext_a_migrate_a
)
)
)
(sleep g_order_delay)
; == exterior a ==
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(ai_set_orders covenant_infantry cov_follow_ext_a)
(ai_set_orders covenant_vehicles cov_drive_ext_a_a)
)
)
(true (ai_set_orders covenant cov_follow_ext_a))
)
(or ; exit conditions
(and
(volume_test_objects tv_ext_a_a (players))
(ai_trigger_test "done_fighting" covenant)
)
(and
(volume_test_objects tv_ext_a_a (players))
(<= (ai_living_count ext_a_sen_a) 0)
(<= (ai_living_count ext_a_flood_a) 0)
)
g_ext_a_migrate_b
)
)
)
(sleep g_order_delay)
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(ai_set_orders covenant_infantry cov_follow_ext_a)
(ai_set_orders covenant_vehicles cov_drive_ext_a_b)
)
)
(true (ai_set_orders covenant cov_follow_ext_a))
)
(or ; exit conditions
(and
(volume_test_objects tv_ext_a_b (players))
(ai_trigger_test "done_fighting" covenant)
)
(and
(volume_test_objects tv_ext_a_b (players))
(<= (ai_living_count ext_a_sen_b) 0)
(<= (ai_living_count ext_a_flood_b) 0)
)
g_ext_a_migrate_c
)
)
)
(sleep g_order_delay)
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(ai_set_orders covenant_infantry cov_follow_ext_a)
(ai_set_orders covenant_vehicles cov_drive_ext_a_c)
)
)
(true (ai_set_orders covenant cov_follow_ext_a))
)
(or ; exit conditions
(and
(volume_test_objects tv_ext_a_c (players))
(ai_trigger_test "done_fighting" covenant)
)
(and
(volume_test_objects tv_ext_a_c (players))
(<= (ai_living_count ext_a_sen_c) 0)
(<= (ai_living_count ext_a_flood_c) 0)
)
g_ext_a_migrate_d
)
)
)
(sleep g_order_delay)
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(ai_set_orders covenant_infantry cov_follow_ext_a)
(ai_set_orders covenant_vehicles cov_drive_ext_a_d)
)
)
(true (ai_set_orders covenant cov_follow_ext_a))
)
(or ; exit conditions
(and
(volume_test_objects tv_ext_a_d (players))
(ai_trigger_test "done_fighting" covenant)
)
(and
(volume_test_objects tv_ext_a_d (players))
(<= (ai_living_count ext_a_sen_d) 0)
(<= (ai_living_count ext_a_flood_d) 0)
)
g_ext_a_migrate_e
)
)
)
(sleep g_order_delay)
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(ai_set_orders covenant_infantry cov_follow_ext_a)
(ai_set_orders covenant_vehicles cov_drive_ext_a_e)
)
)
(true (ai_set_orders covenant cov_follow_ext_a))
)
(or ; exit conditions
(and
(volume_test_objects tv_ext_a_e (players))
(ai_trigger_test "done_fighting" covenant)
)
(and
(volume_test_objects tv_ext_a_e (players))
(<= (ai_living_count ext_a_sen_e) 0)
(<= (ai_living_count ext_a_flood_e) 0)
)
g_ext_a_migrate_f
)
)
)
(sleep g_order_delay)
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(ai_set_orders covenant_infantry cov_follow_ext_a_fact_ent)
(ai_set_orders covenant_vehicles cov_drive_ext_a_f)
)
)
(true (ai_set_orders covenant cov_follow_ext_a_fact_ent))
)
(or ; exit conditions
(and
(volume_test_objects tv_ext_a_f (players))
(ai_trigger_test "done_fighting" covenant)
)
(and
(volume_test_objects tv_ext_a_f (players))
(<= (ai_living_count ext_a_sen_f) 0)
(<= (ai_living_count ext_a_flood_f) 0)
)
g_ext_a_fact_ent_migrate
)
)
)
(sleep g_order_delay)
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(ai_set_orders covenant_infantry cov_follow_ext_a_fact_ent)
(ai_set_orders covenant_vehicles cov_drive_fact_ent)
)
)
(true (ai_set_orders covenant cov_follow_ext_a_fact_ent))
)
(or ; exit conditions
(and
(ai_trigger_test "done_fighting" covenant)
g_fact_ent_sen_spawn
)
(and
(<= (ai_living_count fact_ent_sentinels) 0)
(<= (ai_living_count fact_ent_flood) 0)
g_fact_ent_sen_spawn
)
(volume_test_objects tv_fact_ent_follow (players))
)
)
)
(sleep g_order_delay)
(cs_run_command_script covenant cs_fact_ent_exit_veh) ; new order set in the command script
)
(global boolean g_ext_b_migrate_1 0)
(global boolean g_ext_b_migrate_2 0)
(global boolean g_ext_b_migrate_3 0)
(global boolean g_ext_b_migrate_4 0)
(global boolean g_ext_b_migrate_5 0)
(script command_script cs_ext_b_exit
(cs_enable_pathfinding_failsafe true)
(cs_go_to_nearest ext_b_exit)
9/22
9/22
(ai_set_orders covenant cov_ext_b_exit)
(sleep 30)
(ai_vehicle_exit covenant)
)
(script dormant ext_b_vehicle_orders
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(ai_set_orders covenant_infantry cov_follow_ext_b)
(ai_set_orders covenant_vehicles cov_drive_ext_b_a)
)
)
(true (ai_set_orders covenant cov_follow_ext_b))
)
(ai_magically_see covenant ext_b_flood)
g_ext_b_migrate_1)
)
(sleep g_order_delay)
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(ai_set_orders covenant_infantry cov_follow_ext_b)
(ai_set_orders covenant_vehicles cov_drive_ext_b_b)
)
)
(true (ai_set_orders covenant cov_follow_ext_b))
)
(ai_magically_see covenant ext_b_flood)
g_ext_b_migrate_2)
)
(sleep (* g_order_delay 3))
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(ai_set_orders covenant_infantry cov_follow_ext_b)
(ai_set_orders covenant_vehicles cov_drive_ext_b_b)
)
)
(true (ai_set_orders covenant cov_follow_ext_b))
)
(ai_magically_see covenant ext_b_flood)
(or ; exit conditions
(and
(<= (ai_living_count ext_b_flood_b) 0)
(<= (ai_living_count ext_b_sentinels_b) 0)
)
g_ext_b_migrate_3
)
)
)
(sleep g_order_delay)
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(ai_set_orders covenant_infantry cov_follow_ext_b)
(ai_set_orders covenant_vehicles cov_drive_ext_b_c)
)
)
(true (ai_set_orders covenant cov_follow_ext_b_bk))
)
(ai_magically_see covenant ext_b_flood)
(or ; exit condition
(and
(<= (ai_living_count ext_b_flood_c) 0)
(<= (ai_living_count ext_b_sentinels_c) 0)
)
g_ext_b_migrate_4
)
)
)
(sleep g_order_delay)
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(ai_set_orders covenant_infantry cov_follow_ext_b)
(ai_set_orders covenant_vehicles cov_drive_ext_b_d)
)
)
(true (ai_set_orders covenant cov_follow_ext_b_bk))
)
(ai_magically_see covenant ext_b_flood)
g_ext_b_migrate_5)
)
(sleep (* g_order_delay 3))
(cs_run_command_script covenant cs_ext_b_exit) ; new order set in the command script
(sleep_until (= (structure_bsp_index) 3))
(ai_migrate covenant key_cov_dump)
(sleep 5)
(ai_teleport_to_starting_location_if_outside_bsp key_cov_dump)
(sleep 5)
(ai_set_orders covenant cov_follow_key_ent)
)
;====== COVENANT DEFENSE =================================================================
(script command_script cs_cov_def_phantom
(cs_fly_to qz_cov_def/drop)
(sleep_until g_qz_cov_def_progress)
; (cs_vehicle_speed .35)
( cs_fly_to qz_cov_def / drop .1 )
( sleep 30 )
; (vehicle_unload (ai_vehicle_get_from_starting_location qz_cov_def_spectre/spectre) "phantom_p")
( sleep 30 )
; (unit_exit_vehicle (ai_vehicle_get_from_starting_location qz_cov_def_spectre/spectre))
( sleep ( * 30 2 ) )
(cs_vehicle_speed .85)
(cs_fly_to_and_face qz_cov_def/p4 qz_cov_def/p1 3)
(cs_vehicle_speed 1)
( cs_fly_to qz_cov_def / p0 3 )
( cs_vehicle_speed .7 )
(cs_fly_by qz_cov_def/p1 10)
( cs_vehicle_speed 1 )
(cs_fly_by qz_cov_def/p2 10)
(cs_fly_by qz_cov_def/p3 10)
(ai_erase ai_current_squad)
)
(script command_script cs_cov_def_spec_ops_a
(cs_enable_pathfinding_failsafe true)
(cs_look_player true)
(sleep_until g_qz_cov_def_progress 5)
(cs_go_to_vehicle (ai_vehicle_get_from_starting_location qz_cov_def_ghosts/a))
)
(script command_script cs_cov_def_spec_ops_b
(cs_enable_pathfinding_failsafe true)
(cs_look_player true)
(sleep_until g_qz_cov_def_progress 5)
(cs_go_to_vehicle (ai_vehicle_get_from_starting_location qz_cov_def_ghosts/b))
)
(script command_script cs_cov_def_spec_ops_c
(cs_enable_pathfinding_failsafe true)
(cs_look_player true)
(sleep_until g_qz_cov_def_progress 5)
(cs_go_to_vehicle (ai_vehicle_get_from_starting_location qz_cov_def_spectre/spectre))
)
(script command_script cs_cov_def_spec_ops_d
(cs_enable_pathfinding_failsafe true)
(cs_look_player true)
(sleep_until g_qz_cov_def_progress 5)
(cs_go_to_vehicle (ai_vehicle_get_from_starting_location qz_cov_def_spectre/spectre))
)
;====== VEHICLE INTERIOR SCRIPTS =======================================================
(script command_script cs_go_to_scorpion
(cs_enable_pathfinding_failsafe true)
(cs_go_to_vehicle (ai_vehicle_get_from_starting_location veh_int_scorpion/scorpion))
)
(script command_script cs_go_to_wraith
(cs_enable_pathfinding_failsafe true)
(cs_go_to_vehicle (ai_vehicle_get_from_starting_location veh_int_wraith/wraith))
)
(global boolean g_veh_int_ghost_spawn 0)
(global short g_veh_int_ghost_limit 0)
(global short g_veh_int_ghost_number 0)
(script dormant ai_veh_int_ghost_spawn
(sleep_until (<= (ai_living_count veh_int_flood_ghosts_ini) 0))
(if debug (print "waking vehicle interior ghost spawner"))
(cond
((difficulty_normal) (begin (set g_veh_int_ghost_limit 6) (set g_veh_int_ghost_number 1)))
((difficulty_heroic) (begin (set g_veh_int_ghost_limit 8) (set g_veh_int_ghost_number 2)))
((difficulty_legendary) (begin (set g_veh_int_ghost_limit 10) (set g_veh_int_ghost_number 3)))
)
(sleep_until
(begin
(sleep_until (<= (ai_living_count veh_int_flood_ghosts_bk) 0))
(sleep 90)
(if debug (print "placing ghosts"))
(ai_place veh_int_flood_ghosts_bk g_veh_int_ghost_number)
(or ; exit conditions
(>= (ai_spawn_count veh_int_flood_ghosts_bk) g_veh_int_ghost_limit)
g_veh_int_ghost_spawn)
)
)
(if (<= (ai_living_count veh_int_flood_ghosts_bk) 0) (ai_place veh_int_flood_ghosts_bk))
)
;====== QUARANTINE ZONE EXTERIOR A =======================================================
(script dormant dam_door_a
(sleep_until
(begin
(sleep_until (volume_test_objects tv_dam_door_a (players)) 5)
(device_set_position dam_door_a 1)
false)
)
)
(script dormant dam_door_b
(sleep_until
(begin
(sleep_until (volume_test_objects tv_dam_door_b (players)) 5)
(device_set_position dam_door_b 1)
false)
)
)
(script command_script cs_ext_a_enf_ini
(cs_shoot 1)
(cs_vehicle_boost 1)
(cs_fly_by qz_ext_a_enf/p0 3)
(cs_fly_by qz_ext_a_enf/p1 3)
(cs_fly_by qz_ext_a_enf/p2 3)
(cs_vehicle_boost 0)
)
(script command_script cs_ext_a_pelican
; (cs_enable_pathfinding_failsafe true)
(cs_shoot false)
(vehicle_load_magic
(ai_vehicle_get_from_starting_location qz_ext_a_dam_human/pelican)
"pelican_lc"
(ai_vehicle_get_from_starting_location qz_ext_a_dam_human/scorpion)
)
(cs_fly_by qz_ext_a_pelican/p0 3)
( cs_fly_by qz_ext_a_pelican / p1 3 )
(cs_fly_by qz_ext_a_pelican/p2 3)
(cs_fly_by qz_ext_a_pelican/p3 5)
( cs_fly_by qz_ext_a_pelican / p4 3 )
(cs_fly_by qz_ext_a_pelican/p5 3)
(sleep 30)
(ai_erase ai_current_squad)
)
(script command_script cs_boost_1_5
(cs_vehicle_boost true)
(sleep (* 30 1.5))
(cs_vehicle_boost false)
)
(global vehicle v_ext_a_phantom none)
(script command_script cs_ext_a_phantom
(ai_place qz_ext_a_spec_ops)
(ai_place qz_ext_a_ghosts)
(cs_shoot true)
(cs_enable_pathfinding_failsafe true)
(sleep 1)
(vehicle_load_magic
v_ext_a_phantom
"phantom_p"
(ai_actors qz_ext_a_spec_ops)
)
(vehicle_load_magic
v_ext_a_phantom
"phantom_sc01"
(ai_vehicle_get_from_starting_location qz_ext_a_ghosts/a)
)
(vehicle_load_magic
v_ext_a_phantom
"phantom_sc02"
(ai_vehicle_get_from_starting_location qz_ext_a_ghosts/b)
)
(sleep 1)
(cs_vehicle_boost true)
(cs_fly_by qz_ext_a_phantom/p0 5)
(cs_vehicle_boost false)
(cs_fly_by qz_ext_a_phantom/p1 5)
(cs_fly_by qz_ext_a_phantom/p2 4)
(cs_fly_to_and_face qz_ext_a_phantom/p3 qz_ext_a_phantom/unit_face)
(cs_vehicle_speed .75)
(cs_fly_to_and_face qz_ext_a_phantom/drop_units qz_ext_a_phantom/unit_face 2)
(object_set_phantom_power v_ext_a_phantom 1)
(sleep 45)
(vehicle_unload v_ext_a_phantom "phantom_p_a01")
(sleep 30)
(vehicle_unload v_ext_a_phantom "phantom_p_a02")
(sleep 30)
(vehicle_unload v_ext_a_phantom "phantom_p_a03")
( sleep 20 )
(sleep 45)
(cs_fly_to_and_face qz_ext_a_phantom/drop_ghosts qz_ext_a_phantom/face 2)
(sleep_until (not (volume_test_objects_all tv_qz_ext_a_ghost_drop (players))))
(sleep 45)
(vehicle_unload v_ext_a_phantom "phantom_sc")
(sleep 90)
(object_set_phantom_power v_ext_a_phantom 0)
(cs_vehicle_speed 1)
(cs_fly_by qz_ext_a_phantom/p6)
(cs_fly_by qz_ext_a_phantom/p4)
(cs_vehicle_boost true)
(cs_fly_by qz_ext_a_phantom/p7)
(ai_erase ai_current_actor)
)
(global boolean g_qz_ext_a_wraith_shoot 0)
(script command_script cs_wraiths_shoot
(cs_abort_on_damage true)
(sleep_until
(begin
(begin_random
(begin
(cs_shoot_point true qz_ext_a_wraiths/p0)
(sleep (random_range 30 60))
)
(begin
(cs_shoot_point true qz_ext_a_wraiths/p1)
(sleep (random_range 30 60))
)
(begin
(cs_shoot_point true qz_ext_a_wraiths/p2)
(sleep (random_range 30 60))
)
(begin
(cs_shoot_point true qz_ext_a_wraiths/p3)
(sleep (random_range 30 60))
)
(begin
(cs_shoot_point true qz_ext_a_wraiths/p4)
(sleep (random_range 30 60))
)
(begin
(cs_shoot_point true qz_ext_a_wraiths/p5)
(sleep (random_range 30 60))
)
(begin
(cs_shoot_point true qz_ext_a_wraiths/p6)
(sleep (random_range 30 60))
)
(begin
(cs_shoot_point true qz_ext_a_wraiths/p7)
(sleep (random_range 30 60))
)
)
g_qz_ext_a_wraith_shoot)
)
)
(global boolean g_ext_a_dam_enf 0)
(script dormant ai_ext_a_dam_enforcers
(sleep_until
(begin
(sleep_until (<= (ai_living_count ext_a_sen_dam_b) 0))
(sleep 90)
(ai_place qz_ext_a_dam_enf_door)
(or
(>= (ai_spawn_count qz_ext_a_dam_enf_door) 3)
g_ext_a_dam_enf
)
)
)
)
(script dormant ai_qz_ext_a_wraiths
(ai_place qz_ext_a_flood_wraith_fr)
(ai_place qz_ext_a_flood_wraith_bk)
(ai_place qz_ext_a_flood_wraith_ledge)
)
(global boolean g_qz_ext_a_flood_ghosts 0)
(script dormant ai_qz_ext_a_ghosts
(sleep_until
(begin
(sleep_until (<= (ai_living_count qz_ext_a_flood_ghosts) 0))
(if g_qz_ext_a_flood_ghosts (sleep_forever))
(sleep (random_range 60 120))
(ai_place qz_ext_a_flood_ghosts)
g_qz_ext_a_flood_ghosts)
)
)
(script dormant ai_fact_ent_sen_spawn
(sleep_until
(begin
(sleep_until (<= (ai_living_count fact_ent_sen) 1))
(sleep (random_range 15 30))
(ai_place fact_ent_sen)
(set g_fact_ent_sen_count (+ g_fact_ent_sen_count 1))
(if (= g_fact_ent_sen_count g_fact_ent_sen_index) (set g_fact_ent_sen_spawn 1))
g_fact_ent_sen_spawn)
)
)
(script dormant ai_fact_ent_enf_spawn
(sleep_until
(begin
(sleep_until (<= (ai_living_count fact_ent_enf) 0))
(sleep (random_range 30 60))
(ai_place fact_ent_enf)
(set g_fact_ent_enf_count (+ g_fact_ent_enf_count 1))
(if (= g_fact_ent_enf_count g_fact_ent_enf_index) (set g_fact_ent_sen_spawn 1))
g_fact_ent_sen_spawn)
)
)
(global boolean g_qz_ext_a_d_spawn 1)
(script dormant ai_qz_ext_a_d_spawn
(sleep_until (volume_test_objects tv_ext_a_d (players)))
(if g_qz_ext_a_d_spawn
(begin
(ai_place qz_ext_a_flood_d)
(ai_place qz_ext_a_enf_bk)
)
)
)
= = = = = CRASHED FACTORY SCRIPTS = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
;Respawns exit Flood until the player reaches the end
(script dormant factory_1_flood_respawn ; turn this one off after a few waves (count waves with AI_SPAWN_COUNT)
(sleep_until
(begin
(sleep_until
(OR
(= (volume_test_objects vol_factory_1_mid_03 (players)) TRUE)
(< (ai_nonswarm_count factory1_flood) 3)
)
)
(if (= (volume_test_objects vol_factory_1_mid_03 (players)) FALSE)
(ai_place factory_1_flood_end 1)
(sleep 60)
)
(or
(= (volume_test_objects vol_factory_1_mid_03 (players)) TRUE)
(>= (ai_spawn_count factory_1_flood_end) 10)
)
)
)
)
;Respawns sentinels over course of encounter, switching to different spawn points as the player pushes in
(script dormant factory_1_sentinel_respawn_01
(sleep_until
(begin
(sleep_until
(OR
(= (volume_test_objects vol_factory_1_mid_01 (players)) TRUE)
(< (ai_living_count factory1_sentinels) 2)
)
)
(if (= (volume_test_objects vol_factory_1_mid_01 (players)) FALSE)
(ai_place factory_1_sentinels_01_low 1)
(sleep 120)
)
(if (= (volume_test_objects vol_factory_1_mid_01 (players)) FALSE)
(ai_place factory_1_sentinels_01_high 1)
(sleep 120)
)
(or
(= (volume_test_objects vol_factory_1_mid_01 (players)) TRUE)
(>= (+
(ai_spawn_count factory_1_sentinels_01_low)
(ai_spawn_count factory_1_sentinels_01_high)
)
3)
)
)
)
)
(script dormant factory_1_sentinel_respawn_02
(sleep_until
(begin
(sleep_until
(OR
(= (volume_test_objects vol_factory_1_mid_02 (players)) TRUE)
(< (ai_living_count factory1_sentinels) 2)
)
)
(if (= (volume_test_objects vol_factory_1_mid_02 (players)) FALSE)
(ai_place factory_1_sentinels_02_low 1)
(sleep 120)
)
(if (= (volume_test_objects vol_factory_1_mid_02 (players)) FALSE)
(ai_place factory_1_sentinels_02_high 1)
(sleep 120)
)
(or
(= (volume_test_objects vol_factory_1_mid_02 (players)) TRUE)
(>= (+
(ai_spawn_count factory_1_sentinels_02_low)
(ai_spawn_count factory_1_sentinels_02_high)
)
6)
)
)
)
)
;Respawns the sentinels fighting the flood at the exit
(script dormant factory_1_sentinel_enders
(sleep_until
(begin
(sleep_until
(OR
(= (volume_test_objects vol_factory_1_mid_03 (players)) TRUE)
(< (ai_living_count factory1_sentinels) 2)
)
)
(if (= (volume_test_objects vol_factory_1_mid_03 (players)) FALSE)
(ai_place factory_1_sentinels_03_low 1)
(sleep 120)
)
(if (= (volume_test_objects vol_factory_1_mid_03 (players)) FALSE)
(ai_place factory_1_sentinels_03_high 1)
(sleep 120)
)
(or
(= (volume_test_objects vol_factory_1_mid_03 (players)) TRUE)
(>= (+
(ai_spawn_count factory_1_sentinels_03_low)
(ai_spawn_count factory_1_sentinels_03_high)
)
6)
)
)
)
)
;Waits until major is dead before the Flood pour in
(script dormant factory_1_flood_surge
(sleep_until (= (ai_living_count factory_1_major) 0))
(sleep_forever factory_1_flood_respawn)
(ai_set_orders factory1_flood factory_1_flood_tubes_fwd)
(sleep_until
(begin
(sleep_until
(OR
(= (volume_test_objects vol_factory_1_mid_03 (players)) TRUE)
(< (ai_nonswarm_count factory1_flood) 3)
)
)
(if (= (volume_test_objects vol_factory_1_mid_03 (players)) FALSE)
(ai_place factory_1_flood_end 1)
(sleep 120)
)
(if (= (volume_test_objects vol_factory_1_mid_03 (players)) FALSE)
(ai_place factory_1_flood_tubes_far 1)
(sleep 120)
)
(if (= (volume_test_objects vol_factory_1_mid_03 (players)) FALSE)
(ai_place factory_1_flood_tubes_near 1)
(sleep 120)
)
(if (= (volume_test_objects vol_factory_1_mid_03 (players)) FALSE)
(ai_place factory_1_flood_alcove 1)
(sleep 120)
)
(or
(= (volume_test_objects vol_factory_1_mid_03 (players)) TRUE)
(>= (+
(ai_spawn_count factory_1_flood_end)
(ai_spawn_count factory_1_flood_tubes_far)
(ai_spawn_count factory_1_flood_tubes_near)
(ai_spawn_count factory_1_flood_alcove)
)
10)
)
)
)
(sleep_until
(begin
(sleep_until
(OR
(= (volume_test_objects vol_factory_1_exit (players)) TRUE)
(< (ai_nonswarm_count factory1_flood) 2)
)
)
(if (= (volume_test_objects vol_factory_1_exit (players)) FALSE)
(ai_place factory_1_flood_end 1)
(sleep 120)
)
(or
(= (volume_test_objects vol_factory_1_exit (players)) TRUE)
(>= (ai_spawn_count factory_1_flood_end) 8)
)
)
)
)
Overall script for sentinel factory 1
(script dormant sent_factory_1_start
(sleep_until (= (volume_test_objects vol_factory_1_enter (players)) TRUE))
(game_save)
(ai_place factory_1_sentinels_intro)
(ai_place factory_1_flood_intro)
(ai_place factory_1_major)
(ai_place factory_1_sentinels_initial_mid)
(ai_place factory_1_flood_initial_mid)
(wake factory_1_flood_surge)
(wake factory_1_flood_respawn)
(wake factory_1_sentinel_respawn_01)
(wake factory_1_sentinel_enders)
(sleep_until
(OR
(= (volume_test_objects vol_factory_1_mid_01 (players)) TRUE)
(< (ai_nonswarm_count factory1_enemies) 8)
)
)
(game_save_no_timeout)
(ai_place factory_1_sentinels_initial_end)
(ai_place factory_1_flood_initial_end)
(sleep_until (= (volume_test_objects vol_factory_1_mid_01 (players)) TRUE))
(game_save)
(sleep_forever factory_1_sentinel_respawn_01)
(wake factory_1_sentinel_respawn_02)
(ai_renew covenant)
(sleep_until (= (volume_test_objects vol_factory_1_mid_02 (players)) TRUE))
(game_save)
(sleep_forever factory_1_sentinel_respawn_02)
(sleep_until (= (volume_test_objects vol_factory_1_mid_03 (players)) TRUE))
(game_save)
(sleep_forever factory_1_sentinel_enders)
(sleep_forever factory_1_flood_respawn)
(sleep_until (= (volume_test_objects vol_factory_1_exit (players)) TRUE))
(game_save)
(if (= (ai_living_count factory_1_major) 1)
(sleep_forever factory_1_flood_surge)
)
)
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
(global boolean g_gorge_sen_spawn 0)
(script dormant ai_sentinel_spawn
(sleep_until
(begin
(sleep_until (<= (ai_living_count gorge_sen) 0))
(sleep 150)
(ai_place gorge_sen)
g_gorge_sen_spawn)
)
)
(script dormant ai_gorge
( ai_place gorge_jugg_a )
( ai_place gorge_jugg_b )
(ai_place gorge_flood_ini)
(ai_place gorge_enf)
(wake ai_sentinel_spawn)
(sleep_until (volume_test_objects tv_gorge_mid (players)))
(game_save_no_timeout)
(ai_place gorge_flood_bk)
(sleep_until (volume_test_objects tv_gorge_bk_cave (players)))
(ai_place gorge_flood_bk_cave)
(set g_gorge_sen_spawn 1)
)
= = = = = FACTORY 2 SCRIPTS = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
(script dormant ai_factory2
(ai_place factory2_flood_ini)
(sleep_until (volume_test_objects tv_factory2_mid (players)))
(game_save_no_timeout)
(if (<= (ai_living_count factory2_flood) 4)
(begin
(ai_place factory2_flood_mid)
(ai_place factory2_flood_bk)
)
)
(sleep_until (volume_test_objects tv_factory2_bk (players)))
(game_save)
(ai_place factory2_flood_bk_tunnel)
(ai_place factory2_sen_bk_tunnel)
)
;===== QUARANTINE ZONE EXTERIOR B ========================================================
(script dormant ai_constructor_flock
(flock_start constructor_swarm)
(sleep 150)
(flock_stop constructor_swarm)
)
(global boolean g_ext_b_phantom 0)
(global vehicle v_ext_b_phantom none)
(script command_script cs_ext_b_phantom ; called from the starting location
(cs_shoot true)
(cs_enable_pathfinding_failsafe true)
(ai_place qz_ext_b_cov_spec_ops)
( ai_place qz_ext_b_cov_ghosts )
(ai_place qz_ext_b_cov_spectre)
(object_cannot_die (ai_get_object qz_ext_b_cov_spec_ops/soc) true)
(sleep 1)
(vehicle_load_magic v_ext_b_phantom "phantom_p" (ai_actors qz_ext_b_cov_spec_ops))
(vehicle_load_magic v_ext_b_phantom "phantom_sc01" (ai_vehicle_get_from_starting_location qz_ext_b_cov_ghosts/a))
(vehicle_load_magic v_ext_b_phantom "phantom_sc02" (ai_vehicle_get_from_starting_location qz_ext_b_cov_ghosts/b))
(vehicle_load_magic v_ext_b_phantom "phantom_lc" (ai_vehicle_get_from_starting_location qz_ext_b_cov_spectre/spectre))
(sleep 1)
(cs_vehicle_boost true)
(cs_fly_by qz_ext_b_phantom/p0 5)
(cs_fly_by qz_ext_b_phantom/p1 5)
(cs_vehicle_boost false)
(ai_magically_see qz_ext_b_wraith_a qz_ext_b_cov_phantom)
(cs_fly_by qz_ext_b_phantom/p2 5)
(cs_fly_by qz_ext_b_phantom/p3 3)
(cs_fly_to qz_ext_b_phantom/p4)
(cs_face true qz_ext_b_phantom/p2)
( sleep 30 )
(cs_vehicle_speed .65)
(cs_fly_to_and_face qz_ext_b_phantom/drop qz_ext_b_phantom/p2)
(object_set_phantom_power v_ext_b_phantom 1)
; (sleep_until g_ext_b_phantom)
(sleep 45)
(vehicle_unload v_ext_b_phantom "phantom_sc")
(vehicle_unload v_ext_b_phantom "phantom_lc")
(sleep 45)
(vehicle_unload v_ext_b_phantom "phantom_p_a01")
(sleep 30)
(vehicle_unload v_ext_b_phantom "phantom_p_a02")
(sleep 30)
(vehicle_unload v_ext_b_phantom "phantom_p_a03")
(sleep 45)
(object_set_phantom_power v_ext_b_phantom 0)
; (ai_vehicle_enter qz_ext_b_cov_spec_ops (ai_vehicle_get_from_starting_location qz_ext_b_cov_ghosts/a))
; (ai_vehicle_enter qz_ext_b_cov_spec_ops (ai_vehicle_get_from_starting_location qz_ext_b_cov_ghosts/b))
(ai_vehicle_enter qz_ext_b_cov_spec_ops (ai_vehicle_get_from_starting_location qz_ext_b_cov_spectre/spectre))
(cs_face false qz_ext_b_phantom/p2)
(cs_vehicle_speed 1)
(sleep 60)
(wake sc_ext_b)
(cs_fly_by qz_ext_b_phantom/p2 3)
(cs_fly_by qz_ext_b_phantom/p1 3)
(cs_fly_by qz_ext_b_phantom/p0 3)
(ai_erase ai_current_squad)
)
(global boolean g_ext_b_ent_phantom 0)
(script command_script cs_ext_b_ent_phantom ; called from the starting location
(cs_enable_pathfinding_failsafe 1)
(cs_vehicle_boost true)
(cs_fly_by qz_ext_b_ent_phantom/p0 5)
(cs_fly_by qz_ext_b_ent_phantom/p1 5)
(cs_fly_by qz_ext_b_ent_phantom/p2 5)
(cs_vehicle_boost false)
(cs_fly_to qz_ext_b_ent_phantom/p3)
(cs_face true qz_ext_b_ent_phantom/p5)
( sleep 30 )
(cs_vehicle_speed .65)
(cs_fly_to qz_ext_b_ent_phantom/drop)
(sleep_until g_ext_b_ent_phantom)
(cs_face false qz_ext_b_ent_phantom/p5)
(cs_vehicle_speed 1)
(cs_fly_by qz_ext_b_ent_phantom/p5 3)
(cs_vehicle_boost true)
(cs_fly_by qz_ext_b_ent_phantom/p6 3)
(ai_erase ai_current_squad)
)
(script dormant ai_ext_b_exit_tube_a
(sleep_until (volume_test_objects tv_ext_b_exit_tube_a (players)))
(ai_place qz_ext_b_ent_flood_tube_a (pin (- 8 (ai_nonswarm_count ext_b_flood)) 0 6))
)
(script dormant ai_ext_b_exit_tube_b
(sleep_until (volume_test_objects tv_ext_b_exit_tube_b (players)))
(ai_place qz_ext_b_ent_flood_tube_b (pin (- 8 (ai_nonswarm_count ext_b_flood)) 0 6))
)
(global boolean g_ext_b_enforcer 0)
(script dormant ai_ext_b_enf_spawn
(sleep_until
(begin
(sleep_until (<= (ai_living_count ext_b_sentinels_b) 0))
(cond
((volume_test_objects tv_ext_b_mid (players)) (ai_place qz_ext_b_enf_b))
(true (ai_place qz_ext_b_enf_a))
)
(or ; exit conditions
(>= (ai_spawn_count ext_b_sentinels_b) 4)
g_ext_b_enforcer
)
)
)
)
(global boolean g_ext_b_bk_ghost_spawn 0)
(global short g_ext_b_bk_ghost_limit 0)
(global short g_ext_b_bk_ghost_number 0)
(script dormant ai_ext_b_bk_ghost_spawn
(cond
((difficulty_normal) (begin (set g_ext_b_bk_ghost_limit 6) (set g_ext_b_bk_ghost_number 1)))
((difficulty_heroic) (begin (set g_ext_b_bk_ghost_limit 8) (set g_ext_b_bk_ghost_number 2)))
((difficulty_legendary) (begin (set g_ext_b_bk_ghost_limit 10) (set g_ext_b_bk_ghost_number 3)))
)
(sleep_until
(begin
(sleep_until (<= (ai_living_count qz_ext_b_ent_ghost_bk) 0))
(sleep 90)
(if debug (print "placing ghosts"))
(ai_place qz_ext_b_ent_ghost_bk g_ext_b_bk_ghost_number)
(or ; exit conditions
(>= (ai_spawn_count qz_ext_b_ent_ghost_bk) g_ext_b_bk_ghost_limit)
g_ext_b_bk_ghost_spawn)
)
)
)
;= KEY CONTROL ===========================================================================
;*
;|Scripts which drive the key's motion through the level.
|Also , scripts which drive Tartarus 's dropship , and the human key .
;|
;*;
;- Globals ---------------------------------------------------------------------
; Flags for transmitting key state
(global boolean g_key_started false)
(global boolean g_key_lock0_entered false)
(global boolean g_key_lock0_first_loadpoint false)
(global boolean g_key_lock0_second_loadpoint false)
(global boolean g_key_lock0_begin_human false)
(global boolean g_key_lock0_door1 false)
(global boolean g_key_cruise_entered false)
(global boolean g_key_cruise_first_loadpoint false)
(global boolean g_key_cruise_halfway false)
(global boolean g_key_shaft_entered false)
(global boolean g_key_shaft_rising false)
(global boolean g_key_shaft_near_exterior false)
(global boolean g_key_lock1_entered false)
(global boolean g_key_lock1_first_arch false)
(global boolean g_key_lock1_second_arch false)
(global boolean g_key_library_entered false)
(global boolean g_key_library_arrival false)
;- Event Control ---------------------------------------------------------------
(script dormant key_ride_door3_main
; Begin opening
(print "key_ride_door3 begins to open")
(device_set_position key_ride_door3 1.0)
; Sleep until finished opening
(sleep_until (>= (device_get_position key_ride_door3) 0.9) 10)
(sleep 60)
; Begin closing
(print "key_ride_door3 begins to close")
(device_set_position key_ride_door3 0.0)
)
(script dormant key_ride_human_door2_main
; Begin opening
(print "human_key_door2 begins to open")
(device_set_position human_key_door2 1.0)
; Sleep until finished opening
(sleep_until (>= (device_get_position human_key_door2) 0.9) 10)
; Begin closing
(print "human_key_door2 begins to close")
(device_set_position human_key_door2 0.0)
)
(script dormant key_ride_door2_main
; Begin opening
(print "key_ride_door2 begins to open")
(device_set_position key_ride_door2 1.0)
; Sleep until finished opening
(sleep_until (>= (device_get_position key_ride_door2) 0.9) 10)
; Begin closing
(print "key_ride_door2 begins to close")
(device_set_position key_ride_door2 0.0)
)
(script dormant key_ride_door1_main
; Begin opening
(print "key_ride_door1 begins to open")
(device_set_position key_ride_door1 1.0)
; Sleep until finished opening
(sleep_until (>= (device_get_position key_ride_door1) 0.9) 10)
(sleep 60)
; Begin closing
(print "key_ride_door1 begins to close")
(device_set_position key_ride_door1 0.0)
)
(script dormant key_ride_door0_main
; Begin opening
(print "key_ride_door0 begins to open")
(device_set_position_immediate key_ride_door0 0.32)
(device_closes_automatically_set key_ride_door0 false)
(device_set_position key_ride_door0 1.0)
; Sleep until finished opening
(sleep_forever)
(sleep_until (>= (device_get_position key_ride_door0) 0.9) 10)
(sleep 540)
; Begin closing
(print "key_ride_door0 begins to close")
(device_set_position key_ride_door0 0.0)
)
(script dormant key_main
For
(wake key_ride_door0_main)
; When awakened, this script starts the key in the correct place and
; drives it for the rest of the mission. Progress is inexorable--everything
; adjusts to the omnipotent key. All fear the key! THE KEY WILL DESTROY YOU
; Make it always active
(pvs_set_object key)
;- Horizontal Section ---------------------------------------
; Start the sound
(sound_looping_start "sound\ambience\device_machines\shq__key\shq__key" none 1.0)
; Set the track and go
(device_set_position_track key track_horiz0 0)
; Get it to the initial position
(device_animate_position key 0.3 0.0 0 0 false)
(sleep 5)
; Teleport the players onto the key
(object_teleport (player0) key_ent0)
(object_teleport (player1) key_ent1)
(sleep 5)
Begin the first leg , to the interior cruise
(device_animate_position key 0.6 75 0 0 false)
(set g_key_started true)
; Sleep until the key is in position to begin opening the next door
(sleep_until
(>= (device_get_position key) 0.35)
3
)
Begin opening the first door
(wake key_ride_door0_main)
Sleep until the key is entering the first lock
(sleep_until
(>= (device_get_position key) 0.4)
3
)
(set g_key_lock0_first_loadpoint true)
Flag that we 're entering the first lock
(set g_key_lock0_entered true)
Sleep until the key is passing the first loading point
(sleep_until
(>= (device_get_position key) 0.43)
3
)
(set g_key_lock0_first_loadpoint true)
; Sleep until the key is in position for a bsp swap
(sleep_until
(>= (device_get_position key) 0.48)
3
)
; Swap BSPs
(switch_bsp_by_name sen_hq_bsp_6)
; Sleep until the key is approaching the next load point
(sleep_until
(>= (device_get_position key) 0.50)
3
)
(set g_key_lock0_second_loadpoint true)
; Sleep until we should start the Human key
(sleep_until
(>= (device_get_position key) 0.50)
3
)
(set g_key_lock0_begin_human true)
; Sleep until the key is in position to begin opening the next door
(sleep_until
(>= (device_get_position key) 0.53)
3
)
(set g_key_lock0_door1 true)
; Begin opening the door
(wake key_ride_door1_main)
; Sleep until the key is entering the interior cruise
(sleep_until
(>= (device_get_position key) 0.58)
3
)
(set g_key_cruise_entered true)
Accelerate
(device_animate_position key 1.0 45 5 10 true)
Sleep until the key is near the first loadpoint , then the second
(sleep_until
(>= (device_get_position key) 0.67)
3
)
(set g_key_cruise_first_loadpoint true)
(sleep_until
(>= (device_get_position key) 0.84)
3
)
(set g_key_cruise_halfway true)
; Sleep until the key is into the vertical rise
(sleep_until
(>= (device_get_position key) 1.0)
3
)
(set g_key_shaft_entered true)
;- Vertical Section -----------------------------------------
; Short pause
(sleep 30)
; Set the tracks and go
(device_set_position_track key track_rise 0)
(device_set_overlay_track key overlay_transform)
; Start the alt track
(sound_looping_set_alternate "sound\ambience\device_machines\shq__key\shq__key" true)
; TRANSFORM AND ROLL OUT!!!1
(device_animate_overlay key 1.0 5 0 0)
(sleep 180)
; Start it moving
(device_animate_position key 1.0 90 20 10 false)
(set g_key_shaft_rising true)
(set g_music_06b_06 1)
; Sleep until the key is near the interior->exterior shaft transition
(sleep_until
(>= (device_get_position key) 0.3)
3
)
(set g_key_shaft_near_exterior true)
Sleep until the key is in position to begin opening the third door
(sleep_until
(>= (device_get_position key) 0.73)
3
)
; Begin opening the door
(wake key_ride_door2_main)
; Sleep until the key is in position to transform back
(sleep_until
(>= (device_get_position key) 1.0)
3
)
(set g_key_lock1_entered true)
; Start the alt track
(sound_looping_stop "sound\ambience\device_machines\shq__key\shq__key")
;- Horizontal Section ---------------------------------------
; Short pause
(sleep 30)
; Set the track and go
(device_set_position_track key track_horiz1 0)
; Start the sound
(sound_looping_start "sound\ambience\device_machines\shq__key\shq__key" none 1.0)
; TRANSFORM AND ROLL OUT!!!1
(device_animate_overlay key 0.0 5 0 0)
(sleep 180)
; Start it moving
(device_animate_position key 1.0 75 10 10 false)
Sleep until the key is near the first arch
(sleep_until
(>= (device_get_position key) 0.15)
3
)
(set g_key_lock1_first_arch true)
Sleep until the key is near the second arch
(sleep_until
(>= (device_get_position key) 0.4)
3
)
(set g_key_lock1_second_arch true)
; Sleep until the key is in position to begin opening the last door
(sleep_until
(>= (device_get_position key) 0.49)
3
)
; Begin opening the door
(wake key_ride_door3_main)
; Sleep until the key is entering the library
(sleep_until
(>= (device_get_position key) 0.65)
3
)
(set g_key_library_entered true)
; Sleep until the key is halfway in
(sleep_until
(>= (device_get_position key) 0.85)
3
)
; Begin tilting up the outriggers
(device_animate_overlay key 1.0 5 0 0)
; Ride it out
(sleep_until
(>= (device_get_position key) 1.0)
3
)
(set g_key_library_arrival true)
(wake chapter_familiar)
(wake sc_dock)
(set g_music_06b_05 0)
; Start the alt track
(sound_looping_stop "sound\ambience\device_machines\shq__key\shq__key")
)
(script dormant key_ride_human_key_main
; Do the exterior stuff
; Sleep until the player is near the interior cruise
(sleep_until g_key_lock0_begin_human 10)
; Place the key, and move it into position
(object_create_anew key_human)
; Make it always active
(pvs_set_object key_human)
; Set the track and go
(device_set_position_track key_human track_horiz0 0)
; Get it to the initial position
(device_animate_position key_human 0.58 0.5 0 0 false)
(sleep 15)
(device_animate_position key_human 1.0 55 5 10 false)
; Sleep until the key is into the vertical rise
(sleep_until
(>= (device_get_position key_human) 1.0)
3
)
;- Vertical Section -----------------------------------------
; Short pause
(sleep 30)
; Set the tracks and go
(device_set_position_track key_human track_rise 0)
(device_set_overlay_track key_human overlay_transform)
; TRANSFORM AND ROLL OUT!!!1
(device_animate_overlay key_human 1.0 5 0 0)
(sleep 180)
; Start it moving
(device_animate_position key_human 1.0 80 20 10 false)
; Sleep until the key is in position to begin opening the door
(sleep_until
(>= (device_get_position key_human) 0.71)
3
)
; Begin opening the door
(wake key_ride_human_door2_main)
; Sleep until the key is in position to transform back
(sleep_until
(>= (device_get_position key_human) 1.0)
3
)
;- Horizontal Section ---------------------------------------
; Short pause, let the other key catch up
(sleep 120)
; Set the track and go
(device_set_position_track key_human track_horiz1 0)
; TRANSFORM AND ROLL OUT!!!1
(device_animate_overlay key_human 0.0 5 0 0)
(sleep 180)
; Start it moving
(device_animate_position key_human 1.0 75 10 10 false)
; Sleep until the key is out of sight, and then end this charade
(sleep_until
(>= (device_get_position key_human) 0.191)
3
)
(object_destroy key_human)
; Set the overlay of the docked key
(object_create_anew key_docked)
(sleep 1)
(device_set_overlay_track key_docked overlay_transform)
(device_animate_overlay key_docked 1.0 0.1 0 0)
)
(script command_script cs_e21_tartarus
(cs_enable_pathfinding_failsafe true)
(print "e21 *tartarus returns from harassing human key*")
(cs_vehicle_boost true)
(cs_fly_by e21_tartarus/p0)
(cs_vehicle_boost false)
; Move in behind the key
(print "e21 *tartarus follows the key in through the door*")
(cs_fly_by e21_tartarus/p1)
; Follow the key
(cs_vehicle_speed 0.75)
(cs_enable_pathfinding_failsafe false)
(sleep_until
(begin
(cs_fly_by key_bsp5/left)
false
)
3
300
)
; Move in behind the key
(cs_vehicle_speed 0.85)
(cs_face true e22_tartarus_bsp6/forward_facing)
; Hold position
(sleep_until
(begin
(cs_fly_by key_bsp5/center)
false
)
3
300
)
)
(script command_script cs_e22_tartarus
(cs_face false e22_tartarus_bsp6/forward_facing)
(cs_fly_by e22_tartarus/p0)
(cs_fly_by e22_tartarus/p1)
; Boost ahead and through
(cs_vehicle_boost true)
(cs_fly_by e22_tartarus/p2)
(cs_vehicle_boost false)
; Wait for them
(cs_fly_to e22_tartarus/p3 1.0)
(sleep 50)
(cs_face true e22_tartarus_bsp6/forward_facing)
(cs_vehicle_speed 0.9)
(cs_fly_by key_bsp6/center_front)
(cs_vehicle_speed 0.9)
(sleep_until
(begin
(cs_fly_by key_bsp6/center_front 1.0)
false
)
3
)
)
(script command_script cs_e23_tartarus
; Head off to the Human key
(cs_vehicle_speed 1.0)
(cs_vehicle_boost true)
(cs_fly_by e23_tartarus/p0)
(cs_fly_by e23_tartarus/p1)
(cs_vehicle_boost false)
(cs_fly_by e23_tartarus/p2)
; Join in with it
(cs_vehicle_speed 1.0)
(sleep_until
(begin
(cs_fly_by key_human_bsp6/left_high 1.0)
false
)
3
360
)
; And teleport him to safety
(cs_teleport e23_tartarus/teleport_dest e23_tartarus/teleport_facing)
(sleep_forever)
)
(script command_script cs_e24_tartarus
(sleep 200)
(cs_vehicle_speed 0.6)
(cs_fly_by e24_tartarus/p0)
(cs_vehicle_speed 1.0)
(cs_fly_by e24_tartarus/p1)
(cs_fly_by e24_tartarus/p2)
(sleep_forever)
)
(script command_script cs_e25_tartarus
(sleep 120)
(cs_face true e25_tartarus/p0)
(sleep 60)
(cs_face false e25_tartarus/p0)
(cs_vehicle_speed 0.6)
(cs_fly_by e25_tartarus/p0)
; Head up to the arch
(cs_vehicle_speed 1.0)
(cs_fly_to e25_tartarus/p1 1.0)
(cs_face true e25_tartarus/p1_facing)
(sleep 320)
(cs_face false e25_tartarus/p1_facing)
Fall in behind the key
(cs_vehicle_speed 1.0)
( cs_fly_by e25_tartarus / p2 1.0 )
(cs_fly_by key_bsp6/center 1.0)
(cs_vehicle_speed 0.9)
(sleep_until
(begin
(cs_fly_by key_bsp6/center 1.0)
false
)
3
)
)
(script command_script cs_e26_tartarus
Fall in behind the key
(cs_vehicle_speed 0.9)
(sleep_until
(begin
(cs_fly_by key_bsp6/center 1.0)
false
)
3
210
)
; Fly off to check out the human key
(cs_fly_to e26_tartarus/p0)
(sleep 120)
(cs_fly_by e26_tartarus/p1)
(cs_fly_by e26_tartarus/p2)
(ai_erase ai_current_squad)
)
(script dormant key_ride_tartarus_main
(ai_place key_ride_tartarus)
; e21 stuff
(cs_run_command_script key_ride_tartarus/tartarus cs_e21_tartarus)
; e22 stuff
(sleep_until (= (structure_bsp_index) 4) 10)
(cs_run_command_script key_ride_tartarus/tartarus cs_e22_tartarus)
; e23 stuff
(sleep_until g_key_cruise_entered 10)
(cs_run_command_script key_ride_tartarus/tartarus cs_e23_tartarus)
; e24 stuff
(sleep_until g_key_shaft_near_exterior 10)
(cs_run_command_script key_ride_tartarus/tartarus cs_e24_tartarus)
; e25 stuff
(sleep_until g_key_lock1_entered 10)
(cs_run_command_script key_ride_tartarus/tartarus cs_e25_tartarus)
; e26 stuff
(sleep_until g_key_library_entered 10)
(cs_run_command_script key_ride_tartarus/tartarus cs_e26_tartarus)
)
(script static void key_ride_test
(wake key_main)
(wake key_ride_human_key_main)
(wake key_ride_tartarus_main)
)
= ENCOUNTER 26 = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
;*
|The Library . MWA - HAH - HAH - HAAAAaaaaa ....
;|
;|Begins when player steps off the key.
;|Ends with the mission.
;|
;|Flood
;| e26_fld_inf0 - Packs of infection forms that scurry about
;|
;|Open Issues
;|
;*;
;- Globals ---------------------------------------------------------------------
Encounter has been activated ?
(global boolean g_e26_ended false)
;- Command Scripts -------------------------------------------------------------
(script command_script cs_e26_fld_infections_entry3
(cs_abort_on_damage true)
(sleep 30)
(cs_go_to e26_fld_infection_forms0/p2)
(cs_go_to e26_fld_infection_forms0/p3)
(cs_go_to e26_fld_infection_forms0/p4)
(cs_go_to e26_fld_infection_forms0/p5)
(ai_erase ai_current_actor)
)
(script command_script cs_e26_fld_infections_entry2
(cs_abort_on_damage true)
(sleep 30)
(cs_go_to e26_fld_infection_forms0/p6)
(cs_go_to e26_fld_infection_forms0/p7)
(cs_go_to e26_fld_infection_forms0/p2)
(cs_go_to e26_fld_infection_forms0/p3)
(cs_go_to e26_fld_infection_forms0/p4)
(cs_go_to e26_fld_infection_forms0/p5)
(ai_erase ai_current_actor)
)
(script command_script cs_e26_fld_infections_entry1
(cs_abort_on_damage true)
(sleep 30)
(cs_go_to e26_fld_infection_forms0/p8)
(cs_go_to e26_fld_infection_forms0/p7)
(cs_go_to e26_fld_infection_forms0/p2)
(cs_go_to e26_fld_infection_forms0/p3)
(cs_go_to e26_fld_infection_forms0/p4)
(cs_go_to e26_fld_infection_forms0/p5)
(ai_erase ai_current_actor)
)
(script command_script cs_e26_fld_infections_entry0
(cs_abort_on_damage true)
(sleep 30)
(cs_go_to e26_fld_infection_forms0/p0)
(cs_go_to e26_fld_infection_forms0/p1)
(cs_go_to e26_fld_infection_forms0/p2)
(cs_go_to e26_fld_infection_forms0/p3)
(cs_go_to e26_fld_infection_forms0/p4)
(cs_go_to e26_fld_infection_forms0/p5)
(ai_erase ai_current_actor)
)
;- Order Scripts ---------------------------------------------------------------
;- Event Scripts ---------------------------------------------------------------
(script dormant e26_smg1
(object_create e26_smg1)
(sleep_until
(begin
(weapon_hold_trigger e26_smg1 0 true)
(sleep_until g_e26_ended 2 (random_range 15 45))
(weapon_hold_trigger e26_smg1 0 false)
(sleep_until g_e26_ended 2 (random_range 45 90))
; Loop until the encounter ends
g_e26_ended
)
1
)
(weapon_hold_trigger e26_smg1 0 false)
(object_destroy e26_smg1)
)
(script dormant e26_smg0
(object_create e26_smg0)
(sleep_until
(begin
(weapon_hold_trigger e26_smg0 0 true)
(sleep_until g_e26_ended 2 (random_range 15 45))
(weapon_hold_trigger e26_smg0 0 false)
(sleep_until g_e26_ended 2 (random_range 45 90))
; Loop until the encounter ends
g_e26_ended
)
1
)
(weapon_hold_trigger e26_smg0 0 false)
(object_destroy e26_smg0)
)
;- Squad Controls --------------------------------------------------------------
(script dormant e26_fld_infections_main
(ai_place e26_fld_infection_forms0/swarm0)
(sleep_until (< (objects_distance_to_flag (players) e26_fld_infs0_1) 10) 10 300)
(ai_place e26_fld_infection_forms0/swarm1)
(sleep_until (< (objects_distance_to_flag (players) e26_fld_infs0_2) 10) 10 300)
(ai_place e26_fld_infection_forms0/swarm2)
(sleep_until (< (objects_distance_to_flag (players) e26_fld_infs0_3) 10) 10 300)
(ai_place e26_fld_infection_forms0/swarm3)
)
;- Init and Cleanup ------------------------------------------------------------
(script dormant e26_main
(sleep_until (volume_test_objects tv_e26_main_begin (players)) 10)
(data_mine_set_mission_segment enc_e26)
(set g_e26_started true)
(print "e26_main")
(game_save)
; Wake subsequent scripts
; Wake control scripts
(wake e26_fld_infections_main)
(wake e26_smg0)
(wake e26_smg1)
Encounter end condition
(sleep_until
(or
(volume_test_objects tv_mission_end0 (players))
(volume_test_objects tv_mission_end1 (players))
)
10
)
(set g_e26_ended 1)
)
= ENCOUNTER 25 = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
;*
|Flood combat in the second interior lock .
;|
;|Begins when the key reaches the top of the shaft.
;|Ends sometime later (indeterminate).
;|
|Elites
;| e25_cov_inf0 - Elite allies
;| (init) - Fighting and covering
;|
;|Flood
;| e25_fld_inf0 - First arch Flood
;| _0 - First carrier wave
;| _1 - Second carrier wave
;| _2 - Combat forms
;| (engage) - Engaging Covenant
;| e25_fld_inf1 - Second arch Flood
;| _0 - First carrier wave
;| _1 - Second carrier wave
;| _2 - Combat forms
;| (engage) - Engaging Covenant
;|
;|Open Issues
;|
;*;
;- Globals ---------------------------------------------------------------------
Encounter has been activated ?
;- Command Scripts -------------------------------------------------------------
(script command_script cs_e25_scene3
; Send both Elites to their destinations
(cs_switch "elite1")
(cs_start_to e25_scenes/p1)
(cs_switch "elite0")
(cs_start_to e25_scenes/p0)
; Wait until he's close to the player or done moving
(sleep_until
(or
(not (cs_moving))
(and
(> (objects_distance_to_object (players) (ai_get_object ai_current_actor)) 0)
(< (objects_distance_to_object (players) (ai_get_object ai_current_actor)) 4)
)
)
)
; Stop and face the player
(cs_face_player true)
(cs_approach (ai_get_object ai_current_actor) 1 1 1) ; Hack, whee
; Wait for the player to be closer still
(sleep_until
(and
(> (objects_distance_to_object (players) (ai_get_object ai_current_actor)) 0)
(< (objects_distance_to_object (players) (ai_get_object ai_current_actor)) 4)
)
)
(print "elite0: we'll guard the key")
(sleep (ai_play_line_at_player ai_current_actor 0910))
(sleep 20)
; Second Elite chimes in
(cs_switch "elite1")
; Wait until he's close to the player or done moving
(sleep_until
(or
(not (cs_moving))
(and
(> (objects_distance_to_object (players) (ai_get_object ai_current_actor)) 0)
(< (objects_distance_to_object (players) (ai_get_object ai_current_actor)) 4)
)
)
)
; Stop and face the player
(cs_face_player true)
(cs_approach (ai_get_object ai_current_actor) 1 1 1) ; Hack, whee
; Wait for the player to be closer still
(sleep_until
(and
(> (objects_distance_to_object (players) (ai_get_object ai_current_actor)) 0)
(< (objects_distance_to_object (players) (ai_get_object ai_current_actor)) 4)
)
)
(print "elite1: git to werk")
(sleep (ai_play_line_at_player ai_current_actor 0920))
)
(script command_script cs_e25_scene1
(cs_start_to e25_scenes/p0)
; Wait until he's close to the player or done moving
(sleep_until
(or
(not (cs_moving))
(and
(> (objects_distance_to_object (players) (ai_get_object ai_current_actor)) 0)
(< (objects_distance_to_object (players) (ai_get_object ai_current_actor)) 4)
)
)
)
; Stop and face the player
(cs_face_player true)
(cs_approach (ai_get_object ai_current_actor) 1 1 1) ; Hack, whee
; Wait for the player to be closer still
(sleep_until
(and
(> (objects_distance_to_object (players) (ai_get_object ai_current_actor)) 0)
(< (objects_distance_to_object (players) (ai_get_object ai_current_actor)) 4)
)
)
(print "elite0: we'll guard the key")
(sleep (ai_play_line_at_player ai_current_actor 0910))
(sleep 15)
(print "elite0: get the icon")
(sleep (ai_play_line_at_player ai_current_actor 0920))
)
(script command_script cs_e25_scene0
haaa hahahaha , 5 million people just shat their pants
(sleep (ai_play_line ai_current_actor 0890))
)
;- Order Scripts ---------------------------------------------------------------
;- Event Scripts ---------------------------------------------------------------
(script dormant e25_dialogue
; Elite scene
(sleep_until
(ai_scene e25_scene0 cs_e25_scene0 e21_cov_inf0)
5
300
)
; Tartarus replies
(sleep 120)
(ai_play_line_on_object none 0900)
; End scene
(sleep_until g_key_library_arrival 10)
; Try the ideal scene
(if (>= (ai_living_count e21_cov_inf0) 2)
; Do the ideal scene
(begin
(sleep_until
(ai_scene e25_scene3 cs_e25_scene3 e21_cov_inf0)
5
)
)
; That failed, so do the singleton scene
(begin
(sleep_until
(ai_scene e25_scene1 cs_e25_scene1 e21_cov_inf0)
5
)
)
)
)
;- Squad Controls --------------------------------------------------------------
(script dormant e25_fld_inf1_main
Wait until the key is near the second arch
(sleep_until g_key_lock1_second_arch 10)
; First volley!
(ai_place e25_fld_inf1_0)
Second volley
(sleep 60)
(ai_place e25_fld_inf1_1)
; Combat forms!
(sleep 60)
(ai_place e25_fld_inf1_2)
)
(script dormant e25_fld_inf0_main
Wait until the key is near the first arch
(sleep_until g_key_lock1_first_arch 10)
; First volley!
(ai_place e25_fld_inf0_0)
Second volley
(sleep 60)
(ai_place e25_fld_inf0_1)
; Combat forms!
(sleep 60)
(ai_place e25_fld_inf0_2)
)
;- Init and Cleanup ------------------------------------------------------------
(script dormant e25_main
(data_mine_set_mission_segment enc_e25)
(sleep_until g_key_lock1_entered 10)
(set g_e25_started true)
(print "e25_main")
(game_save)
; Wake subsequent scripts
(wake e26_main)
; Wake control scripts
; (wake e25_fld_inf0_main)
; (wake e25_fld_inf1_main)
(wake e25_dialogue)
; Shut down
(sleep_until g_e26_started)
(sleep_forever e25_fld_inf0_main)
(sleep_forever e25_fld_inf1_main)
)
= ENCOUNTER 24 = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
;*
;|Flood combat in the vertical section.
;|
;|Begins when the key enters the base of the vertical section.
;|Ends sometime later (indeterminate).
;|
|Elites
;|
;|Flood
;| e24_fld_juggernaut - Guess
;| (killificate) - Kill folks
;| e24_fld_inf0 - Any leftover combat forms
;| (guard0) - Guard left side
;| (guard1) - Guard right side
;| (follow) - Follow the Juggernaut
;| e24_fld_inf1 - Reinforcements for the juggernaut's posse
;| _0 - From the left side
;| _1 - From the right side
;| (follow) - Follow the Juggernaut
;| e24_fld_inf2 - Reinforcements at the interior->exterior threshhold
;| (follow) - Follow the Juggernaut
| ( engage ) - Free roam if the dies
;|
;|Open Issues
;|
;*;
;- Globals ---------------------------------------------------------------------
Encounter has been activated ?
;- Command Scripts -------------------------------------------------------------
(script command_script cs_e24_fld_inf1_load
(cs_enable_moving true)
(cs_enable_targeting true)
(cs_face_object true key)
; Wait for it...
(sleep 210)
; Board it
(object_cannot_take_damage (ai_get_object ai_current_actor))
(cs_face_object false key)
(cs_ignore_obstacles true)
(cs_enable_pathfinding_failsafe true)
(if (= (random_range 0 2) 0)
(begin
(cs_go_to e24_fld_inf1_load/p0_0)
(cs_go_to e24_fld_inf1_load/p0_1)
)
(begin
(cs_go_to e24_fld_inf1_load/p1_0)
(cs_go_to e24_fld_inf1_load/p1_1)
)
)
; Jump in
(cs_jump_to_point 3 1)
; Migrate them over
(ai_migrate ai_current_actor e21_fld_inf0_0)
; Wait for them to land
(sleep 150)
(object_can_take_damage (ai_get_object ai_current_actor))
)
;- Order Scripts ---------------------------------------------------------------
;- Squad Controls --------------------------------------------------------------
(script dormant e24_fld_inf2_main
(sleep_until g_key_shaft_entered 10)
)
(script dormant e24_fld_inf1_main
(sleep_until g_key_shaft_rising 10)
(ai_place e24_fld_inf1_1)
)
(script dormant e24_fld_inf0_main
(sleep_until g_key_shaft_entered 10)
)
;- Init and Cleanup ------------------------------------------------------------
(script dormant e24_main
(sleep_until g_key_shaft_entered 10)
(data_mine_set_mission_segment enc_e24)
(set g_e24_started true)
(print "e24_main")
(game_save)
; Wake subsequent scripts
(wake e25_main)
; Wake control scripts
; (wake e24_fld_inf0_main)
; (wake e24_fld_inf1_main)
; (wake e24_fld_inf2_main)
; Shut down
(sleep_until g_e25_started)
(sleep_forever e24_fld_inf0_main)
(sleep_forever e24_fld_inf1_main)
(sleep_forever e24_fld_inf2_main)
)
= ENCOUNTER 23 = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
;*
;|Flood combat in the long interior cruise.
;|
;|Begins when the key enters the open space.
;|Ends sometime later (indeterminate).
;|
|Elites
;|
;|Flood
| e23_fld_inf0 - Flood at the second boarding point
;| _0 - Left side
;| (init) - Firing from the boarding point
;| _1 - Right side
;| (init) - Firing from the boarding point
;| (engage) - Leaping aboard the key and engaging
;|
;|Open Issues
;|
;*;
;- Globals ---------------------------------------------------------------------
Encounter has been activated ?
;- Command Scripts -------------------------------------------------------------
(script command_script cs_e23_fld_inf0_0_load
(cs_enable_pathfinding_failsafe true)
(cs_ignore_obstacles true)
(cs_go_to e23_fld_inf0_load/p0_0)
(cs_go_to e23_fld_inf0_load/p0_1)
(cs_jump 15.0 3.0)
)
(script command_script cs_e23_fld_inf0_1_load
(cs_enable_pathfinding_failsafe true)
(cs_ignore_obstacles true)
(cs_go_to e23_fld_inf0_load/p1_0)
(cs_go_to e23_fld_inf0_load/p1_1)
(cs_jump 15.0 3.0)
)
(script command_script cs_e23_scene0
(cs_abort_on_combat_status ai_combat_status_visible)
; Elite 0
(cs_switch "elite0")
(print "dog: the fool...")
(sleep (ai_play_line ai_current_actor 0810))
(sleep 15)
; Elite 0
(cs_switch "elite1")
(print "scl: on the bright side...")
(sleep (ai_play_line ai_current_actor 0820))
)
;- Order Scripts ---------------------------------------------------------------
;- Event Controls --------------------------------------------------------------
(script dormant e23_dialogue
; Tartarus sees the humans
(sleep 90)
(print "Tartarus: Humans! I'll deal with them!")
(sleep (ai_play_line_on_object none 0800))
(sleep 30)
; Run the response scene
(sleep_until
(ai_scene e23_scene0 cs_e23_scene0 e21_cov_inf0)
10
90
)
)
;- Squad Controls --------------------------------------------------------------
(script dormant e23_fld_inf0_main
(sleep_until g_key_cruise_first_loadpoint 10)
; Place the Flood
(ai_place e23_fld_inf0)
; Wait until the key is close enough
(sleep_until g_key_cruise_halfway 10)
(sleep 90)
; Change orders, send them in
(ai_set_orders e23_fld_inf0_0 e23_fld_inf0_engage)
(ai_set_orders e23_fld_inf0_1 e23_fld_inf0_engage)
(cs_run_command_script e23_fld_inf0_0 cs_e23_fld_inf0_0_load)
(cs_run_command_script e23_fld_inf0_1 cs_e23_fld_inf0_1_load)
)
;- Init and Cleanup ------------------------------------------------------------
(script dormant e23_main
(data_mine_set_mission_segment enc_e23)
(sleep_until g_key_cruise_entered 10)
(set g_e23_started true)
(print "e23_main")
(game_save)
; Wake subsequent scripts
(wake e24_main)
; Wake control scripts
; (wake e23_fld_inf0_main)
(wake e23_dialogue)
; Shut down
(sleep_until g_e24_started)
(sleep_forever e23_fld_inf0_main)
)
(script static void test_key_ride2
(device_set_position_immediate key 0.26)
(sleep 1)
(object_teleport (player0) e23_test)
(object_set_velocity (player0) 1 0 0)
(wake key_main)
(wake e23_main)
(sleep 3)
(device_set_position_immediate key 0.26)
(device_set_position key 1.0)
)
= ENCOUNTER 22 = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
;*
|Flood combat in the first interior lock .
;|
;|Begins when the key passes into the lock.
;|Ends sometime later (indeterminate).
;|
|Elites
;|
;|Flood
| e22_fld_inf0 - Flood which boards from the second loading ramp
;| _0 - Left side
;| (init) - Fighting on their side
;| (engage0) - Fighting on the key, on the left side
;| _1 - Right side
;| (init) - Fighting on their side
;| (engage0) - Fighting on the key, on the right side
;| (engage1) - Free roam
;|?? e22_fld_inf1 - Flood who board the key from below
;| (massing) - Massing before attacking
;| (engage) - Attacking when alerted or finished amassing
;|
;|Open Issues
;|
;*;
;- Globals ---------------------------------------------------------------------
Encounter has been activated ?
;- Command Scripts -------------------------------------------------------------
(script command_script cs_e22_hack_divide
(if (< (ai_living_count e22_cov_inf1_0) 2)
(ai_migrate ai_current_actor e22_cov_inf1_0)
(ai_migrate ai_current_actor e22_cov_inf1_1)
)
)
(script command_script cs_e22_fld_inf0_0_load
(cs_enable_moving true)
(cs_enable_targeting true)
(cs_face_object true key)
(sleep_until g_key_lock0_second_loadpoint 1)
; Wait for it...
(sleep 95)
; Board it
(cs_face_object false key)
(unit_impervious ai_current_actor true)
(cs_ignore_obstacles true)
(cs_enable_pathfinding_failsafe true)
(if (= (random_range 0 2) 0)
(begin
(cs_go_to e22_fld_inf0_load/p0_0)
(cs_go_to e22_fld_inf0_load/p0_1)
)
(begin
(cs_go_to e22_fld_inf0_load/p1_0)
(cs_go_to e22_fld_inf0_load/p1_1)
)
)
(cs_move_in_direction 0 1 0)
(unit_impervious ai_current_actor false)
; Migrate them over
(ai_migrate ai_current_actor e21_fld_inf0_0)
)
(script command_script cs_e22_scene0
(cs_abort_on_combat_status ai_combat_status_visible)
; Elite 0
(cs_switch "elite0")
(print "scl: what courage...")
(sleep (ai_play_line ai_current_actor 0780))
(sleep 15)
; Elite 0
(cs_switch "elite1")
(print "dog: ignore him...")
(sleep (ai_play_line ai_current_actor 0790))
)
;- Order Scripts ---------------------------------------------------------------
;- Event Controls --------------------------------------------------------------
(script dormant e22_dialogue
(sleep_until (= (structure_bsp_index) 4))
; Tartarus boosts ahead
(sleep 90)
(print "Tartarus: I will thin their ranks")
(sleep (ai_play_line_on_object none 0770))
(sleep 30)
; Run the response scene
(sleep_until
(ai_scene e22_scene0 cs_e22_scene0 e21_cov_inf0)
10
90
)
)
;- Squad Controls --------------------------------------------------------------
(script dormant e22_fld_inf0_main
(sleep_until g_key_lock0_first_loadpoint 10)
; Place the Flood
(ai_place e22_fld_inf0)
)
;- Init and Cleanup ------------------------------------------------------------
(script dormant e22_main
(sleep_until g_key_lock0_entered 10)
(data_mine_set_mission_segment enc_e22)
(set g_e22_started true)
(print "e22_main")
(game_save)
; Wake subsequent scripts
(wake e23_main)
; Wake control scripts
(wake e22_fld_inf0_main)
(wake e22_dialogue)
; Shut down
(sleep_until g_e23_started)
(sleep_forever e22_fld_inf0_main)
)
= ENCOUNTER 21 = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
;*
;|A running Flood vs. Covenant battle which rages on the key for the entire run.
;|
;|Begins when the cutscene ends.
;|Ends sometime later (indeterminate).
;|
|Elites
;| e21_cov_inf0 - Elite allies
;| (init) - Front idle
;| _0 - Ranged specialists, they hang back
| ( ) - Guarding the left side
;| (guard_right) - Guarding the left side
;| _1 - Close range fighters, they hold the line
;| (advance_left) - Further up the line on the left
| ( advance_right ) - Ditto , for the right
;|
;|Flood
;| e21_fld_inf0 - Flood attacking from the left side of the key
;| _0 - The main squad
;| _1 - Reinforcements from down low
;| _2 - Reinforcements from up high
;| _3 - Carriers from down low
;| (engage0) - Engaging on the left side
| ( ) - Hunting all over the key for the player
;| e21_fld_inf1 - Flood attacking from the right side of the key
;| _0 - The main squad
;| _1 - Reinforcements from down low
;| _2 - Reinforcements from up high
;| _3 - Carriers from down low
;| (engage0) - Engaging on the left side
| ( ) - Hunting all over the key for the player
;|
;*;
;- Globals ---------------------------------------------------------------------
Encounter has been activated ?
;- Command Scripts -------------------------------------------------------------
(script command_script cs_e21_fld_inf1_low_entry
(cs_enable_pathfinding_failsafe true)
(cs_ignore_obstacles true)
(cs_move_in_direction 6 0 0)
; Head to the rally point
(if (= (structure_bsp_index) 3)
(begin
(cs_go_to e21_fld_bsp5/p2)
(cs_abort_on_combat_status ai_combat_status_clear_los)
(cs_go_to e21_fld_bsp5/p1_0)
(cs_go_to e21_fld_bsp5/p1_1)
)
(begin
(cs_go_to e21_fld_bsp6/p2)
(cs_abort_on_combat_status ai_combat_status_clear_los)
(cs_go_to e21_fld_bsp6/p1_0)
(cs_go_to e21_fld_bsp6/p1_1)
)
)
)
(script command_script cs_e21_fld_inf1_high_entry
(cs_abort_on_combat_status ai_combat_status_clear_los)
(cs_enable_pathfinding_failsafe true)
; Jump in
; (cs_jump_to_point 2.5 1)
; Then go to the rally point
(if (= (structure_bsp_index) 3)
(begin
(cs_go_to e21_fld_bsp5/p1_0)
(cs_go_to e21_fld_bsp5/p1_1)
)
(begin
(cs_go_to e21_fld_bsp6/p1_0)
(cs_go_to e21_fld_bsp6/p1_1)
)
)
)
(script command_script cs_e21_fld_inf0_low_entry
(cs_enable_pathfinding_failsafe true)
(cs_ignore_obstacles true)
(cs_move_in_direction 6 0 0)
; Head to the rally point
(if (= (structure_bsp_index) 3)
(begin
(cs_go_to e21_fld_bsp5/p2)
(cs_abort_on_combat_status ai_combat_status_clear_los)
(cs_go_to e21_fld_bsp5/p0_0)
(cs_go_to e21_fld_bsp5/p0_1)
)
(begin
(cs_go_to e21_fld_bsp6/p2)
(cs_abort_on_combat_status ai_combat_status_clear_los)
(cs_go_to e21_fld_bsp6/p0_0)
(cs_go_to e21_fld_bsp6/p0_1)
)
)
)
(script command_script cs_e21_fld_inf0_high_entry
(cs_abort_on_combat_status ai_combat_status_clear_los)
(cs_enable_pathfinding_failsafe true)
; Jump in
; (cs_jump_to_point 2.5 1)
; Head to the rally point
(if (= (structure_bsp_index) 3)
(begin
(cs_go_to e21_fld_bsp5/p0_0)
(cs_go_to e21_fld_bsp5/p0_1)
)
(begin
(cs_go_to e21_fld_bsp6/p0_0)
(cs_go_to e21_fld_bsp6/p0_1)
)
)
)
(script command_script cs_e21_fld_inf0_0_load
(cs_enable_moving true)
(cs_enable_targeting true)
(sleep_until g_key_lock0_first_loadpoint 1)
; Shoot at the key
(sleep 30)
(cs_shoot_point true key_bsp5/p0)
; Wait for it...
(sleep 148)
(cs_shoot_point false key_bsp5/p0)
; Set their orders
(ai_set_orders ai_current_squad e21_fld_inf0_engage0)
; Board it
(cs_ignore_obstacles true)
(cs_enable_pathfinding_failsafe true)
(cs_go_to e21_fld_load/left0)
(cs_go_to e21_fld_load/left1)
(cs_move_in_direction 0 1 0)
)
(script command_script cs_e21_scene0
(print "elite: I grow restless without a target")
(sleep (ai_play_line_at_player ai_current_actor 0730))
)
(script command_script cs_e21_scene1
(print "elite: Look, up ahead! The Parasite readies")
(ai_play_line_at_player ai_current_actor 0760)
(sleep 20)
; Move to a point
(cs_go_to_nearest e21_scene1_points)
(cs_face true e21_fld_load/p0)
(cs_aim true e21_fld_load/p0)
; Wait until we're closer...
(sleep_until g_key_lock0_first_loadpoint 5)
; Shoot a random combat form
(cs_shoot_point true e21_fld_load/p0)
(sleep 90)
)
;- Order Scripts ---------------------------------------------------------------
(script static boolean e21_in_bsp4
(= (structure_bsp_index) 4)
)
;- Event Controls --------------------------------------------------------------
;- Squad Controls --------------------------------------------------------------
(script dormant e21_fld_carriers1_main
; Migrate everyone over
(ai_migrate e21_fld_carriers0 e21_fld_carriers1)
(sleep_until
(begin
Replenish the carrier forms
(if (< (ai_swarm_count e21_fld_carriers1) 2)
; Respawn one
(ai_place e21_fld_carriers1 1)
)
; Loop until the shaft
g_key_lock1_second_arch
)
90
)
)
(script static void e21_fld_inf1_spawn
; Is the player in the way of the lower spawner?
(if (volume_test_objects tv_key_near_lower_spawner (players))
; He is, so spawn from up top
(begin
; Is the other one on the upper left side?
(if (volume_test_objects tv_key_upper_left_side (players))
; He is, spawn from the opposite side
(begin
(ai_place e21_fld_inf1_2 1)
(ai_migrate e21_fld_inf1_2 e21_fld_inf1_0)
(sleep 5)
(ai_magically_see_object e21_fld_inf1_0 (player0))
(ai_magically_see_object e21_fld_inf1_0 (player1))
)
; He is not, spawn from that side
(begin
(ai_place e21_fld_inf0_2 1)
(cs_run_command_script e21_fld_inf0_2 cs_e21_fld_inf1_high_entry)
(ai_migrate e21_fld_inf0_2 e21_fld_inf1_0)
(sleep 5)
(ai_magically_see_object e21_fld_inf1_0 (player0))
(ai_magically_see_object e21_fld_inf1_0 (player1))
)
)
)
; He is not, so spawn from down low
(begin
(ai_place e21_fld_inf1_1 1)
(ai_migrate e21_fld_inf1_1 e21_fld_inf1_0)
(sleep 5)
(ai_magically_see_object e21_fld_inf1_0 (player0))
(ai_magically_see_object e21_fld_inf1_0 (player1))
)
)
)
(script dormant e21_fld_inf1_main
; Migrate everyone over
(ai_migrate e21_fld_inf0 e21_fld_inf1_0)
(sleep_until
(begin
Replenish the combat forms
(if (< (ai_nonswarm_count e21_fld_inf1_0) 8)
; Respawn them
(sleep_until
(begin
(e21_fld_inf1_spawn)
; Until there are enough or the ride is over
(or
(>= (ai_nonswarm_count e21_fld_inf1_0) 8)
g_key_lock1_second_arch
)
)
60
)
)
; Loop until the shaft
g_key_lock1_second_arch
)
900
)
)
(script dormant e21_fld_carriers0_main
; Wait for that initial group to load on board
(sleep_until (= (structure_bsp_index) 4))
(sleep_until
(begin
Replenish the carrier forms
(if (< (ai_nonswarm_count e21_fld_carriers0) 2)
; Respawn one
(ai_place e21_fld_carriers0 1)
)
; Loop until the shaft
g_key_shaft_rising
)
90
)
Switch sides
(wake e21_fld_carriers1_main)
)
(script static void e21_fld_inf0_spawn
; Is the player in the way of the lower spawner?
(if (volume_test_objects tv_key_near_lower_spawner (players))
; He is, so spawn from up top
(begin
; Is the other one on the upper left side?
(if (volume_test_objects tv_key_upper_left_side (players))
; He is, spawn from the opposite side
(begin
(ai_place e21_fld_inf1_2 1)
(cs_run_command_script e21_fld_inf1_2 cs_e21_fld_inf0_high_entry)
(ai_migrate e21_fld_inf1_2 e21_fld_inf0_0)
(sleep 5)
(ai_magically_see_object e21_fld_inf0_0 (player0))
(ai_magically_see_object e21_fld_inf0_0 (player1))
)
; He is not, spawn from that side
(begin
(ai_place e21_fld_inf0_2 1)
(ai_migrate e21_fld_inf0_2 e21_fld_inf0_0)
(sleep 5)
(ai_magically_see_object e21_fld_inf0_0 (player0))
(ai_magically_see_object e21_fld_inf0_0 (player1))
)
)
)
; He is not, so spawn from down low
(begin
(ai_place e21_fld_inf0_1 1)
(ai_migrate e21_fld_inf0_1 e21_fld_inf0_0)
(sleep 5)
(ai_magically_see_object e21_fld_inf0_0 (player0))
(ai_magically_see_object e21_fld_inf0_0 (player1))
)
)
)
(script dormant e21_fld_inf0_main
(ai_place e21_fld_inf0_0)
; Wait for that initial group to load on board
(sleep_until (= (structure_bsp_index) 4))
; Initial spawn
(sleep_until
(begin
(e21_fld_inf0_spawn)
; Until there are enough or the ride is over
(or
(>= (ai_nonswarm_count e21_fld_inf0_0) 8)
g_key_shaft_rising
)
)
)
(sleep_until
(begin
Replenish the combat forms
(if (< (ai_nonswarm_count e21_fld_inf0_0) 8)
; Respawn them
(sleep_until
(begin
(e21_fld_inf0_spawn)
; Until there are enough or the ride is over
(or
(>= (ai_nonswarm_count e21_fld_inf0_0) 8)
g_key_shaft_rising
)
)
60
)
)
; Loop until the shaft
g_key_shaft_rising
)
900
)
Switch sides
(wake e21_fld_inf1_main)
)
(script dormant e21_cov_inf0_main
; Place the Elites
(ai_place e21_cov_inf0)
; Play the scene
(sleep 150)
(sleep_until
(ai_scene e21_scene0 cs_e21_scene0 e21_cov_inf0_1)
5
60
)
; Play the next scene
(sleep 300)
(sleep_until
(ai_scene e21_scene1 cs_e21_scene1 e21_cov_inf0_0)
5
60
)
; Wait for that initial group to load on board
(sleep_until g_key_lock0_first_loadpoint 5)
(game_save)
; Set the orders
(ai_set_orders e21_cov_inf0_0 e21_cov_inf0_0_guard_left)
(ai_set_orders e21_cov_inf0_1 e21_cov_inf0_1_advance_left)
; Wait for the shaft
(sleep_until g_key_shaft_rising)
; Set the orders
(ai_set_orders e21_cov_inf0_0 e21_cov_inf0_0_guard_right)
(ai_set_orders e21_cov_inf0_1 e21_cov_inf0_1_advance_right)
)
;- Init and Cleanup ------------------------------------------------------------
(script dormant e21_main
(sleep_until g_key_started 5)
(data_mine_set_mission_segment enc_e21)
(set g_e21_started true)
(print "e21_main")
; Wake subsequent scripts
(wake e22_main)
; Wake control scripts
(wake e21_cov_inf0_main)
(wake e21_fld_inf0_main)
; (wake e21_fld_carriers0_main)
(wake sc_outer_wall) ; pbertone: dialogue
)
(script static void test_key_ride
(switch_bsp_by_name sen_hq_bsp_5)
(sleep 1)
(object_teleport (player0) key_ent0)
(object_set_velocity (player0) 5 0 0)
(object_teleport (player1) key_ent1)
(object_set_velocity (player1) 5 0 0)
(wake key_main)
(wake key_ride_human_key_main)
(wake key_ride_tartarus_main)
(wake e21_main)
)
;*= KEY RIDE CINEMATIC ====================================================================
;|
|(script dormant cinematic_key_boarding
| ( sleep_until ( volume_test_objects tv_cutscene_key_boarding ( players ) ) 10 )
;|
;| ; Run the cinematic
| ( object_teleport ( ) key_ride_a )
| ( object_set_velocity ( ) 10 0 0 )
| ( object_teleport ( player1 ) key_ride_b )
| ( object_set_velocity ( player1 ) 10 0 0 )
;|
;| ; Once it's done, wake subsequent encounters
;| (wake key_main)
;| (wake key_ride_human_key_main)
;| (wake key_ride_tartarus_main)
;| (wake e21_main)
;|)
;*;
= ENCOUNTER 20 = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
;*
;|A vigorous flood defense of the key.
;|
;|Begins when the player enters the room.
;|Ends when the player leaves the room.
;|
|Elites
| e20_cov_inf0 - The sum of all prior squads , just dump them here
| ( init ) - Positions at the first intersection
| ( ) - Positions at the second intersection
;|
;|Flood
;| e20_fld_infs0 - Infection forms milling through the environment, fleeing
;|
;|Open Issues
;|
;|
;|
;|;- Globals ---------------------------------------------------------------------
;|
|(global boolean g_e20_started false ) ; Encounter has been activated ?
;|
;|
;|;- Command Scripts -------------------------------------------------------------
;|;- Order Scripts ---------------------------------------------------------------
;|;- Squad Controls --------------------------------------------------------------
;|
|(script dormant e20_cov_inf0_main
;| ; FILL THIS WITH MIGRATION COMMANDS
| ( sleep 1 )
;|)
;|
;|
|;- Init and Cleanup ------------------------------------------------------------
;|
|(script dormant e20_main
;| (set g_e20_started true)
;| (print "e20_main")
;| (game_save)
;|
| ; Wake subsequent scripts
;|
;| ; Wake control scripts
;| (wake e20_cov_inf0_main)
;|
;| ; Shut down
| ( sleep_until ( volume_test_objects tv_cutscene_key_boarding ( players ) ) 10 )
;| (sleep_forever e20_cov_inf0_main)
;|
;| ; Start the cutscene
;|
;| ; Clean up
| ( sleep 15 )
;| (ai_erase e20_cov)
;| (ai_erase e20_fld)
;|)
;|
;|(script static void test_key_dock
;| (switch_bsp_by_name sen_hq_bsp_5)
| ( sleep 1 )
| ( object_teleport ( ) e20_test )
| ( ai_place e20_cov_inf0 )
;| (if (not g_e20_started) (wake e20_main))
;|)
;*;
;= KEYRIDE MAIN ==========================================================================
(script dormant begin_key_ride_main
MIGRATE SQUADS HERE
Add ( ai_migrate < your_squad > e20_cov_inf0 ) statements
; Wake the encounters
(wake e21_main)
(wake key_main)
(wake key_ride_human_key_main)
(wake key_ride_tartarus_main)
; (wake cinematic_key_boarding)
)
;= MISSION MAIN ==========================================================================
;=========== ENCOUNTER SCRIPTS ==========
(script dormant enc_cov_charge
(data_mine_set_mission_segment enc_cov_charge)
(print "initialize covenant charge scripts")
(game_save)
(object_dynamic_simulation_disable qz_cov_def_tower_pod_a true)
(object_dynamic_simulation_disable qz_cov_def_tower_pod_b true)
(ai_place qz_cov_def_phantom)
(ai_place qz_cov_def_spectre)
(ai_place qz_cov_def_ghosts)
(ai_place qz_cov_def_spec_ops)
(wake sc_cov_charge)
(sleep_until (or
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_cov_def_spectre/spectre) "spectre_d" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_cov_def_spectre/spectre) "spectre_p_l" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_cov_def_spectre/spectre) "spectre_p_r" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_cov_def_spectre/spectre) "spectre_g" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_cov_def_ghosts/a) "ghost_d" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_cov_def_ghosts/b) "ghost_d" (players))
) 10 (* 30 20))
(set g_qz_cov_def_progress 1)
(sleep 30)
(game_save_no_timeout)
(sleep 90)
(ai_place qz_cov_def_enforcer_a)
(ai_place qz_cov_def_sen_elim)
( if ( difficulty_legendary ) ( ai_place qz_cov_def_enforcer_b ) ( ai_set_orders qz_cov_def_enforcer_a qz_cov_def_mid ) )
(device_set_position qz_door_a 1)
(sleep (* 30 2))
(wake ext_a_vehicle_orders)
(sleep_until (<= (ai_living_count sentinels) 0))
(sleep 30)
(game_save)
(ai_renew covenant)
)
(script dormant enc_vehicle_int
(data_mine_set_mission_segment enc_vehicle_int)
(print "initialize vehicle interior scripts")
(game_save)
(ai_renew covenant)
(ai_disposable cov_def_sentinels true)
(ai_disposable cov_def_enf true)
(set g_veh_int_migrate_a 1)
(set g_music_06b_01 1)
(wake music_06b_01)
(wake sc_qz_veh_int)
1
1
1
2
0
2
(ai_place veh_int_wraith/wraith)
( ai_place veh_int_turrets )
0
(ai_place veh_int_ghost_ab) ;0
(sleep 15)
(device_operates_automatically_set veh_int_door_a 1)
(sleep_until (volume_test_objects tv_veh_int_b (players)))
(game_save)
(ai_renew covenant)
(set g_veh_int_migrate_b 1)
(wake ai_veh_int_ghost_spawn)
2
2
(ai_magically_see veh_int_wraith veh_int_sen)
(ai_place veh_int_flood_bk/runner)
(sleep_until (volume_test_objects tv_veh_int_c (players)))
(data_mine_set_mission_segment enc_vehicle_int_bk)
(game_save)
(set g_veh_int_migrate_c 1)
(wake sc_factory_approach)
(ai_renew covenant)
1
(sleep_until (volume_test_objects tv_veh_int_d (players)))
( device_set_position veh_int_door_b 1 )
(set g_veh_int_migrate_d true)
(set g_veh_int_ghost_spawn 1) ; turn off the ghost spawner
1
)
(script dormant enc_qz_ext_a
(data_mine_set_mission_segment enc_qz_ext_a_dam)
(print "initialize quarantine zone exterior A scripts")
(game_save)
(ai_renew covenant)
(ai_disposable veh_int_flood true)
(ai_disposable veh_int_sen true)
(set g_veh_int_migrate_e 1)
(set g_ext_a_dam_migrate_a 1)
(wake music_06b_02)
(wake ai_ext_a_dam_enforcers)
(device_set_position qz_dam_door_a 1)
; (wake dam_door_a)
; (wake dam_door_b)
(ai_place qz_ext_a_dam_enf/a)
(ai_place qz_ext_a_dam_human)
(ai_place qz_ext_a_dam_sen)
(ai_place qz_ext_a_dam_sen_elim)
(ai_place qz_ext_a_dam_flood_ini)
(wake chapter_competition)
(game_save)
(ai_renew covenant)
(sleep_until (volume_test_objects qz_ext_a_dam_b (players)))
(set g_ext_a_dam_migrate_b 1)
(ai_place qz_ext_a_dam_flood_cliff_a)
(ai_place qz_ext_a_dam_flood_cliff_b)
(sleep_until (volume_test_objects tv_ext_a_a (players)))
;* (sleep_until (or
;| (> (device_get_position dam_door_a) 0)
;| (> (device_get_position dam_door_b) 0)
;| )
);*;
(data_mine_set_mission_segment enc_qz_ext_a)
(game_save)
(ai_renew covenant)
(set g_ext_a_dam_enf 1)
(set g_ext_a_migrate_a 1)
(ai_disposable ext_a_flood_dam_a true)
(ai_disposable ext_a_flood_dam_b true)
(ai_disposable ext_a_sen_dam_a true)
(ai_disposable ext_a_sen_dam_b true)
(wake ai_qz_ext_a_wraiths)
(ai_place qz_ext_a_enf_a)
(ai_place qz_ext_a_flood_rocket)
(if (<= (ai_living_count covenant) 1) (begin (wake sc_ext_a) (ai_place qz_ext_a_phantom)))
(set v_ext_a_phantom (ai_vehicle_get_from_starting_location qz_ext_a_phantom/phantom))
(sleep_until (volume_test_objects tv_ext_a_b (players)))
; (game_save)
(set g_ext_a_migrate_b 1)
(sleep_until (volume_test_objects tv_ext_a_c (players)))
(game_save_no_timeout)
(ai_renew covenant)
(set g_ext_a_migrate_c 1)
(ai_place qz_ext_a_flood_c)
(ai_place qz_ext_a_flood_c2)
(ai_place ext_a_flood_ghost_fr)
(sleep_until (volume_test_objects tv_ext_a_d (players)))
; (game_save_no_timeout)
(set g_ext_a_migrate_d 1)
(wake ai_qz_ext_a_ghosts)
(wake ai_qz_ext_a_d_spawn)
(sleep_until (volume_test_objects tv_ext_a_e (players)))
(game_save)
(ai_renew covenant)
(set g_ext_a_migrate_e 1)
(set g_qz_ext_a_d_spawn 0)
(ai_place ext_a_sen_elim_bk)
(if (<= (ai_living_count qz_ext_a_enf_bk) 0) (ai_place qz_ext_a_enf_bk))
(sleep_until (volume_test_objects tv_ext_a_ghosts_off (players)))
(set g_qz_ext_a_flood_ghosts 1)
(sleep_until (volume_test_objects tv_ext_a_f (players)))
(data_mine_set_mission_segment enc_ext_a_fact_ent)
(game_save_no_timeout)
(set g_ext_a_migrate_f 1)
(set g_music_06b_02 1)
(ai_renew covenant)
( ai_place fact_ent_flood_turrets )
(ai_place fact_ent_flood_scorpion)
( ai_place )
(ai_place fact_ent_flood_wraith_b)
(wake ai_fact_ent_sen_spawn)
(wake ai_fact_ent_enf_spawn)
(sleep_until (volume_test_objects tv_ext_a_fact_ent (players)))
(set g_ext_a_fact_ent_migrate 1)
)
(script dormant enc_crashed_factory
(data_mine_set_mission_segment enc_crashed_factory_a)
(game_save)
(ai_renew covenant)
(ai_disposable ext_a_flood true)
(ai_disposable ext_a_sen true)
(set g_music_06b_02 0)
(set g_music_06b_03 1)
(set g_fact_ent_sen_spawn 1)
(wake music_06b_03)
(wake sent_factory_1_start)
(sleep_until (= (volume_test_objects vol_factory_1_exit (players)) TRUE))
(game_save)
(sleep_until (volume_test_objects tv_gorge (players)))
(data_mine_set_mission_segment enc_crashed_factory_ext)
(game_save)
(ai_disposable factory1_enemies true)
(set g_music_06b_03 0)
(ai_set_orders covenant cov_follow_gorge)
(ai_renew covenant)
(wake ai_gorge)
(sleep_until (volume_test_objects tv_factory2_enter (players)))
(data_mine_set_mission_segment enc_crashed_factory_b)
(game_save)
(ai_disposable gorge_enemies true)
(ai_set_orders covenant cov_follow_factory2)
(ai_renew covenant)
(wake ai_factory2)
)
(script dormant enc_qz_ext_b
(data_mine_set_mission_segment enc_ext_b_fact_exit)
(print "initialize quarantine zone exterior B scripts")
(game_save_no_timeout)
(ai_renew covenant)
(ai_disposable factory2_enemies true)
(wake music_06b_04)
(wake sc_factory_exit)
(wake objective_push_clear)
(wake objective_link_set)
(wake ext_b_vehicle_orders)
(ai_place qz_ext_b_fact_scorpion)
(ai_vehicle_reserve (ai_vehicle_get_from_starting_location qz_ext_b_fact_scorpion/scorpion) true)
( ai_place qz_ext_b_fact_humans )
(ai_place qz_ext_b_fact_wraith)
(ai_place qz_ext_b_fact_ghosts)
(ai_place qz_ext_b_fact_flood)
(ai_place qz_ext_b_fact_ghosts_spare)
(ai_place qz_ext_b_enf_a)
(sleep_until (volume_test_objects tv_ext_b_fact_mid (players)))
(game_save)
(if (random_range 0 2) (ai_place qz_ext_b_fact_warthog) (ai_place qz_ext_b_fact_ghost_bk))
(sleep_until (or
(and
(<= (ai_living_count ext_b_flood_a) 0)
(<= (ai_living_count ext_b_sentinels_a) 0)
)
(volume_test_objects tv_ext_b_gate (players))
)
5)
(data_mine_set_mission_segment enc_qz_ext_b)
(game_save)
(ai_renew covenant)
(set g_ext_b_migrate_1 1)
(wake ai_ext_b_enf_spawn)
(set g_music_06b_04 1)
(ai_place qz_ext_b_cov_phantom)
(ai_place qz_ext_b_wraith_a)
(ai_place qz_ext_b_wraith_b)
(ai_place qz_ext_b_ghosts_a (pin (- 7 (ai_living_count ext_b_flood)) 0 2))
(ai_place qz_ext_b_warthog)
(set v_ext_b_phantom (ai_vehicle_get_from_starting_location qz_ext_b_cov_phantom/phantom))
(sleep_until (or
(and
(<= (ai_living_count ext_b_flood_b) 0)
(<= (ai_living_count ext_b_sentinels_b) 0)
)
(volume_test_objects tv_ext_b_mid (players))
)
5)
(game_save_no_timeout)
(ai_renew covenant)
(set g_ext_b_migrate_2 1)
(ai_place qz_ext_b_ghosts_b)
(ai_place qz_ext_b_warthog_gauss)
(sleep_until (volume_test_objects tv_ext_b_back (players)) 5)
(data_mine_set_mission_segment enc_qz_ext_b_bk)
(game_save_no_timeout)
(ai_renew covenant)
(ai_disposable ext_b_flood true)
(ai_disposable ext_b_sentinels true)
(set g_ext_b_migrate_3 1)
(set g_ext_b_enforcer 1)
(wake ai_constructor_flock)
(wake ai_ext_b_bk_ghost_spawn)
(ai_place qz_ext_b_ent_enf)
(ai_place qz_ext_b_ent_scorpion)
(ai_place qz_ext_b_ent_wraith_a)
( ai_place qz_ext_b_ent_cov_phantom )
(sleep_until (volume_test_objects tv_ext_b_exit (players)) 5)
(data_mine_set_mission_segment enc_qz_ext_b_exit)
(game_save)
(ai_renew covenant)
(set g_ext_b_bk_ghost_spawn 1)
(set g_ext_b_migrate_4 1)
(wake ai_ext_b_exit_tube_a)
(wake ai_ext_b_exit_tube_b)
(ai_place qz_ext_b_ent_turrets)
(sleep_until (or
(and
(<= (ai_living_count ext_b_flood_d) 0)
(<= (ai_living_count ext_b_sentinels_d) 0)
)
(volume_test_objects tv_ext_b_exit_door (players))
)
5)
(game_save_no_timeout)
(ai_renew covenant)
(set g_ext_b_migrate_5 1)
(ai_place qz_ext_b_ent_flood_bk (pin (- 8 (ai_nonswarm_count ext_b_flood)) 0 6))
)
(script dormant enc_key_ride
(print "initialize key ride scripts")
; (game_save)
(ai_renew covenant)
(wake music_06b_05)
(wake music_06b_06)
(wake music_06b_07)
(sleep_until (volume_test_objects tv_key_ride_cinematic (players)))
(cinematic_fade_to_white)
(ai_erase_all)
(object_teleport (player0) key_ride_a)
(object_teleport (player1) key_ride_b)
(sleep 5)
(if (= g_play_cinematics 1)
(begin
(if (cinematic_skip_start)
(begin
(print "c06_intra2")
(c06_intra2)
)
)
(cinematic_skip_stop)
)
)
(wake begin_key_ride_main)
(sleep 25)
(game_save_immediate)
(wake chapter_gallery)
(wake objective_link_clear)
(wake objective_retrieve_set)
(ai_renew covenant)
(camera_control off)
(sleep 1)
(cache_block_for_one_frame)
(sleep 1)
(cinematic_fade_from_white)
)
(script dormant enc_library
(print "initialize library scripts")
(game_save)
(game_save)
(ai_renew covenant)
)
;===========================================================================================================
;============= STARTUP SCRIPT ==============================================================================
;===========================================================================================================
(script dormant mission_floodzone
(cinematic_snap_to_white)
(switch_bsp 0)
(if (= g_play_cinematics 1)
(begin
(if (cinematic_skip_start)
(begin
(print "c06_intra1")
(c06_intra1)
)
)
(cinematic_skip_stop)
)
)
(sleep 2)
(object_teleport (player0) player0_start)
(object_teleport (player1) player1_start)
(wake enc_cov_charge)
(if (difficulty_legendary) (wake ice_cream_superman))
(camera_control off)
(sleep 1)
(cache_block_for_one_frame)
(sleep 1)
(cinematic_fade_from_white_bars)
(wake chapter_mirror)
(wake objective_push_set)
(sleep_until (volume_test_objects tv_vehicle_int (players)))
(wake enc_vehicle_int)
(sleep_until (volume_test_objects tv_qz_ext_a (players)))
(wake enc_qz_ext_a)
(sleep_until (volume_test_objects tv_factory (players)))
(wake enc_crashed_factory)
(sleep_until (volume_test_objects tv_qz_ext_b (players)))
(wake enc_qz_ext_b)
(sleep_until (volume_test_objects tv_key_ride (players)))
(wake enc_key_ride)
TODO : should change this to test g_e26_ended , like this :
; (sleep_until g_e26_ended)
9/18
;* (sleep_until
;| (or
;| g_e26_ended
;| (volume_test_objects tv_x07 (players))
;| )
;| 5)
;*;
(cinematic_fade_to_white)
(ai_erase_all)
(object_teleport (player0) player0_end)
(object_teleport (player1) player1_end)
(if (cinematic_skip_start)
(begin
(print "x07")
(x07)
)
)
(cinematic_skip_stop)
(playtest_mission)
(game_won)
)
(script static void start
(wake mission_floodzone)
)
(script startup mission_main
; Necessary startup stuff
(ai_allegiance covenant player)
(ai_allegiance player covenant)
(ai_allegiance prophet player)
(ai_allegiance player prophet)
(ai_allegiance covenant prophet)
(ai_allegiance prophet covenant)
; Begin the mission
; Comment this out when you're testing individual encounters
(if (> (player_count) 0 ) (start))
)
(script static void test
(set g_play_cinematics 0)
(device_set_position qz_door_a 1)
(device_set_position veh_int_door_a 1)
(device_set_position veh_int_door_b 1)
(device_set_position qz_dam_door_a 1)
(ai_place qz_cov_def_spectre)
(ai_place qz_cov_def_ghosts)
(ai_place qz_cov_def_spec_ops)
(wake ext_a_vehicle_orders)
(wake dam_door_a)
(wake dam_door_b)
(sleep 90)
(set g_qz_cov_def_progress 1)
)
(script static void test_ext_a_phantom
(ai_place qz_ext_a_phantom)
(set v_ext_a_phantom (ai_vehicle_get_from_starting_location qz_ext_a_phantom/phantom))
)
(script static void test_ext_b_phantom
(ai_place qz_ext_b_cov_phantom)
( ai_place qz_ext_b_wraith_a )
(set v_ext_b_phantom (ai_vehicle_get_from_starting_location qz_ext_b_cov_phantom/phantom))
)
| null | https://raw.githubusercontent.com/Nibre/BlamScript-Research/dd17538dcbdc78f391effb341846fbaf9a1f8643/h2v/06b_floodzone/floodzone_mission.lisp | lisp | ========== GLOBALS ==========================================================================
===== !!!! MUSIC !!!! ===========================================================================
(sleep_until (not g_music_06b_01))
(sleep_until (not g_music_06b_04))
(sound_looping_stop scenarios\solo\06b_floodzone\06b_music\06b_04)
(sleep_until (not g_music_06b_06))
(if debug (print "stop music 06b_06"))
(sound_looping_stop scenarios\solo\06b_floodzone\06b_music\06b_06)
= CHAPTER TITLES ========================================================================
= OBJECTIVES ============================================================================
===== DIALOGUE SCENES ===========================================================================
plays right after the insertion cinematic
(if dialogue (print "SPEC-OPS: For those who fell before us!"))
(sleep (ai_play_line_on_object none 0230))
(sleep dialogue_pause)
if there are no enforcers alive when it tries to play this line skip it
|)
*;
plays when the covenant see the flood driving ghosts
plays when you get to the bottom of the dam
plays halfway through the vehicle interior space (unlike what the title would suggest)
plays in the gateway to the final vehicle space (right after the crashed factory exit)
plays at the exit from the crashed sentinel factory
plays when the exterior b covenant reinforcements get dropped off
joe plays this line in his cinematic
plays right after the key cinematic
plays when the key docs in its final position
====== COVENANT VEHICLE MIGRATION =======================================================
== covenant defense ==
*
= = BSP SWAP BULLSHIT = = = = = = = = = = = =
| (if (not (volume_test_object tv_bsp_swap_bullshit (ai_get_object qz_cov_def_spec_ops/a)))
| )
| (if (not (volume_test_object tv_bsp_swap_bullshit (ai_get_object qz_cov_def_spec_ops/b)))
| (cs_run_command_script qz_cov_def_spec_ops/b cov_def_spec_tele_b)
| )
| (if (not (volume_test_object tv_bsp_swap_bullshit (ai_get_object qz_cov_def_spec_ops/c)))
| (cs_run_command_script qz_cov_def_spec_ops/c cov_def_spec_tele_c)
| )
| (if (not (volume_test_object tv_bsp_swap_bullshit (ai_get_object qz_cov_def_spec_ops/d)))
| (cs_run_command_script qz_cov_def_spec_ops/d cov_def_spec_tele_d)
| )
= = BSP SWAP BULLSHIT = = = = = = = = = = = =
*;
VEHICLE INTERIOR START =======================================================================================
exit conditions
exit conditions
exit conditions
exit conditions
exit conditions
EXTERIOR A START =======================================================================================
== upper dam ==
exit conditions
== lower dam ==
exit conditions
== exterior a ==
exit conditions
exit conditions
exit conditions
exit conditions
exit conditions
exit conditions
exit conditions
new order set in the command script
exit conditions
exit condition
new order set in the command script
====== COVENANT DEFENSE =================================================================
(cs_vehicle_speed .35)
(vehicle_unload (ai_vehicle_get_from_starting_location qz_cov_def_spectre/spectre) "phantom_p")
(unit_exit_vehicle (ai_vehicle_get_from_starting_location qz_cov_def_spectre/spectre))
====== VEHICLE INTERIOR SCRIPTS =======================================================
exit conditions
====== QUARANTINE ZONE EXTERIOR A =======================================================
(cs_enable_pathfinding_failsafe true)
Respawns exit Flood until the player reaches the end
turn this one off after a few waves (count waves with AI_SPAWN_COUNT)
Respawns sentinels over course of encounter, switching to different spawn points as the player pushes in
Respawns the sentinels fighting the flood at the exit
Waits until major is dead before the Flood pour in
===== QUARANTINE ZONE EXTERIOR B ========================================================
called from the starting location
(sleep_until g_ext_b_phantom)
(ai_vehicle_enter qz_ext_b_cov_spec_ops (ai_vehicle_get_from_starting_location qz_ext_b_cov_ghosts/a))
(ai_vehicle_enter qz_ext_b_cov_spec_ops (ai_vehicle_get_from_starting_location qz_ext_b_cov_ghosts/b))
called from the starting location
exit conditions
exit conditions
= KEY CONTROL ===========================================================================
*
|Scripts which drive the key's motion through the level.
|
*;
- Globals ---------------------------------------------------------------------
Flags for transmitting key state
- Event Control ---------------------------------------------------------------
Begin opening
Sleep until finished opening
Begin closing
Begin opening
Sleep until finished opening
Begin closing
Begin opening
Sleep until finished opening
Begin closing
Begin opening
Sleep until finished opening
Begin closing
Begin opening
Sleep until finished opening
Begin closing
When awakened, this script starts the key in the correct place and
drives it for the rest of the mission. Progress is inexorable--everything
adjusts to the omnipotent key. All fear the key! THE KEY WILL DESTROY YOU
Make it always active
- Horizontal Section ---------------------------------------
Start the sound
Set the track and go
Get it to the initial position
Teleport the players onto the key
Sleep until the key is in position to begin opening the next door
Sleep until the key is in position for a bsp swap
Swap BSPs
Sleep until the key is approaching the next load point
Sleep until we should start the Human key
Sleep until the key is in position to begin opening the next door
Begin opening the door
Sleep until the key is entering the interior cruise
Sleep until the key is into the vertical rise
- Vertical Section -----------------------------------------
Short pause
Set the tracks and go
Start the alt track
TRANSFORM AND ROLL OUT!!!1
Start it moving
Sleep until the key is near the interior->exterior shaft transition
Begin opening the door
Sleep until the key is in position to transform back
Start the alt track
- Horizontal Section ---------------------------------------
Short pause
Set the track and go
Start the sound
TRANSFORM AND ROLL OUT!!!1
Start it moving
Sleep until the key is in position to begin opening the last door
Begin opening the door
Sleep until the key is entering the library
Sleep until the key is halfway in
Begin tilting up the outriggers
Ride it out
Start the alt track
Do the exterior stuff
Sleep until the player is near the interior cruise
Place the key, and move it into position
Make it always active
Set the track and go
Get it to the initial position
Sleep until the key is into the vertical rise
- Vertical Section -----------------------------------------
Short pause
Set the tracks and go
TRANSFORM AND ROLL OUT!!!1
Start it moving
Sleep until the key is in position to begin opening the door
Begin opening the door
Sleep until the key is in position to transform back
- Horizontal Section ---------------------------------------
Short pause, let the other key catch up
Set the track and go
TRANSFORM AND ROLL OUT!!!1
Start it moving
Sleep until the key is out of sight, and then end this charade
Set the overlay of the docked key
Move in behind the key
Follow the key
Move in behind the key
Hold position
Boost ahead and through
Wait for them
Head off to the Human key
Join in with it
And teleport him to safety
Head up to the arch
Fly off to check out the human key
e21 stuff
e22 stuff
e23 stuff
e24 stuff
e25 stuff
e26 stuff
*
|
|Begins when player steps off the key.
|Ends with the mission.
|
|Flood
| e26_fld_inf0 - Packs of infection forms that scurry about
|
|Open Issues
|
*;
- Globals ---------------------------------------------------------------------
- Command Scripts -------------------------------------------------------------
- Order Scripts ---------------------------------------------------------------
- Event Scripts ---------------------------------------------------------------
Loop until the encounter ends
Loop until the encounter ends
- Squad Controls --------------------------------------------------------------
- Init and Cleanup ------------------------------------------------------------
Wake subsequent scripts
Wake control scripts
*
|
|Begins when the key reaches the top of the shaft.
|Ends sometime later (indeterminate).
|
| e25_cov_inf0 - Elite allies
| (init) - Fighting and covering
|
|Flood
| e25_fld_inf0 - First arch Flood
| _0 - First carrier wave
| _1 - Second carrier wave
| _2 - Combat forms
| (engage) - Engaging Covenant
| e25_fld_inf1 - Second arch Flood
| _0 - First carrier wave
| _1 - Second carrier wave
| _2 - Combat forms
| (engage) - Engaging Covenant
|
|Open Issues
|
*;
- Globals ---------------------------------------------------------------------
- Command Scripts -------------------------------------------------------------
Send both Elites to their destinations
Wait until he's close to the player or done moving
Stop and face the player
Hack, whee
Wait for the player to be closer still
Second Elite chimes in
Wait until he's close to the player or done moving
Stop and face the player
Hack, whee
Wait for the player to be closer still
Wait until he's close to the player or done moving
Stop and face the player
Hack, whee
Wait for the player to be closer still
- Order Scripts ---------------------------------------------------------------
- Event Scripts ---------------------------------------------------------------
Elite scene
Tartarus replies
End scene
Try the ideal scene
Do the ideal scene
That failed, so do the singleton scene
- Squad Controls --------------------------------------------------------------
First volley!
Combat forms!
First volley!
Combat forms!
- Init and Cleanup ------------------------------------------------------------
Wake subsequent scripts
Wake control scripts
(wake e25_fld_inf0_main)
(wake e25_fld_inf1_main)
Shut down
*
|Flood combat in the vertical section.
|
|Begins when the key enters the base of the vertical section.
|Ends sometime later (indeterminate).
|
|
|Flood
| e24_fld_juggernaut - Guess
| (killificate) - Kill folks
| e24_fld_inf0 - Any leftover combat forms
| (guard0) - Guard left side
| (guard1) - Guard right side
| (follow) - Follow the Juggernaut
| e24_fld_inf1 - Reinforcements for the juggernaut's posse
| _0 - From the left side
| _1 - From the right side
| (follow) - Follow the Juggernaut
| e24_fld_inf2 - Reinforcements at the interior->exterior threshhold
| (follow) - Follow the Juggernaut
|
|Open Issues
|
*;
- Globals ---------------------------------------------------------------------
- Command Scripts -------------------------------------------------------------
Wait for it...
Board it
Jump in
Migrate them over
Wait for them to land
- Order Scripts ---------------------------------------------------------------
- Squad Controls --------------------------------------------------------------
- Init and Cleanup ------------------------------------------------------------
Wake subsequent scripts
Wake control scripts
(wake e24_fld_inf0_main)
(wake e24_fld_inf1_main)
(wake e24_fld_inf2_main)
Shut down
*
|Flood combat in the long interior cruise.
|
|Begins when the key enters the open space.
|Ends sometime later (indeterminate).
|
|
|Flood
| _0 - Left side
| (init) - Firing from the boarding point
| _1 - Right side
| (init) - Firing from the boarding point
| (engage) - Leaping aboard the key and engaging
|
|Open Issues
|
*;
- Globals ---------------------------------------------------------------------
- Command Scripts -------------------------------------------------------------
Elite 0
Elite 0
- Order Scripts ---------------------------------------------------------------
- Event Controls --------------------------------------------------------------
Tartarus sees the humans
Run the response scene
- Squad Controls --------------------------------------------------------------
Place the Flood
Wait until the key is close enough
Change orders, send them in
- Init and Cleanup ------------------------------------------------------------
Wake subsequent scripts
Wake control scripts
(wake e23_fld_inf0_main)
Shut down
*
|
|Begins when the key passes into the lock.
|Ends sometime later (indeterminate).
|
|
|Flood
| _0 - Left side
| (init) - Fighting on their side
| (engage0) - Fighting on the key, on the left side
| _1 - Right side
| (init) - Fighting on their side
| (engage0) - Fighting on the key, on the right side
| (engage1) - Free roam
|?? e22_fld_inf1 - Flood who board the key from below
| (massing) - Massing before attacking
| (engage) - Attacking when alerted or finished amassing
|
|Open Issues
|
*;
- Globals ---------------------------------------------------------------------
- Command Scripts -------------------------------------------------------------
Wait for it...
Board it
Migrate them over
Elite 0
Elite 0
- Order Scripts ---------------------------------------------------------------
- Event Controls --------------------------------------------------------------
Tartarus boosts ahead
Run the response scene
- Squad Controls --------------------------------------------------------------
Place the Flood
- Init and Cleanup ------------------------------------------------------------
Wake subsequent scripts
Wake control scripts
Shut down
*
|A running Flood vs. Covenant battle which rages on the key for the entire run.
|
|Begins when the cutscene ends.
|Ends sometime later (indeterminate).
|
| e21_cov_inf0 - Elite allies
| (init) - Front idle
| _0 - Ranged specialists, they hang back
| (guard_right) - Guarding the left side
| _1 - Close range fighters, they hold the line
| (advance_left) - Further up the line on the left
|
|Flood
| e21_fld_inf0 - Flood attacking from the left side of the key
| _0 - The main squad
| _1 - Reinforcements from down low
| _2 - Reinforcements from up high
| _3 - Carriers from down low
| (engage0) - Engaging on the left side
| e21_fld_inf1 - Flood attacking from the right side of the key
| _0 - The main squad
| _1 - Reinforcements from down low
| _2 - Reinforcements from up high
| _3 - Carriers from down low
| (engage0) - Engaging on the left side
|
*;
- Globals ---------------------------------------------------------------------
- Command Scripts -------------------------------------------------------------
Head to the rally point
Jump in
(cs_jump_to_point 2.5 1)
Then go to the rally point
Head to the rally point
Jump in
(cs_jump_to_point 2.5 1)
Head to the rally point
Shoot at the key
Wait for it...
Set their orders
Board it
Move to a point
Wait until we're closer...
Shoot a random combat form
- Order Scripts ---------------------------------------------------------------
- Event Controls --------------------------------------------------------------
- Squad Controls --------------------------------------------------------------
Migrate everyone over
Respawn one
Loop until the shaft
Is the player in the way of the lower spawner?
He is, so spawn from up top
Is the other one on the upper left side?
He is, spawn from the opposite side
He is not, spawn from that side
He is not, so spawn from down low
Migrate everyone over
Respawn them
Until there are enough or the ride is over
Loop until the shaft
Wait for that initial group to load on board
Respawn one
Loop until the shaft
Is the player in the way of the lower spawner?
He is, so spawn from up top
Is the other one on the upper left side?
He is, spawn from the opposite side
He is not, spawn from that side
He is not, so spawn from down low
Wait for that initial group to load on board
Initial spawn
Until there are enough or the ride is over
Respawn them
Until there are enough or the ride is over
Loop until the shaft
Place the Elites
Play the scene
Play the next scene
Wait for that initial group to load on board
Set the orders
Wait for the shaft
Set the orders
- Init and Cleanup ------------------------------------------------------------
Wake subsequent scripts
Wake control scripts
(wake e21_fld_carriers0_main)
pbertone: dialogue
*= KEY RIDE CINEMATIC ====================================================================
|
|
| ; Run the cinematic
|
| ; Once it's done, wake subsequent encounters
| (wake key_main)
| (wake key_ride_human_key_main)
| (wake key_ride_tartarus_main)
| (wake e21_main)
|)
*;
*
|A vigorous flood defense of the key.
|
|Begins when the player enters the room.
|Ends when the player leaves the room.
|
|
|Flood
| e20_fld_infs0 - Infection forms milling through the environment, fleeing
|
|Open Issues
|
|
|
|;- Globals ---------------------------------------------------------------------
|
Encounter has been activated ?
|
|
|;- Command Scripts -------------------------------------------------------------
|;- Order Scripts ---------------------------------------------------------------
|;- Squad Controls --------------------------------------------------------------
|
| ; FILL THIS WITH MIGRATION COMMANDS
|)
|
|
- Init and Cleanup ------------------------------------------------------------
|
| (set g_e20_started true)
| (print "e20_main")
| (game_save)
|
Wake subsequent scripts
|
| ; Wake control scripts
| (wake e20_cov_inf0_main)
|
| ; Shut down
| (sleep_forever e20_cov_inf0_main)
|
| ; Start the cutscene
|
| ; Clean up
| (ai_erase e20_cov)
| (ai_erase e20_fld)
|)
|
|(script static void test_key_dock
| (switch_bsp_by_name sen_hq_bsp_5)
| (if (not g_e20_started) (wake e20_main))
|)
*;
= KEYRIDE MAIN ==========================================================================
Wake the encounters
(wake cinematic_key_boarding)
= MISSION MAIN ==========================================================================
=========== ENCOUNTER SCRIPTS ==========
0
turn off the ghost spawner
(wake dam_door_a)
(wake dam_door_b)
* (sleep_until (or
| (> (device_get_position dam_door_a) 0)
| (> (device_get_position dam_door_b) 0)
| )
*;
(game_save)
(game_save_no_timeout)
(game_save)
===========================================================================================================
============= STARTUP SCRIPT ==============================================================================
===========================================================================================================
(sleep_until g_e26_ended)
* (sleep_until
| (or
| g_e26_ended
| (volume_test_objects tv_x07 (players))
| )
| 5)
*;
Necessary startup stuff
Begin the mission
Comment this out when you're testing individual encounters
| (global boolean debug 1)
(global boolean dialogue 1)
(global boolean g_play_cinematics 1)
(global boolean g_fact_ent_sen_spawn 0)
(global short g_fact_ent_sen_count 0)
(global short g_fact_ent_sen_index 10)
(global short g_fact_ent_enf_count 0)
(global short g_fact_ent_enf_index 3)
(script stub void x07 (print "x07"))
(script stub void c06_intra1 (print "c06_intra1"))
(script stub void c06_intra2 (print "c06_intra2"))
(script command_script cs_invulnerable
(cs_enable_moving 1)
(object_cannot_take_damage (ai_get_object ai_current_actor))
(sleep_until (>= (ai_combat_status ai_current_actor) ai_combat_status_certain))
(sleep (* 30 1))
(object_can_take_damage (ai_get_object ai_current_actor))
)
(script command_script cs_invul_8
(cs_enable_moving 1)
(object_cannot_take_damage (ai_get_object ai_current_actor))
(sleep (* 30 8))
(object_can_take_damage (ai_get_object ai_current_actor))
)
(script command_script cs_kill
(ai_kill_silent ai_current_actor)
)
(script static void no_death
(object_cannot_take_damage (ai_actors covenant))
)
(script dormant ice_cream_superman
(object_create ice_cream_head)
(sleep_until
(or
(unit_has_weapon (unit (player0)) "objects\weapons\multiplayer\ball\head_sp.weapon")
(unit_has_weapon (unit (player1)) "objects\weapons\multiplayer\ball\head_sp.weapon")
)
5)
(if debug (print "you're going to get fat!!!!! or dead..."))
(if debug (print "because now everyone is superman!!!!"))
(ice_cream_flavor_stock 10)
)
(global boolean g_music_06b_01 1)
(global boolean g_music_06b_02 0)
(global boolean g_music_06b_03 0)
(global boolean g_music_06b_04 0)
(global boolean g_music_06b_05 0)
(global boolean g_music_06b_06 0)
(global boolean g_music_06b_07 0)
(script dormant music_06b_01
(sleep_until g_music_06b_01)
(if debug (print "start music 06b_01"))
(sound_looping_start scenarios\solo\06b_floodzone\06b_music\06b_01 none 1)
( if debug ( print " stop music 06b_01 " ) )
4 ( sound_looping_stop scenarios\solo\06b_floodzone\06b_music\06b_01 )
)
(script dormant music_06b_02
(sleep_until g_music_06b_02)
(if debug (print "start music 06b_02"))
(sound_looping_start scenarios\solo\06b_floodzone\06b_music\06b_02 none 1)
(sleep_until (not g_music_06b_02))
(if debug (print "stop music 06b_02"))
(sound_looping_stop scenarios\solo\06b_floodzone\06b_music\06b_02)
)
(script dormant music_06b_03
(sleep_until g_music_06b_03)
(if debug (print "start music 06b_03"))
(sound_looping_start scenarios\solo\06b_floodzone\06b_music\06b_03 none 1)
(sleep_until (not g_music_06b_03))
(if debug (print "stop music 06b_03"))
(sound_looping_stop scenarios\solo\06b_floodzone\06b_music\06b_03)
)
(script dormant music_06b_04
(sleep_until g_music_06b_04)
(if debug (print "start music 06b_04"))
(sound_looping_start scenarios\solo\06b_floodzone\06b_music\06b_04 none 1)
( if debug ( print " stop music 06b_04 " ) )
)
(script dormant music_06b_05
(sleep_until (volume_test_objects tv_e20_dock_entrance (players)))
(set g_music_06b_05 1)
(if debug (print "start music 06b_05"))
(sound_looping_start scenarios\solo\06b_floodzone\06b_music\06b_05 none 1)
(sleep_until (not g_music_06b_05))
(if debug (print "stop music 06b_05"))
(sound_looping_stop scenarios\solo\06b_floodzone\06b_music\06b_05)
)
(script dormant music_06b_06
(sleep_until g_music_06b_06)
(if debug (print "start music 06b_06"))
(sound_looping_start scenarios\solo\06b_floodzone\06b_music\06b_06 none 1)
)
(script dormant music_06b_07
(sleep_until (volume_test_objects tv_music_06b_07 (players)))
(if debug (print "start music 06b_07"))
(sound_looping_start scenarios\solo\06b_floodzone\06b_music\06b_07 none 1)
)
(script dormant chapter_mirror
(sleep 30)
(cinematic_set_title title_1)
(sleep 150)
(hud_cinematic_fade 1 0.5)
(cinematic_show_letterbox false)
)
(script dormant chapter_competition
(sleep 30)
(hud_cinematic_fade 0 0.5)
(cinematic_show_letterbox true)
(sleep 30)
(cinematic_set_title title_2)
(sleep 150)
(hud_cinematic_fade 1 0.5)
(cinematic_show_letterbox false)
)
(script dormant chapter_gallery
(hud_cinematic_fade 0 0.5)
(cinematic_show_letterbox true)
(sleep 30)
(cinematic_set_title title_3)
(sleep 150)
(hud_cinematic_fade 1 0.5)
(cinematic_show_letterbox false)
)
(script dormant chapter_familiar
(hud_cinematic_fade 0 0.5)
(cinematic_show_letterbox true)
(sleep 30)
(cinematic_set_title title_4)
(sleep 150)
(hud_cinematic_fade 1 0.5)
(cinematic_show_letterbox false)
)
(script dormant objective_push_set
(sleep 30)
(print "new objective set:")
(print "Push through the Quarantine-Zone toward The Library.")
(objectives_show_up_to 0)
)
(script dormant objective_push_clear
(print "objective complete:")
(print "Push through the Quarantine-Zone toward The Library.")
(objectives_finish_up_to 0)
)
(script dormant objective_link_set
(sleep 30)
(print "new objective set:")
(print "Link-up with the Spec-Ops Leader, and break through the Flood barricade.")
(objectives_show_up_to 1)
)
(script dormant objective_link_clear
(print "objective complete:")
(print "Link-up with the Spec-Ops Leader, and break through the Flood barricade.")
(objectives_finish_up_to 1)
)
(script dormant objective_retrieve_set
(sleep 30)
(print "new objective set:")
(print "Retrieve the Sacred Icon before the Humans.")
(objectives_show_up_to 2)
)
(script dormant objective_retrieve_clear
(print "objective complete:")
(print "Retrieve the Sacred Icon before the Humans.")
(objectives_finish_up_to 2)
)
(global short dialogue_pause 7)
(global boolean g_qz_cov_def_progress 0)
(script dormant sc_cov_charge
for , because he bitches a lot
(if dialogue (print "COMMANDER: Forward, warriors! And fear not pain or death!"))
(sleep (ai_play_line_on_object none 0220))
(sleep (* dialogue_pause 2))
(if dialogue (print "COMMANDER: Go, Arbiter! I'll follow when our reinforcements arrive!"))
(sleep (ai_play_line_on_object none 0240))
(sleep dialogue_pause)
(sleep_until g_qz_cov_def_progress)
(if (<= (ai_living_count cov_def_enf) 0) (sleep 180) (sleep 30))
if the enforcers are not alive then sleep 180 , if they are then sleep 30
(if (> (ai_living_count cov_def_enf) 0)
(begin
(if dialogue (print "SPEC-OPS: Go, Enforcers!"))
(sleep (ai_play_line covenant 0590))
(sleep dialogue_pause)
)
)
(if dialogue (print "SPEC-OPS: To the vehicles! We'll need their heavy-guns!"))
(sleep (ai_play_line covenant 0600))
(sleep dialogue_pause)
(if dialogue (print "SPEC-OPS: Onward! To the Sacred Icon!"))
(sleep (ai_play_line covenant 0610))
(sleep dialogue_pause)
)
* this was removed because it was blocking the AI from getting into their vehicles
|(script dormant sc_cov_charge
| ( sleep_until ( cs_sc_cov_charge covenant ) )
(script command_script cs_sc_qz_veh_int
(if dialogue (print "SPEC-OPS: What?! The Parasite controls our vehicles?!"))
(sleep (ai_play_line covenant 0620))
(sleep dialogue_pause)
(if dialogue (print "SPEC-OPS: Impossible! It's never done that before!"))
(sleep (ai_play_line covenant 0640))
(sleep dialogue_pause)
(if dialogue (print "SPEC-OPS: No matter. It will die all the same!"))
(sleep (ai_play_line covenant 0650))
(sleep dialogue_pause)
)
(script dormant sc_qz_veh_int
(sleep 180)
(sleep_until (ai_scene sc_qz_veh_int cs_sc_qz_veh_int covenant))
)
(script dormant sc_ext_a
(if dialogue (print "COMMANDER: I'm sending you a squad of my most experienced Warriors, Arbiter."))
(sleep (ai_play_line_on_object none 0650))
(sleep dialogue_pause)
(if dialogue (print "COMMANDER: Do not squander their talents!"))
(sleep (ai_play_line_on_object none 0660))
(sleep dialogue_pause)
)
(script dormant sc_factory_approach
(if dialogue (print "COMMANDER: Commander! We've found a human vehicle!"))
(sleep (ai_play_line covenant 0250))
(sleep dialogue_pause)
(if dialogue (print "SPEC-OPS: Keep moving. I'm on my way."))
(sleep (ai_play_line_on_object none 0260))
(sleep dialogue_pause)
)
(script dormant sc_factory_exit
(sleep 60)
(if dialogue (print "SPEC-OPS: Humans and parasites!"))
(if dialogue (print "This ring has been befouled, but we will wipe it clean!"))
(sleep (ai_play_line covenant 0270))
(sleep dialogue_pause)
(if dialogue (print "SPEC-OPS: Honoring those who built it!"))
(sleep (ai_play_line covenant 0280))
(sleep dialogue_pause)
)
(script dormant sc_human_fools
(if dialogue (print "COMMANDER: Human fools. I almost feel sorry for them."))
(sleep (ai_play_line_on_object none 0290))
(sleep dialogue_pause)
)
(script dormant sc_ext_b
(if dialogue (print "SPEC-OPS: Forward to the Icon!"))
(sleep (ai_play_line covenant 0700))
(sleep dialogue_pause)
(if dialogue (print "SPEC-OPS: The Parasite's ranks swell as we draw nearer to the Library!"))
(sleep (ai_play_line covenant 0710))
(sleep dialogue_pause)
(if dialogue (print "SPEC-OPS: Steel your nerves. We are not turning back!"))
(sleep (ai_play_line covenant 0720))
(sleep dialogue_pause)
)
(script dormant sc_chasm
(if dialogue (print "TARTARUS: I see that coward didn't join you."))
(sleep (ai_play_line_on_object none 0300))
(sleep dialogue_pause)
(if dialogue (print "TARTARUS: I'll do what I can to keep the Flood off your back."))
(sleep (ai_play_line_on_object none 0310))
(sleep dialogue_pause)
)
(script dormant sc_outer_wall
(if dialogue (print "TARTARUS: We cannot let the humans capture the Icon!"))
(sleep (ai_play_line_on_object none 0320))
(sleep dialogue_pause)
(if dialogue (print "TARTARUS: The Hierarchs do not look kindly on failure."))
(sleep (ai_play_line_on_object none 0330))
(sleep dialogue_pause)
)
(script dormant sc_dock
(if dialogue (print "TARTARUS: Hurry, Arbiter! Get the Icon!"))
(sleep (ai_play_line_on_object none 0340))
(sleep dialogue_pause)
)
(script static boolean driver_seat_test
(if
(or
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_cov_def_spectre/spectre) "spectre_d" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_cov_def_ghosts/a) "ghost_d" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_cov_def_ghosts/b) "ghost_d" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location veh_int_flood_ghosts_ini/a) "ghost_d" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location veh_int_flood_ghosts_ini/b) "ghost_d" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location veh_int_hog_ab/hog) "warthog_d" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location veh_int_ghost_ab/a) "ghost_d" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location veh_int_ghost_ab/b) "ghost_d" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location veh_int_scorpion/scorpion) "ghost_d" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location veh_int_flood_hog_bk/warthog) "ghost_d" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location veh_int_flood_ghosts_bk/a) "ghost_d" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location veh_int_flood_ghosts_bk/b) "ghost_d" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_ext_a_ghosts/a) "ghost_d" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_ext_a_ghosts/b) "ghost_d" (players))
)
true false)
)
(script static boolean passenger_seat_test
(if
(or
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_cov_def_spectre/spectre) "spectre_p_l" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_cov_def_spectre/spectre) "spectre_p_r" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_cov_def_spectre/spectre) "spectre_g" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location veh_int_hog_ab/hog) "warthog_p" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location veh_int_hog_ab/hog) "warthog_g" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location veh_int_flood_hog_bk/warthog) "warthog_p" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location veh_int_flood_hog_bk/warthog) "warthog_g" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_ext_b_fact_warthog/warthog) "warthog_p" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_ext_b_fact_warthog/warthog) "warthog_g" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_ext_b_warthog/warthog) "warthog_p" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_ext_b_warthog/warthog) "warthog_g" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_ext_b_warthog_gauss/warthog) "warthog_p" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_ext_b_warthog_gauss/warthog) "warthog_g" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_ext_b_cov_spectre/spectre) "spectre_p_l" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_ext_b_cov_spectre/spectre) "spectre_p_r" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_ext_b_cov_spectre/spectre) "spectre_g" (players))
)
true false)
)
(global short g_order_delay 150)
(script command_script cov_def_spec_tele_a
(cs_teleport bsp_swap_teleport/a bsp_swap_teleport/face)
)
(script command_script cov_def_spec_tele_b
(cs_teleport bsp_swap_teleport/b bsp_swap_teleport/face)
)
(script command_script cov_def_spec_tele_c
(cs_teleport bsp_swap_teleport/c bsp_swap_teleport/face)
)
(script command_script cov_def_spec_tele_d
(cs_teleport bsp_swap_teleport/d bsp_swap_teleport/face)
)
(script command_script cs_fact_ent_exit_veh
(cs_enable_pathfinding_failsafe true)
(cs_go_to_nearest crashed_fact_ent)
9/22
9/22
(ai_set_orders covenant cov_follow_factory1)
(sleep 30)
(ai_vehicle_exit covenant)
)
(global boolean g_veh_int_migrate_a 0)
(global boolean g_veh_int_migrate_b 0)
(global boolean g_veh_int_migrate_c 0)
(global boolean g_veh_int_migrate_d 0)
(global boolean g_veh_int_migrate_e 0)
(global boolean g_ext_a_dam_migrate_a 0)
(global boolean g_ext_a_dam_migrate_b 0)
(global boolean g_ext_a_migrate_a 0)
(global boolean g_ext_a_migrate_b 0)
(global boolean g_ext_a_migrate_c 0)
(global boolean g_ext_a_migrate_d 0)
(global boolean g_ext_a_migrate_e 0)
(global boolean g_ext_a_migrate_f 0)
(global boolean g_ext_a_fact_ent_migrate 0)
(script dormant ext_a_vehicle_orders
(sleep g_order_delay)
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(ai_set_orders covenant cov_drive_cov_def))
)
(true (ai_set_orders covenant cov_follow_cov_def))
)
(= (structure_bsp_index) 1))
)
| ( cs_run_command_script qz_cov_def_spec_ops / a cov_def_spec_tele_a )
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(cond
((= (structure_bsp_index) 0) (begin
(ai_set_orders covenant_infantry cov_follow_cov_def)
(ai_set_orders covenant_vehicles cov_drive_cov_def)
)
)
((= (structure_bsp_index) 1) (begin
(ai_set_orders covenant_infantry cov_follow_veh_int)
(ai_set_orders covenant_vehicles cov_drive_veh_int_a)
)
)
)
)
)
(true
(cond
((= (structure_bsp_index) 0) (ai_set_orders covenant cov_follow_cov_def))
((= (structure_bsp_index) 1) (ai_set_orders covenant cov_follow_veh_int))
)
)
)
(and
(volume_test_objects tv_veh_int_a (players))
(ai_trigger_test "done_fighting" covenant)
)
(and
(volume_test_objects tv_veh_int_a (players))
(<= (ai_living_count veh_int_sen_a) 0)
)
g_veh_int_migrate_b
))
)
(sleep g_order_delay)
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(cond
((= (structure_bsp_index) 0) (begin
(ai_set_orders covenant_infantry cov_follow_cov_def)
(ai_set_orders covenant_vehicles cov_drive_cov_def)
)
)
((= (structure_bsp_index) 1) (begin
(ai_set_orders covenant_infantry cov_follow_veh_int)
(ai_set_orders covenant_vehicles cov_drive_veh_int_b)
)
)
)
)
)
(true
(cond
((= (structure_bsp_index) 0) (ai_set_orders covenant cov_follow_cov_def))
((= (structure_bsp_index) 1) (ai_set_orders covenant cov_follow_veh_int))
)
)
)
(and
(volume_test_objects tv_veh_int_b (players))
(ai_trigger_test "done_fighting" covenant)
)
(and
(volume_test_objects tv_veh_int_b (players))
(<= (ai_living_count veh_int_sen_b) 0)
(<= (ai_living_count veh_int_flood_b) 0)
)
g_veh_int_migrate_c
))
)
(sleep g_order_delay)
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(ai_set_orders covenant_infantry cov_follow_veh_int)
(ai_set_orders covenant_vehicles cov_drive_veh_int_c)
)
)
(true (ai_set_orders covenant cov_follow_veh_int))
)
(and
(volume_test_objects tv_veh_int_c (players))
(ai_trigger_test "done_fighting" covenant)
)
(and
(volume_test_objects tv_veh_int_c (players))
(<= (ai_living_count veh_int_sen_c) 0)
(<= (ai_living_count veh_int_flood_c) 0)
)
g_veh_int_migrate_d
))
)
(sleep g_order_delay)
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(ai_set_orders covenant_infantry cov_follow_veh_int)
(ai_set_orders covenant_vehicles cov_drive_veh_int_d)
)
)
(true (ai_set_orders covenant cov_follow_veh_int))
)
(and
(volume_test_objects tv_veh_int_d (players))
(ai_trigger_test "done_fighting" covenant)
)
(and
(volume_test_objects tv_veh_int_d (players))
(<= (ai_living_count veh_int_sen_d) 0)
(<= (ai_living_count veh_int_flood_d) 0)
)
g_veh_int_migrate_e
))
)
(sleep g_order_delay)
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(ai_set_orders covenant_infantry cov_follow_veh_int)
(ai_set_orders covenant_vehicles cov_drive_veh_int_e)
)
)
(true (ai_set_orders covenant cov_follow_veh_int))
)
(volume_test_objects tv_qz_ext_a (players))
g_ext_a_dam_migrate_a
))
)
(sleep g_order_delay)
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(ai_set_orders covenant_infantry cov_follow_ext_a_dam)
(ai_set_orders covenant_vehicles cov_drive_ext_a_dam_a)
)
)
(true (ai_set_orders covenant cov_follow_ext_a_dam))
)
(and
(volume_test_objects tv_ext_a_dam_a (players))
(ai_trigger_test "done_fighting" covenant)
)
(and
(volume_test_objects tv_ext_a_dam_a (players))
(<= (ai_living_count ext_a_sen_dam_a) 0)
(<= (ai_living_count ext_a_flood_dam_a) 0)
)
g_ext_a_dam_migrate_b
)
)
)
(sleep g_order_delay)
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(ai_set_orders covenant_infantry cov_follow_ext_a_dam)
(ai_set_orders covenant_vehicles cov_drive_ext_a_dam_b)
)
)
(true (ai_set_orders covenant cov_follow_ext_a_dam))
)
(and
(volume_test_objects qz_ext_a_dam_b (players))
(ai_trigger_test "done_fighting" covenant)
)
(and
(volume_test_objects qz_ext_a_dam_b (players))
(<= (ai_living_count ext_a_sen_dam_b) 0)
(<= (ai_living_count ext_a_flood_dam_b) 0)
)
g_ext_a_migrate_a
)
)
)
(sleep g_order_delay)
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(ai_set_orders covenant_infantry cov_follow_ext_a)
(ai_set_orders covenant_vehicles cov_drive_ext_a_a)
)
)
(true (ai_set_orders covenant cov_follow_ext_a))
)
(and
(volume_test_objects tv_ext_a_a (players))
(ai_trigger_test "done_fighting" covenant)
)
(and
(volume_test_objects tv_ext_a_a (players))
(<= (ai_living_count ext_a_sen_a) 0)
(<= (ai_living_count ext_a_flood_a) 0)
)
g_ext_a_migrate_b
)
)
)
(sleep g_order_delay)
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(ai_set_orders covenant_infantry cov_follow_ext_a)
(ai_set_orders covenant_vehicles cov_drive_ext_a_b)
)
)
(true (ai_set_orders covenant cov_follow_ext_a))
)
(and
(volume_test_objects tv_ext_a_b (players))
(ai_trigger_test "done_fighting" covenant)
)
(and
(volume_test_objects tv_ext_a_b (players))
(<= (ai_living_count ext_a_sen_b) 0)
(<= (ai_living_count ext_a_flood_b) 0)
)
g_ext_a_migrate_c
)
)
)
(sleep g_order_delay)
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(ai_set_orders covenant_infantry cov_follow_ext_a)
(ai_set_orders covenant_vehicles cov_drive_ext_a_c)
)
)
(true (ai_set_orders covenant cov_follow_ext_a))
)
(and
(volume_test_objects tv_ext_a_c (players))
(ai_trigger_test "done_fighting" covenant)
)
(and
(volume_test_objects tv_ext_a_c (players))
(<= (ai_living_count ext_a_sen_c) 0)
(<= (ai_living_count ext_a_flood_c) 0)
)
g_ext_a_migrate_d
)
)
)
(sleep g_order_delay)
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(ai_set_orders covenant_infantry cov_follow_ext_a)
(ai_set_orders covenant_vehicles cov_drive_ext_a_d)
)
)
(true (ai_set_orders covenant cov_follow_ext_a))
)
(and
(volume_test_objects tv_ext_a_d (players))
(ai_trigger_test "done_fighting" covenant)
)
(and
(volume_test_objects tv_ext_a_d (players))
(<= (ai_living_count ext_a_sen_d) 0)
(<= (ai_living_count ext_a_flood_d) 0)
)
g_ext_a_migrate_e
)
)
)
(sleep g_order_delay)
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(ai_set_orders covenant_infantry cov_follow_ext_a)
(ai_set_orders covenant_vehicles cov_drive_ext_a_e)
)
)
(true (ai_set_orders covenant cov_follow_ext_a))
)
(and
(volume_test_objects tv_ext_a_e (players))
(ai_trigger_test "done_fighting" covenant)
)
(and
(volume_test_objects tv_ext_a_e (players))
(<= (ai_living_count ext_a_sen_e) 0)
(<= (ai_living_count ext_a_flood_e) 0)
)
g_ext_a_migrate_f
)
)
)
(sleep g_order_delay)
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(ai_set_orders covenant_infantry cov_follow_ext_a_fact_ent)
(ai_set_orders covenant_vehicles cov_drive_ext_a_f)
)
)
(true (ai_set_orders covenant cov_follow_ext_a_fact_ent))
)
(and
(volume_test_objects tv_ext_a_f (players))
(ai_trigger_test "done_fighting" covenant)
)
(and
(volume_test_objects tv_ext_a_f (players))
(<= (ai_living_count ext_a_sen_f) 0)
(<= (ai_living_count ext_a_flood_f) 0)
)
g_ext_a_fact_ent_migrate
)
)
)
(sleep g_order_delay)
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(ai_set_orders covenant_infantry cov_follow_ext_a_fact_ent)
(ai_set_orders covenant_vehicles cov_drive_fact_ent)
)
)
(true (ai_set_orders covenant cov_follow_ext_a_fact_ent))
)
(and
(ai_trigger_test "done_fighting" covenant)
g_fact_ent_sen_spawn
)
(and
(<= (ai_living_count fact_ent_sentinels) 0)
(<= (ai_living_count fact_ent_flood) 0)
g_fact_ent_sen_spawn
)
(volume_test_objects tv_fact_ent_follow (players))
)
)
)
(sleep g_order_delay)
)
(global boolean g_ext_b_migrate_1 0)
(global boolean g_ext_b_migrate_2 0)
(global boolean g_ext_b_migrate_3 0)
(global boolean g_ext_b_migrate_4 0)
(global boolean g_ext_b_migrate_5 0)
(script command_script cs_ext_b_exit
(cs_enable_pathfinding_failsafe true)
(cs_go_to_nearest ext_b_exit)
9/22
9/22
(ai_set_orders covenant cov_ext_b_exit)
(sleep 30)
(ai_vehicle_exit covenant)
)
(script dormant ext_b_vehicle_orders
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(ai_set_orders covenant_infantry cov_follow_ext_b)
(ai_set_orders covenant_vehicles cov_drive_ext_b_a)
)
)
(true (ai_set_orders covenant cov_follow_ext_b))
)
(ai_magically_see covenant ext_b_flood)
g_ext_b_migrate_1)
)
(sleep g_order_delay)
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(ai_set_orders covenant_infantry cov_follow_ext_b)
(ai_set_orders covenant_vehicles cov_drive_ext_b_b)
)
)
(true (ai_set_orders covenant cov_follow_ext_b))
)
(ai_magically_see covenant ext_b_flood)
g_ext_b_migrate_2)
)
(sleep (* g_order_delay 3))
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(ai_set_orders covenant_infantry cov_follow_ext_b)
(ai_set_orders covenant_vehicles cov_drive_ext_b_b)
)
)
(true (ai_set_orders covenant cov_follow_ext_b))
)
(ai_magically_see covenant ext_b_flood)
(and
(<= (ai_living_count ext_b_flood_b) 0)
(<= (ai_living_count ext_b_sentinels_b) 0)
)
g_ext_b_migrate_3
)
)
)
(sleep g_order_delay)
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(ai_set_orders covenant_infantry cov_follow_ext_b)
(ai_set_orders covenant_vehicles cov_drive_ext_b_c)
)
)
(true (ai_set_orders covenant cov_follow_ext_b_bk))
)
(ai_magically_see covenant ext_b_flood)
(and
(<= (ai_living_count ext_b_flood_c) 0)
(<= (ai_living_count ext_b_sentinels_c) 0)
)
g_ext_b_migrate_4
)
)
)
(sleep g_order_delay)
(sleep_until
(begin
(cond
((passenger_seat_test) (begin
(if debug (print "player is passenger"))
(ai_set_orders covenant_infantry cov_follow_ext_b)
(ai_set_orders covenant_vehicles cov_drive_ext_b_d)
)
)
(true (ai_set_orders covenant cov_follow_ext_b_bk))
)
(ai_magically_see covenant ext_b_flood)
g_ext_b_migrate_5)
)
(sleep (* g_order_delay 3))
(sleep_until (= (structure_bsp_index) 3))
(ai_migrate covenant key_cov_dump)
(sleep 5)
(ai_teleport_to_starting_location_if_outside_bsp key_cov_dump)
(sleep 5)
(ai_set_orders covenant cov_follow_key_ent)
)
(script command_script cs_cov_def_phantom
(cs_fly_to qz_cov_def/drop)
(sleep_until g_qz_cov_def_progress)
( cs_fly_to qz_cov_def / drop .1 )
( sleep 30 )
( sleep 30 )
( sleep ( * 30 2 ) )
(cs_vehicle_speed .85)
(cs_fly_to_and_face qz_cov_def/p4 qz_cov_def/p1 3)
(cs_vehicle_speed 1)
( cs_fly_to qz_cov_def / p0 3 )
( cs_vehicle_speed .7 )
(cs_fly_by qz_cov_def/p1 10)
( cs_vehicle_speed 1 )
(cs_fly_by qz_cov_def/p2 10)
(cs_fly_by qz_cov_def/p3 10)
(ai_erase ai_current_squad)
)
(script command_script cs_cov_def_spec_ops_a
(cs_enable_pathfinding_failsafe true)
(cs_look_player true)
(sleep_until g_qz_cov_def_progress 5)
(cs_go_to_vehicle (ai_vehicle_get_from_starting_location qz_cov_def_ghosts/a))
)
(script command_script cs_cov_def_spec_ops_b
(cs_enable_pathfinding_failsafe true)
(cs_look_player true)
(sleep_until g_qz_cov_def_progress 5)
(cs_go_to_vehicle (ai_vehicle_get_from_starting_location qz_cov_def_ghosts/b))
)
(script command_script cs_cov_def_spec_ops_c
(cs_enable_pathfinding_failsafe true)
(cs_look_player true)
(sleep_until g_qz_cov_def_progress 5)
(cs_go_to_vehicle (ai_vehicle_get_from_starting_location qz_cov_def_spectre/spectre))
)
(script command_script cs_cov_def_spec_ops_d
(cs_enable_pathfinding_failsafe true)
(cs_look_player true)
(sleep_until g_qz_cov_def_progress 5)
(cs_go_to_vehicle (ai_vehicle_get_from_starting_location qz_cov_def_spectre/spectre))
)
(script command_script cs_go_to_scorpion
(cs_enable_pathfinding_failsafe true)
(cs_go_to_vehicle (ai_vehicle_get_from_starting_location veh_int_scorpion/scorpion))
)
(script command_script cs_go_to_wraith
(cs_enable_pathfinding_failsafe true)
(cs_go_to_vehicle (ai_vehicle_get_from_starting_location veh_int_wraith/wraith))
)
(global boolean g_veh_int_ghost_spawn 0)
(global short g_veh_int_ghost_limit 0)
(global short g_veh_int_ghost_number 0)
(script dormant ai_veh_int_ghost_spawn
(sleep_until (<= (ai_living_count veh_int_flood_ghosts_ini) 0))
(if debug (print "waking vehicle interior ghost spawner"))
(cond
((difficulty_normal) (begin (set g_veh_int_ghost_limit 6) (set g_veh_int_ghost_number 1)))
((difficulty_heroic) (begin (set g_veh_int_ghost_limit 8) (set g_veh_int_ghost_number 2)))
((difficulty_legendary) (begin (set g_veh_int_ghost_limit 10) (set g_veh_int_ghost_number 3)))
)
(sleep_until
(begin
(sleep_until (<= (ai_living_count veh_int_flood_ghosts_bk) 0))
(sleep 90)
(if debug (print "placing ghosts"))
(ai_place veh_int_flood_ghosts_bk g_veh_int_ghost_number)
(>= (ai_spawn_count veh_int_flood_ghosts_bk) g_veh_int_ghost_limit)
g_veh_int_ghost_spawn)
)
)
(if (<= (ai_living_count veh_int_flood_ghosts_bk) 0) (ai_place veh_int_flood_ghosts_bk))
)
(script dormant dam_door_a
(sleep_until
(begin
(sleep_until (volume_test_objects tv_dam_door_a (players)) 5)
(device_set_position dam_door_a 1)
false)
)
)
(script dormant dam_door_b
(sleep_until
(begin
(sleep_until (volume_test_objects tv_dam_door_b (players)) 5)
(device_set_position dam_door_b 1)
false)
)
)
(script command_script cs_ext_a_enf_ini
(cs_shoot 1)
(cs_vehicle_boost 1)
(cs_fly_by qz_ext_a_enf/p0 3)
(cs_fly_by qz_ext_a_enf/p1 3)
(cs_fly_by qz_ext_a_enf/p2 3)
(cs_vehicle_boost 0)
)
(script command_script cs_ext_a_pelican
(cs_shoot false)
(vehicle_load_magic
(ai_vehicle_get_from_starting_location qz_ext_a_dam_human/pelican)
"pelican_lc"
(ai_vehicle_get_from_starting_location qz_ext_a_dam_human/scorpion)
)
(cs_fly_by qz_ext_a_pelican/p0 3)
( cs_fly_by qz_ext_a_pelican / p1 3 )
(cs_fly_by qz_ext_a_pelican/p2 3)
(cs_fly_by qz_ext_a_pelican/p3 5)
( cs_fly_by qz_ext_a_pelican / p4 3 )
(cs_fly_by qz_ext_a_pelican/p5 3)
(sleep 30)
(ai_erase ai_current_squad)
)
(script command_script cs_boost_1_5
(cs_vehicle_boost true)
(sleep (* 30 1.5))
(cs_vehicle_boost false)
)
(global vehicle v_ext_a_phantom none)
(script command_script cs_ext_a_phantom
(ai_place qz_ext_a_spec_ops)
(ai_place qz_ext_a_ghosts)
(cs_shoot true)
(cs_enable_pathfinding_failsafe true)
(sleep 1)
(vehicle_load_magic
v_ext_a_phantom
"phantom_p"
(ai_actors qz_ext_a_spec_ops)
)
(vehicle_load_magic
v_ext_a_phantom
"phantom_sc01"
(ai_vehicle_get_from_starting_location qz_ext_a_ghosts/a)
)
(vehicle_load_magic
v_ext_a_phantom
"phantom_sc02"
(ai_vehicle_get_from_starting_location qz_ext_a_ghosts/b)
)
(sleep 1)
(cs_vehicle_boost true)
(cs_fly_by qz_ext_a_phantom/p0 5)
(cs_vehicle_boost false)
(cs_fly_by qz_ext_a_phantom/p1 5)
(cs_fly_by qz_ext_a_phantom/p2 4)
(cs_fly_to_and_face qz_ext_a_phantom/p3 qz_ext_a_phantom/unit_face)
(cs_vehicle_speed .75)
(cs_fly_to_and_face qz_ext_a_phantom/drop_units qz_ext_a_phantom/unit_face 2)
(object_set_phantom_power v_ext_a_phantom 1)
(sleep 45)
(vehicle_unload v_ext_a_phantom "phantom_p_a01")
(sleep 30)
(vehicle_unload v_ext_a_phantom "phantom_p_a02")
(sleep 30)
(vehicle_unload v_ext_a_phantom "phantom_p_a03")
( sleep 20 )
(sleep 45)
(cs_fly_to_and_face qz_ext_a_phantom/drop_ghosts qz_ext_a_phantom/face 2)
(sleep_until (not (volume_test_objects_all tv_qz_ext_a_ghost_drop (players))))
(sleep 45)
(vehicle_unload v_ext_a_phantom "phantom_sc")
(sleep 90)
(object_set_phantom_power v_ext_a_phantom 0)
(cs_vehicle_speed 1)
(cs_fly_by qz_ext_a_phantom/p6)
(cs_fly_by qz_ext_a_phantom/p4)
(cs_vehicle_boost true)
(cs_fly_by qz_ext_a_phantom/p7)
(ai_erase ai_current_actor)
)
(global boolean g_qz_ext_a_wraith_shoot 0)
(script command_script cs_wraiths_shoot
(cs_abort_on_damage true)
(sleep_until
(begin
(begin_random
(begin
(cs_shoot_point true qz_ext_a_wraiths/p0)
(sleep (random_range 30 60))
)
(begin
(cs_shoot_point true qz_ext_a_wraiths/p1)
(sleep (random_range 30 60))
)
(begin
(cs_shoot_point true qz_ext_a_wraiths/p2)
(sleep (random_range 30 60))
)
(begin
(cs_shoot_point true qz_ext_a_wraiths/p3)
(sleep (random_range 30 60))
)
(begin
(cs_shoot_point true qz_ext_a_wraiths/p4)
(sleep (random_range 30 60))
)
(begin
(cs_shoot_point true qz_ext_a_wraiths/p5)
(sleep (random_range 30 60))
)
(begin
(cs_shoot_point true qz_ext_a_wraiths/p6)
(sleep (random_range 30 60))
)
(begin
(cs_shoot_point true qz_ext_a_wraiths/p7)
(sleep (random_range 30 60))
)
)
g_qz_ext_a_wraith_shoot)
)
)
(global boolean g_ext_a_dam_enf 0)
(script dormant ai_ext_a_dam_enforcers
(sleep_until
(begin
(sleep_until (<= (ai_living_count ext_a_sen_dam_b) 0))
(sleep 90)
(ai_place qz_ext_a_dam_enf_door)
(or
(>= (ai_spawn_count qz_ext_a_dam_enf_door) 3)
g_ext_a_dam_enf
)
)
)
)
(script dormant ai_qz_ext_a_wraiths
(ai_place qz_ext_a_flood_wraith_fr)
(ai_place qz_ext_a_flood_wraith_bk)
(ai_place qz_ext_a_flood_wraith_ledge)
)
(global boolean g_qz_ext_a_flood_ghosts 0)
(script dormant ai_qz_ext_a_ghosts
(sleep_until
(begin
(sleep_until (<= (ai_living_count qz_ext_a_flood_ghosts) 0))
(if g_qz_ext_a_flood_ghosts (sleep_forever))
(sleep (random_range 60 120))
(ai_place qz_ext_a_flood_ghosts)
g_qz_ext_a_flood_ghosts)
)
)
(script dormant ai_fact_ent_sen_spawn
(sleep_until
(begin
(sleep_until (<= (ai_living_count fact_ent_sen) 1))
(sleep (random_range 15 30))
(ai_place fact_ent_sen)
(set g_fact_ent_sen_count (+ g_fact_ent_sen_count 1))
(if (= g_fact_ent_sen_count g_fact_ent_sen_index) (set g_fact_ent_sen_spawn 1))
g_fact_ent_sen_spawn)
)
)
(script dormant ai_fact_ent_enf_spawn
(sleep_until
(begin
(sleep_until (<= (ai_living_count fact_ent_enf) 0))
(sleep (random_range 30 60))
(ai_place fact_ent_enf)
(set g_fact_ent_enf_count (+ g_fact_ent_enf_count 1))
(if (= g_fact_ent_enf_count g_fact_ent_enf_index) (set g_fact_ent_sen_spawn 1))
g_fact_ent_sen_spawn)
)
)
(global boolean g_qz_ext_a_d_spawn 1)
(script dormant ai_qz_ext_a_d_spawn
(sleep_until (volume_test_objects tv_ext_a_d (players)))
(if g_qz_ext_a_d_spawn
(begin
(ai_place qz_ext_a_flood_d)
(ai_place qz_ext_a_enf_bk)
)
)
)
= = = = = CRASHED FACTORY SCRIPTS = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
(sleep_until
(begin
(sleep_until
(OR
(= (volume_test_objects vol_factory_1_mid_03 (players)) TRUE)
(< (ai_nonswarm_count factory1_flood) 3)
)
)
(if (= (volume_test_objects vol_factory_1_mid_03 (players)) FALSE)
(ai_place factory_1_flood_end 1)
(sleep 60)
)
(or
(= (volume_test_objects vol_factory_1_mid_03 (players)) TRUE)
(>= (ai_spawn_count factory_1_flood_end) 10)
)
)
)
)
(script dormant factory_1_sentinel_respawn_01
(sleep_until
(begin
(sleep_until
(OR
(= (volume_test_objects vol_factory_1_mid_01 (players)) TRUE)
(< (ai_living_count factory1_sentinels) 2)
)
)
(if (= (volume_test_objects vol_factory_1_mid_01 (players)) FALSE)
(ai_place factory_1_sentinels_01_low 1)
(sleep 120)
)
(if (= (volume_test_objects vol_factory_1_mid_01 (players)) FALSE)
(ai_place factory_1_sentinels_01_high 1)
(sleep 120)
)
(or
(= (volume_test_objects vol_factory_1_mid_01 (players)) TRUE)
(>= (+
(ai_spawn_count factory_1_sentinels_01_low)
(ai_spawn_count factory_1_sentinels_01_high)
)
3)
)
)
)
)
(script dormant factory_1_sentinel_respawn_02
(sleep_until
(begin
(sleep_until
(OR
(= (volume_test_objects vol_factory_1_mid_02 (players)) TRUE)
(< (ai_living_count factory1_sentinels) 2)
)
)
(if (= (volume_test_objects vol_factory_1_mid_02 (players)) FALSE)
(ai_place factory_1_sentinels_02_low 1)
(sleep 120)
)
(if (= (volume_test_objects vol_factory_1_mid_02 (players)) FALSE)
(ai_place factory_1_sentinels_02_high 1)
(sleep 120)
)
(or
(= (volume_test_objects vol_factory_1_mid_02 (players)) TRUE)
(>= (+
(ai_spawn_count factory_1_sentinels_02_low)
(ai_spawn_count factory_1_sentinels_02_high)
)
6)
)
)
)
)
(script dormant factory_1_sentinel_enders
(sleep_until
(begin
(sleep_until
(OR
(= (volume_test_objects vol_factory_1_mid_03 (players)) TRUE)
(< (ai_living_count factory1_sentinels) 2)
)
)
(if (= (volume_test_objects vol_factory_1_mid_03 (players)) FALSE)
(ai_place factory_1_sentinels_03_low 1)
(sleep 120)
)
(if (= (volume_test_objects vol_factory_1_mid_03 (players)) FALSE)
(ai_place factory_1_sentinels_03_high 1)
(sleep 120)
)
(or
(= (volume_test_objects vol_factory_1_mid_03 (players)) TRUE)
(>= (+
(ai_spawn_count factory_1_sentinels_03_low)
(ai_spawn_count factory_1_sentinels_03_high)
)
6)
)
)
)
)
(script dormant factory_1_flood_surge
(sleep_until (= (ai_living_count factory_1_major) 0))
(sleep_forever factory_1_flood_respawn)
(ai_set_orders factory1_flood factory_1_flood_tubes_fwd)
(sleep_until
(begin
(sleep_until
(OR
(= (volume_test_objects vol_factory_1_mid_03 (players)) TRUE)
(< (ai_nonswarm_count factory1_flood) 3)
)
)
(if (= (volume_test_objects vol_factory_1_mid_03 (players)) FALSE)
(ai_place factory_1_flood_end 1)
(sleep 120)
)
(if (= (volume_test_objects vol_factory_1_mid_03 (players)) FALSE)
(ai_place factory_1_flood_tubes_far 1)
(sleep 120)
)
(if (= (volume_test_objects vol_factory_1_mid_03 (players)) FALSE)
(ai_place factory_1_flood_tubes_near 1)
(sleep 120)
)
(if (= (volume_test_objects vol_factory_1_mid_03 (players)) FALSE)
(ai_place factory_1_flood_alcove 1)
(sleep 120)
)
(or
(= (volume_test_objects vol_factory_1_mid_03 (players)) TRUE)
(>= (+
(ai_spawn_count factory_1_flood_end)
(ai_spawn_count factory_1_flood_tubes_far)
(ai_spawn_count factory_1_flood_tubes_near)
(ai_spawn_count factory_1_flood_alcove)
)
10)
)
)
)
(sleep_until
(begin
(sleep_until
(OR
(= (volume_test_objects vol_factory_1_exit (players)) TRUE)
(< (ai_nonswarm_count factory1_flood) 2)
)
)
(if (= (volume_test_objects vol_factory_1_exit (players)) FALSE)
(ai_place factory_1_flood_end 1)
(sleep 120)
)
(or
(= (volume_test_objects vol_factory_1_exit (players)) TRUE)
(>= (ai_spawn_count factory_1_flood_end) 8)
)
)
)
)
Overall script for sentinel factory 1
(script dormant sent_factory_1_start
(sleep_until (= (volume_test_objects vol_factory_1_enter (players)) TRUE))
(game_save)
(ai_place factory_1_sentinels_intro)
(ai_place factory_1_flood_intro)
(ai_place factory_1_major)
(ai_place factory_1_sentinels_initial_mid)
(ai_place factory_1_flood_initial_mid)
(wake factory_1_flood_surge)
(wake factory_1_flood_respawn)
(wake factory_1_sentinel_respawn_01)
(wake factory_1_sentinel_enders)
(sleep_until
(OR
(= (volume_test_objects vol_factory_1_mid_01 (players)) TRUE)
(< (ai_nonswarm_count factory1_enemies) 8)
)
)
(game_save_no_timeout)
(ai_place factory_1_sentinels_initial_end)
(ai_place factory_1_flood_initial_end)
(sleep_until (= (volume_test_objects vol_factory_1_mid_01 (players)) TRUE))
(game_save)
(sleep_forever factory_1_sentinel_respawn_01)
(wake factory_1_sentinel_respawn_02)
(ai_renew covenant)
(sleep_until (= (volume_test_objects vol_factory_1_mid_02 (players)) TRUE))
(game_save)
(sleep_forever factory_1_sentinel_respawn_02)
(sleep_until (= (volume_test_objects vol_factory_1_mid_03 (players)) TRUE))
(game_save)
(sleep_forever factory_1_sentinel_enders)
(sleep_forever factory_1_flood_respawn)
(sleep_until (= (volume_test_objects vol_factory_1_exit (players)) TRUE))
(game_save)
(if (= (ai_living_count factory_1_major) 1)
(sleep_forever factory_1_flood_surge)
)
)
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
(global boolean g_gorge_sen_spawn 0)
(script dormant ai_sentinel_spawn
(sleep_until
(begin
(sleep_until (<= (ai_living_count gorge_sen) 0))
(sleep 150)
(ai_place gorge_sen)
g_gorge_sen_spawn)
)
)
(script dormant ai_gorge
( ai_place gorge_jugg_a )
( ai_place gorge_jugg_b )
(ai_place gorge_flood_ini)
(ai_place gorge_enf)
(wake ai_sentinel_spawn)
(sleep_until (volume_test_objects tv_gorge_mid (players)))
(game_save_no_timeout)
(ai_place gorge_flood_bk)
(sleep_until (volume_test_objects tv_gorge_bk_cave (players)))
(ai_place gorge_flood_bk_cave)
(set g_gorge_sen_spawn 1)
)
= = = = = FACTORY 2 SCRIPTS = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
(script dormant ai_factory2
(ai_place factory2_flood_ini)
(sleep_until (volume_test_objects tv_factory2_mid (players)))
(game_save_no_timeout)
(if (<= (ai_living_count factory2_flood) 4)
(begin
(ai_place factory2_flood_mid)
(ai_place factory2_flood_bk)
)
)
(sleep_until (volume_test_objects tv_factory2_bk (players)))
(game_save)
(ai_place factory2_flood_bk_tunnel)
(ai_place factory2_sen_bk_tunnel)
)
(script dormant ai_constructor_flock
(flock_start constructor_swarm)
(sleep 150)
(flock_stop constructor_swarm)
)
(global boolean g_ext_b_phantom 0)
(global vehicle v_ext_b_phantom none)
(cs_shoot true)
(cs_enable_pathfinding_failsafe true)
(ai_place qz_ext_b_cov_spec_ops)
( ai_place qz_ext_b_cov_ghosts )
(ai_place qz_ext_b_cov_spectre)
(object_cannot_die (ai_get_object qz_ext_b_cov_spec_ops/soc) true)
(sleep 1)
(vehicle_load_magic v_ext_b_phantom "phantom_p" (ai_actors qz_ext_b_cov_spec_ops))
(vehicle_load_magic v_ext_b_phantom "phantom_sc01" (ai_vehicle_get_from_starting_location qz_ext_b_cov_ghosts/a))
(vehicle_load_magic v_ext_b_phantom "phantom_sc02" (ai_vehicle_get_from_starting_location qz_ext_b_cov_ghosts/b))
(vehicle_load_magic v_ext_b_phantom "phantom_lc" (ai_vehicle_get_from_starting_location qz_ext_b_cov_spectre/spectre))
(sleep 1)
(cs_vehicle_boost true)
(cs_fly_by qz_ext_b_phantom/p0 5)
(cs_fly_by qz_ext_b_phantom/p1 5)
(cs_vehicle_boost false)
(ai_magically_see qz_ext_b_wraith_a qz_ext_b_cov_phantom)
(cs_fly_by qz_ext_b_phantom/p2 5)
(cs_fly_by qz_ext_b_phantom/p3 3)
(cs_fly_to qz_ext_b_phantom/p4)
(cs_face true qz_ext_b_phantom/p2)
( sleep 30 )
(cs_vehicle_speed .65)
(cs_fly_to_and_face qz_ext_b_phantom/drop qz_ext_b_phantom/p2)
(object_set_phantom_power v_ext_b_phantom 1)
(sleep 45)
(vehicle_unload v_ext_b_phantom "phantom_sc")
(vehicle_unload v_ext_b_phantom "phantom_lc")
(sleep 45)
(vehicle_unload v_ext_b_phantom "phantom_p_a01")
(sleep 30)
(vehicle_unload v_ext_b_phantom "phantom_p_a02")
(sleep 30)
(vehicle_unload v_ext_b_phantom "phantom_p_a03")
(sleep 45)
(object_set_phantom_power v_ext_b_phantom 0)
(ai_vehicle_enter qz_ext_b_cov_spec_ops (ai_vehicle_get_from_starting_location qz_ext_b_cov_spectre/spectre))
(cs_face false qz_ext_b_phantom/p2)
(cs_vehicle_speed 1)
(sleep 60)
(wake sc_ext_b)
(cs_fly_by qz_ext_b_phantom/p2 3)
(cs_fly_by qz_ext_b_phantom/p1 3)
(cs_fly_by qz_ext_b_phantom/p0 3)
(ai_erase ai_current_squad)
)
(global boolean g_ext_b_ent_phantom 0)
(cs_enable_pathfinding_failsafe 1)
(cs_vehicle_boost true)
(cs_fly_by qz_ext_b_ent_phantom/p0 5)
(cs_fly_by qz_ext_b_ent_phantom/p1 5)
(cs_fly_by qz_ext_b_ent_phantom/p2 5)
(cs_vehicle_boost false)
(cs_fly_to qz_ext_b_ent_phantom/p3)
(cs_face true qz_ext_b_ent_phantom/p5)
( sleep 30 )
(cs_vehicle_speed .65)
(cs_fly_to qz_ext_b_ent_phantom/drop)
(sleep_until g_ext_b_ent_phantom)
(cs_face false qz_ext_b_ent_phantom/p5)
(cs_vehicle_speed 1)
(cs_fly_by qz_ext_b_ent_phantom/p5 3)
(cs_vehicle_boost true)
(cs_fly_by qz_ext_b_ent_phantom/p6 3)
(ai_erase ai_current_squad)
)
(script dormant ai_ext_b_exit_tube_a
(sleep_until (volume_test_objects tv_ext_b_exit_tube_a (players)))
(ai_place qz_ext_b_ent_flood_tube_a (pin (- 8 (ai_nonswarm_count ext_b_flood)) 0 6))
)
(script dormant ai_ext_b_exit_tube_b
(sleep_until (volume_test_objects tv_ext_b_exit_tube_b (players)))
(ai_place qz_ext_b_ent_flood_tube_b (pin (- 8 (ai_nonswarm_count ext_b_flood)) 0 6))
)
(global boolean g_ext_b_enforcer 0)
(script dormant ai_ext_b_enf_spawn
(sleep_until
(begin
(sleep_until (<= (ai_living_count ext_b_sentinels_b) 0))
(cond
((volume_test_objects tv_ext_b_mid (players)) (ai_place qz_ext_b_enf_b))
(true (ai_place qz_ext_b_enf_a))
)
(>= (ai_spawn_count ext_b_sentinels_b) 4)
g_ext_b_enforcer
)
)
)
)
(global boolean g_ext_b_bk_ghost_spawn 0)
(global short g_ext_b_bk_ghost_limit 0)
(global short g_ext_b_bk_ghost_number 0)
(script dormant ai_ext_b_bk_ghost_spawn
(cond
((difficulty_normal) (begin (set g_ext_b_bk_ghost_limit 6) (set g_ext_b_bk_ghost_number 1)))
((difficulty_heroic) (begin (set g_ext_b_bk_ghost_limit 8) (set g_ext_b_bk_ghost_number 2)))
((difficulty_legendary) (begin (set g_ext_b_bk_ghost_limit 10) (set g_ext_b_bk_ghost_number 3)))
)
(sleep_until
(begin
(sleep_until (<= (ai_living_count qz_ext_b_ent_ghost_bk) 0))
(sleep 90)
(if debug (print "placing ghosts"))
(ai_place qz_ext_b_ent_ghost_bk g_ext_b_bk_ghost_number)
(>= (ai_spawn_count qz_ext_b_ent_ghost_bk) g_ext_b_bk_ghost_limit)
g_ext_b_bk_ghost_spawn)
)
)
)
|Also , scripts which drive Tartarus 's dropship , and the human key .
(global boolean g_key_started false)
(global boolean g_key_lock0_entered false)
(global boolean g_key_lock0_first_loadpoint false)
(global boolean g_key_lock0_second_loadpoint false)
(global boolean g_key_lock0_begin_human false)
(global boolean g_key_lock0_door1 false)
(global boolean g_key_cruise_entered false)
(global boolean g_key_cruise_first_loadpoint false)
(global boolean g_key_cruise_halfway false)
(global boolean g_key_shaft_entered false)
(global boolean g_key_shaft_rising false)
(global boolean g_key_shaft_near_exterior false)
(global boolean g_key_lock1_entered false)
(global boolean g_key_lock1_first_arch false)
(global boolean g_key_lock1_second_arch false)
(global boolean g_key_library_entered false)
(global boolean g_key_library_arrival false)
(script dormant key_ride_door3_main
(print "key_ride_door3 begins to open")
(device_set_position key_ride_door3 1.0)
(sleep_until (>= (device_get_position key_ride_door3) 0.9) 10)
(sleep 60)
(print "key_ride_door3 begins to close")
(device_set_position key_ride_door3 0.0)
)
(script dormant key_ride_human_door2_main
(print "human_key_door2 begins to open")
(device_set_position human_key_door2 1.0)
(sleep_until (>= (device_get_position human_key_door2) 0.9) 10)
(print "human_key_door2 begins to close")
(device_set_position human_key_door2 0.0)
)
(script dormant key_ride_door2_main
(print "key_ride_door2 begins to open")
(device_set_position key_ride_door2 1.0)
(sleep_until (>= (device_get_position key_ride_door2) 0.9) 10)
(print "key_ride_door2 begins to close")
(device_set_position key_ride_door2 0.0)
)
(script dormant key_ride_door1_main
(print "key_ride_door1 begins to open")
(device_set_position key_ride_door1 1.0)
(sleep_until (>= (device_get_position key_ride_door1) 0.9) 10)
(sleep 60)
(print "key_ride_door1 begins to close")
(device_set_position key_ride_door1 0.0)
)
(script dormant key_ride_door0_main
(print "key_ride_door0 begins to open")
(device_set_position_immediate key_ride_door0 0.32)
(device_closes_automatically_set key_ride_door0 false)
(device_set_position key_ride_door0 1.0)
(sleep_forever)
(sleep_until (>= (device_get_position key_ride_door0) 0.9) 10)
(sleep 540)
(print "key_ride_door0 begins to close")
(device_set_position key_ride_door0 0.0)
)
(script dormant key_main
For
(wake key_ride_door0_main)
(pvs_set_object key)
(sound_looping_start "sound\ambience\device_machines\shq__key\shq__key" none 1.0)
(device_set_position_track key track_horiz0 0)
(device_animate_position key 0.3 0.0 0 0 false)
(sleep 5)
(object_teleport (player0) key_ent0)
(object_teleport (player1) key_ent1)
(sleep 5)
Begin the first leg , to the interior cruise
(device_animate_position key 0.6 75 0 0 false)
(set g_key_started true)
(sleep_until
(>= (device_get_position key) 0.35)
3
)
Begin opening the first door
(wake key_ride_door0_main)
Sleep until the key is entering the first lock
(sleep_until
(>= (device_get_position key) 0.4)
3
)
(set g_key_lock0_first_loadpoint true)
Flag that we 're entering the first lock
(set g_key_lock0_entered true)
Sleep until the key is passing the first loading point
(sleep_until
(>= (device_get_position key) 0.43)
3
)
(set g_key_lock0_first_loadpoint true)
(sleep_until
(>= (device_get_position key) 0.48)
3
)
(switch_bsp_by_name sen_hq_bsp_6)
(sleep_until
(>= (device_get_position key) 0.50)
3
)
(set g_key_lock0_second_loadpoint true)
(sleep_until
(>= (device_get_position key) 0.50)
3
)
(set g_key_lock0_begin_human true)
(sleep_until
(>= (device_get_position key) 0.53)
3
)
(set g_key_lock0_door1 true)
(wake key_ride_door1_main)
(sleep_until
(>= (device_get_position key) 0.58)
3
)
(set g_key_cruise_entered true)
Accelerate
(device_animate_position key 1.0 45 5 10 true)
Sleep until the key is near the first loadpoint , then the second
(sleep_until
(>= (device_get_position key) 0.67)
3
)
(set g_key_cruise_first_loadpoint true)
(sleep_until
(>= (device_get_position key) 0.84)
3
)
(set g_key_cruise_halfway true)
(sleep_until
(>= (device_get_position key) 1.0)
3
)
(set g_key_shaft_entered true)
(sleep 30)
(device_set_position_track key track_rise 0)
(device_set_overlay_track key overlay_transform)
(sound_looping_set_alternate "sound\ambience\device_machines\shq__key\shq__key" true)
(device_animate_overlay key 1.0 5 0 0)
(sleep 180)
(device_animate_position key 1.0 90 20 10 false)
(set g_key_shaft_rising true)
(set g_music_06b_06 1)
(sleep_until
(>= (device_get_position key) 0.3)
3
)
(set g_key_shaft_near_exterior true)
Sleep until the key is in position to begin opening the third door
(sleep_until
(>= (device_get_position key) 0.73)
3
)
(wake key_ride_door2_main)
(sleep_until
(>= (device_get_position key) 1.0)
3
)
(set g_key_lock1_entered true)
(sound_looping_stop "sound\ambience\device_machines\shq__key\shq__key")
(sleep 30)
(device_set_position_track key track_horiz1 0)
(sound_looping_start "sound\ambience\device_machines\shq__key\shq__key" none 1.0)
(device_animate_overlay key 0.0 5 0 0)
(sleep 180)
(device_animate_position key 1.0 75 10 10 false)
Sleep until the key is near the first arch
(sleep_until
(>= (device_get_position key) 0.15)
3
)
(set g_key_lock1_first_arch true)
Sleep until the key is near the second arch
(sleep_until
(>= (device_get_position key) 0.4)
3
)
(set g_key_lock1_second_arch true)
(sleep_until
(>= (device_get_position key) 0.49)
3
)
(wake key_ride_door3_main)
(sleep_until
(>= (device_get_position key) 0.65)
3
)
(set g_key_library_entered true)
(sleep_until
(>= (device_get_position key) 0.85)
3
)
(device_animate_overlay key 1.0 5 0 0)
(sleep_until
(>= (device_get_position key) 1.0)
3
)
(set g_key_library_arrival true)
(wake chapter_familiar)
(wake sc_dock)
(set g_music_06b_05 0)
(sound_looping_stop "sound\ambience\device_machines\shq__key\shq__key")
)
(script dormant key_ride_human_key_main
(sleep_until g_key_lock0_begin_human 10)
(object_create_anew key_human)
(pvs_set_object key_human)
(device_set_position_track key_human track_horiz0 0)
(device_animate_position key_human 0.58 0.5 0 0 false)
(sleep 15)
(device_animate_position key_human 1.0 55 5 10 false)
(sleep_until
(>= (device_get_position key_human) 1.0)
3
)
(sleep 30)
(device_set_position_track key_human track_rise 0)
(device_set_overlay_track key_human overlay_transform)
(device_animate_overlay key_human 1.0 5 0 0)
(sleep 180)
(device_animate_position key_human 1.0 80 20 10 false)
(sleep_until
(>= (device_get_position key_human) 0.71)
3
)
(wake key_ride_human_door2_main)
(sleep_until
(>= (device_get_position key_human) 1.0)
3
)
(sleep 120)
(device_set_position_track key_human track_horiz1 0)
(device_animate_overlay key_human 0.0 5 0 0)
(sleep 180)
(device_animate_position key_human 1.0 75 10 10 false)
(sleep_until
(>= (device_get_position key_human) 0.191)
3
)
(object_destroy key_human)
(object_create_anew key_docked)
(sleep 1)
(device_set_overlay_track key_docked overlay_transform)
(device_animate_overlay key_docked 1.0 0.1 0 0)
)
(script command_script cs_e21_tartarus
(cs_enable_pathfinding_failsafe true)
(print "e21 *tartarus returns from harassing human key*")
(cs_vehicle_boost true)
(cs_fly_by e21_tartarus/p0)
(cs_vehicle_boost false)
(print "e21 *tartarus follows the key in through the door*")
(cs_fly_by e21_tartarus/p1)
(cs_vehicle_speed 0.75)
(cs_enable_pathfinding_failsafe false)
(sleep_until
(begin
(cs_fly_by key_bsp5/left)
false
)
3
300
)
(cs_vehicle_speed 0.85)
(cs_face true e22_tartarus_bsp6/forward_facing)
(sleep_until
(begin
(cs_fly_by key_bsp5/center)
false
)
3
300
)
)
(script command_script cs_e22_tartarus
(cs_face false e22_tartarus_bsp6/forward_facing)
(cs_fly_by e22_tartarus/p0)
(cs_fly_by e22_tartarus/p1)
(cs_vehicle_boost true)
(cs_fly_by e22_tartarus/p2)
(cs_vehicle_boost false)
(cs_fly_to e22_tartarus/p3 1.0)
(sleep 50)
(cs_face true e22_tartarus_bsp6/forward_facing)
(cs_vehicle_speed 0.9)
(cs_fly_by key_bsp6/center_front)
(cs_vehicle_speed 0.9)
(sleep_until
(begin
(cs_fly_by key_bsp6/center_front 1.0)
false
)
3
)
)
(script command_script cs_e23_tartarus
(cs_vehicle_speed 1.0)
(cs_vehicle_boost true)
(cs_fly_by e23_tartarus/p0)
(cs_fly_by e23_tartarus/p1)
(cs_vehicle_boost false)
(cs_fly_by e23_tartarus/p2)
(cs_vehicle_speed 1.0)
(sleep_until
(begin
(cs_fly_by key_human_bsp6/left_high 1.0)
false
)
3
360
)
(cs_teleport e23_tartarus/teleport_dest e23_tartarus/teleport_facing)
(sleep_forever)
)
(script command_script cs_e24_tartarus
(sleep 200)
(cs_vehicle_speed 0.6)
(cs_fly_by e24_tartarus/p0)
(cs_vehicle_speed 1.0)
(cs_fly_by e24_tartarus/p1)
(cs_fly_by e24_tartarus/p2)
(sleep_forever)
)
(script command_script cs_e25_tartarus
(sleep 120)
(cs_face true e25_tartarus/p0)
(sleep 60)
(cs_face false e25_tartarus/p0)
(cs_vehicle_speed 0.6)
(cs_fly_by e25_tartarus/p0)
(cs_vehicle_speed 1.0)
(cs_fly_to e25_tartarus/p1 1.0)
(cs_face true e25_tartarus/p1_facing)
(sleep 320)
(cs_face false e25_tartarus/p1_facing)
Fall in behind the key
(cs_vehicle_speed 1.0)
( cs_fly_by e25_tartarus / p2 1.0 )
(cs_fly_by key_bsp6/center 1.0)
(cs_vehicle_speed 0.9)
(sleep_until
(begin
(cs_fly_by key_bsp6/center 1.0)
false
)
3
)
)
(script command_script cs_e26_tartarus
Fall in behind the key
(cs_vehicle_speed 0.9)
(sleep_until
(begin
(cs_fly_by key_bsp6/center 1.0)
false
)
3
210
)
(cs_fly_to e26_tartarus/p0)
(sleep 120)
(cs_fly_by e26_tartarus/p1)
(cs_fly_by e26_tartarus/p2)
(ai_erase ai_current_squad)
)
(script dormant key_ride_tartarus_main
(ai_place key_ride_tartarus)
(cs_run_command_script key_ride_tartarus/tartarus cs_e21_tartarus)
(sleep_until (= (structure_bsp_index) 4) 10)
(cs_run_command_script key_ride_tartarus/tartarus cs_e22_tartarus)
(sleep_until g_key_cruise_entered 10)
(cs_run_command_script key_ride_tartarus/tartarus cs_e23_tartarus)
(sleep_until g_key_shaft_near_exterior 10)
(cs_run_command_script key_ride_tartarus/tartarus cs_e24_tartarus)
(sleep_until g_key_lock1_entered 10)
(cs_run_command_script key_ride_tartarus/tartarus cs_e25_tartarus)
(sleep_until g_key_library_entered 10)
(cs_run_command_script key_ride_tartarus/tartarus cs_e26_tartarus)
)
(script static void key_ride_test
(wake key_main)
(wake key_ride_human_key_main)
(wake key_ride_tartarus_main)
)
= ENCOUNTER 26 = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
|The Library . MWA - HAH - HAH - HAAAAaaaaa ....
Encounter has been activated ?
(global boolean g_e26_ended false)
(script command_script cs_e26_fld_infections_entry3
(cs_abort_on_damage true)
(sleep 30)
(cs_go_to e26_fld_infection_forms0/p2)
(cs_go_to e26_fld_infection_forms0/p3)
(cs_go_to e26_fld_infection_forms0/p4)
(cs_go_to e26_fld_infection_forms0/p5)
(ai_erase ai_current_actor)
)
(script command_script cs_e26_fld_infections_entry2
(cs_abort_on_damage true)
(sleep 30)
(cs_go_to e26_fld_infection_forms0/p6)
(cs_go_to e26_fld_infection_forms0/p7)
(cs_go_to e26_fld_infection_forms0/p2)
(cs_go_to e26_fld_infection_forms0/p3)
(cs_go_to e26_fld_infection_forms0/p4)
(cs_go_to e26_fld_infection_forms0/p5)
(ai_erase ai_current_actor)
)
(script command_script cs_e26_fld_infections_entry1
(cs_abort_on_damage true)
(sleep 30)
(cs_go_to e26_fld_infection_forms0/p8)
(cs_go_to e26_fld_infection_forms0/p7)
(cs_go_to e26_fld_infection_forms0/p2)
(cs_go_to e26_fld_infection_forms0/p3)
(cs_go_to e26_fld_infection_forms0/p4)
(cs_go_to e26_fld_infection_forms0/p5)
(ai_erase ai_current_actor)
)
(script command_script cs_e26_fld_infections_entry0
(cs_abort_on_damage true)
(sleep 30)
(cs_go_to e26_fld_infection_forms0/p0)
(cs_go_to e26_fld_infection_forms0/p1)
(cs_go_to e26_fld_infection_forms0/p2)
(cs_go_to e26_fld_infection_forms0/p3)
(cs_go_to e26_fld_infection_forms0/p4)
(cs_go_to e26_fld_infection_forms0/p5)
(ai_erase ai_current_actor)
)
(script dormant e26_smg1
(object_create e26_smg1)
(sleep_until
(begin
(weapon_hold_trigger e26_smg1 0 true)
(sleep_until g_e26_ended 2 (random_range 15 45))
(weapon_hold_trigger e26_smg1 0 false)
(sleep_until g_e26_ended 2 (random_range 45 90))
g_e26_ended
)
1
)
(weapon_hold_trigger e26_smg1 0 false)
(object_destroy e26_smg1)
)
(script dormant e26_smg0
(object_create e26_smg0)
(sleep_until
(begin
(weapon_hold_trigger e26_smg0 0 true)
(sleep_until g_e26_ended 2 (random_range 15 45))
(weapon_hold_trigger e26_smg0 0 false)
(sleep_until g_e26_ended 2 (random_range 45 90))
g_e26_ended
)
1
)
(weapon_hold_trigger e26_smg0 0 false)
(object_destroy e26_smg0)
)
(script dormant e26_fld_infections_main
(ai_place e26_fld_infection_forms0/swarm0)
(sleep_until (< (objects_distance_to_flag (players) e26_fld_infs0_1) 10) 10 300)
(ai_place e26_fld_infection_forms0/swarm1)
(sleep_until (< (objects_distance_to_flag (players) e26_fld_infs0_2) 10) 10 300)
(ai_place e26_fld_infection_forms0/swarm2)
(sleep_until (< (objects_distance_to_flag (players) e26_fld_infs0_3) 10) 10 300)
(ai_place e26_fld_infection_forms0/swarm3)
)
(script dormant e26_main
(sleep_until (volume_test_objects tv_e26_main_begin (players)) 10)
(data_mine_set_mission_segment enc_e26)
(set g_e26_started true)
(print "e26_main")
(game_save)
(wake e26_fld_infections_main)
(wake e26_smg0)
(wake e26_smg1)
Encounter end condition
(sleep_until
(or
(volume_test_objects tv_mission_end0 (players))
(volume_test_objects tv_mission_end1 (players))
)
10
)
(set g_e26_ended 1)
)
= ENCOUNTER 25 = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
|Flood combat in the second interior lock .
|Elites
Encounter has been activated ?
(script command_script cs_e25_scene3
(cs_switch "elite1")
(cs_start_to e25_scenes/p1)
(cs_switch "elite0")
(cs_start_to e25_scenes/p0)
(sleep_until
(or
(not (cs_moving))
(and
(> (objects_distance_to_object (players) (ai_get_object ai_current_actor)) 0)
(< (objects_distance_to_object (players) (ai_get_object ai_current_actor)) 4)
)
)
)
(cs_face_player true)
(sleep_until
(and
(> (objects_distance_to_object (players) (ai_get_object ai_current_actor)) 0)
(< (objects_distance_to_object (players) (ai_get_object ai_current_actor)) 4)
)
)
(print "elite0: we'll guard the key")
(sleep (ai_play_line_at_player ai_current_actor 0910))
(sleep 20)
(cs_switch "elite1")
(sleep_until
(or
(not (cs_moving))
(and
(> (objects_distance_to_object (players) (ai_get_object ai_current_actor)) 0)
(< (objects_distance_to_object (players) (ai_get_object ai_current_actor)) 4)
)
)
)
(cs_face_player true)
(sleep_until
(and
(> (objects_distance_to_object (players) (ai_get_object ai_current_actor)) 0)
(< (objects_distance_to_object (players) (ai_get_object ai_current_actor)) 4)
)
)
(print "elite1: git to werk")
(sleep (ai_play_line_at_player ai_current_actor 0920))
)
(script command_script cs_e25_scene1
(cs_start_to e25_scenes/p0)
(sleep_until
(or
(not (cs_moving))
(and
(> (objects_distance_to_object (players) (ai_get_object ai_current_actor)) 0)
(< (objects_distance_to_object (players) (ai_get_object ai_current_actor)) 4)
)
)
)
(cs_face_player true)
(sleep_until
(and
(> (objects_distance_to_object (players) (ai_get_object ai_current_actor)) 0)
(< (objects_distance_to_object (players) (ai_get_object ai_current_actor)) 4)
)
)
(print "elite0: we'll guard the key")
(sleep (ai_play_line_at_player ai_current_actor 0910))
(sleep 15)
(print "elite0: get the icon")
(sleep (ai_play_line_at_player ai_current_actor 0920))
)
(script command_script cs_e25_scene0
haaa hahahaha , 5 million people just shat their pants
(sleep (ai_play_line ai_current_actor 0890))
)
(script dormant e25_dialogue
(sleep_until
(ai_scene e25_scene0 cs_e25_scene0 e21_cov_inf0)
5
300
)
(sleep 120)
(ai_play_line_on_object none 0900)
(sleep_until g_key_library_arrival 10)
(if (>= (ai_living_count e21_cov_inf0) 2)
(begin
(sleep_until
(ai_scene e25_scene3 cs_e25_scene3 e21_cov_inf0)
5
)
)
(begin
(sleep_until
(ai_scene e25_scene1 cs_e25_scene1 e21_cov_inf0)
5
)
)
)
)
(script dormant e25_fld_inf1_main
Wait until the key is near the second arch
(sleep_until g_key_lock1_second_arch 10)
(ai_place e25_fld_inf1_0)
Second volley
(sleep 60)
(ai_place e25_fld_inf1_1)
(sleep 60)
(ai_place e25_fld_inf1_2)
)
(script dormant e25_fld_inf0_main
Wait until the key is near the first arch
(sleep_until g_key_lock1_first_arch 10)
(ai_place e25_fld_inf0_0)
Second volley
(sleep 60)
(ai_place e25_fld_inf0_1)
(sleep 60)
(ai_place e25_fld_inf0_2)
)
(script dormant e25_main
(data_mine_set_mission_segment enc_e25)
(sleep_until g_key_lock1_entered 10)
(set g_e25_started true)
(print "e25_main")
(game_save)
(wake e26_main)
(wake e25_dialogue)
(sleep_until g_e26_started)
(sleep_forever e25_fld_inf0_main)
(sleep_forever e25_fld_inf1_main)
)
= ENCOUNTER 24 = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
|Elites
| ( engage ) - Free roam if the dies
Encounter has been activated ?
(script command_script cs_e24_fld_inf1_load
(cs_enable_moving true)
(cs_enable_targeting true)
(cs_face_object true key)
(sleep 210)
(object_cannot_take_damage (ai_get_object ai_current_actor))
(cs_face_object false key)
(cs_ignore_obstacles true)
(cs_enable_pathfinding_failsafe true)
(if (= (random_range 0 2) 0)
(begin
(cs_go_to e24_fld_inf1_load/p0_0)
(cs_go_to e24_fld_inf1_load/p0_1)
)
(begin
(cs_go_to e24_fld_inf1_load/p1_0)
(cs_go_to e24_fld_inf1_load/p1_1)
)
)
(cs_jump_to_point 3 1)
(ai_migrate ai_current_actor e21_fld_inf0_0)
(sleep 150)
(object_can_take_damage (ai_get_object ai_current_actor))
)
(script dormant e24_fld_inf2_main
(sleep_until g_key_shaft_entered 10)
)
(script dormant e24_fld_inf1_main
(sleep_until g_key_shaft_rising 10)
(ai_place e24_fld_inf1_1)
)
(script dormant e24_fld_inf0_main
(sleep_until g_key_shaft_entered 10)
)
(script dormant e24_main
(sleep_until g_key_shaft_entered 10)
(data_mine_set_mission_segment enc_e24)
(set g_e24_started true)
(print "e24_main")
(game_save)
(wake e25_main)
(sleep_until g_e25_started)
(sleep_forever e24_fld_inf0_main)
(sleep_forever e24_fld_inf1_main)
(sleep_forever e24_fld_inf2_main)
)
= ENCOUNTER 23 = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
|Elites
| e23_fld_inf0 - Flood at the second boarding point
Encounter has been activated ?
(script command_script cs_e23_fld_inf0_0_load
(cs_enable_pathfinding_failsafe true)
(cs_ignore_obstacles true)
(cs_go_to e23_fld_inf0_load/p0_0)
(cs_go_to e23_fld_inf0_load/p0_1)
(cs_jump 15.0 3.0)
)
(script command_script cs_e23_fld_inf0_1_load
(cs_enable_pathfinding_failsafe true)
(cs_ignore_obstacles true)
(cs_go_to e23_fld_inf0_load/p1_0)
(cs_go_to e23_fld_inf0_load/p1_1)
(cs_jump 15.0 3.0)
)
(script command_script cs_e23_scene0
(cs_abort_on_combat_status ai_combat_status_visible)
(cs_switch "elite0")
(print "dog: the fool...")
(sleep (ai_play_line ai_current_actor 0810))
(sleep 15)
(cs_switch "elite1")
(print "scl: on the bright side...")
(sleep (ai_play_line ai_current_actor 0820))
)
(script dormant e23_dialogue
(sleep 90)
(print "Tartarus: Humans! I'll deal with them!")
(sleep (ai_play_line_on_object none 0800))
(sleep 30)
(sleep_until
(ai_scene e23_scene0 cs_e23_scene0 e21_cov_inf0)
10
90
)
)
(script dormant e23_fld_inf0_main
(sleep_until g_key_cruise_first_loadpoint 10)
(ai_place e23_fld_inf0)
(sleep_until g_key_cruise_halfway 10)
(sleep 90)
(ai_set_orders e23_fld_inf0_0 e23_fld_inf0_engage)
(ai_set_orders e23_fld_inf0_1 e23_fld_inf0_engage)
(cs_run_command_script e23_fld_inf0_0 cs_e23_fld_inf0_0_load)
(cs_run_command_script e23_fld_inf0_1 cs_e23_fld_inf0_1_load)
)
(script dormant e23_main
(data_mine_set_mission_segment enc_e23)
(sleep_until g_key_cruise_entered 10)
(set g_e23_started true)
(print "e23_main")
(game_save)
(wake e24_main)
(wake e23_dialogue)
(sleep_until g_e24_started)
(sleep_forever e23_fld_inf0_main)
)
(script static void test_key_ride2
(device_set_position_immediate key 0.26)
(sleep 1)
(object_teleport (player0) e23_test)
(object_set_velocity (player0) 1 0 0)
(wake key_main)
(wake e23_main)
(sleep 3)
(device_set_position_immediate key 0.26)
(device_set_position key 1.0)
)
= ENCOUNTER 22 = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
|Flood combat in the first interior lock .
|Elites
| e22_fld_inf0 - Flood which boards from the second loading ramp
Encounter has been activated ?
(script command_script cs_e22_hack_divide
(if (< (ai_living_count e22_cov_inf1_0) 2)
(ai_migrate ai_current_actor e22_cov_inf1_0)
(ai_migrate ai_current_actor e22_cov_inf1_1)
)
)
(script command_script cs_e22_fld_inf0_0_load
(cs_enable_moving true)
(cs_enable_targeting true)
(cs_face_object true key)
(sleep_until g_key_lock0_second_loadpoint 1)
(sleep 95)
(cs_face_object false key)
(unit_impervious ai_current_actor true)
(cs_ignore_obstacles true)
(cs_enable_pathfinding_failsafe true)
(if (= (random_range 0 2) 0)
(begin
(cs_go_to e22_fld_inf0_load/p0_0)
(cs_go_to e22_fld_inf0_load/p0_1)
)
(begin
(cs_go_to e22_fld_inf0_load/p1_0)
(cs_go_to e22_fld_inf0_load/p1_1)
)
)
(cs_move_in_direction 0 1 0)
(unit_impervious ai_current_actor false)
(ai_migrate ai_current_actor e21_fld_inf0_0)
)
(script command_script cs_e22_scene0
(cs_abort_on_combat_status ai_combat_status_visible)
(cs_switch "elite0")
(print "scl: what courage...")
(sleep (ai_play_line ai_current_actor 0780))
(sleep 15)
(cs_switch "elite1")
(print "dog: ignore him...")
(sleep (ai_play_line ai_current_actor 0790))
)
(script dormant e22_dialogue
(sleep_until (= (structure_bsp_index) 4))
(sleep 90)
(print "Tartarus: I will thin their ranks")
(sleep (ai_play_line_on_object none 0770))
(sleep 30)
(sleep_until
(ai_scene e22_scene0 cs_e22_scene0 e21_cov_inf0)
10
90
)
)
(script dormant e22_fld_inf0_main
(sleep_until g_key_lock0_first_loadpoint 10)
(ai_place e22_fld_inf0)
)
(script dormant e22_main
(sleep_until g_key_lock0_entered 10)
(data_mine_set_mission_segment enc_e22)
(set g_e22_started true)
(print "e22_main")
(game_save)
(wake e23_main)
(wake e22_fld_inf0_main)
(wake e22_dialogue)
(sleep_until g_e23_started)
(sleep_forever e22_fld_inf0_main)
)
= ENCOUNTER 21 = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
|Elites
| ( ) - Guarding the left side
| ( advance_right ) - Ditto , for the right
| ( ) - Hunting all over the key for the player
| ( ) - Hunting all over the key for the player
Encounter has been activated ?
(script command_script cs_e21_fld_inf1_low_entry
(cs_enable_pathfinding_failsafe true)
(cs_ignore_obstacles true)
(cs_move_in_direction 6 0 0)
(if (= (structure_bsp_index) 3)
(begin
(cs_go_to e21_fld_bsp5/p2)
(cs_abort_on_combat_status ai_combat_status_clear_los)
(cs_go_to e21_fld_bsp5/p1_0)
(cs_go_to e21_fld_bsp5/p1_1)
)
(begin
(cs_go_to e21_fld_bsp6/p2)
(cs_abort_on_combat_status ai_combat_status_clear_los)
(cs_go_to e21_fld_bsp6/p1_0)
(cs_go_to e21_fld_bsp6/p1_1)
)
)
)
(script command_script cs_e21_fld_inf1_high_entry
(cs_abort_on_combat_status ai_combat_status_clear_los)
(cs_enable_pathfinding_failsafe true)
(if (= (structure_bsp_index) 3)
(begin
(cs_go_to e21_fld_bsp5/p1_0)
(cs_go_to e21_fld_bsp5/p1_1)
)
(begin
(cs_go_to e21_fld_bsp6/p1_0)
(cs_go_to e21_fld_bsp6/p1_1)
)
)
)
(script command_script cs_e21_fld_inf0_low_entry
(cs_enable_pathfinding_failsafe true)
(cs_ignore_obstacles true)
(cs_move_in_direction 6 0 0)
(if (= (structure_bsp_index) 3)
(begin
(cs_go_to e21_fld_bsp5/p2)
(cs_abort_on_combat_status ai_combat_status_clear_los)
(cs_go_to e21_fld_bsp5/p0_0)
(cs_go_to e21_fld_bsp5/p0_1)
)
(begin
(cs_go_to e21_fld_bsp6/p2)
(cs_abort_on_combat_status ai_combat_status_clear_los)
(cs_go_to e21_fld_bsp6/p0_0)
(cs_go_to e21_fld_bsp6/p0_1)
)
)
)
(script command_script cs_e21_fld_inf0_high_entry
(cs_abort_on_combat_status ai_combat_status_clear_los)
(cs_enable_pathfinding_failsafe true)
(if (= (structure_bsp_index) 3)
(begin
(cs_go_to e21_fld_bsp5/p0_0)
(cs_go_to e21_fld_bsp5/p0_1)
)
(begin
(cs_go_to e21_fld_bsp6/p0_0)
(cs_go_to e21_fld_bsp6/p0_1)
)
)
)
(script command_script cs_e21_fld_inf0_0_load
(cs_enable_moving true)
(cs_enable_targeting true)
(sleep_until g_key_lock0_first_loadpoint 1)
(sleep 30)
(cs_shoot_point true key_bsp5/p0)
(sleep 148)
(cs_shoot_point false key_bsp5/p0)
(ai_set_orders ai_current_squad e21_fld_inf0_engage0)
(cs_ignore_obstacles true)
(cs_enable_pathfinding_failsafe true)
(cs_go_to e21_fld_load/left0)
(cs_go_to e21_fld_load/left1)
(cs_move_in_direction 0 1 0)
)
(script command_script cs_e21_scene0
(print "elite: I grow restless without a target")
(sleep (ai_play_line_at_player ai_current_actor 0730))
)
(script command_script cs_e21_scene1
(print "elite: Look, up ahead! The Parasite readies")
(ai_play_line_at_player ai_current_actor 0760)
(sleep 20)
(cs_go_to_nearest e21_scene1_points)
(cs_face true e21_fld_load/p0)
(cs_aim true e21_fld_load/p0)
(sleep_until g_key_lock0_first_loadpoint 5)
(cs_shoot_point true e21_fld_load/p0)
(sleep 90)
)
(script static boolean e21_in_bsp4
(= (structure_bsp_index) 4)
)
(script dormant e21_fld_carriers1_main
(ai_migrate e21_fld_carriers0 e21_fld_carriers1)
(sleep_until
(begin
Replenish the carrier forms
(if (< (ai_swarm_count e21_fld_carriers1) 2)
(ai_place e21_fld_carriers1 1)
)
g_key_lock1_second_arch
)
90
)
)
(script static void e21_fld_inf1_spawn
(if (volume_test_objects tv_key_near_lower_spawner (players))
(begin
(if (volume_test_objects tv_key_upper_left_side (players))
(begin
(ai_place e21_fld_inf1_2 1)
(ai_migrate e21_fld_inf1_2 e21_fld_inf1_0)
(sleep 5)
(ai_magically_see_object e21_fld_inf1_0 (player0))
(ai_magically_see_object e21_fld_inf1_0 (player1))
)
(begin
(ai_place e21_fld_inf0_2 1)
(cs_run_command_script e21_fld_inf0_2 cs_e21_fld_inf1_high_entry)
(ai_migrate e21_fld_inf0_2 e21_fld_inf1_0)
(sleep 5)
(ai_magically_see_object e21_fld_inf1_0 (player0))
(ai_magically_see_object e21_fld_inf1_0 (player1))
)
)
)
(begin
(ai_place e21_fld_inf1_1 1)
(ai_migrate e21_fld_inf1_1 e21_fld_inf1_0)
(sleep 5)
(ai_magically_see_object e21_fld_inf1_0 (player0))
(ai_magically_see_object e21_fld_inf1_0 (player1))
)
)
)
(script dormant e21_fld_inf1_main
(ai_migrate e21_fld_inf0 e21_fld_inf1_0)
(sleep_until
(begin
Replenish the combat forms
(if (< (ai_nonswarm_count e21_fld_inf1_0) 8)
(sleep_until
(begin
(e21_fld_inf1_spawn)
(or
(>= (ai_nonswarm_count e21_fld_inf1_0) 8)
g_key_lock1_second_arch
)
)
60
)
)
g_key_lock1_second_arch
)
900
)
)
(script dormant e21_fld_carriers0_main
(sleep_until (= (structure_bsp_index) 4))
(sleep_until
(begin
Replenish the carrier forms
(if (< (ai_nonswarm_count e21_fld_carriers0) 2)
(ai_place e21_fld_carriers0 1)
)
g_key_shaft_rising
)
90
)
Switch sides
(wake e21_fld_carriers1_main)
)
(script static void e21_fld_inf0_spawn
(if (volume_test_objects tv_key_near_lower_spawner (players))
(begin
(if (volume_test_objects tv_key_upper_left_side (players))
(begin
(ai_place e21_fld_inf1_2 1)
(cs_run_command_script e21_fld_inf1_2 cs_e21_fld_inf0_high_entry)
(ai_migrate e21_fld_inf1_2 e21_fld_inf0_0)
(sleep 5)
(ai_magically_see_object e21_fld_inf0_0 (player0))
(ai_magically_see_object e21_fld_inf0_0 (player1))
)
(begin
(ai_place e21_fld_inf0_2 1)
(ai_migrate e21_fld_inf0_2 e21_fld_inf0_0)
(sleep 5)
(ai_magically_see_object e21_fld_inf0_0 (player0))
(ai_magically_see_object e21_fld_inf0_0 (player1))
)
)
)
(begin
(ai_place e21_fld_inf0_1 1)
(ai_migrate e21_fld_inf0_1 e21_fld_inf0_0)
(sleep 5)
(ai_magically_see_object e21_fld_inf0_0 (player0))
(ai_magically_see_object e21_fld_inf0_0 (player1))
)
)
)
(script dormant e21_fld_inf0_main
(ai_place e21_fld_inf0_0)
(sleep_until (= (structure_bsp_index) 4))
(sleep_until
(begin
(e21_fld_inf0_spawn)
(or
(>= (ai_nonswarm_count e21_fld_inf0_0) 8)
g_key_shaft_rising
)
)
)
(sleep_until
(begin
Replenish the combat forms
(if (< (ai_nonswarm_count e21_fld_inf0_0) 8)
(sleep_until
(begin
(e21_fld_inf0_spawn)
(or
(>= (ai_nonswarm_count e21_fld_inf0_0) 8)
g_key_shaft_rising
)
)
60
)
)
g_key_shaft_rising
)
900
)
Switch sides
(wake e21_fld_inf1_main)
)
(script dormant e21_cov_inf0_main
(ai_place e21_cov_inf0)
(sleep 150)
(sleep_until
(ai_scene e21_scene0 cs_e21_scene0 e21_cov_inf0_1)
5
60
)
(sleep 300)
(sleep_until
(ai_scene e21_scene1 cs_e21_scene1 e21_cov_inf0_0)
5
60
)
(sleep_until g_key_lock0_first_loadpoint 5)
(game_save)
(ai_set_orders e21_cov_inf0_0 e21_cov_inf0_0_guard_left)
(ai_set_orders e21_cov_inf0_1 e21_cov_inf0_1_advance_left)
(sleep_until g_key_shaft_rising)
(ai_set_orders e21_cov_inf0_0 e21_cov_inf0_0_guard_right)
(ai_set_orders e21_cov_inf0_1 e21_cov_inf0_1_advance_right)
)
(script dormant e21_main
(sleep_until g_key_started 5)
(data_mine_set_mission_segment enc_e21)
(set g_e21_started true)
(print "e21_main")
(wake e22_main)
(wake e21_cov_inf0_main)
(wake e21_fld_inf0_main)
)
(script static void test_key_ride
(switch_bsp_by_name sen_hq_bsp_5)
(sleep 1)
(object_teleport (player0) key_ent0)
(object_set_velocity (player0) 5 0 0)
(object_teleport (player1) key_ent1)
(object_set_velocity (player1) 5 0 0)
(wake key_main)
(wake key_ride_human_key_main)
(wake key_ride_tartarus_main)
(wake e21_main)
)
|(script dormant cinematic_key_boarding
| ( sleep_until ( volume_test_objects tv_cutscene_key_boarding ( players ) ) 10 )
| ( object_teleport ( ) key_ride_a )
| ( object_set_velocity ( ) 10 0 0 )
| ( object_teleport ( player1 ) key_ride_b )
| ( object_set_velocity ( player1 ) 10 0 0 )
= ENCOUNTER 20 = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
|Elites
| e20_cov_inf0 - The sum of all prior squads , just dump them here
| ( init ) - Positions at the first intersection
| ( ) - Positions at the second intersection
|(script dormant e20_cov_inf0_main
| ( sleep 1 )
|(script dormant e20_main
| ( sleep_until ( volume_test_objects tv_cutscene_key_boarding ( players ) ) 10 )
| ( sleep 15 )
| ( sleep 1 )
| ( object_teleport ( ) e20_test )
| ( ai_place e20_cov_inf0 )
(script dormant begin_key_ride_main
MIGRATE SQUADS HERE
Add ( ai_migrate < your_squad > e20_cov_inf0 ) statements
(wake e21_main)
(wake key_main)
(wake key_ride_human_key_main)
(wake key_ride_tartarus_main)
)
(script dormant enc_cov_charge
(data_mine_set_mission_segment enc_cov_charge)
(print "initialize covenant charge scripts")
(game_save)
(object_dynamic_simulation_disable qz_cov_def_tower_pod_a true)
(object_dynamic_simulation_disable qz_cov_def_tower_pod_b true)
(ai_place qz_cov_def_phantom)
(ai_place qz_cov_def_spectre)
(ai_place qz_cov_def_ghosts)
(ai_place qz_cov_def_spec_ops)
(wake sc_cov_charge)
(sleep_until (or
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_cov_def_spectre/spectre) "spectre_d" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_cov_def_spectre/spectre) "spectre_p_l" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_cov_def_spectre/spectre) "spectre_p_r" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_cov_def_spectre/spectre) "spectre_g" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_cov_def_ghosts/a) "ghost_d" (players))
(vehicle_test_seat_list (ai_vehicle_get_from_starting_location qz_cov_def_ghosts/b) "ghost_d" (players))
) 10 (* 30 20))
(set g_qz_cov_def_progress 1)
(sleep 30)
(game_save_no_timeout)
(sleep 90)
(ai_place qz_cov_def_enforcer_a)
(ai_place qz_cov_def_sen_elim)
( if ( difficulty_legendary ) ( ai_place qz_cov_def_enforcer_b ) ( ai_set_orders qz_cov_def_enforcer_a qz_cov_def_mid ) )
(device_set_position qz_door_a 1)
(sleep (* 30 2))
(wake ext_a_vehicle_orders)
(sleep_until (<= (ai_living_count sentinels) 0))
(sleep 30)
(game_save)
(ai_renew covenant)
)
(script dormant enc_vehicle_int
(data_mine_set_mission_segment enc_vehicle_int)
(print "initialize vehicle interior scripts")
(game_save)
(ai_renew covenant)
(ai_disposable cov_def_sentinels true)
(ai_disposable cov_def_enf true)
(set g_veh_int_migrate_a 1)
(set g_music_06b_01 1)
(wake music_06b_01)
(wake sc_qz_veh_int)
1
1
1
2
0
2
(ai_place veh_int_wraith/wraith)
( ai_place veh_int_turrets )
0
(sleep 15)
(device_operates_automatically_set veh_int_door_a 1)
(sleep_until (volume_test_objects tv_veh_int_b (players)))
(game_save)
(ai_renew covenant)
(set g_veh_int_migrate_b 1)
(wake ai_veh_int_ghost_spawn)
2
2
(ai_magically_see veh_int_wraith veh_int_sen)
(ai_place veh_int_flood_bk/runner)
(sleep_until (volume_test_objects tv_veh_int_c (players)))
(data_mine_set_mission_segment enc_vehicle_int_bk)
(game_save)
(set g_veh_int_migrate_c 1)
(wake sc_factory_approach)
(ai_renew covenant)
1
(sleep_until (volume_test_objects tv_veh_int_d (players)))
( device_set_position veh_int_door_b 1 )
(set g_veh_int_migrate_d true)
1
)
(script dormant enc_qz_ext_a
(data_mine_set_mission_segment enc_qz_ext_a_dam)
(print "initialize quarantine zone exterior A scripts")
(game_save)
(ai_renew covenant)
(ai_disposable veh_int_flood true)
(ai_disposable veh_int_sen true)
(set g_veh_int_migrate_e 1)
(set g_ext_a_dam_migrate_a 1)
(wake music_06b_02)
(wake ai_ext_a_dam_enforcers)
(device_set_position qz_dam_door_a 1)
(ai_place qz_ext_a_dam_enf/a)
(ai_place qz_ext_a_dam_human)
(ai_place qz_ext_a_dam_sen)
(ai_place qz_ext_a_dam_sen_elim)
(ai_place qz_ext_a_dam_flood_ini)
(wake chapter_competition)
(game_save)
(ai_renew covenant)
(sleep_until (volume_test_objects qz_ext_a_dam_b (players)))
(set g_ext_a_dam_migrate_b 1)
(ai_place qz_ext_a_dam_flood_cliff_a)
(ai_place qz_ext_a_dam_flood_cliff_b)
(sleep_until (volume_test_objects tv_ext_a_a (players)))
(data_mine_set_mission_segment enc_qz_ext_a)
(game_save)
(ai_renew covenant)
(set g_ext_a_dam_enf 1)
(set g_ext_a_migrate_a 1)
(ai_disposable ext_a_flood_dam_a true)
(ai_disposable ext_a_flood_dam_b true)
(ai_disposable ext_a_sen_dam_a true)
(ai_disposable ext_a_sen_dam_b true)
(wake ai_qz_ext_a_wraiths)
(ai_place qz_ext_a_enf_a)
(ai_place qz_ext_a_flood_rocket)
(if (<= (ai_living_count covenant) 1) (begin (wake sc_ext_a) (ai_place qz_ext_a_phantom)))
(set v_ext_a_phantom (ai_vehicle_get_from_starting_location qz_ext_a_phantom/phantom))
(sleep_until (volume_test_objects tv_ext_a_b (players)))
(set g_ext_a_migrate_b 1)
(sleep_until (volume_test_objects tv_ext_a_c (players)))
(game_save_no_timeout)
(ai_renew covenant)
(set g_ext_a_migrate_c 1)
(ai_place qz_ext_a_flood_c)
(ai_place qz_ext_a_flood_c2)
(ai_place ext_a_flood_ghost_fr)
(sleep_until (volume_test_objects tv_ext_a_d (players)))
(set g_ext_a_migrate_d 1)
(wake ai_qz_ext_a_ghosts)
(wake ai_qz_ext_a_d_spawn)
(sleep_until (volume_test_objects tv_ext_a_e (players)))
(game_save)
(ai_renew covenant)
(set g_ext_a_migrate_e 1)
(set g_qz_ext_a_d_spawn 0)
(ai_place ext_a_sen_elim_bk)
(if (<= (ai_living_count qz_ext_a_enf_bk) 0) (ai_place qz_ext_a_enf_bk))
(sleep_until (volume_test_objects tv_ext_a_ghosts_off (players)))
(set g_qz_ext_a_flood_ghosts 1)
(sleep_until (volume_test_objects tv_ext_a_f (players)))
(data_mine_set_mission_segment enc_ext_a_fact_ent)
(game_save_no_timeout)
(set g_ext_a_migrate_f 1)
(set g_music_06b_02 1)
(ai_renew covenant)
( ai_place fact_ent_flood_turrets )
(ai_place fact_ent_flood_scorpion)
( ai_place )
(ai_place fact_ent_flood_wraith_b)
(wake ai_fact_ent_sen_spawn)
(wake ai_fact_ent_enf_spawn)
(sleep_until (volume_test_objects tv_ext_a_fact_ent (players)))
(set g_ext_a_fact_ent_migrate 1)
)
(script dormant enc_crashed_factory
(data_mine_set_mission_segment enc_crashed_factory_a)
(game_save)
(ai_renew covenant)
(ai_disposable ext_a_flood true)
(ai_disposable ext_a_sen true)
(set g_music_06b_02 0)
(set g_music_06b_03 1)
(set g_fact_ent_sen_spawn 1)
(wake music_06b_03)
(wake sent_factory_1_start)
(sleep_until (= (volume_test_objects vol_factory_1_exit (players)) TRUE))
(game_save)
(sleep_until (volume_test_objects tv_gorge (players)))
(data_mine_set_mission_segment enc_crashed_factory_ext)
(game_save)
(ai_disposable factory1_enemies true)
(set g_music_06b_03 0)
(ai_set_orders covenant cov_follow_gorge)
(ai_renew covenant)
(wake ai_gorge)
(sleep_until (volume_test_objects tv_factory2_enter (players)))
(data_mine_set_mission_segment enc_crashed_factory_b)
(game_save)
(ai_disposable gorge_enemies true)
(ai_set_orders covenant cov_follow_factory2)
(ai_renew covenant)
(wake ai_factory2)
)
(script dormant enc_qz_ext_b
(data_mine_set_mission_segment enc_ext_b_fact_exit)
(print "initialize quarantine zone exterior B scripts")
(game_save_no_timeout)
(ai_renew covenant)
(ai_disposable factory2_enemies true)
(wake music_06b_04)
(wake sc_factory_exit)
(wake objective_push_clear)
(wake objective_link_set)
(wake ext_b_vehicle_orders)
(ai_place qz_ext_b_fact_scorpion)
(ai_vehicle_reserve (ai_vehicle_get_from_starting_location qz_ext_b_fact_scorpion/scorpion) true)
( ai_place qz_ext_b_fact_humans )
(ai_place qz_ext_b_fact_wraith)
(ai_place qz_ext_b_fact_ghosts)
(ai_place qz_ext_b_fact_flood)
(ai_place qz_ext_b_fact_ghosts_spare)
(ai_place qz_ext_b_enf_a)
(sleep_until (volume_test_objects tv_ext_b_fact_mid (players)))
(game_save)
(if (random_range 0 2) (ai_place qz_ext_b_fact_warthog) (ai_place qz_ext_b_fact_ghost_bk))
(sleep_until (or
(and
(<= (ai_living_count ext_b_flood_a) 0)
(<= (ai_living_count ext_b_sentinels_a) 0)
)
(volume_test_objects tv_ext_b_gate (players))
)
5)
(data_mine_set_mission_segment enc_qz_ext_b)
(game_save)
(ai_renew covenant)
(set g_ext_b_migrate_1 1)
(wake ai_ext_b_enf_spawn)
(set g_music_06b_04 1)
(ai_place qz_ext_b_cov_phantom)
(ai_place qz_ext_b_wraith_a)
(ai_place qz_ext_b_wraith_b)
(ai_place qz_ext_b_ghosts_a (pin (- 7 (ai_living_count ext_b_flood)) 0 2))
(ai_place qz_ext_b_warthog)
(set v_ext_b_phantom (ai_vehicle_get_from_starting_location qz_ext_b_cov_phantom/phantom))
(sleep_until (or
(and
(<= (ai_living_count ext_b_flood_b) 0)
(<= (ai_living_count ext_b_sentinels_b) 0)
)
(volume_test_objects tv_ext_b_mid (players))
)
5)
(game_save_no_timeout)
(ai_renew covenant)
(set g_ext_b_migrate_2 1)
(ai_place qz_ext_b_ghosts_b)
(ai_place qz_ext_b_warthog_gauss)
(sleep_until (volume_test_objects tv_ext_b_back (players)) 5)
(data_mine_set_mission_segment enc_qz_ext_b_bk)
(game_save_no_timeout)
(ai_renew covenant)
(ai_disposable ext_b_flood true)
(ai_disposable ext_b_sentinels true)
(set g_ext_b_migrate_3 1)
(set g_ext_b_enforcer 1)
(wake ai_constructor_flock)
(wake ai_ext_b_bk_ghost_spawn)
(ai_place qz_ext_b_ent_enf)
(ai_place qz_ext_b_ent_scorpion)
(ai_place qz_ext_b_ent_wraith_a)
( ai_place qz_ext_b_ent_cov_phantom )
(sleep_until (volume_test_objects tv_ext_b_exit (players)) 5)
(data_mine_set_mission_segment enc_qz_ext_b_exit)
(game_save)
(ai_renew covenant)
(set g_ext_b_bk_ghost_spawn 1)
(set g_ext_b_migrate_4 1)
(wake ai_ext_b_exit_tube_a)
(wake ai_ext_b_exit_tube_b)
(ai_place qz_ext_b_ent_turrets)
(sleep_until (or
(and
(<= (ai_living_count ext_b_flood_d) 0)
(<= (ai_living_count ext_b_sentinels_d) 0)
)
(volume_test_objects tv_ext_b_exit_door (players))
)
5)
(game_save_no_timeout)
(ai_renew covenant)
(set g_ext_b_migrate_5 1)
(ai_place qz_ext_b_ent_flood_bk (pin (- 8 (ai_nonswarm_count ext_b_flood)) 0 6))
)
(script dormant enc_key_ride
(print "initialize key ride scripts")
(ai_renew covenant)
(wake music_06b_05)
(wake music_06b_06)
(wake music_06b_07)
(sleep_until (volume_test_objects tv_key_ride_cinematic (players)))
(cinematic_fade_to_white)
(ai_erase_all)
(object_teleport (player0) key_ride_a)
(object_teleport (player1) key_ride_b)
(sleep 5)
(if (= g_play_cinematics 1)
(begin
(if (cinematic_skip_start)
(begin
(print "c06_intra2")
(c06_intra2)
)
)
(cinematic_skip_stop)
)
)
(wake begin_key_ride_main)
(sleep 25)
(game_save_immediate)
(wake chapter_gallery)
(wake objective_link_clear)
(wake objective_retrieve_set)
(ai_renew covenant)
(camera_control off)
(sleep 1)
(cache_block_for_one_frame)
(sleep 1)
(cinematic_fade_from_white)
)
(script dormant enc_library
(print "initialize library scripts")
(game_save)
(game_save)
(ai_renew covenant)
)
(script dormant mission_floodzone
(cinematic_snap_to_white)
(switch_bsp 0)
(if (= g_play_cinematics 1)
(begin
(if (cinematic_skip_start)
(begin
(print "c06_intra1")
(c06_intra1)
)
)
(cinematic_skip_stop)
)
)
(sleep 2)
(object_teleport (player0) player0_start)
(object_teleport (player1) player1_start)
(wake enc_cov_charge)
(if (difficulty_legendary) (wake ice_cream_superman))
(camera_control off)
(sleep 1)
(cache_block_for_one_frame)
(sleep 1)
(cinematic_fade_from_white_bars)
(wake chapter_mirror)
(wake objective_push_set)
(sleep_until (volume_test_objects tv_vehicle_int (players)))
(wake enc_vehicle_int)
(sleep_until (volume_test_objects tv_qz_ext_a (players)))
(wake enc_qz_ext_a)
(sleep_until (volume_test_objects tv_factory (players)))
(wake enc_crashed_factory)
(sleep_until (volume_test_objects tv_qz_ext_b (players)))
(wake enc_qz_ext_b)
(sleep_until (volume_test_objects tv_key_ride (players)))
(wake enc_key_ride)
TODO : should change this to test g_e26_ended , like this :
9/18
(cinematic_fade_to_white)
(ai_erase_all)
(object_teleport (player0) player0_end)
(object_teleport (player1) player1_end)
(if (cinematic_skip_start)
(begin
(print "x07")
(x07)
)
)
(cinematic_skip_stop)
(playtest_mission)
(game_won)
)
(script static void start
(wake mission_floodzone)
)
(script startup mission_main
(ai_allegiance covenant player)
(ai_allegiance player covenant)
(ai_allegiance prophet player)
(ai_allegiance player prophet)
(ai_allegiance covenant prophet)
(ai_allegiance prophet covenant)
(if (> (player_count) 0 ) (start))
)
(script static void test
(set g_play_cinematics 0)
(device_set_position qz_door_a 1)
(device_set_position veh_int_door_a 1)
(device_set_position veh_int_door_b 1)
(device_set_position qz_dam_door_a 1)
(ai_place qz_cov_def_spectre)
(ai_place qz_cov_def_ghosts)
(ai_place qz_cov_def_spec_ops)
(wake ext_a_vehicle_orders)
(wake dam_door_a)
(wake dam_door_b)
(sleep 90)
(set g_qz_cov_def_progress 1)
)
(script static void test_ext_a_phantom
(ai_place qz_ext_a_phantom)
(set v_ext_a_phantom (ai_vehicle_get_from_starting_location qz_ext_a_phantom/phantom))
)
(script static void test_ext_b_phantom
(ai_place qz_ext_b_cov_phantom)
( ai_place qz_ext_b_wraith_a )
(set v_ext_b_phantom (ai_vehicle_get_from_starting_location qz_ext_b_cov_phantom/phantom))
)
|
bd67e7c75dd03873164159e2b513f33369d4c6184b78eebd233993324f111a16 | Lisp-Stat/lisp-stat | disasters.lisp | -*- Mode : LISP ; Syntax : Ansi - Common - Lisp ; Base : 10 ; Package : LS - USER -*-
(in-package #:ls-user)
(defdf disasters (read-csv vega:disasters))
(set-properties disasters :label '(:year "Year of disaster"
:deaths "Number of deaths"))
This data set has a bare year value , e.g. ' 1900 ' , that Vega - Lite
interprets as an integer . Transform the column to an ISO-8601
;; format.
(replace-column! disasters 'year #'(lambda (x)
(local-time:encode-timestamp 0 0 0 0 1 1 x)))
;; Categorical variables cannot be automatically determined
(set-properties disasters :type '(:year :temporal
:entity :categorical))
| null | https://raw.githubusercontent.com/Lisp-Stat/lisp-stat/a95bbd3e45c944fc8711721a042f5b1705bfea82/data/disasters.lisp | lisp | Syntax : Ansi - Common - Lisp ; Base : 10 ; Package : LS - USER -*-
format.
Categorical variables cannot be automatically determined | (in-package #:ls-user)
(defdf disasters (read-csv vega:disasters))
(set-properties disasters :label '(:year "Year of disaster"
:deaths "Number of deaths"))
This data set has a bare year value , e.g. ' 1900 ' , that Vega - Lite
interprets as an integer . Transform the column to an ISO-8601
(replace-column! disasters 'year #'(lambda (x)
(local-time:encode-timestamp 0 0 0 0 1 1 x)))
(set-properties disasters :type '(:year :temporal
:entity :categorical))
|
a8f93b347c3a5ebe039a4dfef6c1a476f18bcd12d25672041c804e2cef9d8461 | vmchale/atspkg | Build.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
# LANGUAGE TupleSections #
-- | This module holds various functions for turning a package into a set of rules
-- or an 'IO ()'.
module Language.ATS.Package.Build ( mkPkg
, build
, buildAll
, check
) where
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BSL
import Data.List (intercalate)
import qualified Data.Text as T
import Development.Shake (alwaysRerun, getVerbosity)
import Development.Shake.ATS
import Development.Shake.C (ccFromString)
import Development.Shake.Check
import Development.Shake.Clean
import Development.Shake.Man
import Distribution.ATS.Version
import GHC.Conc
import Language.ATS.Package.Build.C
import Language.ATS.Package.Compiler
import Language.ATS.Package.Config
import Language.ATS.Package.Debian hiding (libraries, target)
import Language.ATS.Package.Dependency
import Language.ATS.Package.Type
import Quaalude
import System.Info (os)
check :: Maybe String -> Maybe FilePath -> IO Bool
check mStr p = do
v <- wants mStr p
let vs = show v
doesFileExist =<< getAppUserDataDirectory ("atspkg" </> vs </> "ATS2-Postiats-gmp-" ++ vs </> "bin" </> "patscc")
wants :: Maybe String -> Maybe FilePath -> IO Version
wants mStr p = compiler <$> getConfig mStr p
-- | Build in current directory or indicated directory
buildAll :: Int
-> Maybe String
-> Maybe String
-> Maybe FilePath
-> IO ()
buildAll v mStr tgt' p = on (*>) (=<< wants mStr p) fetchDef setupDef
where fetchDef = fetchCompiler
setupDef = setupCompiler (toVerbosity v) atslibSetup tgt'
build' :: FilePath -- ^ Directory
-> Maybe String -- ^ Target triple
-> Bool -- ^ Debug build?
-> [String] -- ^ Targets
-> IO ()
build' dir tgt' dbg rs = withCurrentDirectory dir (mkPkgEmpty mempty)
where mkPkgEmpty ts = mkPkg Nothing False True False ts rs tgt' dbg 1
-- | Build a set of targets
build :: Int
-> Bool -- ^ Debug?
-> [String] -- ^ Targets
-> IO ()
build v dbg rs = bool (mkPkgEmpty [buildAll v Nothing Nothing Nothing]) (mkPkgEmpty mempty) =<< check Nothing Nothing
where mkPkgEmpty ts = mkPkg Nothing False True False ts rs Nothing dbg 1
TODO clean generated ATS
mkClean :: Rules ()
mkClean = "clean" ~> do
cleanHaskell
removeFilesAfter "." ["//*.1", "//*_dats.c", "//*_sats.c", "tags", "//*.a"]
removeFilesAfter "target" ["//*"]
removeFilesAfter ".atspkg" ["//*"]
removeFilesAfter "ats-deps" ["//*"]
TODO take more arguments , in particular , include + library dirs
mkInstall :: Maybe String -- ^ Optional target triple
-> Maybe String -- ^ Optional argument to @atspkg.dhall@
-> Rules ()
mkInstall tgt mStr =
"install" ~> do
config <- getConfig mStr Nothing
let libs' = fmap (unpack . libTarget) . libraries $ config
bins = fmap (unpack . target) . bin $ config
incs = ((fmap unpack . includes) =<<) . libraries $ config
libDir = maybe mempty (<> [pathSeparator]) tgt
need (bins <> libs')
home <- liftIO $ getEnv "HOME"
atspkgDir <- liftIO $ getAppUserDataDirectory "atspkg"
let g str = fmap (((home </> str) </>) . takeFileName)
binDest = g (".local" </> "bin") bins
libDest = ((atspkgDir </> libDir </> "lib") </>) . takeFileName <$> libs'
inclDest = ((atspkgDir </> "include") </>) . takeFileName <$> incs
zipWithM_ copyFile' (bins ++ libs' ++ incs) (binDest ++ libDest ++ inclDest)
pa <- pandoc
case man config of
Just mt -> when pa $ do
let mt' = manTarget mt
manDestActual = manDest home mt'
need [mt']
copyFile' mt' manDestActual
Nothing -> pure ()
co <- compleat
case completions config of
Just com -> when co $ do
let com' = unpack com
comDest = home </> ".compleat" </> takeFileName com'
FIXME do this all in one step
copyFile' com' comDest
Nothing -> pure ()
manDest :: FilePath -> FilePath -> FilePath
manDest home mt' =
case os of
"darwin" -> "/usr/local/share/man/man1" </> takeFileName mt'
"linux" -> home </> ".local" </> "share" </> "man" </> "man1" </> takeFileName mt'
_ -> error "Don't know where to install manpages for your OS"
mkManpage :: Maybe String -> Rules ()
mkManpage mStr = do
c <- getConfig mStr Nothing
b <- pandoc
case man c of
Just _ -> when b manpages
_ -> pure ()
parens :: String -> String
parens s = fold [ "(", s, ")" ]
cfgFile :: FilePath
cfgFile = ".atspkg" </> "config"
cfgArgs :: FilePath
cfgArgs = ".atspkg" </> "args"
dhallFile :: FilePath
dhallFile = "atspkg.dhall"
FIXME this does n't rebuild when it should ; it should rebuild when
-- @atspkg.dhall@ changes.
getConfig :: MonadIO m => Maybe String -> Maybe FilePath -> m Pkg
getConfig mStr dir' = liftIO $ do
d <- fromMaybe <$> fmap (</> dhallFile) getCurrentDirectory <*> pure dir'
let go = case mStr of { Just x -> (<> (" " <> parens x)) ; Nothing -> id }
input auto (T.pack (go d))
manTarget :: Text -> FilePath
manTarget m = unpack m -<.> "1"
mkPhony :: Maybe String -> String -> (String -> String) -> (Pkg -> [Bin]) -> [String] -> Rules ()
mkPhony mStr cmdStr f select rs =
cmdStr ~> do
config <- getConfig mStr Nothing
let runs = bool (filter (/= cmdStr) rs) (fmap (unpack . target) . select $ config) (rs == [cmdStr])
need runs
traverse_ cmd_ (f <$> runs)
mkValgrind :: Maybe String -> [String] -> Rules ()
mkValgrind mStr = mkPhony mStr "valgrind" ("valgrind " <>) bin
mkBench :: Maybe String -> [String] -> Rules ()
mkBench mStr = mkPhony mStr "bench" id bench
mkTest :: Maybe String -> [String] -> Rules ()
mkTest mStr = mkPhony mStr "test" id test
mkRun :: Maybe String -> [String] -> Rules ()
mkRun mStr = mkPhony mStr "run" id bin
toVerbosity :: Int -> Verbosity
toVerbosity 0 = Info
toVerbosity 1 = Info
toVerbosity 2 = Info
toVerbosity 3 = Verbose
toVerbosity 4 = Diagnostic
toVerbosity _ = Diagnostic -- should be a warning
options :: Bool -- ^ Whether to rebuild all targets
-> Bool -- ^ Whether to run the linter
-> Bool -- ^ Whether to display profiling information for the build
-> Int -- ^ Number of CPUs
-> Int -- ^ Verbosity level
-> [String] -- ^ A list of targets
-> ShakeOptions
options rba lint tim cpus v rs = shakeOptions { shakeFiles = ".atspkg"
, shakeThreads = cpus
, shakeLint = bool Nothing (Just LintBasic) lint
, shakeVersion = showVersion atspkgVersion
, shakeRebuild = rebuildTargets rba rs
, shakeChange = ChangeModtimeAndDigestInput
, shakeVerbosity = toVerbosity v
, shakeTimings = tim
}
rebuildTargets :: Bool -- ^ Force rebuild of all targets
-> [String] -- ^ Targets
-> [(Rebuild, String)]
rebuildTargets rba rs = foldMap g [ (rba, (RebuildNow ,) <$> patterns rs) ]
where g (b, ts) = bool mempty ts b
patterns = thread (mkPattern <$> ["c", "o", "so", "a", "deb"])
mkPattern ext = ("//*." <> ext :)
cleanConfig :: (MonadIO m) => Maybe String -> [String] -> m Pkg
cleanConfig _ ["clean"] = pure undefined
cleanConfig mStr _ = getConfig mStr Nothing
mkPkg :: Maybe String -- ^ Optional argument to @atspkg.dhall@
-> Bool -- ^ Force rebuild
-> Bool -- ^ Run linter
-> Bool -- ^ Print build profiling information
-> [IO ()] -- ^ Setup
-> [String] -- ^ Targets
-> Maybe String -- ^ Target triple
-> Bool -- ^ Debug build?
-> Int -- ^ Verbosity
-> IO ()
mkPkg mStr rba lint tim setup rs tgt dbg v = do
cfg <- cleanConfig mStr rs
setNumCapabilities =<< getNumProcessors
cpus <- getNumCapabilities
let opt = options rba lint tim cpus v $ pkgToTargets cfg tgt rs
shake opt $
sequence_
[ want (pkgToTargets cfg tgt rs)
, mkClean
, pkgToAction mStr setup rs tgt dbg cfg
]
mkConfig :: Maybe String -> Rules ()
mkConfig mStr = do
shouldWrite' <- shouldWrite mStr cfgArgs
cfgArgs %> \out -> do
alwaysRerun
exists <- liftIO (doesFileExist out)
if not exists || shouldWrite'
then liftIO (BSL.writeFile out (encode mStr))
else mempty
cfgFile %> \out -> do
need [dhallFile, cfgArgs]
let go = case mStr of { Just x -> (<> (" " <> parens x)) ; Nothing -> id }
x <- liftIO $ input auto (T.pack (go "./atspkg.dhall"))
liftIO $ BSL.writeFile out (encode (x :: Pkg))
setTargets :: [String] -> [FilePath] -> Maybe Text -> Rules ()
setTargets rs bins mt = when (null rs) $
case mt of
(Just m) -> want . bool bins (manTarget m : bins) =<< pandoc
Nothing -> want bins
bits :: Maybe String -> Maybe String -> [String] -> Rules ()
bits mStr tgt rs = sequence_ (sequence [ mkManpage, mkInstall tgt, mkConfig ] mStr) <>
biaxe [ mkRun, mkTest, mkBench, mkValgrind ] mStr rs
pkgToTargets :: Pkg -> Maybe String -> [FilePath] -> [FilePath]
pkgToTargets ~Pkg{..} tgt [] = (toTgt tgt . target <$> bin) <> (unpack . libTarget <$> libraries) <> (unpack . cTarget <$> atsSource)
pkgToTargets _ _ ts = ts
noConstr :: ATSConstraint
noConstr = ATSConstraint Nothing Nothing
atslibSetup :: Maybe String -- ^ Optional target triple
-> String -- ^ Library name
-> FilePath -- ^ Filepath
-> IO ()
atslibSetup tgt' lib' p = do
putStrLn $ "installing " ++ lib' ++ "..."
subdirs <- (p:) <$> allSubdirs p
pkgPath <- fromMaybe p <$> findFile subdirs dhallFile
let installDir = takeDirectory pkgPath
build' installDir tgt' False ["install"]
| The directory @~/.atspkg@
pkgHome :: MonadIO m => CCompiler -> m String
pkgHome cc' = liftIO $ getAppUserDataDirectory ("atspkg" </> ccToDir cc')
-- | The directory that will be @PATSHOME@.
patsHomeAtsPkg :: MonadIO m => Version -> m String
patsHomeAtsPkg v = fmap (</> vs </> "ATS2-Postiats-gmp-" ++ vs) (pkgHome (GCC Nothing Nothing))
where vs = show v
home' :: MonadIO m => Version -- ^ Compiler version
-> Version -- ^ Library version
-> m String
home' compV libV = do
h <- patsHomeAtsPkg compV
pure $ h </> "lib" </> "ats2-postiats-" ++ show libV
| This is the variable to be passed to the shell .
patsHomeLocsAtsPkg :: Int -- ^ Depth to recurse
-> String
patsHomeLocsAtsPkg n = intercalate ":" ((<> ".atspkg/contrib") . ("./" <>) <$> g)
where g = [ join $ replicate i "../" | i <- [0..n] ]
toTgt :: Maybe String -> Text -> String
toTgt tgt = maybeTgt tgt . unpack
where maybeTgt (Just t) = (<> ('-' : t))
maybeTgt Nothing = id
pkgToAction :: Maybe String -- ^ Optional extra expression to which we should apply @atspkg.dhall@
-> [IO ()] -- ^ Setup actions to be performed
-> [String] -- ^ Targets
-> Maybe String -- ^ Optional compiler triple (overrides 'ccompiler')
-> Bool -- ^ Debug build?
-> Pkg -- ^ Package data type
-> Rules ()
pkgToAction mStr setup rs tgt dbg ~(Pkg bs ts bnchs lbs mt _ v v' ds cds bdeps ccLocal cf af as dl slv deb al) =
unless (rs == ["clean"]) $ do
let cdps = if (f bs || f ts || f bnchs) && ("gc" `notElem` (fst <$> cds)) then ("gc", noConstr) : cds else cds where f = any gcBin
mkUserConfig
newFlag <- shouldWrite tgt flags
-- this is dumb but w/e
flags %> \out -> do
alwaysRerun
exists <- liftIO (doesFileExist out)
liftIO $ if not exists || newFlag
then BSL.writeFile out (encode tgt)
else mempty
TODO depend on tgt somehow ?
specialDeps %> \out -> do
cfgBin' <- cfgBin
need [ cfgBin', flags, cfgFile ]
v'' <- getVerbosity
liftIO $ fetchDeps v'' (ccFromString cc') mStr setup (first unpack <$> ds) (first unpack <$> cdps) (first unpack <$> bdeps) cfgBin' atslibSetup False *> writeFile out ""
let bins = toTgt tgt . target <$> bs
setTargets rs bins mt
ph <- home' v' v
cDepsRules ph *> bits mStr tgt rs
traverse_ (h ph) lbs
traverse_ (g ph) (bs ++ ts ++ bnchs)
fold (debRules <$> deb)
where g ph (Bin s t ls hs' atg gc' extra) =
atsBin (ATSTarget (dbgFlags (unpack <$> cf)) (atsToolConfig ph) gc' (unpack <$> ls) [unpack s] hs' (unpackTgt <$> atg) mempty (toTgt tgt t) (deps extra) Executable (not dbg))
h ph (Lib _ s t ls _ hs' lnk atg extra sta) =
atsBin (ATSTarget (dbgFlags (unpack <$> cf)) (atsToolConfig ph) False (unpack <$> ls) (unpack <$> s) hs' (unpackTgt <$> atg) (unpackLinks <$> lnk) (unpack t) (deps extra) (k sta) False)
dbgFlags = if dbg then ("-g":) . ("-O0":) . filter (/="-O2") else id
k False = SharedLibrary
k True = StaticLibrary
atsToolConfig ph = ATSToolConfig ph (patsHomeLocsAtsPkg 5) False (ccFromString cc') (not dl) slv al (unpack <$> af)
cDepsRules ph = unless (null as) $ do
let targets = fmap (unpack . cTarget) as
sources = fmap (unpack . atsSrc) as
zipWithM_ (cgen (atsToolConfig ph) [specialDeps, cfgFile] (fmap (unpack . ats) . atsGen =<< as)) sources targets
cc' = maybe (unpack ccLocal) (<> "-gcc") tgt
deps = (flags:) . (specialDeps:) . (cfgFile:) . fmap unpack
unpackLinks :: (Text, Text) -> HATSGen
unpackLinks (t, t') = HATSGen (unpack t) (unpack t')
unpackTgt :: TargetPair -> ATSGen
unpackTgt (TargetPair t t' b) = ATSGen (unpack t) (unpack t') b
specialDeps = ".atspkg" </> "deps" ++ maybe "" ("-" <>) tgt
flags = ".atspkg" </> "flags"
| null | https://raw.githubusercontent.com/vmchale/atspkg/45be7ece6b9e9b09a7151efe53ff7e278112e84d/ats-pkg/src/Language/ATS/Package/Build.hs | haskell | # LANGUAGE OverloadedStrings #
| This module holds various functions for turning a package into a set of rules
or an 'IO ()'.
| Build in current directory or indicated directory
^ Directory
^ Target triple
^ Debug build?
^ Targets
| Build a set of targets
^ Debug?
^ Targets
^ Optional target triple
^ Optional argument to @atspkg.dhall@
@atspkg.dhall@ changes.
should be a warning
^ Whether to rebuild all targets
^ Whether to run the linter
^ Whether to display profiling information for the build
^ Number of CPUs
^ Verbosity level
^ A list of targets
^ Force rebuild of all targets
^ Targets
^ Optional argument to @atspkg.dhall@
^ Force rebuild
^ Run linter
^ Print build profiling information
^ Setup
^ Targets
^ Target triple
^ Debug build?
^ Verbosity
^ Optional target triple
^ Library name
^ Filepath
| The directory that will be @PATSHOME@.
^ Compiler version
^ Library version
^ Depth to recurse
^ Optional extra expression to which we should apply @atspkg.dhall@
^ Setup actions to be performed
^ Targets
^ Optional compiler triple (overrides 'ccompiler')
^ Debug build?
^ Package data type
this is dumb but w/e | # LANGUAGE RecordWildCards #
# LANGUAGE TupleSections #
module Language.ATS.Package.Build ( mkPkg
, build
, buildAll
, check
) where
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BSL
import Data.List (intercalate)
import qualified Data.Text as T
import Development.Shake (alwaysRerun, getVerbosity)
import Development.Shake.ATS
import Development.Shake.C (ccFromString)
import Development.Shake.Check
import Development.Shake.Clean
import Development.Shake.Man
import Distribution.ATS.Version
import GHC.Conc
import Language.ATS.Package.Build.C
import Language.ATS.Package.Compiler
import Language.ATS.Package.Config
import Language.ATS.Package.Debian hiding (libraries, target)
import Language.ATS.Package.Dependency
import Language.ATS.Package.Type
import Quaalude
import System.Info (os)
check :: Maybe String -> Maybe FilePath -> IO Bool
check mStr p = do
v <- wants mStr p
let vs = show v
doesFileExist =<< getAppUserDataDirectory ("atspkg" </> vs </> "ATS2-Postiats-gmp-" ++ vs </> "bin" </> "patscc")
wants :: Maybe String -> Maybe FilePath -> IO Version
wants mStr p = compiler <$> getConfig mStr p
buildAll :: Int
-> Maybe String
-> Maybe String
-> Maybe FilePath
-> IO ()
buildAll v mStr tgt' p = on (*>) (=<< wants mStr p) fetchDef setupDef
where fetchDef = fetchCompiler
setupDef = setupCompiler (toVerbosity v) atslibSetup tgt'
-> IO ()
build' dir tgt' dbg rs = withCurrentDirectory dir (mkPkgEmpty mempty)
where mkPkgEmpty ts = mkPkg Nothing False True False ts rs tgt' dbg 1
build :: Int
-> IO ()
build v dbg rs = bool (mkPkgEmpty [buildAll v Nothing Nothing Nothing]) (mkPkgEmpty mempty) =<< check Nothing Nothing
where mkPkgEmpty ts = mkPkg Nothing False True False ts rs Nothing dbg 1
TODO clean generated ATS
mkClean :: Rules ()
mkClean = "clean" ~> do
cleanHaskell
removeFilesAfter "." ["//*.1", "//*_dats.c", "//*_sats.c", "tags", "//*.a"]
removeFilesAfter "target" ["//*"]
removeFilesAfter ".atspkg" ["//*"]
removeFilesAfter "ats-deps" ["//*"]
TODO take more arguments , in particular , include + library dirs
-> Rules ()
mkInstall tgt mStr =
"install" ~> do
config <- getConfig mStr Nothing
let libs' = fmap (unpack . libTarget) . libraries $ config
bins = fmap (unpack . target) . bin $ config
incs = ((fmap unpack . includes) =<<) . libraries $ config
libDir = maybe mempty (<> [pathSeparator]) tgt
need (bins <> libs')
home <- liftIO $ getEnv "HOME"
atspkgDir <- liftIO $ getAppUserDataDirectory "atspkg"
let g str = fmap (((home </> str) </>) . takeFileName)
binDest = g (".local" </> "bin") bins
libDest = ((atspkgDir </> libDir </> "lib") </>) . takeFileName <$> libs'
inclDest = ((atspkgDir </> "include") </>) . takeFileName <$> incs
zipWithM_ copyFile' (bins ++ libs' ++ incs) (binDest ++ libDest ++ inclDest)
pa <- pandoc
case man config of
Just mt -> when pa $ do
let mt' = manTarget mt
manDestActual = manDest home mt'
need [mt']
copyFile' mt' manDestActual
Nothing -> pure ()
co <- compleat
case completions config of
Just com -> when co $ do
let com' = unpack com
comDest = home </> ".compleat" </> takeFileName com'
FIXME do this all in one step
copyFile' com' comDest
Nothing -> pure ()
manDest :: FilePath -> FilePath -> FilePath
manDest home mt' =
case os of
"darwin" -> "/usr/local/share/man/man1" </> takeFileName mt'
"linux" -> home </> ".local" </> "share" </> "man" </> "man1" </> takeFileName mt'
_ -> error "Don't know where to install manpages for your OS"
mkManpage :: Maybe String -> Rules ()
mkManpage mStr = do
c <- getConfig mStr Nothing
b <- pandoc
case man c of
Just _ -> when b manpages
_ -> pure ()
parens :: String -> String
parens s = fold [ "(", s, ")" ]
cfgFile :: FilePath
cfgFile = ".atspkg" </> "config"
cfgArgs :: FilePath
cfgArgs = ".atspkg" </> "args"
dhallFile :: FilePath
dhallFile = "atspkg.dhall"
FIXME this does n't rebuild when it should ; it should rebuild when
getConfig :: MonadIO m => Maybe String -> Maybe FilePath -> m Pkg
getConfig mStr dir' = liftIO $ do
d <- fromMaybe <$> fmap (</> dhallFile) getCurrentDirectory <*> pure dir'
let go = case mStr of { Just x -> (<> (" " <> parens x)) ; Nothing -> id }
input auto (T.pack (go d))
manTarget :: Text -> FilePath
manTarget m = unpack m -<.> "1"
mkPhony :: Maybe String -> String -> (String -> String) -> (Pkg -> [Bin]) -> [String] -> Rules ()
mkPhony mStr cmdStr f select rs =
cmdStr ~> do
config <- getConfig mStr Nothing
let runs = bool (filter (/= cmdStr) rs) (fmap (unpack . target) . select $ config) (rs == [cmdStr])
need runs
traverse_ cmd_ (f <$> runs)
mkValgrind :: Maybe String -> [String] -> Rules ()
mkValgrind mStr = mkPhony mStr "valgrind" ("valgrind " <>) bin
mkBench :: Maybe String -> [String] -> Rules ()
mkBench mStr = mkPhony mStr "bench" id bench
mkTest :: Maybe String -> [String] -> Rules ()
mkTest mStr = mkPhony mStr "test" id test
mkRun :: Maybe String -> [String] -> Rules ()
mkRun mStr = mkPhony mStr "run" id bin
toVerbosity :: Int -> Verbosity
toVerbosity 0 = Info
toVerbosity 1 = Info
toVerbosity 2 = Info
toVerbosity 3 = Verbose
toVerbosity 4 = Diagnostic
-> ShakeOptions
options rba lint tim cpus v rs = shakeOptions { shakeFiles = ".atspkg"
, shakeThreads = cpus
, shakeLint = bool Nothing (Just LintBasic) lint
, shakeVersion = showVersion atspkgVersion
, shakeRebuild = rebuildTargets rba rs
, shakeChange = ChangeModtimeAndDigestInput
, shakeVerbosity = toVerbosity v
, shakeTimings = tim
}
-> [(Rebuild, String)]
rebuildTargets rba rs = foldMap g [ (rba, (RebuildNow ,) <$> patterns rs) ]
where g (b, ts) = bool mempty ts b
patterns = thread (mkPattern <$> ["c", "o", "so", "a", "deb"])
mkPattern ext = ("//*." <> ext :)
cleanConfig :: (MonadIO m) => Maybe String -> [String] -> m Pkg
cleanConfig _ ["clean"] = pure undefined
cleanConfig mStr _ = getConfig mStr Nothing
-> IO ()
mkPkg mStr rba lint tim setup rs tgt dbg v = do
cfg <- cleanConfig mStr rs
setNumCapabilities =<< getNumProcessors
cpus <- getNumCapabilities
let opt = options rba lint tim cpus v $ pkgToTargets cfg tgt rs
shake opt $
sequence_
[ want (pkgToTargets cfg tgt rs)
, mkClean
, pkgToAction mStr setup rs tgt dbg cfg
]
mkConfig :: Maybe String -> Rules ()
mkConfig mStr = do
shouldWrite' <- shouldWrite mStr cfgArgs
cfgArgs %> \out -> do
alwaysRerun
exists <- liftIO (doesFileExist out)
if not exists || shouldWrite'
then liftIO (BSL.writeFile out (encode mStr))
else mempty
cfgFile %> \out -> do
need [dhallFile, cfgArgs]
let go = case mStr of { Just x -> (<> (" " <> parens x)) ; Nothing -> id }
x <- liftIO $ input auto (T.pack (go "./atspkg.dhall"))
liftIO $ BSL.writeFile out (encode (x :: Pkg))
setTargets :: [String] -> [FilePath] -> Maybe Text -> Rules ()
setTargets rs bins mt = when (null rs) $
case mt of
(Just m) -> want . bool bins (manTarget m : bins) =<< pandoc
Nothing -> want bins
bits :: Maybe String -> Maybe String -> [String] -> Rules ()
bits mStr tgt rs = sequence_ (sequence [ mkManpage, mkInstall tgt, mkConfig ] mStr) <>
biaxe [ mkRun, mkTest, mkBench, mkValgrind ] mStr rs
pkgToTargets :: Pkg -> Maybe String -> [FilePath] -> [FilePath]
pkgToTargets ~Pkg{..} tgt [] = (toTgt tgt . target <$> bin) <> (unpack . libTarget <$> libraries) <> (unpack . cTarget <$> atsSource)
pkgToTargets _ _ ts = ts
noConstr :: ATSConstraint
noConstr = ATSConstraint Nothing Nothing
-> IO ()
atslibSetup tgt' lib' p = do
putStrLn $ "installing " ++ lib' ++ "..."
subdirs <- (p:) <$> allSubdirs p
pkgPath <- fromMaybe p <$> findFile subdirs dhallFile
let installDir = takeDirectory pkgPath
build' installDir tgt' False ["install"]
| The directory @~/.atspkg@
pkgHome :: MonadIO m => CCompiler -> m String
pkgHome cc' = liftIO $ getAppUserDataDirectory ("atspkg" </> ccToDir cc')
patsHomeAtsPkg :: MonadIO m => Version -> m String
patsHomeAtsPkg v = fmap (</> vs </> "ATS2-Postiats-gmp-" ++ vs) (pkgHome (GCC Nothing Nothing))
where vs = show v
-> m String
home' compV libV = do
h <- patsHomeAtsPkg compV
pure $ h </> "lib" </> "ats2-postiats-" ++ show libV
| This is the variable to be passed to the shell .
-> String
patsHomeLocsAtsPkg n = intercalate ":" ((<> ".atspkg/contrib") . ("./" <>) <$> g)
where g = [ join $ replicate i "../" | i <- [0..n] ]
toTgt :: Maybe String -> Text -> String
toTgt tgt = maybeTgt tgt . unpack
where maybeTgt (Just t) = (<> ('-' : t))
maybeTgt Nothing = id
-> Rules ()
pkgToAction mStr setup rs tgt dbg ~(Pkg bs ts bnchs lbs mt _ v v' ds cds bdeps ccLocal cf af as dl slv deb al) =
unless (rs == ["clean"]) $ do
let cdps = if (f bs || f ts || f bnchs) && ("gc" `notElem` (fst <$> cds)) then ("gc", noConstr) : cds else cds where f = any gcBin
mkUserConfig
newFlag <- shouldWrite tgt flags
flags %> \out -> do
alwaysRerun
exists <- liftIO (doesFileExist out)
liftIO $ if not exists || newFlag
then BSL.writeFile out (encode tgt)
else mempty
TODO depend on tgt somehow ?
specialDeps %> \out -> do
cfgBin' <- cfgBin
need [ cfgBin', flags, cfgFile ]
v'' <- getVerbosity
liftIO $ fetchDeps v'' (ccFromString cc') mStr setup (first unpack <$> ds) (first unpack <$> cdps) (first unpack <$> bdeps) cfgBin' atslibSetup False *> writeFile out ""
let bins = toTgt tgt . target <$> bs
setTargets rs bins mt
ph <- home' v' v
cDepsRules ph *> bits mStr tgt rs
traverse_ (h ph) lbs
traverse_ (g ph) (bs ++ ts ++ bnchs)
fold (debRules <$> deb)
where g ph (Bin s t ls hs' atg gc' extra) =
atsBin (ATSTarget (dbgFlags (unpack <$> cf)) (atsToolConfig ph) gc' (unpack <$> ls) [unpack s] hs' (unpackTgt <$> atg) mempty (toTgt tgt t) (deps extra) Executable (not dbg))
h ph (Lib _ s t ls _ hs' lnk atg extra sta) =
atsBin (ATSTarget (dbgFlags (unpack <$> cf)) (atsToolConfig ph) False (unpack <$> ls) (unpack <$> s) hs' (unpackTgt <$> atg) (unpackLinks <$> lnk) (unpack t) (deps extra) (k sta) False)
dbgFlags = if dbg then ("-g":) . ("-O0":) . filter (/="-O2") else id
k False = SharedLibrary
k True = StaticLibrary
atsToolConfig ph = ATSToolConfig ph (patsHomeLocsAtsPkg 5) False (ccFromString cc') (not dl) slv al (unpack <$> af)
cDepsRules ph = unless (null as) $ do
let targets = fmap (unpack . cTarget) as
sources = fmap (unpack . atsSrc) as
zipWithM_ (cgen (atsToolConfig ph) [specialDeps, cfgFile] (fmap (unpack . ats) . atsGen =<< as)) sources targets
cc' = maybe (unpack ccLocal) (<> "-gcc") tgt
deps = (flags:) . (specialDeps:) . (cfgFile:) . fmap unpack
unpackLinks :: (Text, Text) -> HATSGen
unpackLinks (t, t') = HATSGen (unpack t) (unpack t')
unpackTgt :: TargetPair -> ATSGen
unpackTgt (TargetPair t t' b) = ATSGen (unpack t) (unpack t') b
specialDeps = ".atspkg" </> "deps" ++ maybe "" ("-" <>) tgt
flags = ".atspkg" </> "flags"
|
8bf5b44481517a423b7207811ab615474bef2b0b070118c539e13a25f8cdbfed | cgohla/pureshell | Pretty.hs | {-# LANGUAGE DataKinds #-}
# LANGUAGE GADTs #
{-# LANGUAGE KindSignatures #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
module Data.Permutation.Pretty where
import Data.Permutation
import Data.Nat
import Data.Singletons
import Text.PrettyPrint.ANSI.Leijen
natReplicate :: Nat -> a -> [a]
natReplicate Z _a = []
natReplicate (S n) a = a : natReplicate n a
vertical :: Doc
vertical = char '|'
cross :: Doc
cross = text " ╳ "
prettyTransp :: Transp n -> Doc
prettyTransp (Transp n) = cross <+> (hsep $ natReplicate (fromSing n) vertical)
prettyTransp (Shift t) = vertical <+> prettyTransp t
prettyPerm :: Perm n -> Doc
prettyPerm (Ident n) = hsep $ natReplicate (fromSing n) vertical
prettyPerm (TranspCons t p) = vcat [prettyTransp t, prettyPerm p]
-- | prints
--
╳ |
-- | ╳
-- | | |
example :: Doc
example = prettyPerm $
compose (TranspCons (Transp sing) $ Ident sing) $
tensor (Ident $ sing @('S 'Z)) $ TranspCons (Transp (sing)) $
Ident $ sing @('S('S 'Z))
| null | https://raw.githubusercontent.com/cgohla/pureshell/ddaa9956dd4eb04a68eee39ae65395aaeeeb0b50/pureshell/Data/Permutation/Pretty.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE KindSignatures #
| prints
| ╳
| | | | # LANGUAGE GADTs #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
module Data.Permutation.Pretty where
import Data.Permutation
import Data.Nat
import Data.Singletons
import Text.PrettyPrint.ANSI.Leijen
natReplicate :: Nat -> a -> [a]
natReplicate Z _a = []
natReplicate (S n) a = a : natReplicate n a
vertical :: Doc
vertical = char '|'
cross :: Doc
cross = text " ╳ "
prettyTransp :: Transp n -> Doc
prettyTransp (Transp n) = cross <+> (hsep $ natReplicate (fromSing n) vertical)
prettyTransp (Shift t) = vertical <+> prettyTransp t
prettyPerm :: Perm n -> Doc
prettyPerm (Ident n) = hsep $ natReplicate (fromSing n) vertical
prettyPerm (TranspCons t p) = vcat [prettyTransp t, prettyPerm p]
╳ |
example :: Doc
example = prettyPerm $
compose (TranspCons (Transp sing) $ Ident sing) $
tensor (Ident $ sing @('S 'Z)) $ TranspCons (Transp (sing)) $
Ident $ sing @('S('S 'Z))
|
1b273aeedacd5c593f9509d34e178e469004a09ded605a79161f6abbc17ce279 | YoEight/lambda-database-experiment | Operation.hs | --------------------------------------------------------------------------------
-- |
-- Module : Lambda.Client.Operation
Copyright : ( C ) 2017
-- License : (see the file LICENSE)
Maintainer : < >
-- Stability : experimental
-- Portability: non-portable
--
Operation manager . It prepares requests from the user and handle responses
-- from the database server. It also manages operations timeout.
--------------------------------------------------------------------------------
module Lambda.Client.Operation where
--------------------------------------------------------------------------------
import Numeric.Natural
--------------------------------------------------------------------------------
import Lambda.Bus
import Lambda.Prelude
import Lambda.Prelude.Stopwatch
import Protocol.Message
import Protocol.Operation
import Protocol.Package
--------------------------------------------------------------------------------
import Lambda.Client.Messages
import Lambda.Client.Settings
import Lambda.Client.TcpConnection
--------------------------------------------------------------------------------
-- | Meta-information related to operation transaction.
data Meta =
Meta { attempts :: !Natural
-- ^ Number of time this operation has been tried.
, correlation :: !PkgId
-- ^ Id of the transaction.
, started :: !NominalDiffTime
-- ^ Since when this operation has been emitted.
}
--------------------------------------------------------------------------------
| Creates a new ' Meta ' .
newMeta :: Stopwatch -> React Settings Meta
newMeta s = Meta 0 <$> freshPkgId
<*> stopwatchElapsed s
--------------------------------------------------------------------------------
-- | Represents an ongoing transaction.
data Pending where
Pending :: Meta
-> Request a
-> (Either String a -> IO ()) -- The callback to execute once we get a response.
-> Pending
--------------------------------------------------------------------------------
-- | Represents a request put on hold because at the moment it was submitted,
an open ' TcpConnection ' was n't available . Those requests will be retried
-- once the connection manager calls 'tick'.
data Awaiting where
Awaiting :: Request a
-> (Either String a -> IO ())
-> Awaiting
--------------------------------------------------------------------------------
-- | Operation manager reference.
data Manager =
Manager { connRef :: ConnectionRef
^ Allows us to know if a ' TcpConnection ' is available .
, pendings :: IORef (HashMap PkgId Pending)
, awaitings :: IORef (Seq Awaiting)
, stopwatch :: Stopwatch
}
--------------------------------------------------------------------------------
-- | Creates an operation manager instance.
new :: ConnectionRef -> Configure Settings Manager
new ref =
Manager ref <$> newIORef mempty
<*> newIORef mempty
<*> newStopwatch
--------------------------------------------------------------------------------
-- | Submits a new operation request.
submit :: Manager -> NewRequest -> React Settings ()
submit Manager{..} (NewRequest req callback) =
maybeConnection connRef >>= \case
Just conn ->
do meta <- newMeta stopwatch
let op = Operation (correlation meta) req
pending = Pending meta req callback
pkg = createPkg op
modifyIORef' pendings (insertMap (correlation meta) pending)
enqueuePkg conn pkg
Nothing ->
let awaiting = Awaiting req callback
in modifyIORef' awaitings (`snoc` awaiting)
--------------------------------------------------------------------------------
| Updates operation manager state by submitting a incoming ' ' .
arrived :: Manager -> Pkg -> React Settings ()
arrived Manager{..} pkg@Pkg{..} = do
reg <- readIORef pendings
case lookup pkgId reg of
Nothing -> logWarn [i|Unknown request #{pkgId} response. Discarded.|]
Just (Pending _ req callback) ->
do case parseResp pkg req of
Nothing ->
do logError [i|Unexpected request response on #{pkgId}. Discarded|]
liftIO $ callback (Left "Unexpected request")
Just resp -> liftIO $ callback (Right $ responseType resp)
writeIORef pendings (deleteMap pkgId reg)
--------------------------------------------------------------------------------
-- | Performs operation manager internal bookkeepping like keeping track of
-- timeout operations or retrying awaited requests.
-- TODO - Implement pending request checking so we can detect which operation
-- has timeout.
tick :: Manager -> React Settings ()
tick self@Manager{..} = do
logDebug "Enter tick..."
as <- atomicModifyIORef' awaitings $ \cur -> (mempty, cur)
traverse_ submitting as
logDebug "Leave tick."
where
submitting (Awaiting req callback) =
submit self (NewRequest req callback)
| null | https://raw.githubusercontent.com/YoEight/lambda-database-experiment/da4fab8bd358fb8fb78412c805d6f5bc05854432/lambda-client/library/Lambda/Client/Operation.hs | haskell | ------------------------------------------------------------------------------
|
Module : Lambda.Client.Operation
License : (see the file LICENSE)
Stability : experimental
Portability: non-portable
from the database server. It also manages operations timeout.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| Meta-information related to operation transaction.
^ Number of time this operation has been tried.
^ Id of the transaction.
^ Since when this operation has been emitted.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| Represents an ongoing transaction.
The callback to execute once we get a response.
------------------------------------------------------------------------------
| Represents a request put on hold because at the moment it was submitted,
once the connection manager calls 'tick'.
------------------------------------------------------------------------------
| Operation manager reference.
------------------------------------------------------------------------------
| Creates an operation manager instance.
------------------------------------------------------------------------------
| Submits a new operation request.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| Performs operation manager internal bookkeepping like keeping track of
timeout operations or retrying awaited requests.
TODO - Implement pending request checking so we can detect which operation
has timeout. | Copyright : ( C ) 2017
Maintainer : < >
Operation manager . It prepares requests from the user and handle responses
module Lambda.Client.Operation where
import Numeric.Natural
import Lambda.Bus
import Lambda.Prelude
import Lambda.Prelude.Stopwatch
import Protocol.Message
import Protocol.Operation
import Protocol.Package
import Lambda.Client.Messages
import Lambda.Client.Settings
import Lambda.Client.TcpConnection
data Meta =
Meta { attempts :: !Natural
, correlation :: !PkgId
, started :: !NominalDiffTime
}
| Creates a new ' Meta ' .
newMeta :: Stopwatch -> React Settings Meta
newMeta s = Meta 0 <$> freshPkgId
<*> stopwatchElapsed s
data Pending where
Pending :: Meta
-> Request a
-> Pending
an open ' TcpConnection ' was n't available . Those requests will be retried
data Awaiting where
Awaiting :: Request a
-> (Either String a -> IO ())
-> Awaiting
data Manager =
Manager { connRef :: ConnectionRef
^ Allows us to know if a ' TcpConnection ' is available .
, pendings :: IORef (HashMap PkgId Pending)
, awaitings :: IORef (Seq Awaiting)
, stopwatch :: Stopwatch
}
new :: ConnectionRef -> Configure Settings Manager
new ref =
Manager ref <$> newIORef mempty
<*> newIORef mempty
<*> newStopwatch
submit :: Manager -> NewRequest -> React Settings ()
submit Manager{..} (NewRequest req callback) =
maybeConnection connRef >>= \case
Just conn ->
do meta <- newMeta stopwatch
let op = Operation (correlation meta) req
pending = Pending meta req callback
pkg = createPkg op
modifyIORef' pendings (insertMap (correlation meta) pending)
enqueuePkg conn pkg
Nothing ->
let awaiting = Awaiting req callback
in modifyIORef' awaitings (`snoc` awaiting)
| Updates operation manager state by submitting a incoming ' ' .
arrived :: Manager -> Pkg -> React Settings ()
arrived Manager{..} pkg@Pkg{..} = do
reg <- readIORef pendings
case lookup pkgId reg of
Nothing -> logWarn [i|Unknown request #{pkgId} response. Discarded.|]
Just (Pending _ req callback) ->
do case parseResp pkg req of
Nothing ->
do logError [i|Unexpected request response on #{pkgId}. Discarded|]
liftIO $ callback (Left "Unexpected request")
Just resp -> liftIO $ callback (Right $ responseType resp)
writeIORef pendings (deleteMap pkgId reg)
tick :: Manager -> React Settings ()
tick self@Manager{..} = do
logDebug "Enter tick..."
as <- atomicModifyIORef' awaitings $ \cur -> (mempty, cur)
traverse_ submitting as
logDebug "Leave tick."
where
submitting (Awaiting req callback) =
submit self (NewRequest req callback)
|
fc3f5fad1bffa30f35a14d58e3d3523aabc0abb2380ce4159e69fe7ddbe30621 | skanev/playground | 78-tests.scm | (require rackunit rackunit/text-ui)
(load "../78.scm")
(load-relative "../showcase/query/database.scm")
(define (matches-of query)
(let ((processed-query (query-syntax-process query)))
(map (lambda (frame)
(instantiate-exp processed-query frame (lambda (v f) (contract-question-mark v))))
(amb-collect (qeval processed-query '())))))
(define (matches? query)
(not (null? (matches-of query))))
(define sicp-4.78-tests
(test-suite
"Tests for SICP exercise 4.78"
(test-suite "simple queries"
(check-equal? (matches-of '(job ?x (computer programmer)))
'((job (Hacker Alyssa P) (computer programmer))
(job (Fect Cy D) (computer programmer))))
(check-equal? (matches-of '(job ?x (computer ?type)))
'((job (Bitdiddle Ben) (computer wizard))
(job (Hacker Alyssa P) (computer programmer))
(job (Fect Cy D) (computer programmer))
(job (Tweakit Lem E) (computer technician))))
(check-equal? (matches-of '(job ?x (computer . ?type)))
'((job (Bitdiddle Ben) (computer wizard))
(job (Hacker Alyssa P) (computer programmer))
(job (Fect Cy D) (computer programmer))
(job (Tweakit Lem E) (computer technician))
(job (Reasoner Louis) (computer programmer trainee))))
(check-equal? (matches-of '(and (job ?person (computer programmer))
(address ?person ?where)))
'((and (job (Hacker Alyssa P) (computer programmer))
(address (Hacker Alyssa P) (Cambridge (Mass Ave) 78)))
(and (job (Fect Cy D) (computer programmer))
(address (Fect Cy D) (Cambridge (Ames Street) 3)))))
(check-equal? (matches-of '(or (supervisor ?x (Bitdiddle Ben))
(supervisor ?x (Hacker Alyssa P))))
'((or (supervisor (Hacker Alyssa P) (Bitdiddle Ben))
(supervisor (Hacker Alyssa P) (Hacker Alyssa P)))
(or (supervisor (Fect Cy D) (Bitdiddle Ben))
(supervisor (Fect Cy D) (Hacker Alyssa P)))
(or (supervisor (Tweakit Lem E) (Bitdiddle Ben))
(supervisor (Tweakit Lem E) (Hacker Alyssa P)))
(or (supervisor (Reasoner Louis) (Bitdiddle Ben))
(supervisor (Reasoner Louis) (Hacker Alyssa P)))))
(check-equal? (matches-of '(and (supervisor ?x (Bitdiddle Ben))
(not (job ?x (computer programmer)))))
'((and (supervisor (Tweakit Lem E) (Bitdiddle Ben))
(not (job (Tweakit Lem E) (computer programmer))))))
(check-equal? (matches-of '(and (salary ?person ?amount)
(lisp-value > ?amount 30000)))
'((and (salary (Warbucks Oliver) 150000)
(lisp-value > 150000 30000))
(and (salary (Bitdiddle Ben) 60000)
(lisp-value > 60000 30000))
(and (salary (Hacker Alyssa P) 40000)
(lisp-value > 40000 30000))
(and (salary (Fect Cy D) 35000)
(lisp-value > 35000 30000))
(and (salary (Scrooge Eben) 75000)
(lisp-value > 75000 30000)))))
(test-suite "rules"
(check-true (matches? '(same x x)))
(check-true (matches? '(lives-near (Hacker Alyssa P) (Fect Cy D))))
(check-false (matches? '(lives-near (Hacker Alyssa P) (Bitdiddle Ben))))
(check-true (matches? '(wheel (Warbucks Oliver))))
(check-true (matches? '(wheel (Bitdiddle Ben))))
(check-false (matches? '(wheel (Hacker Alyssa P))))
(check-true (matches? '(outranked-by (Bitdiddle Ben) (Warbucks Oliver))))
(check-true (matches? '(outranked-by (Hacker Alyssa P) (Warbucks Oliver))))
(check-true (matches? '(outranked-by (Reasoner Louis) (Warbucks Oliver))))
(check-true (matches? '(outranked-by (Hacker Alyssa P) (Bitdiddle Ben))))
(check-true (matches? '(outranked-by (Reasoner Louis) (Bitdiddle Ben))))
(check-true (matches? '(outranked-by (Reasoner Louis) (Hacker Alyssa P))))
(check-false (matches? '(outranked-by (Warbucks Oliver) (Bitdiddle Ben))))
(check-false (matches? '(outranked-by (Eben Scrooge) (Bitdiddle Ben))))
(check-false (matches? '(outranked-by (Bitdiddle Ben) (Eben Scrooge)))))
(test-suite "logic as programs"
(check-equal? (matches-of '(append-to-form (a b) (c d) ?z))
'((append-to-form (a b) (c d) (a b c d))))
(check-equal? (matches-of '(append-to-form (a b) ?y (a b c d)))
'((append-to-form (a b) (c d) (a b c d))))
(check-equal? (matches-of '(append-to-form ?x ?y (a b c d)))
'((append-to-form () (a b c d) (a b c d))
(append-to-form (a) (b c d) (a b c d))
(append-to-form (a b) (c d) (a b c d))
(append-to-form (a b c) (d) (a b c d))
(append-to-form (a b c d) () (a b c d)))))
))
(run-tests sicp-4.78-tests)
| null | https://raw.githubusercontent.com/skanev/playground/d88e53a7f277b35041c2f709771a0b96f993b310/scheme/sicp/04/tests/78-tests.scm | scheme | (require rackunit rackunit/text-ui)
(load "../78.scm")
(load-relative "../showcase/query/database.scm")
(define (matches-of query)
(let ((processed-query (query-syntax-process query)))
(map (lambda (frame)
(instantiate-exp processed-query frame (lambda (v f) (contract-question-mark v))))
(amb-collect (qeval processed-query '())))))
(define (matches? query)
(not (null? (matches-of query))))
(define sicp-4.78-tests
(test-suite
"Tests for SICP exercise 4.78"
(test-suite "simple queries"
(check-equal? (matches-of '(job ?x (computer programmer)))
'((job (Hacker Alyssa P) (computer programmer))
(job (Fect Cy D) (computer programmer))))
(check-equal? (matches-of '(job ?x (computer ?type)))
'((job (Bitdiddle Ben) (computer wizard))
(job (Hacker Alyssa P) (computer programmer))
(job (Fect Cy D) (computer programmer))
(job (Tweakit Lem E) (computer technician))))
(check-equal? (matches-of '(job ?x (computer . ?type)))
'((job (Bitdiddle Ben) (computer wizard))
(job (Hacker Alyssa P) (computer programmer))
(job (Fect Cy D) (computer programmer))
(job (Tweakit Lem E) (computer technician))
(job (Reasoner Louis) (computer programmer trainee))))
(check-equal? (matches-of '(and (job ?person (computer programmer))
(address ?person ?where)))
'((and (job (Hacker Alyssa P) (computer programmer))
(address (Hacker Alyssa P) (Cambridge (Mass Ave) 78)))
(and (job (Fect Cy D) (computer programmer))
(address (Fect Cy D) (Cambridge (Ames Street) 3)))))
(check-equal? (matches-of '(or (supervisor ?x (Bitdiddle Ben))
(supervisor ?x (Hacker Alyssa P))))
'((or (supervisor (Hacker Alyssa P) (Bitdiddle Ben))
(supervisor (Hacker Alyssa P) (Hacker Alyssa P)))
(or (supervisor (Fect Cy D) (Bitdiddle Ben))
(supervisor (Fect Cy D) (Hacker Alyssa P)))
(or (supervisor (Tweakit Lem E) (Bitdiddle Ben))
(supervisor (Tweakit Lem E) (Hacker Alyssa P)))
(or (supervisor (Reasoner Louis) (Bitdiddle Ben))
(supervisor (Reasoner Louis) (Hacker Alyssa P)))))
(check-equal? (matches-of '(and (supervisor ?x (Bitdiddle Ben))
(not (job ?x (computer programmer)))))
'((and (supervisor (Tweakit Lem E) (Bitdiddle Ben))
(not (job (Tweakit Lem E) (computer programmer))))))
(check-equal? (matches-of '(and (salary ?person ?amount)
(lisp-value > ?amount 30000)))
'((and (salary (Warbucks Oliver) 150000)
(lisp-value > 150000 30000))
(and (salary (Bitdiddle Ben) 60000)
(lisp-value > 60000 30000))
(and (salary (Hacker Alyssa P) 40000)
(lisp-value > 40000 30000))
(and (salary (Fect Cy D) 35000)
(lisp-value > 35000 30000))
(and (salary (Scrooge Eben) 75000)
(lisp-value > 75000 30000)))))
(test-suite "rules"
(check-true (matches? '(same x x)))
(check-true (matches? '(lives-near (Hacker Alyssa P) (Fect Cy D))))
(check-false (matches? '(lives-near (Hacker Alyssa P) (Bitdiddle Ben))))
(check-true (matches? '(wheel (Warbucks Oliver))))
(check-true (matches? '(wheel (Bitdiddle Ben))))
(check-false (matches? '(wheel (Hacker Alyssa P))))
(check-true (matches? '(outranked-by (Bitdiddle Ben) (Warbucks Oliver))))
(check-true (matches? '(outranked-by (Hacker Alyssa P) (Warbucks Oliver))))
(check-true (matches? '(outranked-by (Reasoner Louis) (Warbucks Oliver))))
(check-true (matches? '(outranked-by (Hacker Alyssa P) (Bitdiddle Ben))))
(check-true (matches? '(outranked-by (Reasoner Louis) (Bitdiddle Ben))))
(check-true (matches? '(outranked-by (Reasoner Louis) (Hacker Alyssa P))))
(check-false (matches? '(outranked-by (Warbucks Oliver) (Bitdiddle Ben))))
(check-false (matches? '(outranked-by (Eben Scrooge) (Bitdiddle Ben))))
(check-false (matches? '(outranked-by (Bitdiddle Ben) (Eben Scrooge)))))
(test-suite "logic as programs"
(check-equal? (matches-of '(append-to-form (a b) (c d) ?z))
'((append-to-form (a b) (c d) (a b c d))))
(check-equal? (matches-of '(append-to-form (a b) ?y (a b c d)))
'((append-to-form (a b) (c d) (a b c d))))
(check-equal? (matches-of '(append-to-form ?x ?y (a b c d)))
'((append-to-form () (a b c d) (a b c d))
(append-to-form (a) (b c d) (a b c d))
(append-to-form (a b) (c d) (a b c d))
(append-to-form (a b c) (d) (a b c d))
(append-to-form (a b c d) () (a b c d)))))
))
(run-tests sicp-4.78-tests)
| |
76e2f780e6d31f1578da18fae2e641b5e3b165659e23b47a41def702ce536335 | Rober-t/apxr_run | neuron.erl | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Copyright ( C ) 2009 by , DXNN Research Group ,
%%%
%%%
%%% The original release of this source code was introduced and explained
in a book ( available for purchase on Amazon ) by :
%%%
Handbook of Neuroevolution Through Erlang . Springer 2012 ,
print ISBN : 978 - 1 - 4614 - 4462 - 6 ebook ISBN : 978 - 1 - 4614 - 4463 - 6 .
%%%
%%% The original release of this source code was introduced and explained
in a book ( available for purchase on Amazon ) by :
%%%
Handbook of Neuroevolution Through Erlang . Springer 2012 ,
print ISBN : 978 - 1 - 4614 - 4462 - 6 ebook ISBN : 978 - 1 - 4614 - 4463 - 6 .
%%%
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.
Deus Ex Neural Network : : DXNN % % % % % % % % % % % % % % % % % % % % % % % % % % %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Modified Copyright ( C ) 2018 ApproximateReality
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%----------------------------------------------------------------------------
%%% @doc The neuron is a signal processing element. It accepts signals,
%%% accumulates them into an ordered vector, then processes this input
%%% vector to produce an output, and finally passes the output to other
%%% elements it is connected to. The neuron never interacts with the
%%% environment directly, and even when it does receive signals and
%%% produces output signals, it does not know whether these input signals
%%% are coming from sensors or neurons, or whether it is sending its
%%% output signals to other neurons or actuators. All the neuron does is
%%% have a list of of input Pids from which it expects to receive
%%% signals, a list of output Pids to which the neuron sends its output,
%%% a weight list correlated with the input Pids, and an activation
%%% function it applies to the dot product of the input vector and its
%%% weight vector. The neuron waits until it receives all the input
%%% signals, and then passes the output onwards.
%%% NOTE: The neuron is the basic processing element, the basic processing
%%% node in the neural network system. The neurons in this system we’ve
%%% created are more general than those used by others. They can easily
%%% use various activation functions, and to accept and output vectors.
%%% Because we can use anything for the activation function, including
%%% logical operators, the neurons are really just processing nodes. In
some sense , this system is not a Topology and Weight Evolving
Artificial Neural Network , but a Topology and Parameter Evolving
Universal Learning Network ( TPEULN ) . Nevertheless , we will continue
%%% referring to these processing elements as neurons.
%%% @end
%%%----------------------------------------------------------------------------
-module(neuron).
Start / Stop
-export([
start/2,
stop/2
]).
%% API
-export([
init_phase2/12,
forward/3,
weight_backup/2,
weight_restore/2,
weight_perturb/3,
reset_prep/2,
get_backup/2,
perturb_pf/2,
perturb_weights_p/4
]).
%% Callbacks
-export([
init/1,
loop/1, loop/6,
handle/2,
terminate/1
]).
Xref
-ignore_xref([
loop/1, loop/6,
handle/2,
perturb_pf/2,
perturb_weights_p/4,
terminate/1
]).
%%%============================================================================
%%% Types
%%%============================================================================
-record(neuron_state, {
id :: models:neuron_id(),
cx_pid :: pid(),
af :: models:neural_af(),
aggr_f :: atom(),
heredity_type :: darwinian | lamarckian,
si_pids :: [pid()] | [ok],
The input_pids that are currently effective and represent the neuron 's
% processing dynamics.
si_pidps_current :: [{pid(), [float()]}],
A second input_pids list , which represents the state of input_pids right
% after perturbation, before the synaptic weights are affected by the
% neuron's plasticity function (bl -> before learning). When a neuron is
% requested to to perturb its synaptic weights, right after the weights are
perturbed , we want to save this new input_pids list , before plasticity gets
% a chance to modify the synaptic weights. Afterwards, the neuron can process
% the input signals using its input_pids_current, and its learning rule can
% affect the input_pids_current list. But input_pids_bl will remain unchanged.
si_pidps_bl :: [{pid(), [float()]}],
% When a neuron is sent the weight_backup message, it is here that
% heredity_type plays its role. When its << darwinian >>, the neuron saves the
% input_pids_bl to input_pids_backup, instead of the input_pids_current which
% could have been modified by some learning rule by this point. On the other
hand , when the heredity_type is < < > > , the neuron saves the
% input_pids_current to input_pids_backup. The input_pids_current represents
% the synaptic weights that could have been updated if the neuron allows for
% plasticity, and thus the input_pids_backup will then contain not the initial
% state of the synaptic weight list with which the neuron started, but the
% state of the synaptic weights after the the neuron has experienced,
% processed, and had its synaptic weights modified by its learning rule.
si_pidps_backup :: [{pid(), [float()]}],
mi_pids :: [pid()] | [ok],
mi_pidps_current :: [{pid(), [float()]}],
mi_pidps_backup :: [{pid(), [float()]}],
pf_current :: {models:neural_pfn(), [float()]},
pf_backup :: {models:neural_pfn(), [float()]},
output_pids :: [pid()],
ro_pids :: [pid()]
}).
-type state() :: #neuron_state{}.
%%%============================================================================
%%% Configuration
%%%============================================================================
-define(SAT_LIMIT, math:pi() * 2).
%%%============================================================================
%%% API
%%%============================================================================
%%-----------------------------------------------------------------------------
@doc Spawns a Neuron process belonging to the process that
%% spawned it and calls init to initialize.
%% @end
%%-----------------------------------------------------------------------------
-spec start(node(), pid()) -> pid().
start(Node, ExoselfPid) ->
spawn_link(Node, ?MODULE, init, [ExoselfPid]).
%%-----------------------------------------------------------------------------
@doc Terminates neuron .
%% @end
%%-----------------------------------------------------------------------------
-spec stop(pid(), pid()) -> ok.
stop(Pid, ExoselfPid) ->
Pid ! {ExoselfPid, stop},
ok.
%%-----------------------------------------------------------------------------
%% @doc Initializes the neuron setting it to its initial state.
%% @end
%%-----------------------------------------------------------------------------
-spec init_phase2(pid(), pid(), models:neuron_id(), pid(), models:neural_af(),
{models:neural_pfn(), [float()]}, atom(), darwinian | lamarckian, [tuple()], [tuple()], [pid()],
[pid()]) -> ok.
init_phase2(Pid, ExoselfPid, Id, CxPid, AF, PF, AggrF, HeredityType, SIPidPs, MIPidPs, OutputPids,
ROPids) ->
Pid ! {handle, {init_phase2, ExoselfPid, Id, CxPid, AF, PF, AggrF, HeredityType, SIPidPs,
MIPidPs, OutputPids, ROPids}},
ok.
%%-----------------------------------------------------------------------------
@doc The Neuron process waits for vector signals from all the processes
%% that it's connected from, taking the dot product of the input and
%% weight vectors, and then adding it to the accumulator. Once all the
signals from InputPids are received , the accumulator contains the
%% dot product to which the neuron then adds the bias and executes the
%% activation function. After fanning out the output signal, the neuron
%% again returns to waiting for incoming signals.
%% @end
%%-----------------------------------------------------------------------------
-spec forward(pid(), pid(), float()) -> ok.
forward(Pid, IPid, Input) ->
Pid ! {handle, {forward, IPid, Input}},
ok.
%%-----------------------------------------------------------------------------
%% @doc weight_backup The signal from the exoself, which tells the neuron
that the NN system performs best when this particular neuron is using
%% its current synaptic weight combination, and thus it should save this
synaptic weight list as , and that it is the best weight
%% combination achieved thus far. The message is sent if after the weight
perturbation , the NN 's evaluation achieves a higher fitness than when
the neurons of this NN used their previous synaptic weights .
%% @end
%%-----------------------------------------------------------------------------
-spec weight_backup(pid(), pid()) -> ok.
weight_backup(Pid, ExoselfPid) ->
Pid ! {handle, {ExoselfPid, weight_backup}},
ok.
%%-----------------------------------------------------------------------------
%% @doc weight_restore This message is sent from the exoself, and it tells
the neuron that it should restore its synaptic weight list to the one
previously used , saved as . This message is usually sent if
after the weight perturbation , the NN based agent 's evaluation performs
%% worse than it did with its previous synaptic weight combinations.
%% @end
%%-----------------------------------------------------------------------------
-spec weight_restore(pid(), pid()) -> ok.
weight_restore(Pid, ExoselfPid) ->
Pid ! {handle, {ExoselfPid, weight_restore}},
ok.
%%-----------------------------------------------------------------------------
%% @doc weight_perturb Uses the Spread value for the purpose of generating
%% synaptic weight perturbations.
%% @end
%%-----------------------------------------------------------------------------
-spec weight_perturb(pid(), pid(), integer()) -> ok.
weight_perturb(Pid, ExoselfPid, Spread) ->
Pid ! {handle, {ExoselfPid, weight_perturb, Spread}},
ok.
%%-----------------------------------------------------------------------------
%% @doc reset_prep This is message is sent after a single evaluation is
%% completed, and the exoself wishes to reset all the neurons to their
%% original states, with empty inboxes. Once a neuron receives this
%% message, it goes into a reset_prep state, flushes its buffer/inbox, and
then awaits for the { ExoselfPid , reset } signal . When the neuron receives
the { ExoselfPid , reset } message , it again sends out the default output
message to all its recurrent connections ( Ids stored in the ro_ids
%% list), and then finally drops back into its main receive loop.
%% @end
%%-----------------------------------------------------------------------------
-spec reset_prep(pid(), pid()) -> ok.
reset_prep(Pid, ExoselfPid) ->
Pid ! {handle, {ExoselfPid, reset_prep}},
ok.
%%-----------------------------------------------------------------------------
%% @doc get_backup neuron sends back to the exoself its last best synaptic
%% weight combination, stored as the MInputPids list.
%% @end
%%-----------------------------------------------------------------------------
-spec get_backup(pid(), pid()) -> ok.
get_backup(Pid, ExoselfPid) ->
Pid ! {handle, {ExoselfPid, get_backup}},
ok.
%%-----------------------------------------------------------------------------
%% @doc perturb_pf perturbs the plasticity function.
%% @end
%%----------------------------------------------------------------------------
-spec perturb_pf(float(), {atom(), [float()]}) -> {atom(), [float()]}.
perturb_pf(Spread, {PFName, PFParameters}) ->
do_perturb_pf(Spread, {PFName, PFParameters}).
%%-----------------------------------------------------------------------------
%% @doc The perturb_weights_p function is the function that actually goes
%% through each weight block, and perturbs each weight with a
%% probability of MP. If the weight is chosen to be perturbed, the
%% perturbation intensity is chosen uniformly between -Spread and
%% Spread.
%% @end
%%-----------------------------------------------------------------------------
-spec perturb_weights_p(float(), float(), [{float(), [float()]}], [float()]) -> [float()].
perturb_weights_p(Spread, MP, [{W, LPs} | Weights], Acc) ->
do_perturb_weights_p(Spread, MP, [{W, LPs} | Weights], Acc).
%%%============================================================================
%%% Callbacks
%%%============================================================================
%%-----------------------------------------------------------------------------
@private
@doc Whenever a Neuron process is started via the start function this
%% function is called by the new process to initialize.
%% @end
%%-----------------------------------------------------------------------------
-spec init(pid()) -> no_return().
init(ExoselfPid) ->
utils:random_seed(),
logr:debug({neuron, init, ok, undefined, []}),
loop(ExoselfPid).
%%-----------------------------------------------------------------------------
@private
%% @doc During initialization the neuron sends out the default forward signals
%% to any elements in its ro_ids list, if any.
%% @end
%%-----------------------------------------------------------------------------
-spec loop(pid()) -> no_return().
loop(ExoselfPid) ->
receive
{handle, {init_phase2, ExoselfPid, Id, CxPid, AF, PF, AggrF, HeredityType, SIPidPs, MIPidPs,
OutputPids, ROPids}} ->
SIPids = append_ipids(SIPidPs),
MIPids = append_ipids(MIPidPs),
NewState = handle(init_phase2, {Id, CxPid, AF, PF, AggrF, HeredityType, SIPidPs, MIPidPs,
OutputPids, ROPids, SIPids, MIPids}),
loop(NewState, ExoselfPid, SIPids, MIPids, [], [])
end.
%%-----------------------------------------------------------------------------
@private
%% @doc Receive and handle messages.
%% @end
%%-----------------------------------------------------------------------------
-spec loop(state(), pid(), [ok] | [pid()], [ok] | [pid()], [{pid(), [float()]}] | [],
[{pid(), [float()]}] | []) -> no_return().
loop(State, ExoselfPid, [ok], [ok], SIAcc, MIAcc) ->
NewState = handle(forward_output, {SIAcc, MIAcc, State}),
SIPids = NewState#neuron_state.si_pids,
MIPids = NewState#neuron_state.mi_pids,
loop(NewState, ExoselfPid, SIPids, MIPids, [], []);
loop(State, ExoselfPid, [SIPid | SIPids], [MIPid | MIPids], SIAcc, MIAcc) ->
receive
{handle, {forward, SIPid, Input}} ->
logr:debug({neuron, msg, ok, "SIPid forward message received", [SIPid]}),
loop(State, ExoselfPid, SIPids, [MIPid | MIPids], [{SIPid, Input} | SIAcc], MIAcc);
{handle, {forward, MIPid, Input}} ->
logr:debug({neuron, msg, ok, "MIPid forward message received", [MIPid]}),
loop(State, ExoselfPid, [SIPid | SIPids], MIPids, SIAcc, [{MIPid, Input} | MIAcc]);
{forward, SIPid, Input} ->
logr:debug({neuron, msg, ok, "SIPid forward message received", [SIPid]}),
loop(State, ExoselfPid, SIPids, [MIPid | MIPids], [{SIPid, Input} | SIAcc], MIAcc);
{forward, MIPid, Input} ->
logr:debug({neuron, msg, ok, "MIPid forward message received", [MIPid]}),
loop(State, ExoselfPid, [SIPid | SIPids], MIPids, SIAcc, [{MIPid, Input} | MIAcc]);
{handle, {ExoselfPid, weight_backup}} ->
NewState = handle(weight_backup, State),
loop(NewState, ExoselfPid, [SIPid | SIPids], [MIPid | MIPids], SIAcc, MIAcc);
{handle, {ExoselfPid, weight_restore}} ->
NewState = handle(weight_restore, State),
loop(NewState, ExoselfPid, [SIPid | SIPids], [MIPid | MIPids], SIAcc, MIAcc);
{handle, {ExoselfPid, weight_perturb, Spread}} ->
NewState = handle(weight_perturb, {State, Spread}),
loop(NewState, ExoselfPid, [SIPid | SIPids], [MIPid | MIPids], SIAcc, MIAcc);
{handle, {ExoselfPid, reset_prep}} ->
flush_buffer(),
ExoselfPid ! {self(), ready},
ROPids = State#neuron_state.ro_pids,
receive
{ExoselfPid, reset} ->
logr:debug({neuron, reset, ok, "Fanning out ROPids", [ROPids]}),
fanout(ROPids);
{ExoselfPid, stop} ->
terminate(normal)
end,
loop(State, ExoselfPid, State#neuron_state.si_pids, State#neuron_state.mi_pids, [], []);
{handle, {ExoselfPid, get_backup}} ->
handle(get_backup, {State, ExoselfPid}),
loop(State, ExoselfPid, [SIPid | SIPids], [MIPid | MIPids], SIAcc, MIAcc);
{ExoselfPid, stop} ->
terminate(normal)
end.
%%-----------------------------------------------------------------------------
@private
%% @doc This function is called to terminate the process. It performs
%% any necessary cleaning up before exiting with the << Reason >>
%% parameter that it was called with.
%% @end
%%-----------------------------------------------------------------------------
-spec terminate(atom()) -> ok.
terminate(Reason) ->
logr:debug({neuron, terminate, ok, undefined, [Reason]}),
exit(Reason).
%%%============================================================================
Internal functions
%%%============================================================================
handle(init_phase2, {Id, CxPid, AF, PF, AggrF, HeredityType, SIPidPs, MIPidPs, OutputPids, ROPids,
SIPids, MIPids}) ->
fanout(ROPids),
logr:debug({neuron, init2, ok, undefined, []}),
State = #neuron_state{
id = Id,
cx_pid = CxPid,
af = AF,
pf_current = PF,
pf_backup = PF,
aggr_f = AggrF,
heredity_type = HeredityType,
si_pids = SIPids,
si_pidps_bl = SIPidPs,
si_pidps_current = SIPidPs,
si_pidps_backup = SIPidPs,
mi_pids = MIPids,
mi_pidps_current = MIPidPs,
mi_pidps_backup = MIPidPs,
output_pids = OutputPids,
ro_pids = ROPids
},
State;
handle(forward_output, {SIAcc, MIAcc, State}) ->
OutputSatLimit = app_config:get_env(output_sat_limit),
{PFName, PFParameters} = State#neuron_state.pf_current,
AF = State#neuron_state.af,
AggrF = State#neuron_state.aggr_f,
OrderedSIAcc = lists:reverse(SIAcc),
SIPidPs = State#neuron_state.si_pidps_current,
SOutput = [sat(functions:AF(signal_aggregator:AggrF(OrderedSIAcc, SIPidPs)), OutputSatLimit)],
NewState = case PFName of
none ->
State;
_ ->
OrderedMIAcc = lists:reverse(MIAcc),
MIPidPs = State#neuron_state.mi_pidps_current,
MAggregationProduct = signal_aggregator:dot_product(OrderedMIAcc, MIPidPs),
MOutput = sat(functions:tanh(MAggregationProduct), ?SAT_LIMIT),
USIPidPs = plasticity:PFName([MOutput | PFParameters], OrderedSIAcc, SIPidPs, SOutput),
State#neuron_state{si_pidps_current = USIPidPs}
end,
OutputPids = State#neuron_state.output_pids,
Actuator or Neuron .
logr:debug({neuron, forward_output, ok, undefined, []}),
NewState;
handle(weight_backup, State) ->
NewState = case State#neuron_state.heredity_type of
darwinian ->
State#neuron_state{
si_pidps_backup = State#neuron_state.si_pidps_bl,
mi_pidps_backup = State#neuron_state.mi_pidps_current,
pf_backup = State#neuron_state.pf_current
};
lamarckian ->
State#neuron_state{
si_pidps_backup = State#neuron_state.si_pidps_current,
mi_pidps_backup = State#neuron_state.mi_pidps_current,
pf_backup = State#neuron_state.pf_current
}
end,
logr:debug({neuron, weight_backup, ok, undefined, []}),
NewState;
handle(weight_restore, State) ->
NewState = State#neuron_state{
si_pidps_bl = State#neuron_state.si_pidps_backup,
si_pidps_current = State#neuron_state.si_pidps_backup,
mi_pidps_current = State#neuron_state.mi_pidps_backup,
pf_current = State#neuron_state.pf_backup
},
logr:debug({neuron, weight_restore, ok, undefined, []}),
NewState;
handle(weight_perturb, {State, Spread}) ->
PerturbedSIPidPs = perturb_ipidps(Spread, State#neuron_state.si_pidps_backup),
PerturbedMIPidPs = perturb_ipidps(Spread, State#neuron_state.mi_pidps_backup),
PerturbedPF = perturb_pf(Spread, State#neuron_state.pf_backup),
NewState = State#neuron_state{
si_pidps_bl = PerturbedSIPidPs,
si_pidps_current = PerturbedSIPidPs,
mi_pidps_current = PerturbedMIPidPs,
pf_current = PerturbedPF
},
logr:debug({neuron, weight_perturb, ok, undefined, []}),
NewState;
handle(get_backup, {State, ExoselfPid}) ->
NId = State#neuron_state.id,
ExoselfPid ! {self(), NId, State#neuron_state.si_pidps_backup,
State#neuron_state.mi_pidps_backup, State#neuron_state.pf_backup},
logr:debug({neuron, get_backup, ok, undefined, []}).
do_perturb_pf(Spread, {PFName, PFParameters}) ->
UPFParameters = [sat(PFParameter + (rand:uniform() - 0.5) * Spread, -?SAT_LIMIT, ?SAT_LIMIT) ||
PFParameter <- PFParameters],
{PFName, UPFParameters}.
append_ipids(IPidPs) ->
lists:append([IPid || {IPid, _W} <- IPidPs, IPid =/= bias], [ok]).
%%----------------------------------------------------------------------------
@private
%% @doc The perturb_ipidps function calculates the probability with which
%% each neuron in the InputPidPs is chosen to be perturbed. The
%% probability is based on the total number of weights in the
%% InputPidPs list, with the actual mutation probability equating to
%% the inverse of square root of total number of weights.
%% @end
%%----------------------------------------------------------------------------
perturb_ipidps(_Spread, []) ->
[];
perturb_ipidps(Spread, InputPidPs) ->
TotWeights = lists:sum([length(WeightsP) || {_InputPid, WeightsP} <- InputPidPs]),
MP = 1 / math:sqrt(TotWeights),
perturb_ipidps(Spread, MP, InputPidPs, []).
%%----------------------------------------------------------------------------
@private
%% @doc The perturb_ipidps function calculates the probability with which
%% each neuron in the InputPidPs is chosen to be perturbed. The
%% probability is based on the total number of weights in the
%% InputPidPs list, with the actual mutation probability equating to
%% the inverse of square root of total number of weights.
%% @end
%%----------------------------------------------------------------------------
perturb_ipidps(Spread, MP, [{InputPid, WeightsP} | InputPidPs], Acc) ->
UWeightsP = do_perturb_weights_p(Spread, MP, WeightsP, []),
perturb_ipidps(Spread, MP, InputPidPs, [{InputPid, UWeightsP} | Acc]);
perturb_ipidps(_Spread, _MP, [], Acc) ->
lists:reverse(Acc).
%%----------------------------------------------------------------------------
@private
%% @doc The do_perturb_weights_p function goes through each weights block and
%% calls the do_perturb_weights_p to perturb the weights.
%% @end
%%----------------------------------------------------------------------------
do_perturb_weights_p(Spread, MP, [{W, LPs} | Weights], Acc) ->
UW = case rand:uniform() < MP of
true ->
sat((rand:uniform() -0.5) * 2 * Spread + W, -?SAT_LIMIT, ?SAT_LIMIT);
false ->
W
end,
do_perturb_weights_p(Spread, MP, Weights, [{UW, LPs} | Acc]);
do_perturb_weights_p(_Spread, _MP, [], Acc) ->
lists:reverse(Acc).
%%-----------------------------------------------------------------------------
@private
%% @doc The fanout function fans out the Msg to all the Pids in its list.
%% @end
%%-----------------------------------------------------------------------------
fanout([Pid | Pids]) ->
ROSignal = app_config:get_env(ro_signal),
Pid ! {forward, self(), ROSignal},
fanout(Pids);
fanout([])->
true.
%%-----------------------------------------------------------------------------
@private
%% @doc The flush_buffer cleans out the element's inbox.
%% @end
%%-----------------------------------------------------------------------------
flush_buffer() ->
receive
_ ->
flush_buffer()
after 0 ->
done
end.
%%-----------------------------------------------------------------------------
@private
@doc The sat function simply ensures that the is neither less than
%% min or greater than max.
%% @end
%%-----------------------------------------------------------------------------
sat(Val, Limit) ->
sat(Val, -Limit, Limit).
sat(Val, Min, _Max) when Val < Min ->
Min;
sat(Val, _Min, Max) when Val > Max ->
Max;
sat(Val, _Min, _Max) ->
Val. | null | https://raw.githubusercontent.com/Rober-t/apxr_run/9c62ab028af7ff3768ffe3f27b8eef1799540f05/src/agent_mgr/neuron.erl | erlang |
The original release of this source code was introduced and explained
The original release of this source code was introduced and explained
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
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.
% % % % % % % % % % % % % % % % % % % % % % % % % %
----------------------------------------------------------------------------
@doc The neuron is a signal processing element. It accepts signals,
accumulates them into an ordered vector, then processes this input
vector to produce an output, and finally passes the output to other
elements it is connected to. The neuron never interacts with the
environment directly, and even when it does receive signals and
produces output signals, it does not know whether these input signals
are coming from sensors or neurons, or whether it is sending its
output signals to other neurons or actuators. All the neuron does is
have a list of of input Pids from which it expects to receive
signals, a list of output Pids to which the neuron sends its output,
a weight list correlated with the input Pids, and an activation
function it applies to the dot product of the input vector and its
weight vector. The neuron waits until it receives all the input
signals, and then passes the output onwards.
NOTE: The neuron is the basic processing element, the basic processing
node in the neural network system. The neurons in this system we’ve
created are more general than those used by others. They can easily
use various activation functions, and to accept and output vectors.
Because we can use anything for the activation function, including
logical operators, the neurons are really just processing nodes. In
referring to these processing elements as neurons.
@end
----------------------------------------------------------------------------
API
Callbacks
============================================================================
Types
============================================================================
processing dynamics.
after perturbation, before the synaptic weights are affected by the
neuron's plasticity function (bl -> before learning). When a neuron is
requested to to perturb its synaptic weights, right after the weights are
a chance to modify the synaptic weights. Afterwards, the neuron can process
the input signals using its input_pids_current, and its learning rule can
affect the input_pids_current list. But input_pids_bl will remain unchanged.
When a neuron is sent the weight_backup message, it is here that
heredity_type plays its role. When its << darwinian >>, the neuron saves the
input_pids_bl to input_pids_backup, instead of the input_pids_current which
could have been modified by some learning rule by this point. On the other
input_pids_current to input_pids_backup. The input_pids_current represents
the synaptic weights that could have been updated if the neuron allows for
plasticity, and thus the input_pids_backup will then contain not the initial
state of the synaptic weight list with which the neuron started, but the
state of the synaptic weights after the the neuron has experienced,
processed, and had its synaptic weights modified by its learning rule.
============================================================================
Configuration
============================================================================
============================================================================
API
============================================================================
-----------------------------------------------------------------------------
spawned it and calls init to initialize.
@end
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
@end
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
@doc Initializes the neuron setting it to its initial state.
@end
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
that it's connected from, taking the dot product of the input and
weight vectors, and then adding it to the accumulator. Once all the
dot product to which the neuron then adds the bias and executes the
activation function. After fanning out the output signal, the neuron
again returns to waiting for incoming signals.
@end
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
@doc weight_backup The signal from the exoself, which tells the neuron
its current synaptic weight combination, and thus it should save this
combination achieved thus far. The message is sent if after the weight
@end
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
@doc weight_restore This message is sent from the exoself, and it tells
worse than it did with its previous synaptic weight combinations.
@end
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
@doc weight_perturb Uses the Spread value for the purpose of generating
synaptic weight perturbations.
@end
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
@doc reset_prep This is message is sent after a single evaluation is
completed, and the exoself wishes to reset all the neurons to their
original states, with empty inboxes. Once a neuron receives this
message, it goes into a reset_prep state, flushes its buffer/inbox, and
list), and then finally drops back into its main receive loop.
@end
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
@doc get_backup neuron sends back to the exoself its last best synaptic
weight combination, stored as the MInputPids list.
@end
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
@doc perturb_pf perturbs the plasticity function.
@end
----------------------------------------------------------------------------
-----------------------------------------------------------------------------
@doc The perturb_weights_p function is the function that actually goes
through each weight block, and perturbs each weight with a
probability of MP. If the weight is chosen to be perturbed, the
perturbation intensity is chosen uniformly between -Spread and
Spread.
@end
-----------------------------------------------------------------------------
============================================================================
Callbacks
============================================================================
-----------------------------------------------------------------------------
function is called by the new process to initialize.
@end
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
@doc During initialization the neuron sends out the default forward signals
to any elements in its ro_ids list, if any.
@end
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
@doc Receive and handle messages.
@end
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
@doc This function is called to terminate the process. It performs
any necessary cleaning up before exiting with the << Reason >>
parameter that it was called with.
@end
-----------------------------------------------------------------------------
============================================================================
============================================================================
----------------------------------------------------------------------------
@doc The perturb_ipidps function calculates the probability with which
each neuron in the InputPidPs is chosen to be perturbed. The
probability is based on the total number of weights in the
InputPidPs list, with the actual mutation probability equating to
the inverse of square root of total number of weights.
@end
----------------------------------------------------------------------------
----------------------------------------------------------------------------
@doc The perturb_ipidps function calculates the probability with which
each neuron in the InputPidPs is chosen to be perturbed. The
probability is based on the total number of weights in the
InputPidPs list, with the actual mutation probability equating to
the inverse of square root of total number of weights.
@end
----------------------------------------------------------------------------
----------------------------------------------------------------------------
@doc The do_perturb_weights_p function goes through each weights block and
calls the do_perturb_weights_p to perturb the weights.
@end
----------------------------------------------------------------------------
-----------------------------------------------------------------------------
@doc The fanout function fans out the Msg to all the Pids in its list.
@end
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
@doc The flush_buffer cleans out the element's inbox.
@end
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
min or greater than max.
@end
----------------------------------------------------------------------------- | Copyright ( C ) 2009 by , DXNN Research Group ,
in a book ( available for purchase on Amazon ) by :
Handbook of Neuroevolution Through Erlang . Springer 2012 ,
print ISBN : 978 - 1 - 4614 - 4462 - 6 ebook ISBN : 978 - 1 - 4614 - 4463 - 6 .
in a book ( available for purchase on Amazon ) by :
Handbook of Neuroevolution Through Erlang . Springer 2012 ,
print ISBN : 978 - 1 - 4614 - 4462 - 6 ebook ISBN : 978 - 1 - 4614 - 4463 - 6 .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
Modified Copyright ( C ) 2018 ApproximateReality
some sense , this system is not a Topology and Weight Evolving
Artificial Neural Network , but a Topology and Parameter Evolving
Universal Learning Network ( TPEULN ) . Nevertheless , we will continue
-module(neuron).
Start / Stop
-export([
start/2,
stop/2
]).
-export([
init_phase2/12,
forward/3,
weight_backup/2,
weight_restore/2,
weight_perturb/3,
reset_prep/2,
get_backup/2,
perturb_pf/2,
perturb_weights_p/4
]).
-export([
init/1,
loop/1, loop/6,
handle/2,
terminate/1
]).
Xref
-ignore_xref([
loop/1, loop/6,
handle/2,
perturb_pf/2,
perturb_weights_p/4,
terminate/1
]).
-record(neuron_state, {
id :: models:neuron_id(),
cx_pid :: pid(),
af :: models:neural_af(),
aggr_f :: atom(),
heredity_type :: darwinian | lamarckian,
si_pids :: [pid()] | [ok],
The input_pids that are currently effective and represent the neuron 's
si_pidps_current :: [{pid(), [float()]}],
A second input_pids list , which represents the state of input_pids right
perturbed , we want to save this new input_pids list , before plasticity gets
si_pidps_bl :: [{pid(), [float()]}],
hand , when the heredity_type is < < > > , the neuron saves the
si_pidps_backup :: [{pid(), [float()]}],
mi_pids :: [pid()] | [ok],
mi_pidps_current :: [{pid(), [float()]}],
mi_pidps_backup :: [{pid(), [float()]}],
pf_current :: {models:neural_pfn(), [float()]},
pf_backup :: {models:neural_pfn(), [float()]},
output_pids :: [pid()],
ro_pids :: [pid()]
}).
-type state() :: #neuron_state{}.
-define(SAT_LIMIT, math:pi() * 2).
@doc Spawns a Neuron process belonging to the process that
-spec start(node(), pid()) -> pid().
start(Node, ExoselfPid) ->
spawn_link(Node, ?MODULE, init, [ExoselfPid]).
@doc Terminates neuron .
-spec stop(pid(), pid()) -> ok.
stop(Pid, ExoselfPid) ->
Pid ! {ExoselfPid, stop},
ok.
-spec init_phase2(pid(), pid(), models:neuron_id(), pid(), models:neural_af(),
{models:neural_pfn(), [float()]}, atom(), darwinian | lamarckian, [tuple()], [tuple()], [pid()],
[pid()]) -> ok.
init_phase2(Pid, ExoselfPid, Id, CxPid, AF, PF, AggrF, HeredityType, SIPidPs, MIPidPs, OutputPids,
ROPids) ->
Pid ! {handle, {init_phase2, ExoselfPid, Id, CxPid, AF, PF, AggrF, HeredityType, SIPidPs,
MIPidPs, OutputPids, ROPids}},
ok.
@doc The Neuron process waits for vector signals from all the processes
signals from InputPids are received , the accumulator contains the
-spec forward(pid(), pid(), float()) -> ok.
forward(Pid, IPid, Input) ->
Pid ! {handle, {forward, IPid, Input}},
ok.
that the NN system performs best when this particular neuron is using
synaptic weight list as , and that it is the best weight
perturbation , the NN 's evaluation achieves a higher fitness than when
the neurons of this NN used their previous synaptic weights .
-spec weight_backup(pid(), pid()) -> ok.
weight_backup(Pid, ExoselfPid) ->
Pid ! {handle, {ExoselfPid, weight_backup}},
ok.
the neuron that it should restore its synaptic weight list to the one
previously used , saved as . This message is usually sent if
after the weight perturbation , the NN based agent 's evaluation performs
-spec weight_restore(pid(), pid()) -> ok.
weight_restore(Pid, ExoselfPid) ->
Pid ! {handle, {ExoselfPid, weight_restore}},
ok.
-spec weight_perturb(pid(), pid(), integer()) -> ok.
weight_perturb(Pid, ExoselfPid, Spread) ->
Pid ! {handle, {ExoselfPid, weight_perturb, Spread}},
ok.
then awaits for the { ExoselfPid , reset } signal . When the neuron receives
the { ExoselfPid , reset } message , it again sends out the default output
message to all its recurrent connections ( Ids stored in the ro_ids
-spec reset_prep(pid(), pid()) -> ok.
reset_prep(Pid, ExoselfPid) ->
Pid ! {handle, {ExoselfPid, reset_prep}},
ok.
-spec get_backup(pid(), pid()) -> ok.
get_backup(Pid, ExoselfPid) ->
Pid ! {handle, {ExoselfPid, get_backup}},
ok.
-spec perturb_pf(float(), {atom(), [float()]}) -> {atom(), [float()]}.
perturb_pf(Spread, {PFName, PFParameters}) ->
do_perturb_pf(Spread, {PFName, PFParameters}).
-spec perturb_weights_p(float(), float(), [{float(), [float()]}], [float()]) -> [float()].
perturb_weights_p(Spread, MP, [{W, LPs} | Weights], Acc) ->
do_perturb_weights_p(Spread, MP, [{W, LPs} | Weights], Acc).
@private
@doc Whenever a Neuron process is started via the start function this
-spec init(pid()) -> no_return().
init(ExoselfPid) ->
utils:random_seed(),
logr:debug({neuron, init, ok, undefined, []}),
loop(ExoselfPid).
@private
-spec loop(pid()) -> no_return().
loop(ExoselfPid) ->
receive
{handle, {init_phase2, ExoselfPid, Id, CxPid, AF, PF, AggrF, HeredityType, SIPidPs, MIPidPs,
OutputPids, ROPids}} ->
SIPids = append_ipids(SIPidPs),
MIPids = append_ipids(MIPidPs),
NewState = handle(init_phase2, {Id, CxPid, AF, PF, AggrF, HeredityType, SIPidPs, MIPidPs,
OutputPids, ROPids, SIPids, MIPids}),
loop(NewState, ExoselfPid, SIPids, MIPids, [], [])
end.
@private
-spec loop(state(), pid(), [ok] | [pid()], [ok] | [pid()], [{pid(), [float()]}] | [],
[{pid(), [float()]}] | []) -> no_return().
loop(State, ExoselfPid, [ok], [ok], SIAcc, MIAcc) ->
NewState = handle(forward_output, {SIAcc, MIAcc, State}),
SIPids = NewState#neuron_state.si_pids,
MIPids = NewState#neuron_state.mi_pids,
loop(NewState, ExoselfPid, SIPids, MIPids, [], []);
loop(State, ExoselfPid, [SIPid | SIPids], [MIPid | MIPids], SIAcc, MIAcc) ->
receive
{handle, {forward, SIPid, Input}} ->
logr:debug({neuron, msg, ok, "SIPid forward message received", [SIPid]}),
loop(State, ExoselfPid, SIPids, [MIPid | MIPids], [{SIPid, Input} | SIAcc], MIAcc);
{handle, {forward, MIPid, Input}} ->
logr:debug({neuron, msg, ok, "MIPid forward message received", [MIPid]}),
loop(State, ExoselfPid, [SIPid | SIPids], MIPids, SIAcc, [{MIPid, Input} | MIAcc]);
{forward, SIPid, Input} ->
logr:debug({neuron, msg, ok, "SIPid forward message received", [SIPid]}),
loop(State, ExoselfPid, SIPids, [MIPid | MIPids], [{SIPid, Input} | SIAcc], MIAcc);
{forward, MIPid, Input} ->
logr:debug({neuron, msg, ok, "MIPid forward message received", [MIPid]}),
loop(State, ExoselfPid, [SIPid | SIPids], MIPids, SIAcc, [{MIPid, Input} | MIAcc]);
{handle, {ExoselfPid, weight_backup}} ->
NewState = handle(weight_backup, State),
loop(NewState, ExoselfPid, [SIPid | SIPids], [MIPid | MIPids], SIAcc, MIAcc);
{handle, {ExoselfPid, weight_restore}} ->
NewState = handle(weight_restore, State),
loop(NewState, ExoselfPid, [SIPid | SIPids], [MIPid | MIPids], SIAcc, MIAcc);
{handle, {ExoselfPid, weight_perturb, Spread}} ->
NewState = handle(weight_perturb, {State, Spread}),
loop(NewState, ExoselfPid, [SIPid | SIPids], [MIPid | MIPids], SIAcc, MIAcc);
{handle, {ExoselfPid, reset_prep}} ->
flush_buffer(),
ExoselfPid ! {self(), ready},
ROPids = State#neuron_state.ro_pids,
receive
{ExoselfPid, reset} ->
logr:debug({neuron, reset, ok, "Fanning out ROPids", [ROPids]}),
fanout(ROPids);
{ExoselfPid, stop} ->
terminate(normal)
end,
loop(State, ExoselfPid, State#neuron_state.si_pids, State#neuron_state.mi_pids, [], []);
{handle, {ExoselfPid, get_backup}} ->
handle(get_backup, {State, ExoselfPid}),
loop(State, ExoselfPid, [SIPid | SIPids], [MIPid | MIPids], SIAcc, MIAcc);
{ExoselfPid, stop} ->
terminate(normal)
end.
@private
-spec terminate(atom()) -> ok.
terminate(Reason) ->
logr:debug({neuron, terminate, ok, undefined, [Reason]}),
exit(Reason).
Internal functions
handle(init_phase2, {Id, CxPid, AF, PF, AggrF, HeredityType, SIPidPs, MIPidPs, OutputPids, ROPids,
SIPids, MIPids}) ->
fanout(ROPids),
logr:debug({neuron, init2, ok, undefined, []}),
State = #neuron_state{
id = Id,
cx_pid = CxPid,
af = AF,
pf_current = PF,
pf_backup = PF,
aggr_f = AggrF,
heredity_type = HeredityType,
si_pids = SIPids,
si_pidps_bl = SIPidPs,
si_pidps_current = SIPidPs,
si_pidps_backup = SIPidPs,
mi_pids = MIPids,
mi_pidps_current = MIPidPs,
mi_pidps_backup = MIPidPs,
output_pids = OutputPids,
ro_pids = ROPids
},
State;
handle(forward_output, {SIAcc, MIAcc, State}) ->
OutputSatLimit = app_config:get_env(output_sat_limit),
{PFName, PFParameters} = State#neuron_state.pf_current,
AF = State#neuron_state.af,
AggrF = State#neuron_state.aggr_f,
OrderedSIAcc = lists:reverse(SIAcc),
SIPidPs = State#neuron_state.si_pidps_current,
SOutput = [sat(functions:AF(signal_aggregator:AggrF(OrderedSIAcc, SIPidPs)), OutputSatLimit)],
NewState = case PFName of
none ->
State;
_ ->
OrderedMIAcc = lists:reverse(MIAcc),
MIPidPs = State#neuron_state.mi_pidps_current,
MAggregationProduct = signal_aggregator:dot_product(OrderedMIAcc, MIPidPs),
MOutput = sat(functions:tanh(MAggregationProduct), ?SAT_LIMIT),
USIPidPs = plasticity:PFName([MOutput | PFParameters], OrderedSIAcc, SIPidPs, SOutput),
State#neuron_state{si_pidps_current = USIPidPs}
end,
OutputPids = State#neuron_state.output_pids,
Actuator or Neuron .
logr:debug({neuron, forward_output, ok, undefined, []}),
NewState;
handle(weight_backup, State) ->
NewState = case State#neuron_state.heredity_type of
darwinian ->
State#neuron_state{
si_pidps_backup = State#neuron_state.si_pidps_bl,
mi_pidps_backup = State#neuron_state.mi_pidps_current,
pf_backup = State#neuron_state.pf_current
};
lamarckian ->
State#neuron_state{
si_pidps_backup = State#neuron_state.si_pidps_current,
mi_pidps_backup = State#neuron_state.mi_pidps_current,
pf_backup = State#neuron_state.pf_current
}
end,
logr:debug({neuron, weight_backup, ok, undefined, []}),
NewState;
handle(weight_restore, State) ->
NewState = State#neuron_state{
si_pidps_bl = State#neuron_state.si_pidps_backup,
si_pidps_current = State#neuron_state.si_pidps_backup,
mi_pidps_current = State#neuron_state.mi_pidps_backup,
pf_current = State#neuron_state.pf_backup
},
logr:debug({neuron, weight_restore, ok, undefined, []}),
NewState;
handle(weight_perturb, {State, Spread}) ->
PerturbedSIPidPs = perturb_ipidps(Spread, State#neuron_state.si_pidps_backup),
PerturbedMIPidPs = perturb_ipidps(Spread, State#neuron_state.mi_pidps_backup),
PerturbedPF = perturb_pf(Spread, State#neuron_state.pf_backup),
NewState = State#neuron_state{
si_pidps_bl = PerturbedSIPidPs,
si_pidps_current = PerturbedSIPidPs,
mi_pidps_current = PerturbedMIPidPs,
pf_current = PerturbedPF
},
logr:debug({neuron, weight_perturb, ok, undefined, []}),
NewState;
handle(get_backup, {State, ExoselfPid}) ->
NId = State#neuron_state.id,
ExoselfPid ! {self(), NId, State#neuron_state.si_pidps_backup,
State#neuron_state.mi_pidps_backup, State#neuron_state.pf_backup},
logr:debug({neuron, get_backup, ok, undefined, []}).
do_perturb_pf(Spread, {PFName, PFParameters}) ->
UPFParameters = [sat(PFParameter + (rand:uniform() - 0.5) * Spread, -?SAT_LIMIT, ?SAT_LIMIT) ||
PFParameter <- PFParameters],
{PFName, UPFParameters}.
append_ipids(IPidPs) ->
lists:append([IPid || {IPid, _W} <- IPidPs, IPid =/= bias], [ok]).
@private
perturb_ipidps(_Spread, []) ->
[];
perturb_ipidps(Spread, InputPidPs) ->
TotWeights = lists:sum([length(WeightsP) || {_InputPid, WeightsP} <- InputPidPs]),
MP = 1 / math:sqrt(TotWeights),
perturb_ipidps(Spread, MP, InputPidPs, []).
@private
perturb_ipidps(Spread, MP, [{InputPid, WeightsP} | InputPidPs], Acc) ->
UWeightsP = do_perturb_weights_p(Spread, MP, WeightsP, []),
perturb_ipidps(Spread, MP, InputPidPs, [{InputPid, UWeightsP} | Acc]);
perturb_ipidps(_Spread, _MP, [], Acc) ->
lists:reverse(Acc).
@private
do_perturb_weights_p(Spread, MP, [{W, LPs} | Weights], Acc) ->
UW = case rand:uniform() < MP of
true ->
sat((rand:uniform() -0.5) * 2 * Spread + W, -?SAT_LIMIT, ?SAT_LIMIT);
false ->
W
end,
do_perturb_weights_p(Spread, MP, Weights, [{UW, LPs} | Acc]);
do_perturb_weights_p(_Spread, _MP, [], Acc) ->
lists:reverse(Acc).
@private
fanout([Pid | Pids]) ->
ROSignal = app_config:get_env(ro_signal),
Pid ! {forward, self(), ROSignal},
fanout(Pids);
fanout([])->
true.
@private
flush_buffer() ->
receive
_ ->
flush_buffer()
after 0 ->
done
end.
@private
@doc The sat function simply ensures that the is neither less than
sat(Val, Limit) ->
sat(Val, -Limit, Limit).
sat(Val, Min, _Max) when Val < Min ->
Min;
sat(Val, _Min, Max) when Val > Max ->
Max;
sat(Val, _Min, _Max) ->
Val. |
1c9a4275bb00ad37f8855ce638cdb88b472bfd6daf082753966ca09b62fe97f5 | rtoy/ansi-cl-tests | get-internal-time.lsp | ;-*- Mode: Lisp -*-
Author :
Created : Sun May 8 20:28:21 2005
Contains : Tests of GET - INTERNAL - REAL - TIME , GET - INTERNAL - RUN - TIME
(in-package :cl-test)
(deftest get-internal-real-time.1
(notnot-mv (typep (multiple-value-list (get-internal-real-time)) '(cons unsigned-byte null)))
t)
(deftest get-internal-real-time.2
(funcall
(compile
nil
'(lambda ()
(let ((prev (get-internal-real-time)))
(loop for next = (get-internal-real-time)
repeat 100000
do (assert (>= next prev))
do (setf prev next))))))
nil)
(deftest get-internal-real-time.error.1
(signals-error (get-internal-real-time nil) program-error)
t)
(deftest get-internal-real-time.error.2
(signals-error (get-internal-real-time :allow-other-keys t) program-error)
t)
;;;;;
(deftest get-internal-run-time.1
(notnot-mv (typep (multiple-value-list (get-internal-run-time)) '(cons unsigned-byte null)))
t)
(deftest get-internal-run-time.2
(funcall
(compile
nil
'(lambda ()
(let ((prev (get-internal-run-time)))
(loop for next = (get-internal-run-time)
repeat 100000
do (assert (>= next prev))
do (setf prev next))))))
nil)
(deftest get-internal-run-time.error.1
(signals-error (get-internal-run-time nil) program-error)
t)
(deftest get-internal-run-time.error.2
(signals-error (get-internal-run-time :allow-other-keys t) program-error)
t)
;;;
(deftest internal-time-units-per-second.1
(notnot-mv (constantp 'internal-time-units-per-second))
t)
(deftest internal-time-units-per-second.2
(notnot-mv (typep internal-time-units-per-second '(integer 1)))
t)
| null | https://raw.githubusercontent.com/rtoy/ansi-cl-tests/9708f3977220c46def29f43bb237e97d62033c1d/get-internal-time.lsp | lisp | -*- Mode: Lisp -*-
| Author :
Created : Sun May 8 20:28:21 2005
Contains : Tests of GET - INTERNAL - REAL - TIME , GET - INTERNAL - RUN - TIME
(in-package :cl-test)
(deftest get-internal-real-time.1
(notnot-mv (typep (multiple-value-list (get-internal-real-time)) '(cons unsigned-byte null)))
t)
(deftest get-internal-real-time.2
(funcall
(compile
nil
'(lambda ()
(let ((prev (get-internal-real-time)))
(loop for next = (get-internal-real-time)
repeat 100000
do (assert (>= next prev))
do (setf prev next))))))
nil)
(deftest get-internal-real-time.error.1
(signals-error (get-internal-real-time nil) program-error)
t)
(deftest get-internal-real-time.error.2
(signals-error (get-internal-real-time :allow-other-keys t) program-error)
t)
(deftest get-internal-run-time.1
(notnot-mv (typep (multiple-value-list (get-internal-run-time)) '(cons unsigned-byte null)))
t)
(deftest get-internal-run-time.2
(funcall
(compile
nil
'(lambda ()
(let ((prev (get-internal-run-time)))
(loop for next = (get-internal-run-time)
repeat 100000
do (assert (>= next prev))
do (setf prev next))))))
nil)
(deftest get-internal-run-time.error.1
(signals-error (get-internal-run-time nil) program-error)
t)
(deftest get-internal-run-time.error.2
(signals-error (get-internal-run-time :allow-other-keys t) program-error)
t)
(deftest internal-time-units-per-second.1
(notnot-mv (constantp 'internal-time-units-per-second))
t)
(deftest internal-time-units-per-second.2
(notnot-mv (typep internal-time-units-per-second '(integer 1)))
t)
|
4043ccbd803896497f4b2ad34a8dff4ca0c77e3b72c839884951f20feff4ebe3 | shonfeder/um-abt | abt.mli | Copyright ( c ) 2021 Shon Feder
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
, 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 .
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. *)
* { 1 Overview }
[ um - abt ] is a library for constructing and manipulating the abstract syntax
of languages that use { { ! module : Var } variables } .
[ um - abt ] provides unifiable abstract binding trees ( UABTs ) . An { b abstract
binding tree } ( ABT ) is an { i abstract syntax tree } ( AST ) , enriched with
constructs to manage variable binding and scope .
[ um - abt ] extends ABTs with support for { { ! module : Make . Unification } nominal
unification } ( unificaiton modulo ɑ - equivalence ) .
{ 1 Example }
A succinct example of the typical use of this library can be seen in the
following implementation of the untyped λ - calculus .
Define your language 's operators :
{ [
( * Define the usual operators , but without the variables , since we get those free
[um-abt] is a library for constructing and manipulating the abstract syntax
of languages that use {{!module:Var} variables}.
[um-abt] provides unifiable abstract binding trees (UABTs). An {b abstract
binding tree} (ABT) is an {i abstract syntax tree} (AST), enriched with
constructs to manage variable binding and scope.
[um-abt] extends ABTs with support for {{!module:Make.Unification} nominal
unification} (unificaiton modulo ɑ-equivalence).
{1 Example}
A succinct example of the typical use of this library can be seen in the
following implementation of the untyped λ-calculus.
Define your language's operators:
{[
(* Define the usual operators, but without the variables, since we get those free *)
module O = struct
type 'a t =
| App of 'a * 'a
| Lam of 'a
[@@deriving eq, map, fold]
let to_string : string t -> string = function
| App (l, m) -> Printf.sprintf "(%s %s)" l m
| Lam abs -> Printf.sprintf "(λ%s)" abs
end
]}
(Note the use of {{:-ppx/ppx_deriving} ppx_deriving}
to derive most values automatically.)
Generate your the ABT representing your syntax, and define combinators to
easily and safely construct terms of your lanugage construct:
{[
(* Generate the syntax, which will include a type [t] of the ABTs over the operators **)
open Abt.Make (O)
(* Define some constructors to ensure correct construction *)
let app m n : t =
[ op ] lifts an operator into an ABT
op (App (m, n))
let lam x m : t =
(* ["x" #. scope] binds all free variables named "x" in the [scope] *)
op (Lam (x #. m))
]}
Define the dynamics of your language (here using the variable substitution
function [subst], provided by the generated syntax):
{[
let rec eval : t -> t =
fun t ->
match t with
| Opr (App (m, n)) -> apply (eval m) (eval n)
(* No other terms can be evaluated *)
| _ -> t
and apply : t -> t -> t =
fun m n ->
match m with
| Bnd (bnd, t) -> subst bnd ~value:n t
| Opr (Lam bnd) -> eval (apply bnd n)
(* otherwise the application can't be evaluated *)
| _ -> app m n
]}
Enjoy unification and ɑ-equivalence:
{[
(* An example term *)
let k = lam "x" (lam "y" x)
(* The generated [Syntax] module includes a [Unification] submodule
- the [=?=] operator checks for unifiability
- the [=.=] operator gives an [Ok] result with the unified term, if its operands unify,
or else an [Error] indicating why the unification failed
- the [unify] function is like [=.=], but it also gives the substitution used to produce
a unified term *)
let ((=?=), (=.=), unify) = Unification.((=?=), (=.=), unify) in
(* A free variable will unify with anything *)
assert (v "X" =?= s);
(* Unification is modulo ɑ-equivalence *)
assert (lam "y" (lam "x" y) =?= lam "x" (lam "y" x));
(* Here we unify the free variable "M" with the body of the [k] combinator,
note that the nominal unification is modulo bound variables: *)
let unified_term = (lam "z" (v "M") =.= k) |> Result.get_ok in
assert (to_string unified_term = "(λz.(λy.z))");
]}
*)
* { 1 Modules and interfaces }
(** The interface for a module that defines the operators of a language *)
module type Operator = sig
type 'a t [@@deriving sexp]
* The type of the operator , usually represented as a sum type .
Each operator should be have the form
{ [
of ' a * ' a * ... * ' a
] }
Where the free variables [ ' a ] are arguments to the operator [ Foo ] .
Each operator should be have the form
{[
Foo of 'a * 'a * ... * 'a
]}
Where the free variables ['a] are arguments to the operator [Foo]. *)
val map : ('a -> 'b) -> 'a t -> 'b t
val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool
val fold : ('a -> 'b -> 'a) -> 'a -> 'b t -> 'a
val to_string : string t -> string
end
* Variables , named by strings , which can be bound to a { ! module : Var . Binding } or
left free .
left free. *)
module Var : sig
(** A binding is an immutable reference, to which a bound can refer. *)
module Binding : sig
include Map.OrderedType
val equal : t -> t -> bool
val v : string -> t
(** [binding s] is a new binding for variables named [s] *)
val name : t -> string
end
type t = private
| Free of string
| Bound of Binding.t (** A varibale of type [t] is either free or bound. *)
[@@deriving sexp]
val compare : t -> t -> int
* Bound variables are equal if they are have the same binding , free
variables are greater than bound variables , and variables are otherwise
compared lexigraphically by name .
Specifically ,
[ compare a b ] is [ 0 ] iff
- [ is_free a & & is_free b ] and [ name a = name b ]
- [ is_bound a & & is_bound b ] and both [ a ] and [ b ] are bound to the same
{ ! type : binding } by way of { ! : bind } .
[ compare a b ] is [ String.compare ( name a ) ( name b ) ] if
[ is_free a & & is_free b ] or [ is_bound a & & is_bound b ] .
[ compare a b ] is -1 if [ is_bound a ] and [ is_free b ] or 1 if [ is_free a ]
and [ is_bound b ]
variables are greater than bound variables, and variables are otherwise
compared lexigraphically by name.
Specifically,
[compare a b] is [0] iff
- [is_free a && is_free b] and [name a = name b]
- [is_bound a && is_bound b] and both [a] and [b] are bound to the same
{!type:binding} by way of {!val:bind}.
[compare a b] is [String.compare (name a) (name b)] if
[is_free a && is_free b] or [is_bound a && is_bound b].
[compare a b] is -1 if [is_bound a] and [is_free b] or 1 if [is_free a]
and [is_bound b] *)
val equal : t -> t -> bool
* [ equal a b ] is [ true ] iff
- [ is_free a & & is_free b ] and [ name a = name b ]
- [ is_bound a & & is_bound b ] and both [ a ] and [ b ] are bound to the same
{ ! type : binding } by way of { ! : bind } .
- [is_free a && is_free b] and [name a = name b]
- [is_bound a && is_bound b] and both [a] and [b] are bound to the same
{!type:binding} by way of {!val:bind}. *)
val is_free : t -> bool
val is_bound : t -> bool
val v : string -> t
val to_string : t -> string
val to_string_debug : t -> string
(** Includes the unique ID of any bound variables *)
val name : t -> string
(** [name v] is [to_string v] *)
val bind : t -> Binding.t -> t option
* [ bind v bnd ] is [ Some var ] when [ is_free v ] and [ name v = Binding.name ] ,
where [ var ] is a new variable with the same name but bound to [ bnd ] .
Otherwise , it is [ None ] .
See { ! : equal } .
where [var] is a new variable with the same name but bound to [bnd].
Otherwise, it is [None].
See {!val:equal}. *)
val is_bound_to : t -> Binding.t -> bool
* [ is_bound_to v bnd ] is [ true ] if [ v ] is bound to [ bnd ] , via { ! : bind }
val of_binding : Binding.t -> t
(** [of_binding bnd] is a variable bound to [bnd] *)
val to_binding : t -> Binding.t option
* [ to_binding v ] is [ Some bnd ] iff [ v ] is bound to [ bnd ] via { ! : bind } .
Otherwise it is [ None ] .
Otherwise it is [None]. *)
module Set : Set.S with type elt = t
module Map : Map.S with type key = t
end
(** The interface of the family of UABTs representings a syntax *)
module type Syntax = sig
module Op : Operator
* The type of ABT 's constructed from the operators defind in [ O ]
type t = private
| Var of Var.t (** Variables *)
| Bnd of Var.Binding.t * t (** Scoped variable binding *)
| Opr of t Op.t (** Operators specified in {!Op} *)
[@@deriving sexp]
val bind : Var.Binding.t -> t -> t
* [ bind bnd t ] is a branch of the ABT , in which any free variables in [ t ]
matching the name of [ bnd ] are bound to [ bnd ] .
matching the name of [bnd] are bound to [bnd]. *)
val of_var : Var.t -> t
* [ of_var v ] is a leaf in the ABT consisting of the variable [ v ]
val v : string -> t
* [ v x ] is a leaf in the ABT consisting of a variable named [ x ]
val op : t Op.t -> t
* [ op o ] is a branch in the ABT consisting of the operator [ o ]
val ( #. ) : string -> t -> t
(** [x #. t] is a new abt obtained by binding all {i free} variables named
[x] in [t]
Note that this does {b not} substitute variables for a {i value}, (for
which, see {!subst}). This only binds the free variables within the scope
of an abstraction that ranges over the given (sub) abt [t]. *)
val subst : Var.Binding.t -> value:t -> t -> t
* [ subst bnd ~value t ] is a new ABT obtained by substituting [ value ] for
all variables bound to [ bnd ] .
all variables bound to [bnd]. *)
val subst_var : string -> value:t -> t -> t
* [ subst_var name ~value t ] is a new abt obtained by substituting [ value ] for
the outermost scope of variables bound to [ name ] in [ t ]
the outermost scope of variables bound to [name] in [t] *)
val to_sexp : t -> Sexplib.Sexp.t
(** [to_sexp t] is the representation of [t] as an s-expression *)
val of_sexp : Sexplib.Sexp.t -> t
(** [of_sexp s] is Abt represented by the s-expression [s] *)
val to_string : t -> string
(** [to_string t] is the representation of [t] as a string *)
val equal : t -> t -> bool
(** [equal t t'] is [true] when [t] and [t'] are alpha equivalent and [false] otherwise *)
val case :
var:(Var.t -> 'a)
-> bnd:(Var.Binding.t * t -> 'a)
-> opr:(t Op.t -> 'a)
-> t
-> 'a
* Case analysis for eleminating ABTs
This is an alternative to using pattern - based elimination .
@param var function to apply to variables
@param bnd function to apply to bindings
@param opr function to apply to operators
This is an alternative to using pattern-based elimination.
@param var function to apply to variables
@param bnd function to apply to bindings
@param opr function to apply to operators *)
val subterms : t -> t list
(** [subterms t] is a list of all the subterms in [t], including [t] itself *)
val free_vars : t -> Var.Set.t
(** [free_vars t] is the set of variables that are free in in [t] *)
val is_closed : t -> bool
(** [is_closed t] if [true] if there are no free variables in [t], otherwise false *)
module Unification : sig
module Subst : sig
type term = t
* An alias for the type of the ABT for reference in the context of the substitution
type t
(** Substitutions mapping free variables to terms *)
val find : Var.t -> t -> term option
(** [find v s] is [Some term] if [v] is bound to [term] in the
substitution [s], otherwise it is [None]*)
val bindings : t -> (Var.t * term) list
(** [bindings s] is a list of all the bindings in [s] *)
val to_string : t -> string
end
type error =
[ `Unification of Var.t option * t * t
| `Occurs of Var.t * t
| `Cycle of Subst.t
]
(** Errors returned when unification fails *)
val unify : t -> t -> (t * Subst.t, error) Result.t
(** [unify a b] is [Ok (union, substitution)] when [a] and [b] can be
unified into the term [union] and [substitution] is the most general
unifier. Otherwise it is [Error err)], for which, see {!type:error} *)
val ( =.= ) : t -> t -> (t, error) Result.t
* [ a = .= b ] is [ unify a b |
val ( =?= ) : t -> t -> bool
(** [a =?= b] is [true] iff [a =.= b] is an [Ok _] value *)
end
end
* [ Make ( Op ) ] is a module for constructing and manipulating the
{ ! module : Syntax } of a language with { ! module : Operator}s defined by [ Op ] .
{!module:Syntax} of a language with {!module:Operator}s defined by [Op]. *)
module Make (Op : Operator) : Syntax with module Op = Op
| null | https://raw.githubusercontent.com/shonfeder/um-abt/2b3860b8f9217b04e7cb0645ede7726988c3735b/lib/abt.mli | ocaml | Define the usual operators, but without the variables, since we get those free
Generate the syntax, which will include a type [t] of the ABTs over the operators *
Define some constructors to ensure correct construction
["x" #. scope] binds all free variables named "x" in the [scope]
No other terms can be evaluated
otherwise the application can't be evaluated
An example term
The generated [Syntax] module includes a [Unification] submodule
- the [=?=] operator checks for unifiability
- the [=.=] operator gives an [Ok] result with the unified term, if its operands unify,
or else an [Error] indicating why the unification failed
- the [unify] function is like [=.=], but it also gives the substitution used to produce
a unified term
A free variable will unify with anything
Unification is modulo ɑ-equivalence
Here we unify the free variable "M" with the body of the [k] combinator,
note that the nominal unification is modulo bound variables:
* The interface for a module that defines the operators of a language
* A binding is an immutable reference, to which a bound can refer.
* [binding s] is a new binding for variables named [s]
* A varibale of type [t] is either free or bound.
* Includes the unique ID of any bound variables
* [name v] is [to_string v]
* [of_binding bnd] is a variable bound to [bnd]
* The interface of the family of UABTs representings a syntax
* Variables
* Scoped variable binding
* Operators specified in {!Op}
* [x #. t] is a new abt obtained by binding all {i free} variables named
[x] in [t]
Note that this does {b not} substitute variables for a {i value}, (for
which, see {!subst}). This only binds the free variables within the scope
of an abstraction that ranges over the given (sub) abt [t].
* [to_sexp t] is the representation of [t] as an s-expression
* [of_sexp s] is Abt represented by the s-expression [s]
* [to_string t] is the representation of [t] as a string
* [equal t t'] is [true] when [t] and [t'] are alpha equivalent and [false] otherwise
* [subterms t] is a list of all the subterms in [t], including [t] itself
* [free_vars t] is the set of variables that are free in in [t]
* [is_closed t] if [true] if there are no free variables in [t], otherwise false
* Substitutions mapping free variables to terms
* [find v s] is [Some term] if [v] is bound to [term] in the
substitution [s], otherwise it is [None]
* [bindings s] is a list of all the bindings in [s]
* Errors returned when unification fails
* [unify a b] is [Ok (union, substitution)] when [a] and [b] can be
unified into the term [union] and [substitution] is the most general
unifier. Otherwise it is [Error err)], for which, see {!type:error}
* [a =?= b] is [true] iff [a =.= b] is an [Ok _] value | Copyright ( c ) 2021 Shon Feder
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
, 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 .
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. *)
* { 1 Overview }
[ um - abt ] is a library for constructing and manipulating the abstract syntax
of languages that use { { ! module : Var } variables } .
[ um - abt ] provides unifiable abstract binding trees ( UABTs ) . An { b abstract
binding tree } ( ABT ) is an { i abstract syntax tree } ( AST ) , enriched with
constructs to manage variable binding and scope .
[ um - abt ] extends ABTs with support for { { ! module : Make . Unification } nominal
unification } ( unificaiton modulo ɑ - equivalence ) .
{ 1 Example }
A succinct example of the typical use of this library can be seen in the
following implementation of the untyped λ - calculus .
Define your language 's operators :
{ [
( * Define the usual operators , but without the variables , since we get those free
[um-abt] is a library for constructing and manipulating the abstract syntax
of languages that use {{!module:Var} variables}.
[um-abt] provides unifiable abstract binding trees (UABTs). An {b abstract
binding tree} (ABT) is an {i abstract syntax tree} (AST), enriched with
constructs to manage variable binding and scope.
[um-abt] extends ABTs with support for {{!module:Make.Unification} nominal
unification} (unificaiton modulo ɑ-equivalence).
{1 Example}
A succinct example of the typical use of this library can be seen in the
following implementation of the untyped λ-calculus.
Define your language's operators:
{[
module O = struct
type 'a t =
| App of 'a * 'a
| Lam of 'a
[@@deriving eq, map, fold]
let to_string : string t -> string = function
| App (l, m) -> Printf.sprintf "(%s %s)" l m
| Lam abs -> Printf.sprintf "(λ%s)" abs
end
]}
(Note the use of {{:-ppx/ppx_deriving} ppx_deriving}
to derive most values automatically.)
Generate your the ABT representing your syntax, and define combinators to
easily and safely construct terms of your lanugage construct:
{[
open Abt.Make (O)
let app m n : t =
[ op ] lifts an operator into an ABT
op (App (m, n))
let lam x m : t =
op (Lam (x #. m))
]}
Define the dynamics of your language (here using the variable substitution
function [subst], provided by the generated syntax):
{[
let rec eval : t -> t =
fun t ->
match t with
| Opr (App (m, n)) -> apply (eval m) (eval n)
| _ -> t
and apply : t -> t -> t =
fun m n ->
match m with
| Bnd (bnd, t) -> subst bnd ~value:n t
| Opr (Lam bnd) -> eval (apply bnd n)
| _ -> app m n
]}
Enjoy unification and ɑ-equivalence:
{[
let k = lam "x" (lam "y" x)
let ((=?=), (=.=), unify) = Unification.((=?=), (=.=), unify) in
assert (v "X" =?= s);
assert (lam "y" (lam "x" y) =?= lam "x" (lam "y" x));
let unified_term = (lam "z" (v "M") =.= k) |> Result.get_ok in
assert (to_string unified_term = "(λz.(λy.z))");
]}
*)
* { 1 Modules and interfaces }
module type Operator = sig
type 'a t [@@deriving sexp]
* The type of the operator , usually represented as a sum type .
Each operator should be have the form
{ [
of ' a * ' a * ... * ' a
] }
Where the free variables [ ' a ] are arguments to the operator [ Foo ] .
Each operator should be have the form
{[
Foo of 'a * 'a * ... * 'a
]}
Where the free variables ['a] are arguments to the operator [Foo]. *)
val map : ('a -> 'b) -> 'a t -> 'b t
val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool
val fold : ('a -> 'b -> 'a) -> 'a -> 'b t -> 'a
val to_string : string t -> string
end
* Variables , named by strings , which can be bound to a { ! module : Var . Binding } or
left free .
left free. *)
module Var : sig
module Binding : sig
include Map.OrderedType
val equal : t -> t -> bool
val v : string -> t
val name : t -> string
end
type t = private
| Free of string
[@@deriving sexp]
val compare : t -> t -> int
* Bound variables are equal if they are have the same binding , free
variables are greater than bound variables , and variables are otherwise
compared lexigraphically by name .
Specifically ,
[ compare a b ] is [ 0 ] iff
- [ is_free a & & is_free b ] and [ name a = name b ]
- [ is_bound a & & is_bound b ] and both [ a ] and [ b ] are bound to the same
{ ! type : binding } by way of { ! : bind } .
[ compare a b ] is [ String.compare ( name a ) ( name b ) ] if
[ is_free a & & is_free b ] or [ is_bound a & & is_bound b ] .
[ compare a b ] is -1 if [ is_bound a ] and [ is_free b ] or 1 if [ is_free a ]
and [ is_bound b ]
variables are greater than bound variables, and variables are otherwise
compared lexigraphically by name.
Specifically,
[compare a b] is [0] iff
- [is_free a && is_free b] and [name a = name b]
- [is_bound a && is_bound b] and both [a] and [b] are bound to the same
{!type:binding} by way of {!val:bind}.
[compare a b] is [String.compare (name a) (name b)] if
[is_free a && is_free b] or [is_bound a && is_bound b].
[compare a b] is -1 if [is_bound a] and [is_free b] or 1 if [is_free a]
and [is_bound b] *)
val equal : t -> t -> bool
* [ equal a b ] is [ true ] iff
- [ is_free a & & is_free b ] and [ name a = name b ]
- [ is_bound a & & is_bound b ] and both [ a ] and [ b ] are bound to the same
{ ! type : binding } by way of { ! : bind } .
- [is_free a && is_free b] and [name a = name b]
- [is_bound a && is_bound b] and both [a] and [b] are bound to the same
{!type:binding} by way of {!val:bind}. *)
val is_free : t -> bool
val is_bound : t -> bool
val v : string -> t
val to_string : t -> string
val to_string_debug : t -> string
val name : t -> string
val bind : t -> Binding.t -> t option
* [ bind v bnd ] is [ Some var ] when [ is_free v ] and [ name v = Binding.name ] ,
where [ var ] is a new variable with the same name but bound to [ bnd ] .
Otherwise , it is [ None ] .
See { ! : equal } .
where [var] is a new variable with the same name but bound to [bnd].
Otherwise, it is [None].
See {!val:equal}. *)
val is_bound_to : t -> Binding.t -> bool
* [ is_bound_to v bnd ] is [ true ] if [ v ] is bound to [ bnd ] , via { ! : bind }
val of_binding : Binding.t -> t
val to_binding : t -> Binding.t option
* [ to_binding v ] is [ Some bnd ] iff [ v ] is bound to [ bnd ] via { ! : bind } .
Otherwise it is [ None ] .
Otherwise it is [None]. *)
module Set : Set.S with type elt = t
module Map : Map.S with type key = t
end
module type Syntax = sig
module Op : Operator
* The type of ABT 's constructed from the operators defind in [ O ]
type t = private
[@@deriving sexp]
val bind : Var.Binding.t -> t -> t
* [ bind bnd t ] is a branch of the ABT , in which any free variables in [ t ]
matching the name of [ bnd ] are bound to [ bnd ] .
matching the name of [bnd] are bound to [bnd]. *)
val of_var : Var.t -> t
* [ of_var v ] is a leaf in the ABT consisting of the variable [ v ]
val v : string -> t
* [ v x ] is a leaf in the ABT consisting of a variable named [ x ]
val op : t Op.t -> t
* [ op o ] is a branch in the ABT consisting of the operator [ o ]
val ( #. ) : string -> t -> t
val subst : Var.Binding.t -> value:t -> t -> t
* [ subst bnd ~value t ] is a new ABT obtained by substituting [ value ] for
all variables bound to [ bnd ] .
all variables bound to [bnd]. *)
val subst_var : string -> value:t -> t -> t
* [ subst_var name ~value t ] is a new abt obtained by substituting [ value ] for
the outermost scope of variables bound to [ name ] in [ t ]
the outermost scope of variables bound to [name] in [t] *)
val to_sexp : t -> Sexplib.Sexp.t
val of_sexp : Sexplib.Sexp.t -> t
val to_string : t -> string
val equal : t -> t -> bool
val case :
var:(Var.t -> 'a)
-> bnd:(Var.Binding.t * t -> 'a)
-> opr:(t Op.t -> 'a)
-> t
-> 'a
* Case analysis for eleminating ABTs
This is an alternative to using pattern - based elimination .
@param var function to apply to variables
@param bnd function to apply to bindings
@param opr function to apply to operators
This is an alternative to using pattern-based elimination.
@param var function to apply to variables
@param bnd function to apply to bindings
@param opr function to apply to operators *)
val subterms : t -> t list
val free_vars : t -> Var.Set.t
val is_closed : t -> bool
module Unification : sig
module Subst : sig
type term = t
* An alias for the type of the ABT for reference in the context of the substitution
type t
val find : Var.t -> t -> term option
val bindings : t -> (Var.t * term) list
val to_string : t -> string
end
type error =
[ `Unification of Var.t option * t * t
| `Occurs of Var.t * t
| `Cycle of Subst.t
]
val unify : t -> t -> (t * Subst.t, error) Result.t
val ( =.= ) : t -> t -> (t, error) Result.t
* [ a = .= b ] is [ unify a b |
val ( =?= ) : t -> t -> bool
end
end
* [ Make ( Op ) ] is a module for constructing and manipulating the
{ ! module : Syntax } of a language with { ! module : Operator}s defined by [ Op ] .
{!module:Syntax} of a language with {!module:Operator}s defined by [Op]. *)
module Make (Op : Operator) : Syntax with module Op = Op
|
db52332812d81831ae65a7e73f30dda58c7a111536d7da712b89cd9316810ba8 | lilactown/lilac.town | visual_spec.clj | (ns lilactown.site.projects.visual-spec
(:require [garden.core :as garden]
[garden.stylesheet :refer [at-media]]
[garden.units :refer [px]]
[lilactown.client.core :as client]))
(def styles
[[:* {:box-sizing "border-box"}]
[:body {:font-family "Roboto Condensed, sans-serif"
:background-color "#fbfbfb"
:color "#3b3b3b"}]
[:h1 :h2 :h3 :h4 {:font-family "Roboto Slab, serif"}
[:small {:font-size "0.7em"
:display "block"
:color "#9a549a"
:margin "-10px 0 0 90px"}]]
[:a {:color "#371940"
:text-decoration "none"}
[:&:hover {:color "#9a549a"}]]
[:.title {:margin-bottom "10px"}]
[:#main {:max-width "670px"
:margin "40px auto 20px"}]
[:#sweeper ]])
(defn render []
[:html
[:meta {:charset "UTF-8"}]
[:meta {:name "viewport" :content "width=device-width,initial-scale=1"}]
[:head
[:title "Will Acton"]
[:link {:href ""
:rel "preload"
:as "style"}]
[:link {:href "+Condensed|Roboto+Slab"
:rel "preload"
:as "style"}]]
[:body
[:div#main
[:div {:style "margin: 0 10px"}
[:a {:href "/"}
[:h1.title "lilac.town"
[:small "Projects"]]]
[:div [:h2 {:style "margin: 0"}"Visual Spec"]]]]
[:div#app]
(client/module {:module :visual-spec
:init 'lilactown.client.visual-spec/start!
:ref "#app"})
[:link {:href ""
:rel "stylesheet"}]
[:link {:href "+Condensed|Roboto+Slab"
:rel "stylesheet"}]
[:link {:rel "stylesheet" :href "/assets/css/codemirror.css"}]
[:style
(garden/css styles)]
[:script#mainjs {:src "/visual-spec/js/main.js" :async true
:type "text/javascript"}]]])
| null | https://raw.githubusercontent.com/lilactown/lilac.town/295669e4511e79877da14232457dea26f098acd8/src/lilactown/site/projects/visual_spec.clj | clojure | (ns lilactown.site.projects.visual-spec
(:require [garden.core :as garden]
[garden.stylesheet :refer [at-media]]
[garden.units :refer [px]]
[lilactown.client.core :as client]))
(def styles
[[:* {:box-sizing "border-box"}]
[:body {:font-family "Roboto Condensed, sans-serif"
:background-color "#fbfbfb"
:color "#3b3b3b"}]
[:h1 :h2 :h3 :h4 {:font-family "Roboto Slab, serif"}
[:small {:font-size "0.7em"
:display "block"
:color "#9a549a"
:margin "-10px 0 0 90px"}]]
[:a {:color "#371940"
:text-decoration "none"}
[:&:hover {:color "#9a549a"}]]
[:.title {:margin-bottom "10px"}]
[:#main {:max-width "670px"
:margin "40px auto 20px"}]
[:#sweeper ]])
(defn render []
[:html
[:meta {:charset "UTF-8"}]
[:meta {:name "viewport" :content "width=device-width,initial-scale=1"}]
[:head
[:title "Will Acton"]
[:link {:href ""
:rel "preload"
:as "style"}]
[:link {:href "+Condensed|Roboto+Slab"
:rel "preload"
:as "style"}]]
[:body
[:div#main
[:div {:style "margin: 0 10px"}
[:a {:href "/"}
[:h1.title "lilac.town"
[:small "Projects"]]]
[:div [:h2 {:style "margin: 0"}"Visual Spec"]]]]
[:div#app]
(client/module {:module :visual-spec
:init 'lilactown.client.visual-spec/start!
:ref "#app"})
[:link {:href ""
:rel "stylesheet"}]
[:link {:href "+Condensed|Roboto+Slab"
:rel "stylesheet"}]
[:link {:rel "stylesheet" :href "/assets/css/codemirror.css"}]
[:style
(garden/css styles)]
[:script#mainjs {:src "/visual-spec/js/main.js" :async true
:type "text/javascript"}]]])
| |
a3021d37a16749bfb46760fd8035054984d5db68f0efb5e6726dc3638b12f77b | sonowz/advent-of-code-haskell | Day06.hs | module Y2021.Day06 where
import Data.Text (split)
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as MV
import Lib.IO
import Lib.Types
import Relude
import Relude.Extra.Bifunctor
import Relude.Extra.Foldable1
import Relude.Extra.Map
import Relude.Extra.Newtype
import Relude.Extra.Tuple
import Relude.Unsafe ((!!))
-----------------------
-- Type declarations --
-----------------------
newtype FishState = FishState [Integer] deriving (Show)
------------
-- Part 1 --
------------
solve1 :: FishState -> Integer
solve1 fishState = sum (un @[Integer] fishState80)
where fishState80 = iterate step fishState !! 80
step :: FishState -> FishState
step (FishState days) = FishState newState where
-- Exhaustive pattern matching, using Maybe monad
(day0, day1to6, day7, day8) = fromJust $ do
let (day0:day1to6, [day7, day8]) = splitAt 7 days
return (day0, day1to6, day7, day8)
fromJust = fromMaybe (error "Invalid State!")
newState = day1to6 <> [day7 + day0, day8, day0]
------------
Part 2 --
------------
solve2 :: FishState -> Integer
solve2 fishState = sum (un @[Integer] fishState256)
where fishState256 = iterate step fishState !! 256
--------------------
Main & Parsing --
--------------------
main' :: IO ()
main' = do
initFishState <-
parseFishState . (!! 0) <$> readFileLines "inputs/Y2021/Day06.txt" :: IO FishState
print $ solve1 initFishState
print $ solve2 initFishState
-- Stateful creation
parseFishState :: Text -> FishState
parseFishState line = (FishState . toList) $ V.create $ do
vecState <- MV.replicate 9 0
forM_ fishes (addFish vecState)
return vecState
where
fishes = readInt <$> split (== ',') line :: [Int]
addFish state fish = MV.modify state (+ 1) fish
| null | https://raw.githubusercontent.com/sonowz/advent-of-code-haskell/b1231172ea4e11720e498ae8dc5c93f2e6d2f3f7/src/Y2021/Day06.hs | haskell | ---------------------
Type declarations --
---------------------
----------
Part 1 --
----------
Exhaustive pattern matching, using Maybe monad
----------
----------
------------------
------------------
Stateful creation | module Y2021.Day06 where
import Data.Text (split)
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as MV
import Lib.IO
import Lib.Types
import Relude
import Relude.Extra.Bifunctor
import Relude.Extra.Foldable1
import Relude.Extra.Map
import Relude.Extra.Newtype
import Relude.Extra.Tuple
import Relude.Unsafe ((!!))
newtype FishState = FishState [Integer] deriving (Show)
solve1 :: FishState -> Integer
solve1 fishState = sum (un @[Integer] fishState80)
where fishState80 = iterate step fishState !! 80
step :: FishState -> FishState
step (FishState days) = FishState newState where
(day0, day1to6, day7, day8) = fromJust $ do
let (day0:day1to6, [day7, day8]) = splitAt 7 days
return (day0, day1to6, day7, day8)
fromJust = fromMaybe (error "Invalid State!")
newState = day1to6 <> [day7 + day0, day8, day0]
solve2 :: FishState -> Integer
solve2 fishState = sum (un @[Integer] fishState256)
where fishState256 = iterate step fishState !! 256
main' :: IO ()
main' = do
initFishState <-
parseFishState . (!! 0) <$> readFileLines "inputs/Y2021/Day06.txt" :: IO FishState
print $ solve1 initFishState
print $ solve2 initFishState
parseFishState :: Text -> FishState
parseFishState line = (FishState . toList) $ V.create $ do
vecState <- MV.replicate 9 0
forM_ fishes (addFish vecState)
return vecState
where
fishes = readInt <$> split (== ',') line :: [Int]
addFish state fish = MV.modify state (+ 1) fish
|
7691660149ea9dbdd359d9babe3f381d4efc4c5c73c0ade431790a5182b1a69c | thephoeron/quipper-language | PhaseTest.hs | This file is part of Quipper . Copyright ( C ) 2011 - 2014 . Please see the
-- file COPYRIGHT for a list of authors, copyright holders, licensing,
-- and other details. All rights reserved.
--
-- ======================================================================
-- $ Test whether the quantum simulator works correctly on a global
-- phase gate.
import Quipper
import QuipperLib.Simulation
-- | This function should compute a Not gate.
testcirc :: Qubit -> Circ Qubit
testcirc a = do
hadamard_at a
global_phase 1.0 `controlled` a
hadamard_at a
return a
main = do
b <- run_generic_io d testcirc False
putStrLn ("testcirc False = " ++ show b)
b <- run_generic_io d testcirc True
putStrLn ("testcirc True = " ++ show b)
where
d :: Double
d = undefined
| null | https://raw.githubusercontent.com/thephoeron/quipper-language/15e555343a15c07b9aa97aced1ada22414f04af6/tests/PhaseTest.hs | haskell | file COPYRIGHT for a list of authors, copyright holders, licensing,
and other details. All rights reserved.
======================================================================
$ Test whether the quantum simulator works correctly on a global
phase gate.
| This function should compute a Not gate. | This file is part of Quipper . Copyright ( C ) 2011 - 2014 . Please see the
import Quipper
import QuipperLib.Simulation
testcirc :: Qubit -> Circ Qubit
testcirc a = do
hadamard_at a
global_phase 1.0 `controlled` a
hadamard_at a
return a
main = do
b <- run_generic_io d testcirc False
putStrLn ("testcirc False = " ++ show b)
b <- run_generic_io d testcirc True
putStrLn ("testcirc True = " ++ show b)
where
d :: Double
d = undefined
|
3e9cf54d0fd9e60fe512980e1b2d6507fb85c40c6ec70618e3073e2d64689a3f | Shopify/kubepacity | Main.hs | # LANGUAGE DeriveGeneric #
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Kube
import Objects
import Data.Aeson (decodeStrict, ToJSON, FromJSON)
import Turtle
import Data.Text (Text)
import Data.Text.Encoding (encodeUtf8)
import GHC.Generics
-- Used to decode JSON list of pods.
newtype PodSet = PodSet { items :: [Pod] }
deriving (Show, Eq, Generic, FromJSON)
parser :: Parser Context
parser = Context <$> optText "context" 'c' "the context to visualize"
A WIP main for messing around with parsing .
main :: IO ()
main = do
context <- options "kubepacity" parser
names <- getNodeNames context
podsJSON <- strict . getPods context . head $ names
let (Just set) = decodeStrict . encodeUtf8 $ podsJSON
mapM_ print (items set)
| null | https://raw.githubusercontent.com/Shopify/kubepacity/96e04a9f2327ff0436cb5059ca36795b17a8b469/app/Main.hs | haskell | # LANGUAGE DeriveAnyClass #
# LANGUAGE OverloadedStrings #
Used to decode JSON list of pods. | # LANGUAGE DeriveGeneric #
module Main where
import Kube
import Objects
import Data.Aeson (decodeStrict, ToJSON, FromJSON)
import Turtle
import Data.Text (Text)
import Data.Text.Encoding (encodeUtf8)
import GHC.Generics
newtype PodSet = PodSet { items :: [Pod] }
deriving (Show, Eq, Generic, FromJSON)
parser :: Parser Context
parser = Context <$> optText "context" 'c' "the context to visualize"
A WIP main for messing around with parsing .
main :: IO ()
main = do
context <- options "kubepacity" parser
names <- getNodeNames context
podsJSON <- strict . getPods context . head $ names
let (Just set) = decodeStrict . encodeUtf8 $ podsJSON
mapM_ print (items set)
|
d4998e136b674ee125eb475439d9423b3be9cf4c8a860e887f2da7d2531a25b6 | reddit-archive/reddit1.0 | cookiehash.lisp | ;;;; Copyright 2018 Reddit, 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.
(in-package :reddit)
(defparameter *secret* "blargo")
(defun iso-time ()
(let ((itime (format-time nil (get-time) :format :iso)))
(subseq itime 0 (position #\, itime))))
(defun hashstr (str)
(byte-array-to-hex-string (digest-sequence :sha256 (ascii-string-to-byte-array str))))
(defun cookie-str (sn pass)
(let ((time (iso-time)))
(makestr sn "," time ","
(hashstr (makestr time sn pass *secret*)))))
(defun valid-cookie (str)
"returns the userid for cookie if valid, otherwise nil"
(when (= (count #\, str :test #'char=) 2)
(when-bind* ((sn (subseq str 0 (position #\, str :test #'char=)))
(time (subseq str (+ 1 (length sn)) (position #\, str :from-end t :test #'char=)))
(hash (subseq str (+ (length sn) (length time) 2)))
(pass (user-pass sn)))
(when (string= hash (hashstr (makestr time sn pass *secret*)))
(user-id (get-user sn))))))
| null | https://raw.githubusercontent.com/reddit-archive/reddit1.0/bb4fbdb5871a32709df30540685cf44c637bf203/cookiehash.lisp | lisp | Copyright 2018 Reddit, 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
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
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
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. | the Software without restriction , including without limitation the rights to
of the Software , and to permit persons to whom the Software is furnished to do
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 FROM ,
(in-package :reddit)
(defparameter *secret* "blargo")
(defun iso-time ()
(let ((itime (format-time nil (get-time) :format :iso)))
(subseq itime 0 (position #\, itime))))
(defun hashstr (str)
(byte-array-to-hex-string (digest-sequence :sha256 (ascii-string-to-byte-array str))))
(defun cookie-str (sn pass)
(let ((time (iso-time)))
(makestr sn "," time ","
(hashstr (makestr time sn pass *secret*)))))
(defun valid-cookie (str)
"returns the userid for cookie if valid, otherwise nil"
(when (= (count #\, str :test #'char=) 2)
(when-bind* ((sn (subseq str 0 (position #\, str :test #'char=)))
(time (subseq str (+ 1 (length sn)) (position #\, str :from-end t :test #'char=)))
(hash (subseq str (+ (length sn) (length time) 2)))
(pass (user-pass sn)))
(when (string= hash (hashstr (makestr time sn pass *secret*)))
(user-id (get-user sn))))))
|
20b8f751f402a47cac2850d05d39db269dc58e294c693472fb43beab80bee57c | erlanglab/elab | elab_procs.erl | -module(elab_procs).
-export([parse/1,
info/0]).
-define(RE_RUN_OPTION, [{capture, all_names, binary}]).
-define(RE_PATTERN, <<"\\((?<MFA>.*) \\+ ">>).
info() ->
parse(erlang:system_info(procs)).
parse(ProcsBin) ->
{ok, MP} = re:compile(?RE_PATTERN),
parse_dump(binary:split(ProcsBin, <<"\n">>, [global]), {[], []}, MP).
parse_dump([], {ProcAcc, PortAcc}, _MP) ->
#{procs => ProcAcc, ports => PortAcc};
parse_dump([<<"=proc:", ProcId/binary>> | T], {ProcAcc, PortAcc}, MP) ->
{Proc, Tail} = parse_dump_proc(T, #{pid => ProcId}, MP),
parse_dump(Tail, {[Proc | ProcAcc], PortAcc}, MP);
parse_dump([<<"=port:", PortId/binary>> | T], {ProcAcc, PortAcc}, MP) ->
{Port, Tail} = parse_dump_port(T, #{port => PortId}),
parse_dump(Tail, {ProcAcc, [Port | PortAcc]}, MP).
%% -------------------------
%% Example of a process dump
%% -------------------------
%% =proc:<0.0.0>
State : Waiting
%% Name: init
%% Spawned as: erl_init:start/2
%% Spawned by: []
Message queue length : 0
Number of heap fragments : 0
Heap fragment data : 0
Link list : [ < 0.9.0 > , < 0.44.0 > , < 0.42.0 > , < 0.10.0 > ]
Reductions : 3266
Stack+heap : 987
OldHeap : 610
Heap unused : 844
OldHeap unused : 470
%% BinVHeap: 0
%% OldBinVHeap: 0
BinVHeap unused : 46422
OldBinVHeap unused : 46422
Memory : 13776
%% Last scheduled in for: module1:stack_test3/1">>
Stack dump :
Program counter : ( init : loop/1 + 56 )
%% arity = 0
%%
%% 0x00007f73e3840220 []
%%
0x00007f73e3840228 Return stack_test3/1 + 64 )
%%
0x00007f73e3840230 Return addr 0x00007f73e8835898 ( : stack_test2/1 + 64 )
%%
0x00007f73e3840238 Return addr 0x00007f73e8835830 ( module3 : )
%%
0x00007f73e3840240 Return addr ( < terminate process normally > )
%%
0x0000000104874940 Return addr 0x000000010320dac0 ( < terminate process normally > )
Internal State : ACT_PRIO_NORMAL | USR_PRIO_NORMAL | PRQ_PRIO_NORMAL
parse_dump_proc([<<"State: ", State/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{state => State}, MP);
parse_dump_proc([<<"Name: ", Name/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{name => Name}, MP);
parse_dump_proc([<<"Spawned as: ", SpawnedAs/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{spawned_as => SpawnedAs}, MP);
parse_dump_proc([<<"Spawned by: ", SpawnedBy/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{spawned_by => SpawnedBy}, MP);
parse_dump_proc([<<"Message queue length: ", MessageQueueLen/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{message_queue_len => MessageQueueLen}, MP);
parse_dump_proc([<<"Number of heap fragments: ", HeapFragmentNum/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{heap_fragment_num => HeapFragmentNum}, MP);
parse_dump_proc([<<"Heap fragment data: ", HeapFragmentData/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{heap_fragment_data => HeapFragmentData}, MP);
parse_dump_proc([<<"Current call: ", CurrentCall/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{current_call => CurrentCall}, MP);
parse_dump_proc([<<"Last calls: ", LastCalls/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{last_calls => LastCalls}, MP);
parse_dump_proc([<<"Dictionary: ", Dictionary/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{dictionary => Dictionary}, MP);
parse_dump_proc([<<"Link list: ", Links/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{links => Links}, MP);
parse_dump_proc([<<"Reductions: 0">> | T], Map, MP) ->
a special case of zero reductions of the just spawned process
zeros do n't work well with a logarithmic scale , so make it 1
parse_dump_proc(T, Map#{reductions => <<"1">>}, MP);
parse_dump_proc([<<"Reductions: ", Reductions/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{reductions => Reductions}, MP);
parse_dump_proc([<<"Stack+heap: ", StackHeapSize/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{stack_heap_size => StackHeapSize}, MP);
parse_dump_proc([<<"OldHeap: ", OldHeap/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{old_heap_size => OldHeap}, MP);
parse_dump_proc([<<"Heap unused: ", HeapUnused/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{heap_unused_size => HeapUnused}, MP);
parse_dump_proc([<<"OldHeap unused: ", OldHeapUnused/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{old_heap_unused_size => OldHeapUnused}, MP);
parse_dump_proc([<<"BinVHeap: ", BinVHeap/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{bin_vheap_size => BinVHeap}, MP);
parse_dump_proc([<<"OldBinVHeap: ", OldBinVHeap/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{bin_old_vheap_size => OldBinVHeap}, MP);
parse_dump_proc([<<"BinVHeap unused: ", BinVHeapUnused/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{bin_vheap_unused_size => BinVHeapUnused}, MP);
parse_dump_proc([<<"OldBinVHeap unused: ", OldBinVHeapUnused/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{bin_old_vheap_unused_size => OldBinVHeapUnused}, MP);
parse_dump_proc([<<"Memory: ", Memory/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{memory => Memory}, MP);
parse_dump_proc([<<"Last scheduled in for: ", LastScheduled/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{last_scheduled_in_for => LastScheduled}, MP);
parse_dump_proc([<<"Stack dump:">> | T], Map, MP) ->
{StackDump, T2} = parse_dump_stack(T, [], MP),
parse_dump_proc(T2, Map#{stack_dump => StackDump}, MP);
parse_dump_proc([<<"Internal State: ", InternalState/binary>> | T], Map, _MP) ->
{Map#{internal_state => InternalState}, T};
parse_dump_proc([], Map, _MP) ->
{Map, []};
parse_dump_proc([_Line | T], Map, MP) ->
parse_dump_proc(T, Map, MP).
parse_dump_stack([], StackDumpAcc, _MP) ->
{StackDumpAcc, []};
parse_dump_stack([<<"Internal State: ", _/binary>> | _] = ProcsDump, StackDumpAcc, _MP) ->
{StackDumpAcc, ProcsDump};
parse_dump_stack([<<"0x", _/binary>> = Line | T], StackDumpAcc, MP) ->
case re:run(Line, MP, ?RE_RUN_OPTION) of
nomatch ->
parse_dump_stack(T, StackDumpAcc, MP);
{match, [MFA]} ->
parse_dump_stack(T, [MFA | StackDumpAcc], MP)
end;
parse_dump_stack([_ | T], StackDumpAcc, MP) ->
parse_dump_stack(T, StackDumpAcc, MP).
%% ----------------------
%% Example of a port dump
%% ----------------------
%% =port:#Port<0.4>
State : CONNECTED|BINARY_IO|PORT_LOCK
Task Flags : CHK_UNSET_BUSY_Q
Slot : 32
%% Connected: <0.58.0>
%% Links: <0.58.0>
%% Monitors: (<0.61.0>,#Ref<0.2601428397.3356491778.28209>)
%% Port controls linked-in driver: tcp_inet
Input : 0
Output : 20
Queue : 0
%% Port Data: inet_tcp
parse_dump_port([<<"State: ", State/binary>> | T], Map) ->
parse_dump_port(T, Map#{state => State});
parse_dump_port([<<"Task Flags: ", TaskFlags/binary>> | T], Map) ->
parse_dump_port(T, Map#{task_flags => TaskFlags});
parse_dump_port([<<"Slot: ", Slot/binary>> | T], Map) ->
parse_dump_port(T, Map#{slot => Slot});
parse_dump_port([<<"Connected: ", Connected/binary>> | T], Map) ->
parse_dump_port(T, Map#{connected => Connected});
parse_dump_port([<<"Links: ", Links/binary>> | T], Map) ->
parse_dump_port(T, Map#{links => Links});
parse_dump_port([<<"Monitors: ", Monitors/binary>> | T], Map) ->
parse_dump_port(T, Map#{monitors => Monitors});
parse_dump_port([<<"Port Data: ", PortData/binary>> | T], Map) ->
parse_dump_port(T, Map#{port_data => PortData});
parse_dump_port([<<"Port ", _/binary>> = Desc | T], Map) ->
parse_dump_port(T, Map#{desc => Desc});
zeros do n't work well with a logarithmic scale , so make it 1
parse_dump_port([<<"Input: 0">> | T], Map) ->
parse_dump_port(T, Map#{input => <<"1">>});
parse_dump_port([<<"Output: 0">> | T], Map) ->
parse_dump_port(T, Map#{output => <<"1">>});
parse_dump_port([<<"Input: ", Input/binary>> | T], Map) ->
parse_dump_port(T, Map#{input => Input});
parse_dump_port([<<"Output: ", Output/binary>> | T], Map) ->
parse_dump_port(T, Map#{output => Output});
parse_dump_port([<<"Queue: ", Queue/binary>> | T], Map) ->
parse_dump_port(T, Map#{queue => Queue});
parse_dump_port([<<"=port:", _/binary>> | _] = PortDump, Map) ->
{Map, PortDump};
parse_dump_port([<<>> | T], Map) ->
{Map, T};
parse_dump_port([_Line | T], Map) ->
parse_dump_port(T, Map). | null | https://raw.githubusercontent.com/erlanglab/elab/a9b2513f37a22bf74dad0607dcac234bba2b8da6/src/elab_procs.erl | erlang | -------------------------
Example of a process dump
-------------------------
=proc:<0.0.0>
Name: init
Spawned as: erl_init:start/2
Spawned by: []
BinVHeap: 0
OldBinVHeap: 0
Last scheduled in for: module1:stack_test3/1">>
arity = 0
0x00007f73e3840220 []
----------------------
Example of a port dump
----------------------
=port:#Port<0.4>
Connected: <0.58.0>
Links: <0.58.0>
Monitors: (<0.61.0>,#Ref<0.2601428397.3356491778.28209>)
Port controls linked-in driver: tcp_inet
Port Data: inet_tcp | -module(elab_procs).
-export([parse/1,
info/0]).
-define(RE_RUN_OPTION, [{capture, all_names, binary}]).
-define(RE_PATTERN, <<"\\((?<MFA>.*) \\+ ">>).
info() ->
parse(erlang:system_info(procs)).
parse(ProcsBin) ->
{ok, MP} = re:compile(?RE_PATTERN),
parse_dump(binary:split(ProcsBin, <<"\n">>, [global]), {[], []}, MP).
parse_dump([], {ProcAcc, PortAcc}, _MP) ->
#{procs => ProcAcc, ports => PortAcc};
parse_dump([<<"=proc:", ProcId/binary>> | T], {ProcAcc, PortAcc}, MP) ->
{Proc, Tail} = parse_dump_proc(T, #{pid => ProcId}, MP),
parse_dump(Tail, {[Proc | ProcAcc], PortAcc}, MP);
parse_dump([<<"=port:", PortId/binary>> | T], {ProcAcc, PortAcc}, MP) ->
{Port, Tail} = parse_dump_port(T, #{port => PortId}),
parse_dump(Tail, {ProcAcc, [Port | PortAcc]}, MP).
State : Waiting
Message queue length : 0
Number of heap fragments : 0
Heap fragment data : 0
Link list : [ < 0.9.0 > , < 0.44.0 > , < 0.42.0 > , < 0.10.0 > ]
Reductions : 3266
Stack+heap : 987
OldHeap : 610
Heap unused : 844
OldHeap unused : 470
BinVHeap unused : 46422
OldBinVHeap unused : 46422
Memory : 13776
Stack dump :
Program counter : ( init : loop/1 + 56 )
0x00007f73e3840228 Return stack_test3/1 + 64 )
0x00007f73e3840230 Return addr 0x00007f73e8835898 ( : stack_test2/1 + 64 )
0x00007f73e3840238 Return addr 0x00007f73e8835830 ( module3 : )
0x00007f73e3840240 Return addr ( < terminate process normally > )
0x0000000104874940 Return addr 0x000000010320dac0 ( < terminate process normally > )
Internal State : ACT_PRIO_NORMAL | USR_PRIO_NORMAL | PRQ_PRIO_NORMAL
parse_dump_proc([<<"State: ", State/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{state => State}, MP);
parse_dump_proc([<<"Name: ", Name/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{name => Name}, MP);
parse_dump_proc([<<"Spawned as: ", SpawnedAs/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{spawned_as => SpawnedAs}, MP);
parse_dump_proc([<<"Spawned by: ", SpawnedBy/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{spawned_by => SpawnedBy}, MP);
parse_dump_proc([<<"Message queue length: ", MessageQueueLen/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{message_queue_len => MessageQueueLen}, MP);
parse_dump_proc([<<"Number of heap fragments: ", HeapFragmentNum/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{heap_fragment_num => HeapFragmentNum}, MP);
parse_dump_proc([<<"Heap fragment data: ", HeapFragmentData/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{heap_fragment_data => HeapFragmentData}, MP);
parse_dump_proc([<<"Current call: ", CurrentCall/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{current_call => CurrentCall}, MP);
parse_dump_proc([<<"Last calls: ", LastCalls/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{last_calls => LastCalls}, MP);
parse_dump_proc([<<"Dictionary: ", Dictionary/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{dictionary => Dictionary}, MP);
parse_dump_proc([<<"Link list: ", Links/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{links => Links}, MP);
parse_dump_proc([<<"Reductions: 0">> | T], Map, MP) ->
a special case of zero reductions of the just spawned process
zeros do n't work well with a logarithmic scale , so make it 1
parse_dump_proc(T, Map#{reductions => <<"1">>}, MP);
parse_dump_proc([<<"Reductions: ", Reductions/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{reductions => Reductions}, MP);
parse_dump_proc([<<"Stack+heap: ", StackHeapSize/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{stack_heap_size => StackHeapSize}, MP);
parse_dump_proc([<<"OldHeap: ", OldHeap/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{old_heap_size => OldHeap}, MP);
parse_dump_proc([<<"Heap unused: ", HeapUnused/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{heap_unused_size => HeapUnused}, MP);
parse_dump_proc([<<"OldHeap unused: ", OldHeapUnused/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{old_heap_unused_size => OldHeapUnused}, MP);
parse_dump_proc([<<"BinVHeap: ", BinVHeap/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{bin_vheap_size => BinVHeap}, MP);
parse_dump_proc([<<"OldBinVHeap: ", OldBinVHeap/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{bin_old_vheap_size => OldBinVHeap}, MP);
parse_dump_proc([<<"BinVHeap unused: ", BinVHeapUnused/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{bin_vheap_unused_size => BinVHeapUnused}, MP);
parse_dump_proc([<<"OldBinVHeap unused: ", OldBinVHeapUnused/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{bin_old_vheap_unused_size => OldBinVHeapUnused}, MP);
parse_dump_proc([<<"Memory: ", Memory/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{memory => Memory}, MP);
parse_dump_proc([<<"Last scheduled in for: ", LastScheduled/binary>> | T], Map, MP) ->
parse_dump_proc(T, Map#{last_scheduled_in_for => LastScheduled}, MP);
parse_dump_proc([<<"Stack dump:">> | T], Map, MP) ->
{StackDump, T2} = parse_dump_stack(T, [], MP),
parse_dump_proc(T2, Map#{stack_dump => StackDump}, MP);
parse_dump_proc([<<"Internal State: ", InternalState/binary>> | T], Map, _MP) ->
{Map#{internal_state => InternalState}, T};
parse_dump_proc([], Map, _MP) ->
{Map, []};
parse_dump_proc([_Line | T], Map, MP) ->
parse_dump_proc(T, Map, MP).
parse_dump_stack([], StackDumpAcc, _MP) ->
{StackDumpAcc, []};
parse_dump_stack([<<"Internal State: ", _/binary>> | _] = ProcsDump, StackDumpAcc, _MP) ->
{StackDumpAcc, ProcsDump};
parse_dump_stack([<<"0x", _/binary>> = Line | T], StackDumpAcc, MP) ->
case re:run(Line, MP, ?RE_RUN_OPTION) of
nomatch ->
parse_dump_stack(T, StackDumpAcc, MP);
{match, [MFA]} ->
parse_dump_stack(T, [MFA | StackDumpAcc], MP)
end;
parse_dump_stack([_ | T], StackDumpAcc, MP) ->
parse_dump_stack(T, StackDumpAcc, MP).
State : CONNECTED|BINARY_IO|PORT_LOCK
Task Flags : CHK_UNSET_BUSY_Q
Slot : 32
Input : 0
Output : 20
Queue : 0
parse_dump_port([<<"State: ", State/binary>> | T], Map) ->
parse_dump_port(T, Map#{state => State});
parse_dump_port([<<"Task Flags: ", TaskFlags/binary>> | T], Map) ->
parse_dump_port(T, Map#{task_flags => TaskFlags});
parse_dump_port([<<"Slot: ", Slot/binary>> | T], Map) ->
parse_dump_port(T, Map#{slot => Slot});
parse_dump_port([<<"Connected: ", Connected/binary>> | T], Map) ->
parse_dump_port(T, Map#{connected => Connected});
parse_dump_port([<<"Links: ", Links/binary>> | T], Map) ->
parse_dump_port(T, Map#{links => Links});
parse_dump_port([<<"Monitors: ", Monitors/binary>> | T], Map) ->
parse_dump_port(T, Map#{monitors => Monitors});
parse_dump_port([<<"Port Data: ", PortData/binary>> | T], Map) ->
parse_dump_port(T, Map#{port_data => PortData});
parse_dump_port([<<"Port ", _/binary>> = Desc | T], Map) ->
parse_dump_port(T, Map#{desc => Desc});
zeros do n't work well with a logarithmic scale , so make it 1
parse_dump_port([<<"Input: 0">> | T], Map) ->
parse_dump_port(T, Map#{input => <<"1">>});
parse_dump_port([<<"Output: 0">> | T], Map) ->
parse_dump_port(T, Map#{output => <<"1">>});
parse_dump_port([<<"Input: ", Input/binary>> | T], Map) ->
parse_dump_port(T, Map#{input => Input});
parse_dump_port([<<"Output: ", Output/binary>> | T], Map) ->
parse_dump_port(T, Map#{output => Output});
parse_dump_port([<<"Queue: ", Queue/binary>> | T], Map) ->
parse_dump_port(T, Map#{queue => Queue});
parse_dump_port([<<"=port:", _/binary>> | _] = PortDump, Map) ->
{Map, PortDump};
parse_dump_port([<<>> | T], Map) ->
{Map, T};
parse_dump_port([_Line | T], Map) ->
parse_dump_port(T, Map). |
b7a6e74ed4470b6b636a8c9cf98b01d665e3da191d58bde9ce59fb7359694e62 | typeclasses/haskell-phrasebook | test-file-handles.hs | main = propertyMain $ withTests 1 $ property do
x <- exeStdout $ phrasebook "file-handles"
strLines x === [ "hello", "False", "world", "True" ]
| null | https://raw.githubusercontent.com/typeclasses/haskell-phrasebook/2b0aa44ef6f6e9745c51ed47b4e59ff704346c87/tests/test-file-handles.hs | haskell | main = propertyMain $ withTests 1 $ property do
x <- exeStdout $ phrasebook "file-handles"
strLines x === [ "hello", "False", "world", "True" ]
| |
d4ba3f690904a01fd345931b7a550040ed4f0b29878cb79a88026d70162b58e7 | yogthos/components-example | core.clj | (ns components-example.core
(:require [components-example.handler :as handler]
[luminus.repl-server :as repl]
[luminus.http-server :as http]
[components-example.config :refer [env]]
[clojure.tools.cli :refer [parse-opts]]
[clojure.tools.logging :as log]
[mount.core :as mount])
(:gen-class))
(def cli-options
[["-p" "--port PORT" "Port number"
:parse-fn #(Integer/parseInt %)]])
(mount/defstate ^{:on-reload :noop}
http-server
:start
(http/start
(-> @env
(assoc :handler (handler/app))
(update :port #(or (-> @env :options :port) %))))
:stop
(http/stop @http-server))
(mount/defstate ^{:on-reload :noop}
repl-server
:start
(when-let [nrepl-port (:nrepl-port @env)]
(repl/start {:port nrepl-port}))
:stop
(when @repl-server
(repl/stop @repl-server)))
(defn stop-app []
(doseq [component (:stopped (mount/stop))]
(log/info component "stopped"))
(shutdown-agents))
(defn start-app [args]
(mount/in-cljc-mode)
(doseq [component (-> args
(parse-opts cli-options)
mount/start-with-args
:started)]
(log/info component "started"))
(.addShutdownHook (Runtime/getRuntime) (Thread. stop-app)))
(defn -main [& args]
(start-app args))
| null | https://raw.githubusercontent.com/yogthos/components-example/c369bde7916b6d15cb6a8b4ab05c562e16755b2a/src/clj/components_example/core.clj | clojure | (ns components-example.core
(:require [components-example.handler :as handler]
[luminus.repl-server :as repl]
[luminus.http-server :as http]
[components-example.config :refer [env]]
[clojure.tools.cli :refer [parse-opts]]
[clojure.tools.logging :as log]
[mount.core :as mount])
(:gen-class))
(def cli-options
[["-p" "--port PORT" "Port number"
:parse-fn #(Integer/parseInt %)]])
(mount/defstate ^{:on-reload :noop}
http-server
:start
(http/start
(-> @env
(assoc :handler (handler/app))
(update :port #(or (-> @env :options :port) %))))
:stop
(http/stop @http-server))
(mount/defstate ^{:on-reload :noop}
repl-server
:start
(when-let [nrepl-port (:nrepl-port @env)]
(repl/start {:port nrepl-port}))
:stop
(when @repl-server
(repl/stop @repl-server)))
(defn stop-app []
(doseq [component (:stopped (mount/stop))]
(log/info component "stopped"))
(shutdown-agents))
(defn start-app [args]
(mount/in-cljc-mode)
(doseq [component (-> args
(parse-opts cli-options)
mount/start-with-args
:started)]
(log/info component "started"))
(.addShutdownHook (Runtime/getRuntime) (Thread. stop-app)))
(defn -main [& args]
(start-app args))
| |
4f6c9271aeeb84ce1a02a56b2f54487d72f146c7776a46ded8c970ac98bb5ce4 | ragkousism/Guix-on-Hurd | make-bootstrap.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2012 , 2013 , 2014 , 2015 , 2016 < >
Copyright © 2017 < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU 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.
;;;
;;; GNU Guix 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 GNU . If not , see < / > .
(define-module (gnu packages make-bootstrap)
#:use-module (guix utils)
#:use-module (guix packages)
#:use-module (guix licenses)
#:use-module (guix build-system trivial)
#:use-module (guix build-system gnu)
#:use-module ((gnu packages) #:select (search-patch))
#:use-module (gnu packages base)
#:use-module (gnu packages cross-base)
#:use-module (gnu packages bash)
#:use-module (gnu packages compression)
#:use-module (gnu packages gawk)
#:use-module (gnu packages gcc)
#:use-module (gnu packages guile)
#:use-module (gnu packages bdw-gc)
#:use-module (gnu packages linux)
#:use-module (gnu packages hurd)
#:use-module (gnu packages multiprecision)
#:use-module (ice-9 match)
#:use-module (srfi srfi-1)
#:export (%bootstrap-binaries-tarball
%binutils-bootstrap-tarball
%glibc-bootstrap-tarball
%gcc-bootstrap-tarball
%guile-bootstrap-tarball
%bootstrap-tarballs
%guile-static-stripped))
;;; Commentary:
;;;
;;; This module provides tools to build tarballs of the "bootstrap binaries"
;;; used in (gnu packages bootstrap). These statically-linked binaries are
;;; taken for granted and used as the root of the whole bootstrap procedure.
;;;
;;; Code:
(define* (glibc-for-bootstrap #:optional (base glibc))
"Return a libc deriving from BASE whose `system' and `popen' functions looks
for `sh' in $PATH, and without nscd, and with static NSS modules."
(package (inherit base)
(source (origin (inherit (package-source base))
(patches (cons (search-patch "glibc-bootstrap-system.patch")
(origin-patches (package-source base))))))
(arguments
(substitute-keyword-arguments (package-arguments base)
((#:configure-flags flags)
Arrange so that getaddrinfo & co. do not contact the nscd ,
and can use statically - linked NSS modules .
`(cons* "--disable-nscd" "--disable-build-nscd"
"--enable-static-nss"
,flags))))
;; Remove the 'debug' output to allow bit-reproducible builds (when the
;; 'debug' output is used, ELF files end up with a .gnu_debuglink, which
includes a CRC of the corresponding debugging symbols ; those symbols
contain store file names , so the CRC changes at every rebuild . )
(outputs (delete "debug" (package-outputs base)))))
(define (package-with-relocatable-glibc p)
"Return a variant of P that uses the libc as defined by
`glibc-for-bootstrap'."
(define (cross-bootstrap-libc)
(let ((target (%current-target-system)))
(glibc-for-bootstrap
;; `cross-libc' already returns a cross libc, so clear
;; %CURRENT-TARGET-SYSTEM.
(parameterize ((%current-target-system #f))
(cross-libc target)))))
Standard inputs with the above libc and corresponding GCC .
(define (inputs)
(if (%current-target-system) ; is this package cross built?
`(("cross-libc" ,(cross-bootstrap-libc)))
'()))
(define (native-inputs)
(if (%current-target-system)
(let ((target (%current-target-system)))
`(("cross-gcc" ,(cross-gcc target
(cross-binutils target)
(cross-bootstrap-libc)))
("cross-binutils" ,(cross-binutils target))
,@(%final-inputs)))
`(("libc" ,(glibc-for-bootstrap))
("gcc" ,(package (inherit gcc)
all in one so libgcc_s is easily found
(inputs
`(("libc",(glibc-for-bootstrap))
,@(package-inputs gcc)))))
,@(fold alist-delete (%final-inputs) '("libc" "gcc")))))
(package-with-explicit-inputs p inputs
(current-source-location)
#:native-inputs native-inputs))
(define %static-inputs
Packages that are to be used as % BOOTSTRAP - INPUTS .
(let ((coreutils (package (inherit coreutils)
(arguments
`(#:configure-flags
'("--disable-nls"
"--disable-silent-rules"
"--enable-no-install-program=stdbuf,libstdbuf.so"
"CFLAGS=-Os -g0" ; smaller, please
"LDFLAGS=-static -pthread")
signal - related Gnulib tests fail
,@(package-arguments coreutils)))
Remove optional dependencies such as GMP . Keep Perl
;; except if it's missing (which is the case when
;; cross-compiling).
(inputs (match (assoc "perl" (package-inputs coreutils))
(#f '())
(x (list x))))
;; Remove the 'debug' output (see above for the reason.)
(outputs '("out"))))
(bzip2 (package (inherit bzip2)
(arguments
(substitute-keyword-arguments (package-arguments bzip2)
((#:phases phases)
`(alist-cons-before
'build 'dash-static
(lambda _
(substitute* "Makefile"
(("^LDFLAGS[[:blank:]]*=.*$")
"LDFLAGS = -static")))
,phases))))))
(xz (package (inherit xz)
(arguments
`(#:strip-flags '("--strip-all")
#:phases (alist-cons-before
'configure 'static-executable
(lambda _
;; Ask Libtool for a static executable.
(substitute* "src/xz/Makefile.in"
(("^xz_LDADD =")
"xz_LDADD = -all-static")))
%standard-phases)))))
(gawk (package (inherit gawk)
(source (origin (inherit (package-source gawk))
(patches (cons (search-patch "gawk-shell.patch")
(origin-patches
(package-source gawk))))))
(arguments
Starting from gawk 4.1.0 , some of the tests for the
;; plug-in mechanism just fail on static builds:
;;
;; ./fts.awk:1: error: can't open shared library `filefuncs' for reading (No such file or directory)
#:tests? #f
,@(substitute-keyword-arguments (package-arguments gawk)
((#:phases phases)
`(alist-cons-before
'configure 'no-export-dynamic
(lambda _
;; Since we use `-static', remove
;; `-export-dynamic'.
(substitute* "configure"
(("-Wl,-export-dynamic") "")))
,phases)))))
(inputs (if (%current-target-system)
`(("bash" ,static-bash))
'()))))
(tar (package (inherit tar)
(arguments
'(#:phases (modify-phases %standard-phases
(add-before 'build 'set-shell-file-name
(lambda _
;; Do not use "/bin/sh" to run programs; see
;; <-devel/2016-09/msg02272.html>.
(substitute* "src/system.c"
(("/bin/sh") "sh")
(("execv ") "execvp "))
#t)))))))
(finalize (compose static-package
package-with-relocatable-glibc)))
`(,@(map (match-lambda
((name package)
(list name (finalize package))))
`(("tar" ,tar)
("gzip" ,gzip)
("bzip2" ,bzip2)
("xz" ,xz)
("patch" ,patch)
("coreutils" ,coreutils)
("sed" ,sed)
;; We don't want to retain a reference to /gnu/store in the
;; bootstrap versions of egrep/fgrep, so we remove the custom
;; phase added since grep@2.25. The effect is 'egrep' and
;; 'fgrep' look for 'grep' in $PATH.
("grep" ,(package
(inherit grep)
(arguments
(substitute-keyword-arguments (package-arguments grep)
((#:phases phases)
`(modify-phases ,phases
(delete 'fix-egrep-and-fgrep)))))))
("gawk" ,gawk)))
("bash" ,static-bash))))
(define %static-binaries
(package
(name "static-binaries")
(version "0")
(build-system trivial-build-system)
(source #f)
(inputs %static-inputs)
(arguments
`(#:modules ((guix build utils))
#:builder
(begin
(use-modules (ice-9 ftw)
(ice-9 match)
(srfi srfi-1)
(srfi srfi-26)
(guix build utils))
(let ()
(define (directory-contents dir)
(map (cut string-append dir "/" <>)
(scandir dir (negate (cut member <> '("." ".."))))))
(define (copy-directory source destination)
(for-each (lambda (file)
(format #t "copying ~s...~%" file)
(copy-file file
(string-append destination "/"
(basename file))))
(directory-contents source)))
(let* ((out (assoc-ref %outputs "out"))
(bin (string-append out "/bin")))
(mkdir-p bin)
;; Copy Coreutils binaries.
(let* ((coreutils (assoc-ref %build-inputs "coreutils"))
(source (string-append coreutils "/bin")))
(copy-directory source bin))
For the other inputs , copy just one binary , which has the
;; same name as the input.
(for-each (match-lambda
((name . dir)
(let ((source (string-append dir "/bin/" name)))
(format #t "copying ~s...~%" source)
(copy-file source
(string-append bin "/" name)))))
(alist-delete "coreutils" %build-inputs))
;; But of course, there are exceptions to this rule.
(let ((grep (assoc-ref %build-inputs "grep")))
(install-file (string-append grep "/bin/fgrep") bin)
(install-file (string-append grep "/bin/egrep") bin))
;; Clear references to the store path.
(for-each remove-store-references
(directory-contents bin))
(with-directory-excursion bin
Programs such as 's build system want these aliases .
(symlink "bash" "sh")
(symlink "gawk" "awk"))
#t)))))
(synopsis "Statically-linked bootstrap binaries")
(description
"Binaries used to bootstrap the distribution.")
(license gpl3+)
(home-page #f)))
(define %binutils-static
;; Statically-linked Binutils.
(package (inherit binutils)
(name "binutils-static")
(arguments
`(#:configure-flags (cons "--disable-gold"
,(match (memq #:configure-flags
(package-arguments binutils))
((#:configure-flags flags _ ...)
flags)))
#:strip-flags '("--strip-all")
#:phases (alist-cons-before
'configure 'all-static
(lambda _
;; The `-all-static' libtool flag can only be passed
;; after `configure', since configure tests don't use
;; libtool, and only for executables built with libtool.
(substitute* '("binutils/Makefile.in"
"gas/Makefile.in"
"ld/Makefile.in")
(("^LDFLAGS =(.*)$" line)
(string-append line
"\nAM_LDFLAGS = -static -all-static\n"))))
%standard-phases)))))
(define %binutils-static-stripped
;; The subset of Binutils that we need.
(package (inherit %binutils-static)
(name (string-append (package-name %binutils-static) "-stripped"))
(build-system trivial-build-system)
(outputs '("out"))
(arguments
`(#:modules ((guix build utils))
#:builder
(begin
(use-modules (guix build utils))
(setvbuf (current-output-port) _IOLBF)
(let* ((in (assoc-ref %build-inputs "binutils"))
(out (assoc-ref %outputs "out"))
(bin (string-append out "/bin")))
(mkdir-p bin)
(for-each (lambda (file)
(let ((target (string-append bin "/" file)))
(format #t "copying `~a'...~%" file)
(copy-file (string-append in "/bin/" file)
target)
(remove-store-references target)))
'("ar" "as" "ld" "nm" "objcopy" "objdump"
"ranlib" "readelf" "size" "strings" "strip"))
#t))))
(inputs `(("binutils" ,%binutils-static)))))
(define (%glibc-stripped)
GNU libc 's essential shared libraries , dynamic linker , and headers ,
;; with all references to store directories stripped. As a result,
;; libc.so is unusable and need to be patched for proper relocation.
(let ((glibc (glibc-for-bootstrap)))
(package (inherit glibc)
(name "glibc-stripped")
(build-system trivial-build-system)
(arguments
`(#:modules ((guix build utils)
(guix build make-bootstrap))
#:builder
(begin
(use-modules (guix build make-bootstrap))
(make-stripped-libc (assoc-ref %outputs "out")
(assoc-ref %build-inputs "libc")
(assoc-ref %build-inputs "kernel-headers")))))
(inputs `(("kernel-headers"
,(if (or (and (%current-target-system)
(hurd-triplet? (%current-target-system)))
(string-suffix? "-hurd" (%current-system)))
gnumach-headers
linux-libre-headers))
("libc" ,(let ((target (%current-target-system)))
(if target
(glibc-for-bootstrap
(parameterize ((%current-target-system #f))
(cross-libc target)))
glibc)))))
;; Only one output.
(outputs '("out")))))
(define %gcc-static
A statically - linked GCC , with stripped - down functionality .
(package-with-relocatable-glibc
(package (inherit gcc)
(name "gcc-static")
all in one
(arguments
`(#:modules ((guix build utils)
(guix build gnu-build-system)
(srfi srfi-1)
(srfi srfi-26)
(ice-9 regex))
,@(substitute-keyword-arguments (package-arguments gcc)
((#:guile _) #f)
((#:implicit-inputs? _) #t)
((#:configure-flags flags)
`(append (list
;; We don't need a full bootstrap here.
"--disable-bootstrap"
;; Make sure '-static' is passed where it matters.
"--with-stage1-ldflags=-static"
GCC 4.8 + requires a C++ compiler and library .
"--enable-languages=c,c++"
;; Make sure gcc-nm doesn't require liblto_plugin.so.
"--disable-lto"
"--disable-shared"
"--disable-plugin"
"--disable-libmudflap"
"--disable-libatomic"
"--disable-libsanitizer"
"--disable-libitm"
"--disable-libgomp"
"--disable-libcilkrts"
"--disable-libvtv"
"--disable-libssp"
"--disable-libquadmath")
(remove (cut string-match "--(.*plugin|enable-languages)" <>)
,flags)))
((#:phases phases)
`(alist-cons-after
'pre-configure 'remove-lgcc_s
(lambda _
Remove the ' -lgcc_s ' added to GNU_USER_TARGET_LIB_SPEC in
;; the 'pre-configure phase of our main gcc package, because
;; that shared library is not present in this static gcc. See
;; <-devel/2015-01/msg00008.html>.
(substitute* (cons "gcc/config/rs6000/sysv4.h"
(find-files "gcc/config"
"^gnu-user.*\\.h$"))
((" -lgcc_s}}") "}}")))
,phases)))))
(native-inputs
(if (%current-target-system)
When doing a Canadian cross , we need GMP / MPFR / MPC both
;; as target inputs and as native inputs; the latter is
;; needed when building build-time tools ('genconstants',
;; etc.) Failing to do that leads to misdetections of
;; declarations by 'gcc/configure', and eventually to
;; duplicate declarations as reported in
;; <>.
("gmp-native" ,gmp)
("mpfr-native" ,mpfr)
("mpc-native" ,mpc)
,@(package-native-inputs gcc))
(package-native-inputs gcc))))))
(define %gcc-stripped
The subset of GCC files needed for bootstrap .
(package (inherit gcc)
(name "gcc-stripped")
(build-system trivial-build-system)
(source #f)
only one output
(arguments
`(#:modules ((guix build utils))
#:builder
(begin
(use-modules (srfi srfi-1)
(srfi srfi-26)
(guix build utils))
(setvbuf (current-output-port) _IOLBF)
(let* ((out (assoc-ref %outputs "out"))
(bindir (string-append out "/bin"))
(libdir (string-append out "/lib"))
(includedir (string-append out "/include"))
(libexecdir (string-append out "/libexec"))
(gcc (assoc-ref %build-inputs "gcc")))
(copy-recursively (string-append gcc "/bin") bindir)
(for-each remove-store-references
(find-files bindir ".*"))
(copy-recursively (string-append gcc "/lib") libdir)
(for-each remove-store-references
(remove (cut string-suffix? ".h" <>)
(find-files libdir ".*")))
(copy-recursively (string-append gcc "/libexec")
libexecdir)
(for-each remove-store-references
(find-files libexecdir ".*"))
Starting from GCC 4.8 , helper programs built natively
( ‘ genchecksum ’ , ‘ gcc - nm ’ , etc . ) rely on C++ headers .
(copy-recursively (string-append gcc "/include/c++")
(string-append includedir "/c++"))
;; For native builds, check whether the binaries actually work.
,(if (%current-target-system)
'#t
'(every (lambda (prog)
(zero? (system* (string-append gcc "/bin/" prog)
"--version")))
'("gcc" "g++" "cpp")))))))
(inputs `(("gcc" ,%gcc-static)))))
(define %guile-static
A statically - linked that is relocatable -- i.e. , it can search
.scm and .go files relative to its installation directory , rather
;; than in hard-coded configure-time paths.
(let* ((patches (cons* (search-patch "guile-relocatable.patch")
(search-patch "guile-default-utf8.patch")
(search-patch "guile-linux-syscalls.patch")
(origin-patches (package-source guile-2.0))))
(source (origin (inherit (package-source guile-2.0))
(patches patches)))
(guile (package (inherit guile-2.0)
(name (string-append (package-name guile-2.0) "-static"))
(replacement #f)
(source source)
(synopsis "Statically-linked and relocatable Guile")
;; Remove the 'debug' output (see above for the reason.)
(outputs (delete "debug" (package-outputs guile-2.0)))
(propagated-inputs
`(("bdw-gc" ,libgc)
,@(alist-delete "bdw-gc"
(package-propagated-inputs guile-2.0))))
(arguments
`(;; When `configure' checks for ltdl availability, it
;; doesn't try to link using libtool, and thus fails
;; because of a missing -ldl. Work around that.
#:configure-flags '("LDFLAGS=-ldl")
#:phases (alist-cons-before
'configure 'static-guile
(lambda _
(substitute* "libguile/Makefile.in"
;; Create a statically-linked `guile'
;; executable.
(("^guile_LDFLAGS =")
"guile_LDFLAGS = -all-static")
;; Add `-ldl' *after* libguile-2.0.la.
(("^guile_LDADD =(.*)$" _ ldadd)
(string-append "guile_LDADD = "
(string-trim-right ldadd)
" -ldl\n"))))
%standard-phases)
;; There are uses of `dynamic-link' in
;; {foreign,coverage}.test that don't fly here.
#:tests? #f)))))
(package-with-relocatable-glibc (static-package guile))))
(define %guile-static-stripped
A stripped static binary , for use during bootstrap .
(package (inherit %guile-static)
(name "guile-static-stripped")
(build-system trivial-build-system)
(arguments
`(#:modules ((guix build utils))
#:builder
(let ()
(use-modules (guix build utils))
(let* ((in (assoc-ref %build-inputs "guile"))
(out (assoc-ref %outputs "out"))
(guile1 (string-append in "/bin/guile"))
(guile2 (string-append out "/bin/guile")))
(mkdir-p (string-append out "/share/guile/2.0"))
(copy-recursively (string-append in "/share/guile/2.0")
(string-append out "/share/guile/2.0"))
(mkdir-p (string-append out "/lib/guile/2.0/ccache"))
(copy-recursively (string-append in "/lib/guile/2.0/ccache")
(string-append out "/lib/guile/2.0/ccache"))
(mkdir (string-append out "/bin"))
(copy-file guile1 guile2)
Does the relocated work ?
(and ,(if (%current-target-system)
#t
'(zero? (system* guile2 "--version")))
(begin
Strip store references .
(remove-store-references guile2)
Does the stripped work ? If it aborts , it could be
;; that it tries to open iconv descriptors and fails because
libc 's iconv data is n't available ( see
;; `guile-default-utf8.patch'.)
,(if (%current-target-system)
#t
'(zero? (system* guile2 "--version")))))))))
(inputs `(("guile" ,%guile-static)))
(outputs '("out"))
(synopsis "Minimal statically-linked and relocatable Guile")))
(define (tarball-package pkg)
"Return a package containing a tarball of PKG."
(package (inherit pkg)
(name (string-append (package-name pkg) "-tarball"))
(build-system trivial-build-system)
(native-inputs `(("tar" ,tar)
("xz" ,xz)))
(inputs `(("input" ,pkg)))
(arguments
(let ((name (package-name pkg))
(version (package-version pkg)))
`(#:modules ((guix build utils))
#:builder
(begin
(use-modules (guix build utils))
(let ((out (assoc-ref %outputs "out"))
(input (assoc-ref %build-inputs "input"))
(tar (assoc-ref %build-inputs "tar"))
(xz (assoc-ref %build-inputs "xz")))
(mkdir out)
(set-path-environment-variable "PATH" '("bin") (list tar xz))
(with-directory-excursion input
(zero? (system* "tar" "cJvf"
(string-append out "/"
,name "-" ,version
"-"
,(or (%current-target-system)
(%current-system))
".tar.xz")
"."
;; avoid non-determinism in the archive
"--sort=name" "--mtime=@0"
"--owner=root:0" "--group=root:0"))))))))))
(define %bootstrap-binaries-tarball
;; A tarball with the statically-linked bootstrap binaries.
(tarball-package %static-binaries))
(define %binutils-bootstrap-tarball
A tarball with the statically - linked Binutils programs .
(tarball-package %binutils-static-stripped))
(define (%glibc-bootstrap-tarball)
A tarball with GNU libc 's shared libraries , dynamic linker , and headers .
(tarball-package (%glibc-stripped)))
(define %gcc-bootstrap-tarball
A tarball with a dynamic - linked GCC and its headers .
(tarball-package %gcc-stripped))
(define %guile-bootstrap-tarball
A tarball with the statically - linked , relocatable .
(tarball-package %guile-static-stripped))
(define %bootstrap-tarballs
;; A single derivation containing all the bootstrap tarballs, for
;; convenience.
(package
(name "bootstrap-tarballs")
(version "0")
(source #f)
(build-system trivial-build-system)
(arguments
`(#:modules ((guix build utils))
#:builder
(let ((out (assoc-ref %outputs "out")))
(use-modules (guix build utils)
(ice-9 match)
(srfi srfi-26))
(setvbuf (current-output-port) _IOLBF)
(mkdir out)
(chdir out)
(for-each (match-lambda
((name . directory)
(for-each (lambda (file)
(format #t "~a -> ~a~%" file out)
(symlink file (basename file)))
(find-files directory "\\.tar\\."))))
%build-inputs)
#t)))
(inputs `(("guile-tarball" ,%guile-bootstrap-tarball)
("gcc-tarball" ,%gcc-bootstrap-tarball)
("binutils-tarball" ,%binutils-bootstrap-tarball)
("glibc-tarball" ,(%glibc-bootstrap-tarball))
("coreutils&co-tarball" ,%bootstrap-binaries-tarball)))
(synopsis "Tarballs containing all the bootstrap binaries")
(description synopsis)
(home-page #f)
(license gpl3+)))
;;; make-bootstrap.scm ends here
| null | https://raw.githubusercontent.com/ragkousism/Guix-on-Hurd/e951bb2c0c4961dc6ac2bda8f331b9c4cee0da95/gnu/packages/make-bootstrap.scm | scheme | GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix 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.
Commentary:
This module provides tools to build tarballs of the "bootstrap binaries"
used in (gnu packages bootstrap). These statically-linked binaries are
taken for granted and used as the root of the whole bootstrap procedure.
Code:
Remove the 'debug' output to allow bit-reproducible builds (when the
'debug' output is used, ELF files end up with a .gnu_debuglink, which
those symbols
`cross-libc' already returns a cross libc, so clear
%CURRENT-TARGET-SYSTEM.
is this package cross built?
smaller, please
except if it's missing (which is the case when
cross-compiling).
Remove the 'debug' output (see above for the reason.)
Ask Libtool for a static executable.
plug-in mechanism just fail on static builds:
./fts.awk:1: error: can't open shared library `filefuncs' for reading (No such file or directory)
Since we use `-static', remove
`-export-dynamic'.
Do not use "/bin/sh" to run programs; see
<-devel/2016-09/msg02272.html>.
We don't want to retain a reference to /gnu/store in the
bootstrap versions of egrep/fgrep, so we remove the custom
phase added since grep@2.25. The effect is 'egrep' and
'fgrep' look for 'grep' in $PATH.
Copy Coreutils binaries.
same name as the input.
But of course, there are exceptions to this rule.
Clear references to the store path.
Statically-linked Binutils.
The `-all-static' libtool flag can only be passed
after `configure', since configure tests don't use
libtool, and only for executables built with libtool.
The subset of Binutils that we need.
with all references to store directories stripped. As a result,
libc.so is unusable and need to be patched for proper relocation.
Only one output.
We don't need a full bootstrap here.
Make sure '-static' is passed where it matters.
Make sure gcc-nm doesn't require liblto_plugin.so.
the 'pre-configure phase of our main gcc package, because
that shared library is not present in this static gcc. See
<-devel/2015-01/msg00008.html>.
as target inputs and as native inputs; the latter is
needed when building build-time tools ('genconstants',
etc.) Failing to do that leads to misdetections of
declarations by 'gcc/configure', and eventually to
duplicate declarations as reported in
<>.
For native builds, check whether the binaries actually work.
than in hard-coded configure-time paths.
Remove the 'debug' output (see above for the reason.)
When `configure' checks for ltdl availability, it
doesn't try to link using libtool, and thus fails
because of a missing -ldl. Work around that.
Create a statically-linked `guile'
executable.
Add `-ldl' *after* libguile-2.0.la.
There are uses of `dynamic-link' in
{foreign,coverage}.test that don't fly here.
that it tries to open iconv descriptors and fails because
`guile-default-utf8.patch'.)
avoid non-determinism in the archive
A tarball with the statically-linked bootstrap binaries.
A single derivation containing all the bootstrap tarballs, for
convenience.
make-bootstrap.scm ends here | Copyright © 2012 , 2013 , 2014 , 2015 , 2016 < >
Copyright © 2017 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages make-bootstrap)
#:use-module (guix utils)
#:use-module (guix packages)
#:use-module (guix licenses)
#:use-module (guix build-system trivial)
#:use-module (guix build-system gnu)
#:use-module ((gnu packages) #:select (search-patch))
#:use-module (gnu packages base)
#:use-module (gnu packages cross-base)
#:use-module (gnu packages bash)
#:use-module (gnu packages compression)
#:use-module (gnu packages gawk)
#:use-module (gnu packages gcc)
#:use-module (gnu packages guile)
#:use-module (gnu packages bdw-gc)
#:use-module (gnu packages linux)
#:use-module (gnu packages hurd)
#:use-module (gnu packages multiprecision)
#:use-module (ice-9 match)
#:use-module (srfi srfi-1)
#:export (%bootstrap-binaries-tarball
%binutils-bootstrap-tarball
%glibc-bootstrap-tarball
%gcc-bootstrap-tarball
%guile-bootstrap-tarball
%bootstrap-tarballs
%guile-static-stripped))
(define* (glibc-for-bootstrap #:optional (base glibc))
"Return a libc deriving from BASE whose `system' and `popen' functions looks
for `sh' in $PATH, and without nscd, and with static NSS modules."
(package (inherit base)
(source (origin (inherit (package-source base))
(patches (cons (search-patch "glibc-bootstrap-system.patch")
(origin-patches (package-source base))))))
(arguments
(substitute-keyword-arguments (package-arguments base)
((#:configure-flags flags)
Arrange so that getaddrinfo & co. do not contact the nscd ,
and can use statically - linked NSS modules .
`(cons* "--disable-nscd" "--disable-build-nscd"
"--enable-static-nss"
,flags))))
contain store file names , so the CRC changes at every rebuild . )
(outputs (delete "debug" (package-outputs base)))))
(define (package-with-relocatable-glibc p)
"Return a variant of P that uses the libc as defined by
`glibc-for-bootstrap'."
(define (cross-bootstrap-libc)
(let ((target (%current-target-system)))
(glibc-for-bootstrap
(parameterize ((%current-target-system #f))
(cross-libc target)))))
Standard inputs with the above libc and corresponding GCC .
(define (inputs)
`(("cross-libc" ,(cross-bootstrap-libc)))
'()))
(define (native-inputs)
(if (%current-target-system)
(let ((target (%current-target-system)))
`(("cross-gcc" ,(cross-gcc target
(cross-binutils target)
(cross-bootstrap-libc)))
("cross-binutils" ,(cross-binutils target))
,@(%final-inputs)))
`(("libc" ,(glibc-for-bootstrap))
("gcc" ,(package (inherit gcc)
all in one so libgcc_s is easily found
(inputs
`(("libc",(glibc-for-bootstrap))
,@(package-inputs gcc)))))
,@(fold alist-delete (%final-inputs) '("libc" "gcc")))))
(package-with-explicit-inputs p inputs
(current-source-location)
#:native-inputs native-inputs))
(define %static-inputs
Packages that are to be used as % BOOTSTRAP - INPUTS .
(let ((coreutils (package (inherit coreutils)
(arguments
`(#:configure-flags
'("--disable-nls"
"--disable-silent-rules"
"--enable-no-install-program=stdbuf,libstdbuf.so"
"LDFLAGS=-static -pthread")
signal - related Gnulib tests fail
,@(package-arguments coreutils)))
Remove optional dependencies such as GMP . Keep Perl
(inputs (match (assoc "perl" (package-inputs coreutils))
(#f '())
(x (list x))))
(outputs '("out"))))
(bzip2 (package (inherit bzip2)
(arguments
(substitute-keyword-arguments (package-arguments bzip2)
((#:phases phases)
`(alist-cons-before
'build 'dash-static
(lambda _
(substitute* "Makefile"
(("^LDFLAGS[[:blank:]]*=.*$")
"LDFLAGS = -static")))
,phases))))))
(xz (package (inherit xz)
(arguments
`(#:strip-flags '("--strip-all")
#:phases (alist-cons-before
'configure 'static-executable
(lambda _
(substitute* "src/xz/Makefile.in"
(("^xz_LDADD =")
"xz_LDADD = -all-static")))
%standard-phases)))))
(gawk (package (inherit gawk)
(source (origin (inherit (package-source gawk))
(patches (cons (search-patch "gawk-shell.patch")
(origin-patches
(package-source gawk))))))
(arguments
Starting from gawk 4.1.0 , some of the tests for the
#:tests? #f
,@(substitute-keyword-arguments (package-arguments gawk)
((#:phases phases)
`(alist-cons-before
'configure 'no-export-dynamic
(lambda _
(substitute* "configure"
(("-Wl,-export-dynamic") "")))
,phases)))))
(inputs (if (%current-target-system)
`(("bash" ,static-bash))
'()))))
(tar (package (inherit tar)
(arguments
'(#:phases (modify-phases %standard-phases
(add-before 'build 'set-shell-file-name
(lambda _
(substitute* "src/system.c"
(("/bin/sh") "sh")
(("execv ") "execvp "))
#t)))))))
(finalize (compose static-package
package-with-relocatable-glibc)))
`(,@(map (match-lambda
((name package)
(list name (finalize package))))
`(("tar" ,tar)
("gzip" ,gzip)
("bzip2" ,bzip2)
("xz" ,xz)
("patch" ,patch)
("coreutils" ,coreutils)
("sed" ,sed)
("grep" ,(package
(inherit grep)
(arguments
(substitute-keyword-arguments (package-arguments grep)
((#:phases phases)
`(modify-phases ,phases
(delete 'fix-egrep-and-fgrep)))))))
("gawk" ,gawk)))
("bash" ,static-bash))))
(define %static-binaries
(package
(name "static-binaries")
(version "0")
(build-system trivial-build-system)
(source #f)
(inputs %static-inputs)
(arguments
`(#:modules ((guix build utils))
#:builder
(begin
(use-modules (ice-9 ftw)
(ice-9 match)
(srfi srfi-1)
(srfi srfi-26)
(guix build utils))
(let ()
(define (directory-contents dir)
(map (cut string-append dir "/" <>)
(scandir dir (negate (cut member <> '("." ".."))))))
(define (copy-directory source destination)
(for-each (lambda (file)
(format #t "copying ~s...~%" file)
(copy-file file
(string-append destination "/"
(basename file))))
(directory-contents source)))
(let* ((out (assoc-ref %outputs "out"))
(bin (string-append out "/bin")))
(mkdir-p bin)
(let* ((coreutils (assoc-ref %build-inputs "coreutils"))
(source (string-append coreutils "/bin")))
(copy-directory source bin))
For the other inputs , copy just one binary , which has the
(for-each (match-lambda
((name . dir)
(let ((source (string-append dir "/bin/" name)))
(format #t "copying ~s...~%" source)
(copy-file source
(string-append bin "/" name)))))
(alist-delete "coreutils" %build-inputs))
(let ((grep (assoc-ref %build-inputs "grep")))
(install-file (string-append grep "/bin/fgrep") bin)
(install-file (string-append grep "/bin/egrep") bin))
(for-each remove-store-references
(directory-contents bin))
(with-directory-excursion bin
Programs such as 's build system want these aliases .
(symlink "bash" "sh")
(symlink "gawk" "awk"))
#t)))))
(synopsis "Statically-linked bootstrap binaries")
(description
"Binaries used to bootstrap the distribution.")
(license gpl3+)
(home-page #f)))
(define %binutils-static
(package (inherit binutils)
(name "binutils-static")
(arguments
`(#:configure-flags (cons "--disable-gold"
,(match (memq #:configure-flags
(package-arguments binutils))
((#:configure-flags flags _ ...)
flags)))
#:strip-flags '("--strip-all")
#:phases (alist-cons-before
'configure 'all-static
(lambda _
(substitute* '("binutils/Makefile.in"
"gas/Makefile.in"
"ld/Makefile.in")
(("^LDFLAGS =(.*)$" line)
(string-append line
"\nAM_LDFLAGS = -static -all-static\n"))))
%standard-phases)))))
(define %binutils-static-stripped
(package (inherit %binutils-static)
(name (string-append (package-name %binutils-static) "-stripped"))
(build-system trivial-build-system)
(outputs '("out"))
(arguments
`(#:modules ((guix build utils))
#:builder
(begin
(use-modules (guix build utils))
(setvbuf (current-output-port) _IOLBF)
(let* ((in (assoc-ref %build-inputs "binutils"))
(out (assoc-ref %outputs "out"))
(bin (string-append out "/bin")))
(mkdir-p bin)
(for-each (lambda (file)
(let ((target (string-append bin "/" file)))
(format #t "copying `~a'...~%" file)
(copy-file (string-append in "/bin/" file)
target)
(remove-store-references target)))
'("ar" "as" "ld" "nm" "objcopy" "objdump"
"ranlib" "readelf" "size" "strings" "strip"))
#t))))
(inputs `(("binutils" ,%binutils-static)))))
(define (%glibc-stripped)
GNU libc 's essential shared libraries , dynamic linker , and headers ,
(let ((glibc (glibc-for-bootstrap)))
(package (inherit glibc)
(name "glibc-stripped")
(build-system trivial-build-system)
(arguments
`(#:modules ((guix build utils)
(guix build make-bootstrap))
#:builder
(begin
(use-modules (guix build make-bootstrap))
(make-stripped-libc (assoc-ref %outputs "out")
(assoc-ref %build-inputs "libc")
(assoc-ref %build-inputs "kernel-headers")))))
(inputs `(("kernel-headers"
,(if (or (and (%current-target-system)
(hurd-triplet? (%current-target-system)))
(string-suffix? "-hurd" (%current-system)))
gnumach-headers
linux-libre-headers))
("libc" ,(let ((target (%current-target-system)))
(if target
(glibc-for-bootstrap
(parameterize ((%current-target-system #f))
(cross-libc target)))
glibc)))))
(outputs '("out")))))
(define %gcc-static
A statically - linked GCC , with stripped - down functionality .
(package-with-relocatable-glibc
(package (inherit gcc)
(name "gcc-static")
all in one
(arguments
`(#:modules ((guix build utils)
(guix build gnu-build-system)
(srfi srfi-1)
(srfi srfi-26)
(ice-9 regex))
,@(substitute-keyword-arguments (package-arguments gcc)
((#:guile _) #f)
((#:implicit-inputs? _) #t)
((#:configure-flags flags)
`(append (list
"--disable-bootstrap"
"--with-stage1-ldflags=-static"
GCC 4.8 + requires a C++ compiler and library .
"--enable-languages=c,c++"
"--disable-lto"
"--disable-shared"
"--disable-plugin"
"--disable-libmudflap"
"--disable-libatomic"
"--disable-libsanitizer"
"--disable-libitm"
"--disable-libgomp"
"--disable-libcilkrts"
"--disable-libvtv"
"--disable-libssp"
"--disable-libquadmath")
(remove (cut string-match "--(.*plugin|enable-languages)" <>)
,flags)))
((#:phases phases)
`(alist-cons-after
'pre-configure 'remove-lgcc_s
(lambda _
Remove the ' -lgcc_s ' added to GNU_USER_TARGET_LIB_SPEC in
(substitute* (cons "gcc/config/rs6000/sysv4.h"
(find-files "gcc/config"
"^gnu-user.*\\.h$"))
((" -lgcc_s}}") "}}")))
,phases)))))
(native-inputs
(if (%current-target-system)
When doing a Canadian cross , we need GMP / MPFR / MPC both
("gmp-native" ,gmp)
("mpfr-native" ,mpfr)
("mpc-native" ,mpc)
,@(package-native-inputs gcc))
(package-native-inputs gcc))))))
(define %gcc-stripped
The subset of GCC files needed for bootstrap .
(package (inherit gcc)
(name "gcc-stripped")
(build-system trivial-build-system)
(source #f)
only one output
(arguments
`(#:modules ((guix build utils))
#:builder
(begin
(use-modules (srfi srfi-1)
(srfi srfi-26)
(guix build utils))
(setvbuf (current-output-port) _IOLBF)
(let* ((out (assoc-ref %outputs "out"))
(bindir (string-append out "/bin"))
(libdir (string-append out "/lib"))
(includedir (string-append out "/include"))
(libexecdir (string-append out "/libexec"))
(gcc (assoc-ref %build-inputs "gcc")))
(copy-recursively (string-append gcc "/bin") bindir)
(for-each remove-store-references
(find-files bindir ".*"))
(copy-recursively (string-append gcc "/lib") libdir)
(for-each remove-store-references
(remove (cut string-suffix? ".h" <>)
(find-files libdir ".*")))
(copy-recursively (string-append gcc "/libexec")
libexecdir)
(for-each remove-store-references
(find-files libexecdir ".*"))
Starting from GCC 4.8 , helper programs built natively
( ‘ genchecksum ’ , ‘ gcc - nm ’ , etc . ) rely on C++ headers .
(copy-recursively (string-append gcc "/include/c++")
(string-append includedir "/c++"))
,(if (%current-target-system)
'#t
'(every (lambda (prog)
(zero? (system* (string-append gcc "/bin/" prog)
"--version")))
'("gcc" "g++" "cpp")))))))
(inputs `(("gcc" ,%gcc-static)))))
(define %guile-static
A statically - linked that is relocatable -- i.e. , it can search
.scm and .go files relative to its installation directory , rather
(let* ((patches (cons* (search-patch "guile-relocatable.patch")
(search-patch "guile-default-utf8.patch")
(search-patch "guile-linux-syscalls.patch")
(origin-patches (package-source guile-2.0))))
(source (origin (inherit (package-source guile-2.0))
(patches patches)))
(guile (package (inherit guile-2.0)
(name (string-append (package-name guile-2.0) "-static"))
(replacement #f)
(source source)
(synopsis "Statically-linked and relocatable Guile")
(outputs (delete "debug" (package-outputs guile-2.0)))
(propagated-inputs
`(("bdw-gc" ,libgc)
,@(alist-delete "bdw-gc"
(package-propagated-inputs guile-2.0))))
(arguments
#:configure-flags '("LDFLAGS=-ldl")
#:phases (alist-cons-before
'configure 'static-guile
(lambda _
(substitute* "libguile/Makefile.in"
(("^guile_LDFLAGS =")
"guile_LDFLAGS = -all-static")
(("^guile_LDADD =(.*)$" _ ldadd)
(string-append "guile_LDADD = "
(string-trim-right ldadd)
" -ldl\n"))))
%standard-phases)
#:tests? #f)))))
(package-with-relocatable-glibc (static-package guile))))
(define %guile-static-stripped
A stripped static binary , for use during bootstrap .
(package (inherit %guile-static)
(name "guile-static-stripped")
(build-system trivial-build-system)
(arguments
`(#:modules ((guix build utils))
#:builder
(let ()
(use-modules (guix build utils))
(let* ((in (assoc-ref %build-inputs "guile"))
(out (assoc-ref %outputs "out"))
(guile1 (string-append in "/bin/guile"))
(guile2 (string-append out "/bin/guile")))
(mkdir-p (string-append out "/share/guile/2.0"))
(copy-recursively (string-append in "/share/guile/2.0")
(string-append out "/share/guile/2.0"))
(mkdir-p (string-append out "/lib/guile/2.0/ccache"))
(copy-recursively (string-append in "/lib/guile/2.0/ccache")
(string-append out "/lib/guile/2.0/ccache"))
(mkdir (string-append out "/bin"))
(copy-file guile1 guile2)
Does the relocated work ?
(and ,(if (%current-target-system)
#t
'(zero? (system* guile2 "--version")))
(begin
Strip store references .
(remove-store-references guile2)
Does the stripped work ? If it aborts , it could be
libc 's iconv data is n't available ( see
,(if (%current-target-system)
#t
'(zero? (system* guile2 "--version")))))))))
(inputs `(("guile" ,%guile-static)))
(outputs '("out"))
(synopsis "Minimal statically-linked and relocatable Guile")))
(define (tarball-package pkg)
"Return a package containing a tarball of PKG."
(package (inherit pkg)
(name (string-append (package-name pkg) "-tarball"))
(build-system trivial-build-system)
(native-inputs `(("tar" ,tar)
("xz" ,xz)))
(inputs `(("input" ,pkg)))
(arguments
(let ((name (package-name pkg))
(version (package-version pkg)))
`(#:modules ((guix build utils))
#:builder
(begin
(use-modules (guix build utils))
(let ((out (assoc-ref %outputs "out"))
(input (assoc-ref %build-inputs "input"))
(tar (assoc-ref %build-inputs "tar"))
(xz (assoc-ref %build-inputs "xz")))
(mkdir out)
(set-path-environment-variable "PATH" '("bin") (list tar xz))
(with-directory-excursion input
(zero? (system* "tar" "cJvf"
(string-append out "/"
,name "-" ,version
"-"
,(or (%current-target-system)
(%current-system))
".tar.xz")
"."
"--sort=name" "--mtime=@0"
"--owner=root:0" "--group=root:0"))))))))))
(define %bootstrap-binaries-tarball
(tarball-package %static-binaries))
(define %binutils-bootstrap-tarball
A tarball with the statically - linked Binutils programs .
(tarball-package %binutils-static-stripped))
(define (%glibc-bootstrap-tarball)
A tarball with GNU libc 's shared libraries , dynamic linker , and headers .
(tarball-package (%glibc-stripped)))
(define %gcc-bootstrap-tarball
A tarball with a dynamic - linked GCC and its headers .
(tarball-package %gcc-stripped))
(define %guile-bootstrap-tarball
A tarball with the statically - linked , relocatable .
(tarball-package %guile-static-stripped))
(define %bootstrap-tarballs
(package
(name "bootstrap-tarballs")
(version "0")
(source #f)
(build-system trivial-build-system)
(arguments
`(#:modules ((guix build utils))
#:builder
(let ((out (assoc-ref %outputs "out")))
(use-modules (guix build utils)
(ice-9 match)
(srfi srfi-26))
(setvbuf (current-output-port) _IOLBF)
(mkdir out)
(chdir out)
(for-each (match-lambda
((name . directory)
(for-each (lambda (file)
(format #t "~a -> ~a~%" file out)
(symlink file (basename file)))
(find-files directory "\\.tar\\."))))
%build-inputs)
#t)))
(inputs `(("guile-tarball" ,%guile-bootstrap-tarball)
("gcc-tarball" ,%gcc-bootstrap-tarball)
("binutils-tarball" ,%binutils-bootstrap-tarball)
("glibc-tarball" ,(%glibc-bootstrap-tarball))
("coreutils&co-tarball" ,%bootstrap-binaries-tarball)))
(synopsis "Tarballs containing all the bootstrap binaries")
(description synopsis)
(home-page #f)
(license gpl3+)))
|
9b9e5066f2372d641aac86ca89bb46c8536834e81ed570a970e4ed38881aab49 | RutledgePaulV/datalogger | provider_test.clj | (ns datalogger.impl.provider-test
(:require [clojure.test :refer :all])
(:import [datalogger.impl provider]))
(deftest getRequestedApiVersion-test
(is (string? (.getRequestedApiVersion (new provider)))))
| null | https://raw.githubusercontent.com/RutledgePaulV/datalogger/2bd99d7bac4f69583c49f98acdfe4aa16de6926d/test/datalogger/impl/provider_test.clj | clojure | (ns datalogger.impl.provider-test
(:require [clojure.test :refer :all])
(:import [datalogger.impl provider]))
(deftest getRequestedApiVersion-test
(is (string? (.getRequestedApiVersion (new provider)))))
| |
ceb5a8f4a021392eb5823ed6e39ddcc2321e4f9861995d38ab1df3065853515a | Cognician/datomic-doc | service.clj | (ns cognician.datomic-doc.service
(:require [cognician.datomic-doc :as dd]
[cognician.datomic-doc.ring :as ring]
[org.httpkit.server :as http]
[ring.util.response :as response]))
(def db-uri
"Fill in your own database uri here, or if you just want to demo,
follow the steps at -sample#getting-the-data
to download a data set."
"datomic:free:4334/*")
(def config
{::dd/datomic-uri db-uri
::dd/allow-read-pred (constantly true)
::dd/allow-write-pred (constantly true)
::dd/deprecated-attr :cognician/deprecated
::dd/dev-mode? true})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Web server
(def handler
(ring/wrap-datomic-doc #(response/response (pr-str %)) config))
(defonce server (atom nil))
(defn start-web []
(reset! server (http/run-server handler {:port 8080})))
(defn stop-web []
(when-let [stop-fn @server]
(stop-fn))
(reset! server nil))
| null | https://raw.githubusercontent.com/Cognician/datomic-doc/93b52e5778a1e1083c4f7b333518bfc8c344a725/src/cognician/datomic_doc/service.clj | clojure |
Web server | (ns cognician.datomic-doc.service
(:require [cognician.datomic-doc :as dd]
[cognician.datomic-doc.ring :as ring]
[org.httpkit.server :as http]
[ring.util.response :as response]))
(def db-uri
"Fill in your own database uri here, or if you just want to demo,
follow the steps at -sample#getting-the-data
to download a data set."
"datomic:free:4334/*")
(def config
{::dd/datomic-uri db-uri
::dd/allow-read-pred (constantly true)
::dd/allow-write-pred (constantly true)
::dd/deprecated-attr :cognician/deprecated
::dd/dev-mode? true})
(def handler
(ring/wrap-datomic-doc #(response/response (pr-str %)) config))
(defonce server (atom nil))
(defn start-web []
(reset! server (http/run-server handler {:port 8080})))
(defn stop-web []
(when-let [stop-fn @server]
(stop-fn))
(reset! server nil))
|
f76da4beb73d9ba9579c022e9b2e59e0442e3868b2d784955eb3c352f321232e | chiroptical/book-of-monads | FreeStyle.hs | # LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE DeriveFunctor #
# LANGUAGE TypeOperators #
module FreeStyle where
import Free
data FSF r =
WriteFile FilePath String (Either IOError () -> r)
| ReadFile FilePath (Either IOError String -> r)
deriving Functor
data RandomGenF r = Random Int Int deriving Functor
data FSRandomF r = FSF r :+: RandomGenF r
-- Free r, r :k: * -> * (:k: reads "with kind")
type FSRandom = Free FSRandomF
type FSRandom = Free (FSF :+: RandomGenF)
data (f :+: g) a = InL (f a) | InR (g a)
Exercise 14.1 , show that Sum f g is a Functor if both f and g are Functors
instance (Functor f, Functor g) => Functor (f :+: g) where
fmap f (InR fa) = InR $ f <$> fa
fmap f (InL fa) = InL $ f <$> fa
Interpretation will take the following shape , where { M } is the Monad to transform to
-- interpret = foldFree interpret'
-- where
-- interpret' :: (f :+: g) a -> {M} a
-- interpret' = _a
combine :: (f a -> m a) -> (g a -> m a) -> (f :+: g) a -> m a
combine f _ (InL x) = f x
combine _ g (InR x) = g x
writeFile :: FilePath -> String -> FSRandom (Either IOError ())
writeFile path contents = liftF (InL $ WriteFile path contents id)
readFile :: FilePath -> FSRandom (Either IOError String)
readFile path = liftF (InL $ ReadFile path id)
random :: Int -> Int -> FSRandom Int
random x y = liftF (InR $ Random x y)
class f :<: g where
inject :: f a -> g a
instance f :<: f where
inject = id
instance f :<: (f :+: g) where
inject = InL
instance (f :<: h) => f :<: (g :+: h) where
inject = InR . inject
writeFile_ :: (Functor f, FSF :<: f) => FilePath -> String -> Free f (Either IOError ())
writeFile_ path contents = liftF (inject $ WriteFile path contents id)
readFile_ :: (Functor f, FSF :<: f) => FilePath -> Free f (Either IOError String)
readFile_ path = liftF (inject $ ReadFile path id)
random_ :: (Functor f, RandomGenF :<: f) => Int -> Int -> Free f Int
random_ x y = liftF (inject $ Random x y)
randomWrite :: (Functor f, FSF :<: f, RandomGenF :<: f) => FilePath -> Free f (Either IOError ())
randomWrite path = do
number <- random_ 1 100
writeFile_ path (show number)
| null | https://raw.githubusercontent.com/chiroptical/book-of-monads/c2eff1c67a8958b28cfd2001d652f8b68e7c84df/chapter14/src/FreeStyle.hs | haskell | Free r, r :k: * -> * (:k: reads "with kind")
interpret = foldFree interpret'
where
interpret' :: (f :+: g) a -> {M} a
interpret' = _a | # LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE DeriveFunctor #
# LANGUAGE TypeOperators #
module FreeStyle where
import Free
data FSF r =
WriteFile FilePath String (Either IOError () -> r)
| ReadFile FilePath (Either IOError String -> r)
deriving Functor
data RandomGenF r = Random Int Int deriving Functor
data FSRandomF r = FSF r :+: RandomGenF r
type FSRandom = Free FSRandomF
type FSRandom = Free (FSF :+: RandomGenF)
data (f :+: g) a = InL (f a) | InR (g a)
Exercise 14.1 , show that Sum f g is a Functor if both f and g are Functors
instance (Functor f, Functor g) => Functor (f :+: g) where
fmap f (InR fa) = InR $ f <$> fa
fmap f (InL fa) = InL $ f <$> fa
Interpretation will take the following shape , where { M } is the Monad to transform to
combine :: (f a -> m a) -> (g a -> m a) -> (f :+: g) a -> m a
combine f _ (InL x) = f x
combine _ g (InR x) = g x
writeFile :: FilePath -> String -> FSRandom (Either IOError ())
writeFile path contents = liftF (InL $ WriteFile path contents id)
readFile :: FilePath -> FSRandom (Either IOError String)
readFile path = liftF (InL $ ReadFile path id)
random :: Int -> Int -> FSRandom Int
random x y = liftF (InR $ Random x y)
class f :<: g where
inject :: f a -> g a
instance f :<: f where
inject = id
instance f :<: (f :+: g) where
inject = InL
instance (f :<: h) => f :<: (g :+: h) where
inject = InR . inject
writeFile_ :: (Functor f, FSF :<: f) => FilePath -> String -> Free f (Either IOError ())
writeFile_ path contents = liftF (inject $ WriteFile path contents id)
readFile_ :: (Functor f, FSF :<: f) => FilePath -> Free f (Either IOError String)
readFile_ path = liftF (inject $ ReadFile path id)
random_ :: (Functor f, RandomGenF :<: f) => Int -> Int -> Free f Int
random_ x y = liftF (inject $ Random x y)
randomWrite :: (Functor f, FSF :<: f, RandomGenF :<: f) => FilePath -> Free f (Either IOError ())
randomWrite path = do
number <- random_ 1 100
writeFile_ path (show number)
|
58336e267fafecd8c2417be17fcc72cffd71ee65497170eb8984907bea24bb4d | metabase/metabase | cron.clj | (ns metabase.util.cron
"Utility functions for converting frontend schedule dictionaries to cron strings and vice versa.
See -scheduler.org/documentation/quartz-2.x/tutorials/crontrigger.html#format for details on cron
format."
(:require
[clojure.string :as str]
[metabase.util.i18n :as i18n]
[metabase.util.schema :as su]
[schema.core :as s])
(:import
(net.redhogs.cronparser CronExpressionDescriptor)
(org.quartz CronExpression)))
(set! *warn-on-reflection* true)
(def CronScheduleString
"Schema for a valid cron schedule string."
(su/with-api-error-message
(s/constrained
su/NonBlankString
(fn [^String s]
(try (CronExpression/validateExpression s)
true
(catch Throwable _
false)))
"Invalid cron schedule string.")
"value must be a valid Quartz cron schedule string."))
(def ^:private CronHour
(s/constrained s/Int (fn [n] (<= 0 n 23))))
(def ^:private CronMinute
(s/constrained s/Int (fn [n] (<= 0 n 59))))
(def ScheduleMap
"Schema for a frontend-parsable schedule map. Used for Pulses and DB scheduling."
(su/with-api-error-message
(s/named
{(s/optional-key :schedule_day) (s/maybe (s/enum "sun" "mon" "tue" "wed" "thu" "fri" "sat"))
(s/optional-key :schedule_frame) (s/maybe (s/enum "first" "mid" "last"))
(s/optional-key :schedule_hour) (s/maybe CronHour)
(s/optional-key :schedule_minute) (s/maybe CronMinute)
:schedule_type (s/enum "hourly" "daily" "weekly" "monthly")}
"Expanded schedule map")
"value must be a valid schedule map. See schema in metabase.util.cron for details."))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | SCHEDULE MAP -> CRON STRING |
;;; +----------------------------------------------------------------------------------------------------------------+
(s/defn ^:private cron-string :- CronScheduleString
"Build a cron string from key-value pair parts."
{:style/indent 0}
[{:keys [seconds minutes hours day-of-month month day-of-week year]}]
(str/join " " [(or seconds "0")
(or minutes "0")
(or hours "*")
(or day-of-month "*")
(or month "*")
(or day-of-week "?")
(or year "*")]))
(def ^:private day-of-week->cron
{"sun" 1
"mon" 2
"tue" 3
"wed" 4
"thu" 5
"fri" 6
"sat" 7})
(defn- frame->cron [frame day-of-week]
(if day-of-week
;; specific days of week like Mon or Fri
(assoc {:day-of-month "?"}
:day-of-week (case frame
"first" (str (day-of-week->cron day-of-week) "#1")
"last" (str (day-of-week->cron day-of-week) "L")))
specific CALENDAR DAYS like 1st or 15th
(assoc {:day-of-week "?"}
:day-of-month (case frame
"first" "1"
"mid" "15"
"last" "L"))))
(s/defn ^{:style/indent 0} schedule-map->cron-string :- CronScheduleString
"Convert the frontend schedule map into a cron string."
[{day-of-week :schedule_day, hour :schedule_hour, minute :schedule_minute,
frame :schedule_frame, schedule-type :schedule_type} :- ScheduleMap]
(cron-string (case (keyword schedule-type)
:hourly {:minutes minute}
:daily {:hours (or hour 0)}
:weekly {:hours hour
:day-of-week (day-of-week->cron day-of-week)
:day-of-month "?"}
:monthly (assoc (frame->cron frame day-of-week)
:hours hour))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | CRON STRING -> SCHEDULE MAP |
;;; +----------------------------------------------------------------------------------------------------------------+
(defn- cron->day-of-week [day-of-week]
(when-let [[_ day-of-week] (re-matches #"(^\d).*$" day-of-week)]
(case day-of-week
"1" "sun"
"2" "mon"
"3" "tue"
"4" "wed"
"5" "thu"
"6" "fri"
"7" "sat")))
(defn- cron-day-of-week+day-of-month->frame [day-of-week day-of-month]
(cond
(re-matches #"^\d#1$" day-of-week) "first"
(re-matches #"^\dL$" day-of-week) "last"
(= day-of-month "1") "first"
(= day-of-month "15") "mid"
(= day-of-month "L") "last"
:else nil))
(defn- cron->digit [digit]
(when (and digit
(not= digit "*"))
(Integer/parseInt digit)))
(defn- cron->schedule-type [hours day-of-month day-of-week]
(cond
(and day-of-month
(not= day-of-month "*")
(or (= day-of-week "?")
(re-matches #"^\d#1$" day-of-week)
(re-matches #"^\dL$" day-of-week))) "monthly"
(and day-of-week
(not= day-of-week "?")) "weekly"
(and hours
(not= hours "*")) "daily"
:else "hourly"))
(s/defn ^{:style/indent 0} cron-string->schedule-map :- ScheduleMap
"Convert a normal `cron-string` into the expanded ScheduleMap format used by the frontend."
[cron-string :- CronScheduleString]
(let [[_ mins hours day-of-month _ day-of-week _] (str/split cron-string #"\s+")]
{:schedule_minute (cron->digit mins)
:schedule_day (cron->day-of-week day-of-week)
:schedule_frame (cron-day-of-week+day-of-month->frame day-of-week day-of-month)
:schedule_hour (cron->digit hours)
:schedule_type (cron->schedule-type hours day-of-month day-of-week)}))
(s/defn describe-cron-string :- su/NonBlankString
"Return a human-readable description of a cron expression, localized for the current User."
[cron-string :- CronScheduleString]
(CronExpressionDescriptor/getDescription ^String cron-string, ^java.util.Locale (i18n/user-locale)))
| null | https://raw.githubusercontent.com/metabase/metabase/7e3048bf73f6cb7527579446166d054292166163/src/metabase/util/cron.clj | clojure | +----------------------------------------------------------------------------------------------------------------+
| SCHEDULE MAP -> CRON STRING |
+----------------------------------------------------------------------------------------------------------------+
specific days of week like Mon or Fri
+----------------------------------------------------------------------------------------------------------------+
| CRON STRING -> SCHEDULE MAP |
+----------------------------------------------------------------------------------------------------------------+ | (ns metabase.util.cron
"Utility functions for converting frontend schedule dictionaries to cron strings and vice versa.
See -scheduler.org/documentation/quartz-2.x/tutorials/crontrigger.html#format for details on cron
format."
(:require
[clojure.string :as str]
[metabase.util.i18n :as i18n]
[metabase.util.schema :as su]
[schema.core :as s])
(:import
(net.redhogs.cronparser CronExpressionDescriptor)
(org.quartz CronExpression)))
(set! *warn-on-reflection* true)
(def CronScheduleString
"Schema for a valid cron schedule string."
(su/with-api-error-message
(s/constrained
su/NonBlankString
(fn [^String s]
(try (CronExpression/validateExpression s)
true
(catch Throwable _
false)))
"Invalid cron schedule string.")
"value must be a valid Quartz cron schedule string."))
(def ^:private CronHour
(s/constrained s/Int (fn [n] (<= 0 n 23))))
(def ^:private CronMinute
(s/constrained s/Int (fn [n] (<= 0 n 59))))
(def ScheduleMap
"Schema for a frontend-parsable schedule map. Used for Pulses and DB scheduling."
(su/with-api-error-message
(s/named
{(s/optional-key :schedule_day) (s/maybe (s/enum "sun" "mon" "tue" "wed" "thu" "fri" "sat"))
(s/optional-key :schedule_frame) (s/maybe (s/enum "first" "mid" "last"))
(s/optional-key :schedule_hour) (s/maybe CronHour)
(s/optional-key :schedule_minute) (s/maybe CronMinute)
:schedule_type (s/enum "hourly" "daily" "weekly" "monthly")}
"Expanded schedule map")
"value must be a valid schedule map. See schema in metabase.util.cron for details."))
(s/defn ^:private cron-string :- CronScheduleString
"Build a cron string from key-value pair parts."
{:style/indent 0}
[{:keys [seconds minutes hours day-of-month month day-of-week year]}]
(str/join " " [(or seconds "0")
(or minutes "0")
(or hours "*")
(or day-of-month "*")
(or month "*")
(or day-of-week "?")
(or year "*")]))
(def ^:private day-of-week->cron
{"sun" 1
"mon" 2
"tue" 3
"wed" 4
"thu" 5
"fri" 6
"sat" 7})
(defn- frame->cron [frame day-of-week]
(if day-of-week
(assoc {:day-of-month "?"}
:day-of-week (case frame
"first" (str (day-of-week->cron day-of-week) "#1")
"last" (str (day-of-week->cron day-of-week) "L")))
specific CALENDAR DAYS like 1st or 15th
(assoc {:day-of-week "?"}
:day-of-month (case frame
"first" "1"
"mid" "15"
"last" "L"))))
(s/defn ^{:style/indent 0} schedule-map->cron-string :- CronScheduleString
"Convert the frontend schedule map into a cron string."
[{day-of-week :schedule_day, hour :schedule_hour, minute :schedule_minute,
frame :schedule_frame, schedule-type :schedule_type} :- ScheduleMap]
(cron-string (case (keyword schedule-type)
:hourly {:minutes minute}
:daily {:hours (or hour 0)}
:weekly {:hours hour
:day-of-week (day-of-week->cron day-of-week)
:day-of-month "?"}
:monthly (assoc (frame->cron frame day-of-week)
:hours hour))))
(defn- cron->day-of-week [day-of-week]
(when-let [[_ day-of-week] (re-matches #"(^\d).*$" day-of-week)]
(case day-of-week
"1" "sun"
"2" "mon"
"3" "tue"
"4" "wed"
"5" "thu"
"6" "fri"
"7" "sat")))
(defn- cron-day-of-week+day-of-month->frame [day-of-week day-of-month]
(cond
(re-matches #"^\d#1$" day-of-week) "first"
(re-matches #"^\dL$" day-of-week) "last"
(= day-of-month "1") "first"
(= day-of-month "15") "mid"
(= day-of-month "L") "last"
:else nil))
(defn- cron->digit [digit]
(when (and digit
(not= digit "*"))
(Integer/parseInt digit)))
(defn- cron->schedule-type [hours day-of-month day-of-week]
(cond
(and day-of-month
(not= day-of-month "*")
(or (= day-of-week "?")
(re-matches #"^\d#1$" day-of-week)
(re-matches #"^\dL$" day-of-week))) "monthly"
(and day-of-week
(not= day-of-week "?")) "weekly"
(and hours
(not= hours "*")) "daily"
:else "hourly"))
(s/defn ^{:style/indent 0} cron-string->schedule-map :- ScheduleMap
"Convert a normal `cron-string` into the expanded ScheduleMap format used by the frontend."
[cron-string :- CronScheduleString]
(let [[_ mins hours day-of-month _ day-of-week _] (str/split cron-string #"\s+")]
{:schedule_minute (cron->digit mins)
:schedule_day (cron->day-of-week day-of-week)
:schedule_frame (cron-day-of-week+day-of-month->frame day-of-week day-of-month)
:schedule_hour (cron->digit hours)
:schedule_type (cron->schedule-type hours day-of-month day-of-week)}))
(s/defn describe-cron-string :- su/NonBlankString
"Return a human-readable description of a cron expression, localized for the current User."
[cron-string :- CronScheduleString]
(CronExpressionDescriptor/getDescription ^String cron-string, ^java.util.Locale (i18n/user-locale)))
|
a67694a75f01fdef39b9327b376d151250f89590cae9984fafca838280854175 | travelping/hello | hello_http_client.erl | Copyright 2012 , Travelping GmbH < >
% 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.
@private
-module(hello_http_client).
-behaviour(hello_client).
-export([init_transport/2, send_request/4, terminate_transport/2, handle_info/2]).
-export([http_send/5]).
-export([gen_meta_fields/1]).
-include_lib("ex_uri/include/ex_uri.hrl").
-include("hello.hrl").
-include("hello_log.hrl").
-record(http_options, {
hackney_opts :: list({atom(), term()}),
method = post :: 'put' | 'post'
}).
-record(http_state, {
url :: string(),
path :: string(),
scheme :: atom(),
options :: #http_options{}
}).
%% hello_client callbacks
init_transport(URL, Options) ->
case validate_options(Options) of
{ok, ValOpts} ->
http_connect_url(URL),
{ok, #http_state{url = ex_uri:encode(URL), scheme = URL#ex_uri.scheme, path = URL#ex_uri.path, options = ValOpts}};
{error, Reason} ->
?LOG_ERROR("Http client invoked with invalid options. Terminated with reason ~p.", [Reason],
[{hello_error_reason, {error, Reason, Options}}], ?LOGID39),
{error, Reason}
end.
send_request(Request, Timeout, Signarute, State) when is_binary(Request), is_binary(Signarute) ->
spawn(?MODULE, http_send, [self(), Request, Timeout, Signarute, State]),
{ok, State};
send_request(_, _, _, State) ->
{error, no_valid_request, State}.
terminate_transport(_Reason, _State) ->
ok.
handle_info({dnssd, _Ref, {resolve,{Host, Port, _Txt}}}, State = #http_state{scheme = Scheme, path = Path}) ->
?LOG_DEBUG("DNS discovery service resolved path ~p to host ~p:~w.", [Path, Host, Port],
gen_meta_fields(State), ?LOGID40),
{noreply, State#http_state{url = build_url(Scheme, Host, Path, Port)}};
handle_info({dnssd, _Ref, Msg}, State) ->
?LOG_DEBUG("Https client received message ~p from DNS discovery service.", [Msg],
gen_meta_fields(State), ?LOGID41),
{noreply, State}.
build_url(Scheme, Host, Path, Port) ->
ex_uri:encode(#ex_uri{scheme = Scheme,
authority = #ex_uri_authority{host = clean_host(Host), port = Port},
path = Path}).
clean_host(Host) ->
HostSize = erlang:byte_size(Host),
CleanedHost = case binary:match(Host, <<".local.">>) of
{M, L} when HostSize == (M + L) ->
<<HostCuted:M/binary, _/binary>> = Host,
HostCuted;
_ ->
Host
end,
binary_to_list(CleanedHost).
content_type(Signarute) ->
Json = hello_json:signature(),
MsgPack = hello_msgpack:signature(),
case Signarute of
Json -> <<"application/json">>;
MsgPack -> <<"application/x-msgpack">>;
_ -> <<"application/octet-stream">>
end.
%% http client helpers
http_send(Client, Request, Timeout, Signarute, State = #http_state{url = URL, options = Options}) ->
#http_options{method = Method, hackney_opts = Opts} = Options,
{ok, Vsn} = application:get_key(hello, vsn),
HttpHeaders = case lists:keyfind(http_headers, 1, Opts) of
false ->
[];
{http_headers, CustomHeaders} ->
CustomHeaders
end,
Headers = [{<<"Content-Type">>, content_type(Signarute)},
{<<"Accept">>, content_type(Signarute)},
{<<"User-Agent">>, <<"hello/", (list_to_binary(Vsn))/binary>>}] ++ HttpHeaders,
HttpClientOpts = [{timeout, Timeout} | Opts],
case hackney:Method(URL, Headers, Request, HttpClientOpts) of
{ok, Success, RespHeaders, ClientRef} when Success =:= 200; Success =:= 201; Success =:= 202 ->
case hackney:body(ClientRef) of
{ok, Body} ->
Signature1 = hackney_headers:get_value(<<"content-type">>, hackney_headers:new(RespHeaders), <<"undefined">>),
outgoing_message(Client, Signature1, Body, State);
{error, Error} ->
?LOG_ERROR("Http client received an error after executing a request to ~p with reason ~p.", [URL, Error],
lists:append(gen_meta_fields(State), [{hello_error_reason, {{request, Request}, {error, Error}}}]), ?LOGID42),
Client ! {?INCOMING_MSG, {error, Error, State}},
exit(normal)
end;
{ok, HttpCode, _, _} ->
Client ! {?INCOMING_MSG, {error, HttpCode, State}},
exit(normal);
{error, Reason} ->
?LOG_ERROR("Http client received an error after executing a request to ~p with reason ~p.", [URL, Reason],
lists:append(gen_meta_fields(State), [{hello_error_reason, {{request, Request}, {error, Reason}}}]), ?LOGID42),
Client ! {?INCOMING_MSG, {error, Reason, State}},
exit(normal)
end.
outgoing_message(Client, Signarute, Body, State) ->
Json = hello_json:signature(),
Signarute1 = hello_http_listener:signature(Signarute),
case Signarute1 of
Json ->
Body1 = binary:replace(Body, <<"}{">>, <<"}$$${">>, [global]),
Body2 = binary:replace(Body1, <<"]{">>, <<"]$$${">>, [global]),
Body3 = binary:replace(Body2, <<"}[">>, <<"}$$$[">>, [global]),
Bodies = binary:split(Body3, <<"$$$">>, [global]),
[ Client ! {?INCOMING_MSG, {ok, Signarute1, SingleBody, State}} || SingleBody <- Bodies ];
_NoJson ->
Client ! {?INCOMING_MSG, {ok, Signarute1, Body, State}}
end.
validate_options(Options) ->
validate_options(Options, #http_options{hackney_opts = [{socket_options, [{reuseaddr, true }]}]}).
validate_options([{method, put} | R], Opts) ->
validate_options(R, Opts#http_options{method = put});
validate_options([{method, post} | R], Opts) ->
validate_options(R, Opts#http_options{method = post});
validate_options([{method, _}|_], _) ->
{error, "invalid HTTP method"};
validate_options([{http_headers, Headers} | R], Opts) ->
validate_options(R, Opts#http_options{hackney_opts = [{http_headers, Headers} | Opts#http_options.hackney_opts]});
validate_options([{Option, Value} | R], Opts) when is_atom(Option) ->
validate_options(R, Opts#http_options{hackney_opts = [{Option, Value} | Opts#http_options.hackney_opts]});
validate_options([_ | R], Opts) ->
validate_options(R, Opts);
validate_options([], Opts) ->
{ok, Opts}.
http_connect_url(#ex_uri{authority = #ex_uri_authority{host = Host}, path = [$/|Path]} = URI) ->
case hello_lib:is_dnssd_started() of
true ->
dnssd:resolve(list_to_binary(Path), <<"_", (list_to_binary(Host))/binary, "._tcp.">>, <<"local.">>);
false -> URI
end;
http_connect_url(URI) ->
URI.
gen_meta_fields(#http_state{url = URL, path = Path}) ->
[{hello_transport, http}, {hello_transport_url, URL}, {hello_transport_path, Path}].
| null | https://raw.githubusercontent.com/travelping/hello/b2697428efe777e8be657d31ca22d80378041d7c/src/transports/hello_http_client.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.
hello_client callbacks
http client helpers | Copyright 2012 , Travelping GmbH < >
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
@private
-module(hello_http_client).
-behaviour(hello_client).
-export([init_transport/2, send_request/4, terminate_transport/2, handle_info/2]).
-export([http_send/5]).
-export([gen_meta_fields/1]).
-include_lib("ex_uri/include/ex_uri.hrl").
-include("hello.hrl").
-include("hello_log.hrl").
-record(http_options, {
hackney_opts :: list({atom(), term()}),
method = post :: 'put' | 'post'
}).
-record(http_state, {
url :: string(),
path :: string(),
scheme :: atom(),
options :: #http_options{}
}).
init_transport(URL, Options) ->
case validate_options(Options) of
{ok, ValOpts} ->
http_connect_url(URL),
{ok, #http_state{url = ex_uri:encode(URL), scheme = URL#ex_uri.scheme, path = URL#ex_uri.path, options = ValOpts}};
{error, Reason} ->
?LOG_ERROR("Http client invoked with invalid options. Terminated with reason ~p.", [Reason],
[{hello_error_reason, {error, Reason, Options}}], ?LOGID39),
{error, Reason}
end.
send_request(Request, Timeout, Signarute, State) when is_binary(Request), is_binary(Signarute) ->
spawn(?MODULE, http_send, [self(), Request, Timeout, Signarute, State]),
{ok, State};
send_request(_, _, _, State) ->
{error, no_valid_request, State}.
terminate_transport(_Reason, _State) ->
ok.
handle_info({dnssd, _Ref, {resolve,{Host, Port, _Txt}}}, State = #http_state{scheme = Scheme, path = Path}) ->
?LOG_DEBUG("DNS discovery service resolved path ~p to host ~p:~w.", [Path, Host, Port],
gen_meta_fields(State), ?LOGID40),
{noreply, State#http_state{url = build_url(Scheme, Host, Path, Port)}};
handle_info({dnssd, _Ref, Msg}, State) ->
?LOG_DEBUG("Https client received message ~p from DNS discovery service.", [Msg],
gen_meta_fields(State), ?LOGID41),
{noreply, State}.
build_url(Scheme, Host, Path, Port) ->
ex_uri:encode(#ex_uri{scheme = Scheme,
authority = #ex_uri_authority{host = clean_host(Host), port = Port},
path = Path}).
clean_host(Host) ->
HostSize = erlang:byte_size(Host),
CleanedHost = case binary:match(Host, <<".local.">>) of
{M, L} when HostSize == (M + L) ->
<<HostCuted:M/binary, _/binary>> = Host,
HostCuted;
_ ->
Host
end,
binary_to_list(CleanedHost).
content_type(Signarute) ->
Json = hello_json:signature(),
MsgPack = hello_msgpack:signature(),
case Signarute of
Json -> <<"application/json">>;
MsgPack -> <<"application/x-msgpack">>;
_ -> <<"application/octet-stream">>
end.
http_send(Client, Request, Timeout, Signarute, State = #http_state{url = URL, options = Options}) ->
#http_options{method = Method, hackney_opts = Opts} = Options,
{ok, Vsn} = application:get_key(hello, vsn),
HttpHeaders = case lists:keyfind(http_headers, 1, Opts) of
false ->
[];
{http_headers, CustomHeaders} ->
CustomHeaders
end,
Headers = [{<<"Content-Type">>, content_type(Signarute)},
{<<"Accept">>, content_type(Signarute)},
{<<"User-Agent">>, <<"hello/", (list_to_binary(Vsn))/binary>>}] ++ HttpHeaders,
HttpClientOpts = [{timeout, Timeout} | Opts],
case hackney:Method(URL, Headers, Request, HttpClientOpts) of
{ok, Success, RespHeaders, ClientRef} when Success =:= 200; Success =:= 201; Success =:= 202 ->
case hackney:body(ClientRef) of
{ok, Body} ->
Signature1 = hackney_headers:get_value(<<"content-type">>, hackney_headers:new(RespHeaders), <<"undefined">>),
outgoing_message(Client, Signature1, Body, State);
{error, Error} ->
?LOG_ERROR("Http client received an error after executing a request to ~p with reason ~p.", [URL, Error],
lists:append(gen_meta_fields(State), [{hello_error_reason, {{request, Request}, {error, Error}}}]), ?LOGID42),
Client ! {?INCOMING_MSG, {error, Error, State}},
exit(normal)
end;
{ok, HttpCode, _, _} ->
Client ! {?INCOMING_MSG, {error, HttpCode, State}},
exit(normal);
{error, Reason} ->
?LOG_ERROR("Http client received an error after executing a request to ~p with reason ~p.", [URL, Reason],
lists:append(gen_meta_fields(State), [{hello_error_reason, {{request, Request}, {error, Reason}}}]), ?LOGID42),
Client ! {?INCOMING_MSG, {error, Reason, State}},
exit(normal)
end.
outgoing_message(Client, Signarute, Body, State) ->
Json = hello_json:signature(),
Signarute1 = hello_http_listener:signature(Signarute),
case Signarute1 of
Json ->
Body1 = binary:replace(Body, <<"}{">>, <<"}$$${">>, [global]),
Body2 = binary:replace(Body1, <<"]{">>, <<"]$$${">>, [global]),
Body3 = binary:replace(Body2, <<"}[">>, <<"}$$$[">>, [global]),
Bodies = binary:split(Body3, <<"$$$">>, [global]),
[ Client ! {?INCOMING_MSG, {ok, Signarute1, SingleBody, State}} || SingleBody <- Bodies ];
_NoJson ->
Client ! {?INCOMING_MSG, {ok, Signarute1, Body, State}}
end.
validate_options(Options) ->
validate_options(Options, #http_options{hackney_opts = [{socket_options, [{reuseaddr, true }]}]}).
validate_options([{method, put} | R], Opts) ->
validate_options(R, Opts#http_options{method = put});
validate_options([{method, post} | R], Opts) ->
validate_options(R, Opts#http_options{method = post});
validate_options([{method, _}|_], _) ->
{error, "invalid HTTP method"};
validate_options([{http_headers, Headers} | R], Opts) ->
validate_options(R, Opts#http_options{hackney_opts = [{http_headers, Headers} | Opts#http_options.hackney_opts]});
validate_options([{Option, Value} | R], Opts) when is_atom(Option) ->
validate_options(R, Opts#http_options{hackney_opts = [{Option, Value} | Opts#http_options.hackney_opts]});
validate_options([_ | R], Opts) ->
validate_options(R, Opts);
validate_options([], Opts) ->
{ok, Opts}.
http_connect_url(#ex_uri{authority = #ex_uri_authority{host = Host}, path = [$/|Path]} = URI) ->
case hello_lib:is_dnssd_started() of
true ->
dnssd:resolve(list_to_binary(Path), <<"_", (list_to_binary(Host))/binary, "._tcp.">>, <<"local.">>);
false -> URI
end;
http_connect_url(URI) ->
URI.
gen_meta_fields(#http_state{url = URL, path = Path}) ->
[{hello_transport, http}, {hello_transport_url, URL}, {hello_transport_path, Path}].
|
1fb0b00659df5ae08d8ae9c6383440d001e704e6f8866aad78fd6d902e55f491 | SimulaVR/godot-haskell | InputEventMagnifyGesture.hs | # LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving ,
TypeFamilies , TypeOperators , FlexibleContexts , DataKinds ,
MultiParamTypeClasses #
TypeFamilies, TypeOperators, FlexibleContexts, DataKinds,
MultiParamTypeClasses #-}
module Godot.Core.InputEventMagnifyGesture
(Godot.Core.InputEventMagnifyGesture.get_factor,
Godot.Core.InputEventMagnifyGesture.set_factor)
where
import Data.Coerce
import Foreign.C
import Godot.Internal.Dispatch
import qualified Data.Vector as V
import Linear(V2(..),V3(..),M22)
import Data.Colour(withOpacity)
import Data.Colour.SRGB(sRGB)
import System.IO.Unsafe
import Godot.Gdnative.Internal
import Godot.Api.Types
import Godot.Core.InputEventGesture()
instance NodeProperty InputEventMagnifyGesture "factor" Float
'False
where
nodeProperty = (get_factor, wrapDroppingSetter set_factor, Nothing)
# NOINLINE bindInputEventMagnifyGesture_get_factor #
bindInputEventMagnifyGesture_get_factor :: MethodBind
bindInputEventMagnifyGesture_get_factor
= unsafePerformIO $
withCString "InputEventMagnifyGesture" $
\ clsNamePtr ->
withCString "get_factor" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
get_factor ::
(InputEventMagnifyGesture :< cls, Object :< cls) => cls -> IO Float
get_factor cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindInputEventMagnifyGesture_get_factor
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod InputEventMagnifyGesture "get_factor" '[]
(IO Float)
where
nodeMethod = Godot.Core.InputEventMagnifyGesture.get_factor
# NOINLINE bindInputEventMagnifyGesture_set_factor #
bindInputEventMagnifyGesture_set_factor :: MethodBind
bindInputEventMagnifyGesture_set_factor
= unsafePerformIO $
withCString "InputEventMagnifyGesture" $
\ clsNamePtr ->
withCString "set_factor" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
set_factor ::
(InputEventMagnifyGesture :< cls, Object :< cls) =>
cls -> Float -> IO ()
set_factor cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindInputEventMagnifyGesture_set_factor
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod InputEventMagnifyGesture "set_factor" '[Float]
(IO ())
where
nodeMethod = Godot.Core.InputEventMagnifyGesture.set_factor | null | https://raw.githubusercontent.com/SimulaVR/godot-haskell/e8f2c45f1b9cc2f0586ebdc9ec6002c8c2d384ae/src/Godot/Core/InputEventMagnifyGesture.hs | haskell | # LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving ,
TypeFamilies , TypeOperators , FlexibleContexts , DataKinds ,
MultiParamTypeClasses #
TypeFamilies, TypeOperators, FlexibleContexts, DataKinds,
MultiParamTypeClasses #-}
module Godot.Core.InputEventMagnifyGesture
(Godot.Core.InputEventMagnifyGesture.get_factor,
Godot.Core.InputEventMagnifyGesture.set_factor)
where
import Data.Coerce
import Foreign.C
import Godot.Internal.Dispatch
import qualified Data.Vector as V
import Linear(V2(..),V3(..),M22)
import Data.Colour(withOpacity)
import Data.Colour.SRGB(sRGB)
import System.IO.Unsafe
import Godot.Gdnative.Internal
import Godot.Api.Types
import Godot.Core.InputEventGesture()
instance NodeProperty InputEventMagnifyGesture "factor" Float
'False
where
nodeProperty = (get_factor, wrapDroppingSetter set_factor, Nothing)
# NOINLINE bindInputEventMagnifyGesture_get_factor #
bindInputEventMagnifyGesture_get_factor :: MethodBind
bindInputEventMagnifyGesture_get_factor
= unsafePerformIO $
withCString "InputEventMagnifyGesture" $
\ clsNamePtr ->
withCString "get_factor" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
get_factor ::
(InputEventMagnifyGesture :< cls, Object :< cls) => cls -> IO Float
get_factor cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindInputEventMagnifyGesture_get_factor
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod InputEventMagnifyGesture "get_factor" '[]
(IO Float)
where
nodeMethod = Godot.Core.InputEventMagnifyGesture.get_factor
# NOINLINE bindInputEventMagnifyGesture_set_factor #
bindInputEventMagnifyGesture_set_factor :: MethodBind
bindInputEventMagnifyGesture_set_factor
= unsafePerformIO $
withCString "InputEventMagnifyGesture" $
\ clsNamePtr ->
withCString "set_factor" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
set_factor ::
(InputEventMagnifyGesture :< cls, Object :< cls) =>
cls -> Float -> IO ()
set_factor cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindInputEventMagnifyGesture_set_factor
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod InputEventMagnifyGesture "set_factor" '[Float]
(IO ())
where
nodeMethod = Godot.Core.InputEventMagnifyGesture.set_factor | |
dc2f235e4226a178ecfd30a1b112fa7d53a2227e2710b41c9862e1b9e953ca20 | granule-project/granule | Compiler.hs | # LANGUAGE TemplateHaskell #
# LANGUAGE ApplicativeDo #
{-# LANGUAGE PackageImports #-}
# LANGUAGE TypeApplications #
# LANGUAGE NamedFieldPuns #
module Language.Granule.Compiler where
import Control.Exception (SomeException, displayException, try)
import Control.Monad ((<=<), forM_, when)
import Development.GitRev
import Data.Char (isSpace)
import Data.List (isPrefixOf, stripPrefix)
import Data.Maybe (fromMaybe)
import Data.Version (showVersion)
import System.Directory (getAppUserDataDirectory, getCurrentDirectory)
import System.FilePath (takeFileName)
import "Glob" System.FilePath.Glob (glob)
import Options.Applicative
import Options.Applicative.Help.Pretty (string)
import Language.Granule.Checker.Checker
import Language.Granule.Syntax.Def (extendASTWith)
import Language.Granule.Syntax.Preprocessor
import Language.Granule.Syntax.Parser
import Language.Granule.Syntax.Preprocessor.Ascii
import Language.Granule.Syntax.Pretty
import Language.Granule.Utils
import Paths_granule_compiler (version)
import Language.Granule.Compiler.HSCodegen
main :: IO ()
main = do
(globPatterns, config) <- getGrConfig
if null globPatterns
then error "Expected glob pattern"
else compileGrOnFiles globPatterns config
compileGrOnFiles :: [FilePath] -> GrConfig -> IO ()
compileGrOnFiles globPatterns config = let ?globals = grGlobals config in do
pwd <- getCurrentDirectory
forM_ globPatterns $ \pat -> do
paths <- glob pat
case paths of
[] -> error "No matching files"
_ -> forM_ paths $ \path -> do
let fileName = if pwd `isPrefixOf` path then takeFileName path else path
let ?globals = ?globals{ globalsSourceFilePath = Just fileName } in do
printInfo $ "Checking " <> fileName <> "..."
src <- preprocess
(rewriter config)
(keepBackup config)
path
(literateEnvName config)
hsCode <- compile config src
debugM "Code: " hsCode
let outPath = changeFileExtension path
printSuccess $ "Writing " ++ outPath
writeFile outPath hsCode
compile
:: (?globals :: Globals)
=> GrConfig
-> String
-> IO String
compile config input = let ?globals = maybe mempty grGlobals (getEmbeddedGrFlags input) <> ?globals in do
result <- try $ parseAndDoImportsAndFreshenDefs input
case result of
Left (e :: SomeException) -> error $ show e
Right (ast, extensions) ->
-- update globals with extensions
let ?globals = ?globals { globalsExtensions = extensions } in do
reject CBN language pragma
when (CBN `elem` globalsExtensions ?globals) $ error "Cannot compile in CBN mode"
-- Print to terminal when in debugging mode:
debugM "Pretty-printed AST:" $ pretty ast
debugM "Raw AST:" $ show ast
-- Check and evaluate
checked <- try $ check ast
case checked of
Left (e :: SomeException) -> error $ displayException e
Right (Left errs) -> do
error (show errs)
Right (Right (ast', derivedDefs)) -> do
printSuccess "Ok, compiling..."
let ast' = extendASTWith derivedDefs ast
result = cg ast'
case result of
Left e -> error (bold . red . show $ e)
Right str -> return str
changeFileExtension :: String -> String
changeFileExtension str = reverse (drop 2 $ reverse str) ++ "hs"
getEmbeddedGrFlags :: String -> Maybe GrConfig
getEmbeddedGrFlags
= foldr (<|>) Nothing
. map getEmbeddedGrFlagsLine
only check for flags within the top 3 lines
. filter (not . all isSpace)
. lines
where
getEmbeddedGrFlagsLine
= parseGrFlags . dropWhile isSpace
<=< stripPrefix "gr" . dropWhile isSpace
<=< stripPrefix "--" . dropWhile isSpace
parseGrFlags :: String -> Maybe GrConfig
parseGrFlags
= pure . snd
<=< getParseResult . execParserPure (prefs disambiguate) parseGrConfig . words
data GrConfig = GrConfig
{ grRewriter :: Maybe (String -> String)
, grKeepBackup :: Maybe Bool
, grLiterateEnvName :: Maybe String
, grShowVersion :: Bool
, grGlobals :: Globals
}
rewriter :: GrConfig -> Maybe (String -> String)
rewriter c = grRewriter c <|> Nothing
keepBackup :: GrConfig -> Bool
keepBackup = fromMaybe False . grKeepBackup
literateEnvName :: GrConfig -> String
literateEnvName = fromMaybe "granule" . grLiterateEnvName
instance Semigroup GrConfig where
c1 <> c2 = GrConfig
{ grRewriter = grRewriter c1 <|> grRewriter c2
, grKeepBackup = grKeepBackup c1 <|> grKeepBackup c2
, grLiterateEnvName = grLiterateEnvName c1 <|> grLiterateEnvName c2
, grGlobals = grGlobals c1 <> grGlobals c2
, grShowVersion = grShowVersion c1 || grShowVersion c2
}
instance Monoid GrConfig where
mempty = GrConfig
{ grRewriter = Nothing
, grKeepBackup = Nothing
, grLiterateEnvName = Nothing
, grGlobals = mempty
, grShowVersion = False
}
getGrConfig :: IO ([FilePath], GrConfig)
getGrConfig = do
(globPatterns, configCLI) <- getGrCommandLineArgs
configHome <- readUserConfig (grGlobals configCLI)
pure (globPatterns, configCLI <> configHome)
where
TODO : UNIX specific
readUserConfig :: Globals -> IO GrConfig
readUserConfig globals = do
let ?globals = globals
try (getAppUserDataDirectory "granule") >>= \case
Left (e :: SomeException) -> do
debugM "Read user config" $ show e
pure mempty
Right configFile ->
try (parseGrFlags <$> readFile configFile) >>= \case
Left (e :: SomeException) -> do
debugM "Read user config" $ show e
pure mempty
Right Nothing -> do
printInfo . red . unlines $
[ "Couldn't parse granule configuration file at " <> configFile
, "Run `gr --help` to see a list of accepted flags."
]
pure mempty
Right (Just config) -> pure config
getGrCommandLineArgs :: IO ([FilePath], GrConfig)
getGrCommandLineArgs = customExecParser (prefs disambiguate) parseGrConfig
parseGrConfig :: ParserInfo ([FilePath], GrConfig)
parseGrConfig = info (go <**> helper) $ briefDesc
<> (headerDoc . Just . string . unlines)
[ "The Granule Compiler"
, "version: " <> showVersion version
, "branch: " <> $(gitBranch)
, "commit hash: " <> $(gitHash)
, "commit date: " <> $(gitCommitDate)
, if $(gitDirty) then "(uncommitted files present)" else ""
]
<> footer "This software is provided under a BSD3 license and comes with NO WARRANTY WHATSOEVER.\
\ Consult the LICENSE for further information."
where
go = do
globPatterns <-
many $ argument str $ metavar "GLOB_PATTERNS" <> action "file"
<> (help . unwords)
[ "Glob pattern for Granule source files. If the file extension is `.md`/`.tex`, the markdown/TeX preprocessor will be used."
, "If none are given, input will be read from stdin."
]
globalsDebugging <-
flag Nothing (Just True)
$ long "debug"
<> help "Debug mode"
grShowVersion <-
flag False True
$ long "version"
<> help "Show version"
globalsSuppressInfos <-
flag Nothing (Just True)
$ long "no-info"
<> help "Don't output info messages"
globalsSuppressErrors <-
flag Nothing (Just True)
$ long "no-error"
<> help "Don't output error messages"
globalsNoColors <-
flag Nothing (Just True)
$ long "no-color"
<> long "no-colour"
<> help "Turn off colors in terminal output"
globalsAlternativeColors <-
flag Nothing (Just True)
$ long "alternative-colors"
<> long "alternative-colours"
<> help "Print success messages in blue instead of green (may help with color blindness)"
globalsNoEval <-
flag Nothing (Just True)
$ long "no-eval"
<> help "Don't evaluate, only type-check"
globalsTimestamp <-
flag Nothing (Just True)
$ long "timestamp"
<> help "Print timestamp in info and error messages"
globalsSolverTimeoutMillis <-
(optional . option (auto @Integer))
$ long "solver-timeout"
<> (help . unwords)
[ "SMT solver timeout in milliseconds (negative for unlimited)"
, "Defaults to"
, show solverTimeoutMillis <> "ms."
]
globalsIncludePath <-
optional $ strOption
$ long "include-path"
<> help ("Path to the standard library. Defaults to "
<> show includePath)
<> metavar "PATH"
globalsEntryPoint <-
optional $ strOption
$ long "entry-point"
<> help ("Program entry point. Defaults to " <> show entryPoint)
<> metavar "ID"
globalsRewriteHoles <-
flag Nothing (Just True)
$ long "rewrite-holes"
<> help "WARNING: Destructively overwrite equations containing holes to pattern match on generated case-splits."
globalsHoleLine <-
optional . option (auto @Int)
$ long "hole-line"
<> help "The line where the hole you wish to rewrite is located."
<> metavar "LINE"
globalsHoleCol <-
optional . option (auto @Int)
$ long "hole-column"
<> help "The column where the hole you wish to rewrite is located."
<> metavar "COL"
globalsSynthesise <-
flag Nothing (Just True)
$ long "synthesise"
<> help "Turn on program synthesis. Must be used in conjunction with hole-line and hole-column"
globalsIgnoreHoles <-
flag Nothing (Just True)
$ long "ignore-holes"
<> help "Suppress information from holes (treat holes as well-typed)"
globalsSubtractiveSynthesis <-
flag Nothing (Just True)
$ long "subtractive"
<> help "Use subtractive mode for synthesis, rather than additive (default)."
globalsAlternateSynthesisMode <-
flag Nothing (Just True)
$ long "alternate"
<> help "Use alternate mode for synthesis (subtractive divisive, additive naive)"
globalsAltSynthStructuring <-
flag Nothing (Just True)
$ long "altsynthstructuring"
<> help "Use alternate structuring of synthesis rules"
globalsGradeOnRule <-
flag Nothing (Just True)
$ long "gradeonrule"
<> help "Use alternate grade-on-rule mode for synthesis"
globalsSynthTimeoutMillis <-
(optional . option (auto @Integer))
$ long "synth-timeout"
<> (help . unwords)
[ "Synthesis timeout in milliseconds (negative for unlimited)"
, "Defaults to"
, show solverTimeoutMillis <> "ms."
]
globalsSynthIndex <-
(optional . option (auto @Integer))
$ long "synth-index"
<> (help . unwords)
[ "Index of synthesised programs"
, "Defaults to"
, show synthIndex
]
grRewriter
<- flag'
(Just asciiToUnicode)
(long "ascii-to-unicode" <> help "WARNING: Destructively overwrite ascii characters to multi-byte unicode.")
<|> flag Nothing
(Just unicodeToAscii)
(long "unicode-to-ascii" <> help "WARNING: Destructively overwrite multi-byte unicode to ascii.")
grKeepBackup <-
flag Nothing (Just True)
$ long "keep-backup"
<> help "Keep a backup copy of the input file (only has an effect when destructively preprocessing.)"
grLiterateEnvName <-
optional $ strOption
$ long "literate-env-name"
<> help ("Name of the code environment to check in literate files. Defaults to "
<> show (literateEnvName mempty))
globalsBenchmark <-
flag Nothing (Just True)
$ long "benchmark"
<> help "Compute benchmarking results for the synthesis procedure."
globalsBenchmarkRaw <-
flag Nothing (Just True)
$ long "raw-data"
<> help "Show raw data of benchmarking data for synthesis."
pure
( globPatterns
, GrConfig
{ grRewriter
, grKeepBackup
, grLiterateEnvName
, grShowVersion
, grGlobals = Globals
{ globalsDebugging
, globalsNoColors
, globalsAlternativeColors
, globalsNoEval
, globalsSuppressInfos
, globalsSuppressErrors
, globalsIgnoreHoles
, globalsTimestamp
, globalsTesting = Nothing
, globalsSolverTimeoutMillis
, globalsIncludePath
, globalsSourceFilePath = Nothing
, globalsEntryPoint
, globalsRewriteHoles
, globalsHolePosition = (,) <$> globalsHoleLine <*> globalsHoleCol
, globalsSynthesise
, globalsBenchmark
, globalsBenchmarkRaw
, globalsSubtractiveSynthesis
, globalsAlternateSynthesisMode
, globalsAltSynthStructuring
, globalsGradeOnRule
, globalsSynthTimeoutMillis
, globalsSynthIndex
, globalsExtensions = []
}
}
)
where
?globals = mempty @Globals
| null | https://raw.githubusercontent.com/granule-project/granule/aa869e0522ad961f6627e827055700c5fcabfc75/compiler/app/Language/Granule/Compiler.hs | haskell | # LANGUAGE PackageImports #
update globals with extensions
Print to terminal when in debugging mode:
Check and evaluate | # LANGUAGE TemplateHaskell #
# LANGUAGE ApplicativeDo #
# LANGUAGE TypeApplications #
# LANGUAGE NamedFieldPuns #
module Language.Granule.Compiler where
import Control.Exception (SomeException, displayException, try)
import Control.Monad ((<=<), forM_, when)
import Development.GitRev
import Data.Char (isSpace)
import Data.List (isPrefixOf, stripPrefix)
import Data.Maybe (fromMaybe)
import Data.Version (showVersion)
import System.Directory (getAppUserDataDirectory, getCurrentDirectory)
import System.FilePath (takeFileName)
import "Glob" System.FilePath.Glob (glob)
import Options.Applicative
import Options.Applicative.Help.Pretty (string)
import Language.Granule.Checker.Checker
import Language.Granule.Syntax.Def (extendASTWith)
import Language.Granule.Syntax.Preprocessor
import Language.Granule.Syntax.Parser
import Language.Granule.Syntax.Preprocessor.Ascii
import Language.Granule.Syntax.Pretty
import Language.Granule.Utils
import Paths_granule_compiler (version)
import Language.Granule.Compiler.HSCodegen
main :: IO ()
main = do
(globPatterns, config) <- getGrConfig
if null globPatterns
then error "Expected glob pattern"
else compileGrOnFiles globPatterns config
compileGrOnFiles :: [FilePath] -> GrConfig -> IO ()
compileGrOnFiles globPatterns config = let ?globals = grGlobals config in do
pwd <- getCurrentDirectory
forM_ globPatterns $ \pat -> do
paths <- glob pat
case paths of
[] -> error "No matching files"
_ -> forM_ paths $ \path -> do
let fileName = if pwd `isPrefixOf` path then takeFileName path else path
let ?globals = ?globals{ globalsSourceFilePath = Just fileName } in do
printInfo $ "Checking " <> fileName <> "..."
src <- preprocess
(rewriter config)
(keepBackup config)
path
(literateEnvName config)
hsCode <- compile config src
debugM "Code: " hsCode
let outPath = changeFileExtension path
printSuccess $ "Writing " ++ outPath
writeFile outPath hsCode
compile
:: (?globals :: Globals)
=> GrConfig
-> String
-> IO String
compile config input = let ?globals = maybe mempty grGlobals (getEmbeddedGrFlags input) <> ?globals in do
result <- try $ parseAndDoImportsAndFreshenDefs input
case result of
Left (e :: SomeException) -> error $ show e
Right (ast, extensions) ->
let ?globals = ?globals { globalsExtensions = extensions } in do
reject CBN language pragma
when (CBN `elem` globalsExtensions ?globals) $ error "Cannot compile in CBN mode"
debugM "Pretty-printed AST:" $ pretty ast
debugM "Raw AST:" $ show ast
checked <- try $ check ast
case checked of
Left (e :: SomeException) -> error $ displayException e
Right (Left errs) -> do
error (show errs)
Right (Right (ast', derivedDefs)) -> do
printSuccess "Ok, compiling..."
let ast' = extendASTWith derivedDefs ast
result = cg ast'
case result of
Left e -> error (bold . red . show $ e)
Right str -> return str
changeFileExtension :: String -> String
changeFileExtension str = reverse (drop 2 $ reverse str) ++ "hs"
getEmbeddedGrFlags :: String -> Maybe GrConfig
getEmbeddedGrFlags
= foldr (<|>) Nothing
. map getEmbeddedGrFlagsLine
only check for flags within the top 3 lines
. filter (not . all isSpace)
. lines
where
getEmbeddedGrFlagsLine
= parseGrFlags . dropWhile isSpace
<=< stripPrefix "gr" . dropWhile isSpace
<=< stripPrefix "--" . dropWhile isSpace
parseGrFlags :: String -> Maybe GrConfig
parseGrFlags
= pure . snd
<=< getParseResult . execParserPure (prefs disambiguate) parseGrConfig . words
data GrConfig = GrConfig
{ grRewriter :: Maybe (String -> String)
, grKeepBackup :: Maybe Bool
, grLiterateEnvName :: Maybe String
, grShowVersion :: Bool
, grGlobals :: Globals
}
rewriter :: GrConfig -> Maybe (String -> String)
rewriter c = grRewriter c <|> Nothing
keepBackup :: GrConfig -> Bool
keepBackup = fromMaybe False . grKeepBackup
literateEnvName :: GrConfig -> String
literateEnvName = fromMaybe "granule" . grLiterateEnvName
instance Semigroup GrConfig where
c1 <> c2 = GrConfig
{ grRewriter = grRewriter c1 <|> grRewriter c2
, grKeepBackup = grKeepBackup c1 <|> grKeepBackup c2
, grLiterateEnvName = grLiterateEnvName c1 <|> grLiterateEnvName c2
, grGlobals = grGlobals c1 <> grGlobals c2
, grShowVersion = grShowVersion c1 || grShowVersion c2
}
instance Monoid GrConfig where
mempty = GrConfig
{ grRewriter = Nothing
, grKeepBackup = Nothing
, grLiterateEnvName = Nothing
, grGlobals = mempty
, grShowVersion = False
}
getGrConfig :: IO ([FilePath], GrConfig)
getGrConfig = do
(globPatterns, configCLI) <- getGrCommandLineArgs
configHome <- readUserConfig (grGlobals configCLI)
pure (globPatterns, configCLI <> configHome)
where
TODO : UNIX specific
readUserConfig :: Globals -> IO GrConfig
readUserConfig globals = do
let ?globals = globals
try (getAppUserDataDirectory "granule") >>= \case
Left (e :: SomeException) -> do
debugM "Read user config" $ show e
pure mempty
Right configFile ->
try (parseGrFlags <$> readFile configFile) >>= \case
Left (e :: SomeException) -> do
debugM "Read user config" $ show e
pure mempty
Right Nothing -> do
printInfo . red . unlines $
[ "Couldn't parse granule configuration file at " <> configFile
, "Run `gr --help` to see a list of accepted flags."
]
pure mempty
Right (Just config) -> pure config
getGrCommandLineArgs :: IO ([FilePath], GrConfig)
getGrCommandLineArgs = customExecParser (prefs disambiguate) parseGrConfig
parseGrConfig :: ParserInfo ([FilePath], GrConfig)
parseGrConfig = info (go <**> helper) $ briefDesc
<> (headerDoc . Just . string . unlines)
[ "The Granule Compiler"
, "version: " <> showVersion version
, "branch: " <> $(gitBranch)
, "commit hash: " <> $(gitHash)
, "commit date: " <> $(gitCommitDate)
, if $(gitDirty) then "(uncommitted files present)" else ""
]
<> footer "This software is provided under a BSD3 license and comes with NO WARRANTY WHATSOEVER.\
\ Consult the LICENSE for further information."
where
go = do
globPatterns <-
many $ argument str $ metavar "GLOB_PATTERNS" <> action "file"
<> (help . unwords)
[ "Glob pattern for Granule source files. If the file extension is `.md`/`.tex`, the markdown/TeX preprocessor will be used."
, "If none are given, input will be read from stdin."
]
globalsDebugging <-
flag Nothing (Just True)
$ long "debug"
<> help "Debug mode"
grShowVersion <-
flag False True
$ long "version"
<> help "Show version"
globalsSuppressInfos <-
flag Nothing (Just True)
$ long "no-info"
<> help "Don't output info messages"
globalsSuppressErrors <-
flag Nothing (Just True)
$ long "no-error"
<> help "Don't output error messages"
globalsNoColors <-
flag Nothing (Just True)
$ long "no-color"
<> long "no-colour"
<> help "Turn off colors in terminal output"
globalsAlternativeColors <-
flag Nothing (Just True)
$ long "alternative-colors"
<> long "alternative-colours"
<> help "Print success messages in blue instead of green (may help with color blindness)"
globalsNoEval <-
flag Nothing (Just True)
$ long "no-eval"
<> help "Don't evaluate, only type-check"
globalsTimestamp <-
flag Nothing (Just True)
$ long "timestamp"
<> help "Print timestamp in info and error messages"
globalsSolverTimeoutMillis <-
(optional . option (auto @Integer))
$ long "solver-timeout"
<> (help . unwords)
[ "SMT solver timeout in milliseconds (negative for unlimited)"
, "Defaults to"
, show solverTimeoutMillis <> "ms."
]
globalsIncludePath <-
optional $ strOption
$ long "include-path"
<> help ("Path to the standard library. Defaults to "
<> show includePath)
<> metavar "PATH"
globalsEntryPoint <-
optional $ strOption
$ long "entry-point"
<> help ("Program entry point. Defaults to " <> show entryPoint)
<> metavar "ID"
globalsRewriteHoles <-
flag Nothing (Just True)
$ long "rewrite-holes"
<> help "WARNING: Destructively overwrite equations containing holes to pattern match on generated case-splits."
globalsHoleLine <-
optional . option (auto @Int)
$ long "hole-line"
<> help "The line where the hole you wish to rewrite is located."
<> metavar "LINE"
globalsHoleCol <-
optional . option (auto @Int)
$ long "hole-column"
<> help "The column where the hole you wish to rewrite is located."
<> metavar "COL"
globalsSynthesise <-
flag Nothing (Just True)
$ long "synthesise"
<> help "Turn on program synthesis. Must be used in conjunction with hole-line and hole-column"
globalsIgnoreHoles <-
flag Nothing (Just True)
$ long "ignore-holes"
<> help "Suppress information from holes (treat holes as well-typed)"
globalsSubtractiveSynthesis <-
flag Nothing (Just True)
$ long "subtractive"
<> help "Use subtractive mode for synthesis, rather than additive (default)."
globalsAlternateSynthesisMode <-
flag Nothing (Just True)
$ long "alternate"
<> help "Use alternate mode for synthesis (subtractive divisive, additive naive)"
globalsAltSynthStructuring <-
flag Nothing (Just True)
$ long "altsynthstructuring"
<> help "Use alternate structuring of synthesis rules"
globalsGradeOnRule <-
flag Nothing (Just True)
$ long "gradeonrule"
<> help "Use alternate grade-on-rule mode for synthesis"
globalsSynthTimeoutMillis <-
(optional . option (auto @Integer))
$ long "synth-timeout"
<> (help . unwords)
[ "Synthesis timeout in milliseconds (negative for unlimited)"
, "Defaults to"
, show solverTimeoutMillis <> "ms."
]
globalsSynthIndex <-
(optional . option (auto @Integer))
$ long "synth-index"
<> (help . unwords)
[ "Index of synthesised programs"
, "Defaults to"
, show synthIndex
]
grRewriter
<- flag'
(Just asciiToUnicode)
(long "ascii-to-unicode" <> help "WARNING: Destructively overwrite ascii characters to multi-byte unicode.")
<|> flag Nothing
(Just unicodeToAscii)
(long "unicode-to-ascii" <> help "WARNING: Destructively overwrite multi-byte unicode to ascii.")
grKeepBackup <-
flag Nothing (Just True)
$ long "keep-backup"
<> help "Keep a backup copy of the input file (only has an effect when destructively preprocessing.)"
grLiterateEnvName <-
optional $ strOption
$ long "literate-env-name"
<> help ("Name of the code environment to check in literate files. Defaults to "
<> show (literateEnvName mempty))
globalsBenchmark <-
flag Nothing (Just True)
$ long "benchmark"
<> help "Compute benchmarking results for the synthesis procedure."
globalsBenchmarkRaw <-
flag Nothing (Just True)
$ long "raw-data"
<> help "Show raw data of benchmarking data for synthesis."
pure
( globPatterns
, GrConfig
{ grRewriter
, grKeepBackup
, grLiterateEnvName
, grShowVersion
, grGlobals = Globals
{ globalsDebugging
, globalsNoColors
, globalsAlternativeColors
, globalsNoEval
, globalsSuppressInfos
, globalsSuppressErrors
, globalsIgnoreHoles
, globalsTimestamp
, globalsTesting = Nothing
, globalsSolverTimeoutMillis
, globalsIncludePath
, globalsSourceFilePath = Nothing
, globalsEntryPoint
, globalsRewriteHoles
, globalsHolePosition = (,) <$> globalsHoleLine <*> globalsHoleCol
, globalsSynthesise
, globalsBenchmark
, globalsBenchmarkRaw
, globalsSubtractiveSynthesis
, globalsAlternateSynthesisMode
, globalsAltSynthStructuring
, globalsGradeOnRule
, globalsSynthTimeoutMillis
, globalsSynthIndex
, globalsExtensions = []
}
}
)
where
?globals = mempty @Globals
|
9319ed4c0f0800d6056dd78d191cd56909e63c3f109747d666f1b0bb658ad9b5 | j-mie6/ParsleyHaskell | CombinatorAST.hs | {-# LANGUAGE OverloadedStrings #-}
module Parsley.Internal.Core.CombinatorAST (module Parsley.Internal.Core.CombinatorAST) where
import Data.Kind (Type)
import Parsley.Internal.Common (IFunctor(..), Fix, Const1(..), cata, intercalateDiff, (:+:))
import Parsley.Internal.Core.Identifiers (MVar, ΣVar)
import Parsley.Internal.Core.CharPred (CharPred)
import Parsley.Internal.Core.Defunc (Defunc)
|
The opaque datatype that represents parsers .
@since 0.1.0.0
The opaque datatype that represents parsers.
@since 0.1.0.0
-}
newtype Parser a = Parser {unParser :: Fix (Combinator :+: ScopeRegister) a}
Core datatype
data Combinator (k :: Type -> Type) (a :: Type) where
Pure :: Defunc a -> Combinator k a
Satisfy :: CharPred -> Combinator k Char
(:<*>:) :: k (a -> b) -> k a -> Combinator k b
(:*>:) :: k a -> k b -> Combinator k b
(:<*:) :: k a -> k b -> Combinator k a
(:<|>:) :: k a -> k a -> Combinator k a
Empty :: Combinator k a
Try :: k a -> Combinator k a
LookAhead :: k a -> Combinator k a
Let :: Bool -> MVar a -> Combinator k a
NotFollowedBy :: k a -> Combinator k ()
Branch :: k (Either a b) -> k (a -> c) -> k (b -> c) -> Combinator k c
Match :: k a -> [Defunc (a -> Bool)] -> [k b] -> k b -> Combinator k b
Loop :: k () -> k a -> Combinator k a
MakeRegister :: ΣVar a -> k a -> k b -> Combinator k b
GetRegister :: ΣVar a -> Combinator k a
PutRegister :: ΣVar a -> k a -> Combinator k ()
Position :: PosSelector -> Combinator k Int
Debug :: String -> k a -> Combinator k a
MetaCombinator :: MetaCombinator -> k a -> Combinator k a
data ScopeRegister (k :: Type -> Type) (a :: Type) where
ScopeRegister :: k a -> (forall r. Reg r a -> k b) -> ScopeRegister k b
data PosSelector where
Line :: PosSelector
Col :: PosSelector
|
This is an opaque representation of a parsing register . It can not be manipulated as a user , and the
type parameter @r@ is used to ensure that it can not leak out of the scope it has been created in .
It is the abstracted representation of a runtime storage location .
@since 0.1.0.0
This is an opaque representation of a parsing register. It cannot be manipulated as a user, and the
type parameter @r@ is used to ensure that it cannot leak out of the scope it has been created in.
It is the abstracted representation of a runtime storage location.
@since 0.1.0.0
-}
newtype Reg (r :: Type) a = Reg (ΣVar a)
data MetaCombinator where
-- | After this combinator exits, a cut has happened
Cut :: MetaCombinator
-- | This combinator requires a cut from below to respect parsec semantics
RequiresCut :: MetaCombinator
-- | This combinator denotes that within its scope, cut semantics are not enforced
--
-- @since 1.6.0.0
CutImmune :: MetaCombinator
-- Instances
instance IFunctor Combinator where
imap _ (Pure x) = Pure x
imap _ (Satisfy p) = Satisfy p
imap f (p :<*>: q) = f p :<*>: f q
imap f (p :*>: q) = f p :*>: f q
imap f (p :<*: q) = f p :<*: f q
imap f (p :<|>: q) = f p :<|>: f q
imap _ Empty = Empty
imap f (Try p) = Try (f p)
imap f (LookAhead p) = LookAhead (f p)
imap _ (Let r v) = Let r v
imap f (NotFollowedBy p) = NotFollowedBy (f p)
imap f (Branch b p q) = Branch (f b) (f p) (f q)
imap f (Match p fs qs d) = Match (f p) fs (map f qs) (f d)
imap f (Loop body exit) = Loop (f body) (f exit)
imap f (MakeRegister σ p q) = MakeRegister σ (f p) (f q)
imap _ (GetRegister σ) = GetRegister σ
imap f (PutRegister σ p) = PutRegister σ (f p)
imap _ (Position sel) = Position sel
imap f (Debug name p) = Debug name (f p)
imap f (MetaCombinator m p) = MetaCombinator m (f p)
instance Show (Fix Combinator a) where
show = ($ "") . getConst1 . cata (Const1 . alg)
where
alg (Pure x) = "pure " . shows x
alg (Satisfy f) = "satisfy " . shows f
alg (Const1 pf :<*>: Const1 px) = "(" . pf . " <*> " . px . ")"
alg (Const1 p :*>: Const1 q) = "(" . p . " *> " . q . ")"
alg (Const1 p :<*: Const1 q) = "(" . p . " <* " . q . ")"
alg (Const1 p :<|>: Const1 q) = "(" . p . " <|> " . q . ")"
alg Empty = "empty"
alg (Try (Const1 p)) = "try (". p . ")"
alg (LookAhead (Const1 p)) = "lookAhead (" . p . ")"
alg (Let False v) = "let-bound " . shows v
alg (Let True v) = "rec " . shows v
alg (NotFollowedBy (Const1 p)) = "notFollowedBy (" . p . ")"
alg (Branch (Const1 b) (Const1 p) (Const1 q)) = "branch (" . b . ") (" . p . ") (" . q . ")"
alg (Match (Const1 p) fs qs (Const1 def)) = "match (" . p . ") " . shows fs . " [" . intercalateDiff ", " (map getConst1 qs) . "] (" . def . ")"
alg (Loop (Const1 body) (Const1 exit)) = "loop (" . body . ") (" . exit . ")"
alg (MakeRegister σ (Const1 p) (Const1 q)) = "make " . shows σ . " (" . p . ") (" . q . ")"
alg (GetRegister σ) = "get " . shows σ
alg (PutRegister σ (Const1 p)) = "put " . shows σ . " (" . p . ")"
alg (Position Line) = "line"
alg (Position Col) = "col"
alg (Debug _ (Const1 p)) = p
alg (MetaCombinator m (Const1 p)) = p . " [" . shows m . "]"
instance IFunctor ScopeRegister where
imap f (ScopeRegister p g) = ScopeRegister (f p) (f . g)
instance Show MetaCombinator where
show Cut = "coins after"
show RequiresCut = "requires cut"
show CutImmune = "immune to cuts"
# INLINE traverseCombinator #
traverseCombinator :: Applicative m => (forall a. f a -> m (k a)) -> Combinator f a -> m (Combinator k a)
traverseCombinator expose (pf :<*>: px) = (:<*>:) <$> expose pf <*> expose px
traverseCombinator expose (p :*>: q) = (:*>:) <$> expose p <*> expose q
traverseCombinator expose (p :<*: q) = (:<*:) <$> expose p <*> expose q
traverseCombinator expose (p :<|>: q) = (:<|>:) <$> expose p <*> expose q
traverseCombinator _ Empty = pure Empty
traverseCombinator expose (Try p) = Try <$> expose p
traverseCombinator expose (LookAhead p) = LookAhead <$> expose p
traverseCombinator expose (NotFollowedBy p) = NotFollowedBy <$> expose p
traverseCombinator expose (Branch b p q) = Branch <$> expose b <*> expose p <*> expose q
traverseCombinator expose (Match p fs qs d) = Match <$> expose p <*> pure fs <*> traverse expose qs <*> expose d
traverseCombinator expose (Loop body exit) = Loop <$> expose body <*> expose exit
traverseCombinator expose (MakeRegister σ p q) = MakeRegister σ <$> expose p <*> expose q
traverseCombinator _ (GetRegister σ) = pure (GetRegister σ)
traverseCombinator expose (PutRegister σ p) = PutRegister σ <$> expose p
traverseCombinator _ (Position sel) = pure (Position sel)
traverseCombinator expose (Debug name p) = Debug name <$> expose p
traverseCombinator _ (Pure x) = pure (Pure x)
traverseCombinator _ (Satisfy f) = pure (Satisfy f)
traverseCombinator _ (Let r v) = pure (Let r v)
traverseCombinator expose (MetaCombinator m p) = MetaCombinator m <$> expose p
| null | https://raw.githubusercontent.com/j-mie6/ParsleyHaskell/0386a7a8a9bbad3b2bca688a882755a568bd9beb/parsley-core/src/ghc/Parsley/Internal/Core/CombinatorAST.hs | haskell | # LANGUAGE OverloadedStrings #
| After this combinator exits, a cut has happened
| This combinator requires a cut from below to respect parsec semantics
| This combinator denotes that within its scope, cut semantics are not enforced
@since 1.6.0.0
Instances | module Parsley.Internal.Core.CombinatorAST (module Parsley.Internal.Core.CombinatorAST) where
import Data.Kind (Type)
import Parsley.Internal.Common (IFunctor(..), Fix, Const1(..), cata, intercalateDiff, (:+:))
import Parsley.Internal.Core.Identifiers (MVar, ΣVar)
import Parsley.Internal.Core.CharPred (CharPred)
import Parsley.Internal.Core.Defunc (Defunc)
|
The opaque datatype that represents parsers .
@since 0.1.0.0
The opaque datatype that represents parsers.
@since 0.1.0.0
-}
newtype Parser a = Parser {unParser :: Fix (Combinator :+: ScopeRegister) a}
Core datatype
data Combinator (k :: Type -> Type) (a :: Type) where
Pure :: Defunc a -> Combinator k a
Satisfy :: CharPred -> Combinator k Char
(:<*>:) :: k (a -> b) -> k a -> Combinator k b
(:*>:) :: k a -> k b -> Combinator k b
(:<*:) :: k a -> k b -> Combinator k a
(:<|>:) :: k a -> k a -> Combinator k a
Empty :: Combinator k a
Try :: k a -> Combinator k a
LookAhead :: k a -> Combinator k a
Let :: Bool -> MVar a -> Combinator k a
NotFollowedBy :: k a -> Combinator k ()
Branch :: k (Either a b) -> k (a -> c) -> k (b -> c) -> Combinator k c
Match :: k a -> [Defunc (a -> Bool)] -> [k b] -> k b -> Combinator k b
Loop :: k () -> k a -> Combinator k a
MakeRegister :: ΣVar a -> k a -> k b -> Combinator k b
GetRegister :: ΣVar a -> Combinator k a
PutRegister :: ΣVar a -> k a -> Combinator k ()
Position :: PosSelector -> Combinator k Int
Debug :: String -> k a -> Combinator k a
MetaCombinator :: MetaCombinator -> k a -> Combinator k a
data ScopeRegister (k :: Type -> Type) (a :: Type) where
ScopeRegister :: k a -> (forall r. Reg r a -> k b) -> ScopeRegister k b
data PosSelector where
Line :: PosSelector
Col :: PosSelector
|
This is an opaque representation of a parsing register . It can not be manipulated as a user , and the
type parameter @r@ is used to ensure that it can not leak out of the scope it has been created in .
It is the abstracted representation of a runtime storage location .
@since 0.1.0.0
This is an opaque representation of a parsing register. It cannot be manipulated as a user, and the
type parameter @r@ is used to ensure that it cannot leak out of the scope it has been created in.
It is the abstracted representation of a runtime storage location.
@since 0.1.0.0
-}
newtype Reg (r :: Type) a = Reg (ΣVar a)
data MetaCombinator where
Cut :: MetaCombinator
RequiresCut :: MetaCombinator
CutImmune :: MetaCombinator
instance IFunctor Combinator where
imap _ (Pure x) = Pure x
imap _ (Satisfy p) = Satisfy p
imap f (p :<*>: q) = f p :<*>: f q
imap f (p :*>: q) = f p :*>: f q
imap f (p :<*: q) = f p :<*: f q
imap f (p :<|>: q) = f p :<|>: f q
imap _ Empty = Empty
imap f (Try p) = Try (f p)
imap f (LookAhead p) = LookAhead (f p)
imap _ (Let r v) = Let r v
imap f (NotFollowedBy p) = NotFollowedBy (f p)
imap f (Branch b p q) = Branch (f b) (f p) (f q)
imap f (Match p fs qs d) = Match (f p) fs (map f qs) (f d)
imap f (Loop body exit) = Loop (f body) (f exit)
imap f (MakeRegister σ p q) = MakeRegister σ (f p) (f q)
imap _ (GetRegister σ) = GetRegister σ
imap f (PutRegister σ p) = PutRegister σ (f p)
imap _ (Position sel) = Position sel
imap f (Debug name p) = Debug name (f p)
imap f (MetaCombinator m p) = MetaCombinator m (f p)
instance Show (Fix Combinator a) where
show = ($ "") . getConst1 . cata (Const1 . alg)
where
alg (Pure x) = "pure " . shows x
alg (Satisfy f) = "satisfy " . shows f
alg (Const1 pf :<*>: Const1 px) = "(" . pf . " <*> " . px . ")"
alg (Const1 p :*>: Const1 q) = "(" . p . " *> " . q . ")"
alg (Const1 p :<*: Const1 q) = "(" . p . " <* " . q . ")"
alg (Const1 p :<|>: Const1 q) = "(" . p . " <|> " . q . ")"
alg Empty = "empty"
alg (Try (Const1 p)) = "try (". p . ")"
alg (LookAhead (Const1 p)) = "lookAhead (" . p . ")"
alg (Let False v) = "let-bound " . shows v
alg (Let True v) = "rec " . shows v
alg (NotFollowedBy (Const1 p)) = "notFollowedBy (" . p . ")"
alg (Branch (Const1 b) (Const1 p) (Const1 q)) = "branch (" . b . ") (" . p . ") (" . q . ")"
alg (Match (Const1 p) fs qs (Const1 def)) = "match (" . p . ") " . shows fs . " [" . intercalateDiff ", " (map getConst1 qs) . "] (" . def . ")"
alg (Loop (Const1 body) (Const1 exit)) = "loop (" . body . ") (" . exit . ")"
alg (MakeRegister σ (Const1 p) (Const1 q)) = "make " . shows σ . " (" . p . ") (" . q . ")"
alg (GetRegister σ) = "get " . shows σ
alg (PutRegister σ (Const1 p)) = "put " . shows σ . " (" . p . ")"
alg (Position Line) = "line"
alg (Position Col) = "col"
alg (Debug _ (Const1 p)) = p
alg (MetaCombinator m (Const1 p)) = p . " [" . shows m . "]"
instance IFunctor ScopeRegister where
imap f (ScopeRegister p g) = ScopeRegister (f p) (f . g)
instance Show MetaCombinator where
show Cut = "coins after"
show RequiresCut = "requires cut"
show CutImmune = "immune to cuts"
# INLINE traverseCombinator #
traverseCombinator :: Applicative m => (forall a. f a -> m (k a)) -> Combinator f a -> m (Combinator k a)
traverseCombinator expose (pf :<*>: px) = (:<*>:) <$> expose pf <*> expose px
traverseCombinator expose (p :*>: q) = (:*>:) <$> expose p <*> expose q
traverseCombinator expose (p :<*: q) = (:<*:) <$> expose p <*> expose q
traverseCombinator expose (p :<|>: q) = (:<|>:) <$> expose p <*> expose q
traverseCombinator _ Empty = pure Empty
traverseCombinator expose (Try p) = Try <$> expose p
traverseCombinator expose (LookAhead p) = LookAhead <$> expose p
traverseCombinator expose (NotFollowedBy p) = NotFollowedBy <$> expose p
traverseCombinator expose (Branch b p q) = Branch <$> expose b <*> expose p <*> expose q
traverseCombinator expose (Match p fs qs d) = Match <$> expose p <*> pure fs <*> traverse expose qs <*> expose d
traverseCombinator expose (Loop body exit) = Loop <$> expose body <*> expose exit
traverseCombinator expose (MakeRegister σ p q) = MakeRegister σ <$> expose p <*> expose q
traverseCombinator _ (GetRegister σ) = pure (GetRegister σ)
traverseCombinator expose (PutRegister σ p) = PutRegister σ <$> expose p
traverseCombinator _ (Position sel) = pure (Position sel)
traverseCombinator expose (Debug name p) = Debug name <$> expose p
traverseCombinator _ (Pure x) = pure (Pure x)
traverseCombinator _ (Satisfy f) = pure (Satisfy f)
traverseCombinator _ (Let r v) = pure (Let r v)
traverseCombinator expose (MetaCombinator m p) = MetaCombinator m <$> expose p
|
ad0c5b120529929ccbc1eb3f5aed285c7d1662d703c54baea0569808f833af15 | spawnfest/eep49ers | wxStaticBoxSizer.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2008 - 2020 . All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -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.
%%
%% %CopyrightEnd%
%% This file is generated DO NOT EDIT
-module(wxStaticBoxSizer).
-include("wxe.hrl").
-export([destroy/1,getStaticBox/1,new/2,new/3]).
%% inherited exports
-export([add/2,add/3,add/4,addSpacer/2,addStretchSpacer/1,addStretchSpacer/2,
calcMin/1,clear/1,clear/2,detach/2,fit/2,fitInside/2,getChildren/1,getItem/2,
getItem/3,getMinSize/1,getOrientation/1,getPosition/1,getSize/1,hide/2,
hide/3,insert/3,insert/4,insert/5,insertSpacer/3,insertStretchSpacer/2,
insertStretchSpacer/3,isShown/2,layout/1,parent_class/1,prepend/2,
prepend/3,prepend/4,prependSpacer/2,prependStretchSpacer/1,prependStretchSpacer/2,
recalcSizes/1,remove/2,replace/3,replace/4,setDimension/3,setDimension/5,
setItemMinSize/3,setItemMinSize/4,setMinSize/2,setMinSize/3,setSizeHints/2,
setVirtualSizeHints/2,show/2,show/3,showItems/2]).
-type wxStaticBoxSizer() :: wx:wx_object().
-export_type([wxStaticBoxSizer/0]).
%% @hidden
parent_class(wxBoxSizer) -> true;
parent_class(wxSizer) -> true;
parent_class(_Class) -> erlang:error({badtype, ?MODULE}).
%% @doc See <a href="#wxstaticboxsizerwxstaticboxsizer">external documentation</a>.
%% <br /> Also:<br />
new(Box , Orient ) - > wxStaticBoxSizer ( ) when < br / >
Box::wxStaticBox : ( ) , Orient::integer().<br / >
%%
-spec new(Orient, Parent) -> wxStaticBoxSizer() when
Orient::integer(), Parent::wxWindow:wxWindow();
(Box, Orient) -> wxStaticBoxSizer() when
Box::wxStaticBox:wxStaticBox(), Orient::integer().
new(Orient,Parent)
when is_integer(Orient),is_record(Parent, wx_ref) ->
new(Orient,Parent, []);
new(#wx_ref{type=BoxT}=Box,Orient)
when is_integer(Orient) ->
?CLASS(BoxT,wxStaticBox),
wxe_util:queue_cmd(Box,Orient,?get_env(),?wxStaticBoxSizer_new_2),
wxe_util:rec(?wxStaticBoxSizer_new_2).
%% @doc See <a href="#wxstaticboxsizerwxstaticboxsizer">external documentation</a>.
-spec new(Orient, Parent, [Option]) -> wxStaticBoxSizer() when
Orient::integer(), Parent::wxWindow:wxWindow(),
Option :: {'label', unicode:chardata()}.
new(Orient,#wx_ref{type=ParentT}=Parent, Options)
when is_integer(Orient),is_list(Options) ->
?CLASS(ParentT,wxWindow),
MOpts = fun({label, Label}) -> Label_UC = unicode:characters_to_binary(Label),{label,Label_UC};
(BadOpt) -> erlang:error({badoption, BadOpt}) end,
Opts = lists:map(MOpts, Options),
wxe_util:queue_cmd(Orient,Parent, Opts,?get_env(),?wxStaticBoxSizer_new_3),
wxe_util:rec(?wxStaticBoxSizer_new_3).
%% @doc See <a href="#wxstaticboxsizergetstaticbox">external documentation</a>.
-spec getStaticBox(This) -> wxStaticBox:wxStaticBox() when
This::wxStaticBoxSizer().
getStaticBox(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxStaticBoxSizer),
wxe_util:queue_cmd(This,?get_env(),?wxStaticBoxSizer_GetStaticBox),
wxe_util:rec(?wxStaticBoxSizer_GetStaticBox).
%% @doc Destroys this object, do not use object again
-spec destroy(This::wxStaticBoxSizer()) -> 'ok'.
destroy(Obj=#wx_ref{type=Type}) ->
?CLASS(Type,wxStaticBoxSizer),
wxe_util:queue_cmd(Obj, ?get_env(), ?DESTROY_OBJECT),
ok.
From
%% @hidden
getOrientation(This) -> wxBoxSizer:getOrientation(This).
From wxSizer
%% @hidden
showItems(This,Show) -> wxSizer:showItems(This,Show).
%% @hidden
show(This,Window, Options) -> wxSizer:show(This,Window, Options).
%% @hidden
show(This,Window) -> wxSizer:show(This,Window).
%% @hidden
setSizeHints(This,Window) -> wxSizer:setSizeHints(This,Window).
%% @hidden
setItemMinSize(This,Window,Width,Height) -> wxSizer:setItemMinSize(This,Window,Width,Height).
%% @hidden
setItemMinSize(This,Window,Size) -> wxSizer:setItemMinSize(This,Window,Size).
%% @hidden
setMinSize(This,Width,Height) -> wxSizer:setMinSize(This,Width,Height).
%% @hidden
setMinSize(This,Size) -> wxSizer:setMinSize(This,Size).
%% @hidden
setDimension(This,X,Y,Width,Height) -> wxSizer:setDimension(This,X,Y,Width,Height).
%% @hidden
setDimension(This,Pos,Size) -> wxSizer:setDimension(This,Pos,Size).
%% @hidden
replace(This,Oldwin,Newwin, Options) -> wxSizer:replace(This,Oldwin,Newwin, Options).
%% @hidden
replace(This,Oldwin,Newwin) -> wxSizer:replace(This,Oldwin,Newwin).
%% @hidden
remove(This,Index) -> wxSizer:remove(This,Index).
%% @hidden
prependStretchSpacer(This, Options) -> wxSizer:prependStretchSpacer(This, Options).
%% @hidden
prependStretchSpacer(This) -> wxSizer:prependStretchSpacer(This).
%% @hidden
prependSpacer(This,Size) -> wxSizer:prependSpacer(This,Size).
%% @hidden
prepend(This,Width,Height, Options) -> wxSizer:prepend(This,Width,Height, Options).
%% @hidden
prepend(This,Width,Height) -> wxSizer:prepend(This,Width,Height).
%% @hidden
prepend(This,Item) -> wxSizer:prepend(This,Item).
%% @hidden
layout(This) -> wxSizer:layout(This).
%% @hidden
recalcSizes(This) -> wxSizer:recalcSizes(This).
%% @hidden
isShown(This,Window) -> wxSizer:isShown(This,Window).
%% @hidden
insertStretchSpacer(This,Index, Options) -> wxSizer:insertStretchSpacer(This,Index, Options).
%% @hidden
insertStretchSpacer(This,Index) -> wxSizer:insertStretchSpacer(This,Index).
%% @hidden
insertSpacer(This,Index,Size) -> wxSizer:insertSpacer(This,Index,Size).
%% @hidden
insert(This,Index,Width,Height, Options) -> wxSizer:insert(This,Index,Width,Height, Options).
%% @hidden
insert(This,Index,Width,Height) -> wxSizer:insert(This,Index,Width,Height).
%% @hidden
insert(This,Index,Item) -> wxSizer:insert(This,Index,Item).
%% @hidden
hide(This,Window, Options) -> wxSizer:hide(This,Window, Options).
%% @hidden
hide(This,Window) -> wxSizer:hide(This,Window).
%% @hidden
getMinSize(This) -> wxSizer:getMinSize(This).
%% @hidden
getPosition(This) -> wxSizer:getPosition(This).
%% @hidden
getSize(This) -> wxSizer:getSize(This).
%% @hidden
getItem(This,Window, Options) -> wxSizer:getItem(This,Window, Options).
%% @hidden
getItem(This,Window) -> wxSizer:getItem(This,Window).
%% @hidden
getChildren(This) -> wxSizer:getChildren(This).
%% @hidden
fitInside(This,Window) -> wxSizer:fitInside(This,Window).
%% @hidden
setVirtualSizeHints(This,Window) -> wxSizer:setVirtualSizeHints(This,Window).
%% @hidden
fit(This,Window) -> wxSizer:fit(This,Window).
%% @hidden
detach(This,Window) -> wxSizer:detach(This,Window).
%% @hidden
clear(This, Options) -> wxSizer:clear(This, Options).
%% @hidden
clear(This) -> wxSizer:clear(This).
%% @hidden
calcMin(This) -> wxSizer:calcMin(This).
%% @hidden
addStretchSpacer(This, Options) -> wxSizer:addStretchSpacer(This, Options).
%% @hidden
addStretchSpacer(This) -> wxSizer:addStretchSpacer(This).
%% @hidden
addSpacer(This,Size) -> wxSizer:addSpacer(This,Size).
%% @hidden
add(This,Width,Height, Options) -> wxSizer:add(This,Width,Height, Options).
%% @hidden
add(This,Width,Height) -> wxSizer:add(This,Width,Height).
%% @hidden
add(This,Window) -> wxSizer:add(This,Window).
| null | https://raw.githubusercontent.com/spawnfest/eep49ers/d1020fd625a0bbda8ab01caf0e1738eb1cf74886/lib/wx/src/gen/wxStaticBoxSizer.erl | erlang |
%CopyrightBegin%
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
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.
%CopyrightEnd%
This file is generated DO NOT EDIT
inherited exports
@hidden
@doc See <a href="#wxstaticboxsizerwxstaticboxsizer">external documentation</a>.
<br /> Also:<br />
@doc See <a href="#wxstaticboxsizerwxstaticboxsizer">external documentation</a>.
@doc See <a href="#wxstaticboxsizergetstaticbox">external documentation</a>.
@doc Destroys this object, do not use object again
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden | Copyright Ericsson AB 2008 - 2020 . All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(wxStaticBoxSizer).
-include("wxe.hrl").
-export([destroy/1,getStaticBox/1,new/2,new/3]).
-export([add/2,add/3,add/4,addSpacer/2,addStretchSpacer/1,addStretchSpacer/2,
calcMin/1,clear/1,clear/2,detach/2,fit/2,fitInside/2,getChildren/1,getItem/2,
getItem/3,getMinSize/1,getOrientation/1,getPosition/1,getSize/1,hide/2,
hide/3,insert/3,insert/4,insert/5,insertSpacer/3,insertStretchSpacer/2,
insertStretchSpacer/3,isShown/2,layout/1,parent_class/1,prepend/2,
prepend/3,prepend/4,prependSpacer/2,prependStretchSpacer/1,prependStretchSpacer/2,
recalcSizes/1,remove/2,replace/3,replace/4,setDimension/3,setDimension/5,
setItemMinSize/3,setItemMinSize/4,setMinSize/2,setMinSize/3,setSizeHints/2,
setVirtualSizeHints/2,show/2,show/3,showItems/2]).
-type wxStaticBoxSizer() :: wx:wx_object().
-export_type([wxStaticBoxSizer/0]).
parent_class(wxBoxSizer) -> true;
parent_class(wxSizer) -> true;
parent_class(_Class) -> erlang:error({badtype, ?MODULE}).
new(Box , Orient ) - > wxStaticBoxSizer ( ) when < br / >
Box::wxStaticBox : ( ) , Orient::integer().<br / >
-spec new(Orient, Parent) -> wxStaticBoxSizer() when
Orient::integer(), Parent::wxWindow:wxWindow();
(Box, Orient) -> wxStaticBoxSizer() when
Box::wxStaticBox:wxStaticBox(), Orient::integer().
new(Orient,Parent)
when is_integer(Orient),is_record(Parent, wx_ref) ->
new(Orient,Parent, []);
new(#wx_ref{type=BoxT}=Box,Orient)
when is_integer(Orient) ->
?CLASS(BoxT,wxStaticBox),
wxe_util:queue_cmd(Box,Orient,?get_env(),?wxStaticBoxSizer_new_2),
wxe_util:rec(?wxStaticBoxSizer_new_2).
-spec new(Orient, Parent, [Option]) -> wxStaticBoxSizer() when
Orient::integer(), Parent::wxWindow:wxWindow(),
Option :: {'label', unicode:chardata()}.
new(Orient,#wx_ref{type=ParentT}=Parent, Options)
when is_integer(Orient),is_list(Options) ->
?CLASS(ParentT,wxWindow),
MOpts = fun({label, Label}) -> Label_UC = unicode:characters_to_binary(Label),{label,Label_UC};
(BadOpt) -> erlang:error({badoption, BadOpt}) end,
Opts = lists:map(MOpts, Options),
wxe_util:queue_cmd(Orient,Parent, Opts,?get_env(),?wxStaticBoxSizer_new_3),
wxe_util:rec(?wxStaticBoxSizer_new_3).
-spec getStaticBox(This) -> wxStaticBox:wxStaticBox() when
This::wxStaticBoxSizer().
getStaticBox(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxStaticBoxSizer),
wxe_util:queue_cmd(This,?get_env(),?wxStaticBoxSizer_GetStaticBox),
wxe_util:rec(?wxStaticBoxSizer_GetStaticBox).
-spec destroy(This::wxStaticBoxSizer()) -> 'ok'.
destroy(Obj=#wx_ref{type=Type}) ->
?CLASS(Type,wxStaticBoxSizer),
wxe_util:queue_cmd(Obj, ?get_env(), ?DESTROY_OBJECT),
ok.
From
getOrientation(This) -> wxBoxSizer:getOrientation(This).
From wxSizer
showItems(This,Show) -> wxSizer:showItems(This,Show).
show(This,Window, Options) -> wxSizer:show(This,Window, Options).
show(This,Window) -> wxSizer:show(This,Window).
setSizeHints(This,Window) -> wxSizer:setSizeHints(This,Window).
setItemMinSize(This,Window,Width,Height) -> wxSizer:setItemMinSize(This,Window,Width,Height).
setItemMinSize(This,Window,Size) -> wxSizer:setItemMinSize(This,Window,Size).
setMinSize(This,Width,Height) -> wxSizer:setMinSize(This,Width,Height).
setMinSize(This,Size) -> wxSizer:setMinSize(This,Size).
setDimension(This,X,Y,Width,Height) -> wxSizer:setDimension(This,X,Y,Width,Height).
setDimension(This,Pos,Size) -> wxSizer:setDimension(This,Pos,Size).
replace(This,Oldwin,Newwin, Options) -> wxSizer:replace(This,Oldwin,Newwin, Options).
replace(This,Oldwin,Newwin) -> wxSizer:replace(This,Oldwin,Newwin).
remove(This,Index) -> wxSizer:remove(This,Index).
prependStretchSpacer(This, Options) -> wxSizer:prependStretchSpacer(This, Options).
prependStretchSpacer(This) -> wxSizer:prependStretchSpacer(This).
prependSpacer(This,Size) -> wxSizer:prependSpacer(This,Size).
prepend(This,Width,Height, Options) -> wxSizer:prepend(This,Width,Height, Options).
prepend(This,Width,Height) -> wxSizer:prepend(This,Width,Height).
prepend(This,Item) -> wxSizer:prepend(This,Item).
layout(This) -> wxSizer:layout(This).
recalcSizes(This) -> wxSizer:recalcSizes(This).
isShown(This,Window) -> wxSizer:isShown(This,Window).
insertStretchSpacer(This,Index, Options) -> wxSizer:insertStretchSpacer(This,Index, Options).
insertStretchSpacer(This,Index) -> wxSizer:insertStretchSpacer(This,Index).
insertSpacer(This,Index,Size) -> wxSizer:insertSpacer(This,Index,Size).
insert(This,Index,Width,Height, Options) -> wxSizer:insert(This,Index,Width,Height, Options).
insert(This,Index,Width,Height) -> wxSizer:insert(This,Index,Width,Height).
insert(This,Index,Item) -> wxSizer:insert(This,Index,Item).
hide(This,Window, Options) -> wxSizer:hide(This,Window, Options).
hide(This,Window) -> wxSizer:hide(This,Window).
getMinSize(This) -> wxSizer:getMinSize(This).
getPosition(This) -> wxSizer:getPosition(This).
getSize(This) -> wxSizer:getSize(This).
getItem(This,Window, Options) -> wxSizer:getItem(This,Window, Options).
getItem(This,Window) -> wxSizer:getItem(This,Window).
getChildren(This) -> wxSizer:getChildren(This).
fitInside(This,Window) -> wxSizer:fitInside(This,Window).
setVirtualSizeHints(This,Window) -> wxSizer:setVirtualSizeHints(This,Window).
fit(This,Window) -> wxSizer:fit(This,Window).
detach(This,Window) -> wxSizer:detach(This,Window).
clear(This, Options) -> wxSizer:clear(This, Options).
clear(This) -> wxSizer:clear(This).
calcMin(This) -> wxSizer:calcMin(This).
addStretchSpacer(This, Options) -> wxSizer:addStretchSpacer(This, Options).
addStretchSpacer(This) -> wxSizer:addStretchSpacer(This).
addSpacer(This,Size) -> wxSizer:addSpacer(This,Size).
add(This,Width,Height, Options) -> wxSizer:add(This,Width,Height, Options).
add(This,Width,Height) -> wxSizer:add(This,Width,Height).
add(This,Window) -> wxSizer:add(This,Window).
|
3b9c3de553758e9f856ddaf15f22f9fd43448d60c84b749d71c7d28284aeb6e3 | lilactown/helix-todo-mvc | lib.cljc | (ns todo-mvc.lib
#?(:clj (:require [helix.core :as helix]))
#?(:cljs (:require-macros [todo-mvc.lib])))
#?(:clj
(defmacro defnc [type params & body]
(let [opts? (map? (first body)) ;; whether an opts map was passed in
opts (if opts?
(first body)
{})
body (if opts?
(rest body)
body)
;; feature flags to enable by default
default-opts {:helix/features {:fast-refresh true}}]
`(helix.core/defnc ~type ~params
;; we use `merge` here to allow indidivual consumers to override feature
;; flags in special cases
~(merge default-opts opts)
~@body))))
| null | https://raw.githubusercontent.com/lilactown/helix-todo-mvc/bd1be0be6388264b70329817348c6cda616b6fdd/src/todo_mvc/lib.cljc | clojure | whether an opts map was passed in
feature flags to enable by default
we use `merge` here to allow indidivual consumers to override feature
flags in special cases | (ns todo-mvc.lib
#?(:clj (:require [helix.core :as helix]))
#?(:cljs (:require-macros [todo-mvc.lib])))
#?(:clj
(defmacro defnc [type params & body]
opts (if opts?
(first body)
{})
body (if opts?
(rest body)
body)
default-opts {:helix/features {:fast-refresh true}}]
`(helix.core/defnc ~type ~params
~(merge default-opts opts)
~@body))))
|
7c5bbc45613a8217f3ab297251f9da87fe77213175677badc63d848dc64fefca | schibsted/spid-tech-docs | definitions.clj | (ns spid-docs.sample-responses.definitions
(:require [clojure.data.codec.base64 :as base64]
[clojure.data.json :as json]
[spid-client-clojure.core :as spid]
[spid-docs.config :as config]
[spid-docs.sample-responses.defsample :refer [defsample]]))
(defn base64-encode [str]
(String. (base64/encode (.getBytes str)) "UTF-8"))
(defsample GET "/endpoints")
(defsample GET "/describe/{object}" {:object "User"})
(defsample GET "/status")
(defsample GET "/version")
(defsample GET "/terms")
(defsample GET "/email/{email}/status" {:email (base64-encode "")})
(defsample GET "/phone/{phone}/status" {:phone (base64-encode "+46701111111")})
(defsample GET "/clients")
(defsample GET "/logins")
;; Once the user is created, it must also be verified. Unfortunately, this
;; cannot be done through the API. If the user is not verified, certain API
endpoints will fail with a 403 . If running this script from scratch , it must
be run in two passes - first to create the user . In this first run , the first
;; endpoint that expects a verified user will crash. Before attempting the
second run , you must manually verifiy the user by visiting the URL in the
;; generated email. If you want to regenerate the email to find it more easily
;; in the logs, use GET /user/{userId}/trigger/emailverification
;;
Many endpoints will fail with " is not authorized to access this user "
;; when trying it with the ID of an unverificated user.
(defsample johndoe
POST "/user" {:email "" :displayName "John Doe" :name "John Doe"})
(defsample dataobject [user johndoe]
POST "/user/{id}/dataobject/{key}" {:id (:userId user)
:key "mysetting"
:value "My custom value"})
(defsample [user johndoe]
GET "/user/{id}/dataobject/{key}" {:id (:userId user)
:key "mysetting"})
(defsample [user johndoe]
GET "/user/{id}/dataobjects" {:id (:userId user)})
(defsample GET "/dataobjects")
(defsample [user johndoe]
DELETE "/user/{id}/dataobject/{key}" {:id (:userId user)
:key "mysetting"})
(defsample [user johndoe]
GET "/user/{userId}/trigger/{trigger}" {:userId (:userId user)
:trigger "emailverification"})
(defsample janedoe
POST "/signup" {:email ""})
(defsample mycampaign
POST "/campaign" {:title "My Campaign"})
(defsample GET "/campaigns")
(comment
TODO
Pending documentation from on using JWT , and on how to generate a
JWT that will lead to a successful request .
(defsample POST "/signup_jwt" {:jwt "??"})
(defsample POST "/attach_jwt" {:jwt "??"}))
(defsample [user johndoe]
GET "/user/{userId}/varnishId" {:userId (:userId user)})
(defsample [user johndoe]
GET "/user/{userId}" {:userId (:userId user)})
(defsample GET "/users")
(defsample [user johndoe]
GET "/search/users" {:email (:email user)})
(defsample [user johndoe]
GET "/user/{userId}/logins" {:userId (:userId user)})
(defsample [user johndoe]
POST "/user/{userId}" {:userId (:userId user)
:name "John Spencer Doe"
:addresses (json/write-str {:home {:country "Norway"}})})
(defsample GET "/anonymous/users" {:since "2014-01-01"
:until "2014-04-28"})
;; Products
(defsample themovie
POST "/product" {:code "themovie"
:name "The Movie"
:price 9900
:vat 2500
:paymentOptions 2 ;; "Credit card"
" Digital contents "
:currency "NOK"})
(defsample vgplus
POST "/product" {:code "vg+"
:name "VG+"
:price 9900
:vat 2500
:paymentOptions 2 ;; "Credit card"
" Subscription "
:currency "NOK"
:subscriptionPeriod 2592000})
(defsample vgplus-3mo [parent vgplus]
POST "/product" {:code "vg+3mo"
:name "VG+ 3 måneder"
:price 9900
:vat 2500
:paymentOptions 2 ;; "Credit card"
" Subscription "
:currency "NOK"
:parentProductId (:productId parent)
:subscriptionPeriod 2592000})
(defsample vgplus-6mo [parent vgplus]
POST "/product" {:code "vg+6mo"
:name "VG+ 6 måneder"
:price 9516
:vat 2284
:paymentOptions 2 ;; "Credit card"
" Subscription "
:currency "NOK"
:parentProductId (:productId parent)
:subscriptionPeriod 2592000})
(defsample [product themovie]
GET "/product/{id}" {:id (:productId product)})
(defsample [product vgplus]
POST "/product/{id}" {:id (:productId product)
:name "VG PLUSS"})
(defsample [product vgplus]
GET "/product/{productId}/children" {:productId (:productId product)})
(defsample [product vgplus]
GET "/product/{productId}/revisions" {:productId (:productId product)})
(defsample
GET "/products/parents")
(defsample vgplus-bundle
POST "/product" {:code "vg+bundle"
:name "VG+ Alle slag"
:price 9516
:vat 2284
:paymentOptions 2 ;; "Credit card"
:type 1 ;; "Product"
:bundle 1 ;; "Dynamic bundle"
:currency "NOK"})
(defsample [bundle vgplus-bundle
product vgplus-3mo]
POST "/bundle/{bundleId}/product/{productId}" {:bundleId (:productId bundle)
:productId (:productId product)})
(defsample [bundle vgplus-bundle
product vgplus-3mo]
DELETE "/bundle/{bundleId}/product/{productId}" {:bundleId (:productId bundle)
:productId (:productId product)})
(defsample freebies-for-all
POST "/vouchers/group" {:title "Freebies for all"
:type "8" ;; "Voucher as payment method"
:voucherCode "F4A"
:unique 1})
(defsample GET "/vouchers/groups")
(defsample [group freebies-for-all]
GET "/vouchers/group/{voucherGroupId}" {:voucherGroupId (:voucherGroupId group)})
(defsample [group freebies-for-all]
POST "/vouchers/group/{voucherGroupId}" {:voucherGroupId (:voucherGroupId group)
:title "Freebies for everyone!"})
(defsample [group freebies-for-all]
POST "/vouchers/generate/{voucherGroupId}" {:voucherGroupId (:voucherGroupId group)
:amount 3})
(defsample [user johndoe
group freebies-for-all]
POST "/voucher_handout" {:userId (:userId user)
:voucherGroupId (:voucherGroupId group)})
(defsample some-vouchers [group freebies-for-all]
POST "/vouchers/handout/{voucherGroupId}" {:voucherGroupId (:voucherGroupId group)
:amount 1})
(defsample [vouchers some-vouchers]
GET "/voucher/{voucherCode}" {:voucherCode (:voucherCode (first vouchers))})
(defsample [user johndoe]
GET "/user/{userId}/logins" {:userId (:userId user)})
(defsample buy-star-wars-link
POST "/paylink" {:title "Star Wars Movies"
:redirectUri ":8000/callback"
:cancelUri ":8000/cancel"
:clientReference "Order number #3242"
:items (json/write-str [{:description "Star Wars IV"
:price 7983
:vat 1917
:quantity 1}
{:description "Star Wars V"
:price 7983
:vat 1917
:quantity 1}
{:description "Star Wars VI"
:price 7983
:vat 1917
:quantity 1}])})
(defsample [paylink buy-star-wars-link]
GET "/paylink/{paylinkId}" {:paylinkId (:paylinkId paylink)})
(defsample [paylink buy-star-wars-link]
DELETE "/paylink/{paylinkId}" {:paylinkId (:paylinkId paylink)})
(defsample [user johndoe
product themovie]
POST "/user/{userId}/product/{productId}" {:userId (:userId user)
:productId (:productId product)})
(defsample [user johndoe
product themovie]
GET "/user/{userId}/product/{productId}" {:userId (:userId user)
:productId (:productId product)})
(defsample [user johndoe]
GET "/user/{userId}/products" {:userId (:userId user)})
(defsample [user johndoe
product themovie]
DELETE "/user/{userId}/product/{productId}" {:userId (:userId user)
:productId (:productId product)})
(defsample [user johndoe
product vgplus]
POST "/user/{userId}/subscription" {:userId (:userId user)
:productId (:productId product)})
(defsample [user johndoe
subscription vgplus]
GET "/user/{userId}/subscription/{subscriptionId}" {:userId (:userId user)
:subscriptionId (:productId subscription)})
(defsample johndoes-subscriptions [user johndoe]
GET "/user/{userId}/subscriptions" {:userId (:userId user)})
(defsample [user johndoe
subscriptions johndoes-subscriptions]
POST "/user/{userId}/subscription/{subscriptionId}" {:userId (:userId user)
:subscriptionId (:subscriptionId (first (vals subscriptions)))
:autoRenew 1})
(defsample GET "/subscriptions")
(defsample [user johndoe
subscriptions johndoes-subscriptions]
DELETE "/user/{userId}/subscription/{subscriptionId}" {:userId (:userId user)
:subscriptionId (:subscriptionId (first (vals subscriptions)))})
(defsample GET "/digitalcontents")
(defsample GET "/kpis")
(defsample GET "/terms")
(defsample GET "/me")
(defsample GET "/logout")
| null | https://raw.githubusercontent.com/schibsted/spid-tech-docs/ee6a4394e9732572e97fc3a55506b2d6b9a9fe2b/src/spid_docs/sample_responses/definitions.clj | clojure | Once the user is created, it must also be verified. Unfortunately, this
cannot be done through the API. If the user is not verified, certain API
endpoint that expects a verified user will crash. Before attempting the
generated email. If you want to regenerate the email to find it more easily
in the logs, use GET /user/{userId}/trigger/emailverification
when trying it with the ID of an unverificated user.
Products
"Credit card"
"Credit card"
"Credit card"
"Credit card"
"Credit card"
"Product"
"Dynamic bundle"
"Voucher as payment method" | (ns spid-docs.sample-responses.definitions
(:require [clojure.data.codec.base64 :as base64]
[clojure.data.json :as json]
[spid-client-clojure.core :as spid]
[spid-docs.config :as config]
[spid-docs.sample-responses.defsample :refer [defsample]]))
(defn base64-encode [str]
(String. (base64/encode (.getBytes str)) "UTF-8"))
(defsample GET "/endpoints")
(defsample GET "/describe/{object}" {:object "User"})
(defsample GET "/status")
(defsample GET "/version")
(defsample GET "/terms")
(defsample GET "/email/{email}/status" {:email (base64-encode "")})
(defsample GET "/phone/{phone}/status" {:phone (base64-encode "+46701111111")})
(defsample GET "/clients")
(defsample GET "/logins")
endpoints will fail with a 403 . If running this script from scratch , it must
be run in two passes - first to create the user . In this first run , the first
second run , you must manually verifiy the user by visiting the URL in the
Many endpoints will fail with " is not authorized to access this user "
(defsample johndoe
POST "/user" {:email "" :displayName "John Doe" :name "John Doe"})
(defsample dataobject [user johndoe]
POST "/user/{id}/dataobject/{key}" {:id (:userId user)
:key "mysetting"
:value "My custom value"})
(defsample [user johndoe]
GET "/user/{id}/dataobject/{key}" {:id (:userId user)
:key "mysetting"})
(defsample [user johndoe]
GET "/user/{id}/dataobjects" {:id (:userId user)})
(defsample GET "/dataobjects")
(defsample [user johndoe]
DELETE "/user/{id}/dataobject/{key}" {:id (:userId user)
:key "mysetting"})
(defsample [user johndoe]
GET "/user/{userId}/trigger/{trigger}" {:userId (:userId user)
:trigger "emailverification"})
(defsample janedoe
POST "/signup" {:email ""})
(defsample mycampaign
POST "/campaign" {:title "My Campaign"})
(defsample GET "/campaigns")
(comment
TODO
Pending documentation from on using JWT , and on how to generate a
JWT that will lead to a successful request .
(defsample POST "/signup_jwt" {:jwt "??"})
(defsample POST "/attach_jwt" {:jwt "??"}))
(defsample [user johndoe]
GET "/user/{userId}/varnishId" {:userId (:userId user)})
(defsample [user johndoe]
GET "/user/{userId}" {:userId (:userId user)})
(defsample GET "/users")
(defsample [user johndoe]
GET "/search/users" {:email (:email user)})
(defsample [user johndoe]
GET "/user/{userId}/logins" {:userId (:userId user)})
(defsample [user johndoe]
POST "/user/{userId}" {:userId (:userId user)
:name "John Spencer Doe"
:addresses (json/write-str {:home {:country "Norway"}})})
(defsample GET "/anonymous/users" {:since "2014-01-01"
:until "2014-04-28"})
(defsample themovie
POST "/product" {:code "themovie"
:name "The Movie"
:price 9900
:vat 2500
" Digital contents "
:currency "NOK"})
(defsample vgplus
POST "/product" {:code "vg+"
:name "VG+"
:price 9900
:vat 2500
" Subscription "
:currency "NOK"
:subscriptionPeriod 2592000})
(defsample vgplus-3mo [parent vgplus]
POST "/product" {:code "vg+3mo"
:name "VG+ 3 måneder"
:price 9900
:vat 2500
" Subscription "
:currency "NOK"
:parentProductId (:productId parent)
:subscriptionPeriod 2592000})
(defsample vgplus-6mo [parent vgplus]
POST "/product" {:code "vg+6mo"
:name "VG+ 6 måneder"
:price 9516
:vat 2284
" Subscription "
:currency "NOK"
:parentProductId (:productId parent)
:subscriptionPeriod 2592000})
(defsample [product themovie]
GET "/product/{id}" {:id (:productId product)})
(defsample [product vgplus]
POST "/product/{id}" {:id (:productId product)
:name "VG PLUSS"})
(defsample [product vgplus]
GET "/product/{productId}/children" {:productId (:productId product)})
(defsample [product vgplus]
GET "/product/{productId}/revisions" {:productId (:productId product)})
(defsample
GET "/products/parents")
(defsample vgplus-bundle
POST "/product" {:code "vg+bundle"
:name "VG+ Alle slag"
:price 9516
:vat 2284
:currency "NOK"})
(defsample [bundle vgplus-bundle
product vgplus-3mo]
POST "/bundle/{bundleId}/product/{productId}" {:bundleId (:productId bundle)
:productId (:productId product)})
(defsample [bundle vgplus-bundle
product vgplus-3mo]
DELETE "/bundle/{bundleId}/product/{productId}" {:bundleId (:productId bundle)
:productId (:productId product)})
(defsample freebies-for-all
POST "/vouchers/group" {:title "Freebies for all"
:voucherCode "F4A"
:unique 1})
(defsample GET "/vouchers/groups")
(defsample [group freebies-for-all]
GET "/vouchers/group/{voucherGroupId}" {:voucherGroupId (:voucherGroupId group)})
(defsample [group freebies-for-all]
POST "/vouchers/group/{voucherGroupId}" {:voucherGroupId (:voucherGroupId group)
:title "Freebies for everyone!"})
(defsample [group freebies-for-all]
POST "/vouchers/generate/{voucherGroupId}" {:voucherGroupId (:voucherGroupId group)
:amount 3})
(defsample [user johndoe
group freebies-for-all]
POST "/voucher_handout" {:userId (:userId user)
:voucherGroupId (:voucherGroupId group)})
(defsample some-vouchers [group freebies-for-all]
POST "/vouchers/handout/{voucherGroupId}" {:voucherGroupId (:voucherGroupId group)
:amount 1})
(defsample [vouchers some-vouchers]
GET "/voucher/{voucherCode}" {:voucherCode (:voucherCode (first vouchers))})
(defsample [user johndoe]
GET "/user/{userId}/logins" {:userId (:userId user)})
(defsample buy-star-wars-link
POST "/paylink" {:title "Star Wars Movies"
:redirectUri ":8000/callback"
:cancelUri ":8000/cancel"
:clientReference "Order number #3242"
:items (json/write-str [{:description "Star Wars IV"
:price 7983
:vat 1917
:quantity 1}
{:description "Star Wars V"
:price 7983
:vat 1917
:quantity 1}
{:description "Star Wars VI"
:price 7983
:vat 1917
:quantity 1}])})
(defsample [paylink buy-star-wars-link]
GET "/paylink/{paylinkId}" {:paylinkId (:paylinkId paylink)})
(defsample [paylink buy-star-wars-link]
DELETE "/paylink/{paylinkId}" {:paylinkId (:paylinkId paylink)})
(defsample [user johndoe
product themovie]
POST "/user/{userId}/product/{productId}" {:userId (:userId user)
:productId (:productId product)})
(defsample [user johndoe
product themovie]
GET "/user/{userId}/product/{productId}" {:userId (:userId user)
:productId (:productId product)})
(defsample [user johndoe]
GET "/user/{userId}/products" {:userId (:userId user)})
(defsample [user johndoe
product themovie]
DELETE "/user/{userId}/product/{productId}" {:userId (:userId user)
:productId (:productId product)})
(defsample [user johndoe
product vgplus]
POST "/user/{userId}/subscription" {:userId (:userId user)
:productId (:productId product)})
(defsample [user johndoe
subscription vgplus]
GET "/user/{userId}/subscription/{subscriptionId}" {:userId (:userId user)
:subscriptionId (:productId subscription)})
(defsample johndoes-subscriptions [user johndoe]
GET "/user/{userId}/subscriptions" {:userId (:userId user)})
(defsample [user johndoe
subscriptions johndoes-subscriptions]
POST "/user/{userId}/subscription/{subscriptionId}" {:userId (:userId user)
:subscriptionId (:subscriptionId (first (vals subscriptions)))
:autoRenew 1})
(defsample GET "/subscriptions")
(defsample [user johndoe
subscriptions johndoes-subscriptions]
DELETE "/user/{userId}/subscription/{subscriptionId}" {:userId (:userId user)
:subscriptionId (:subscriptionId (first (vals subscriptions)))})
(defsample GET "/digitalcontents")
(defsample GET "/kpis")
(defsample GET "/terms")
(defsample GET "/me")
(defsample GET "/logout")
|
f971696bc9e1ef78d4efc5b52abeee23f14aa64aceae1516b8af8128213f6706 | klutometis/clrs | quantiles.scm | (define (quantile-statistics A p r k)
(let* ((n (vector-length A))
(statistics (map (lambda (quantile)
(exact-floor (/ (* quantile n) k)))
(iota (- k 1) 1))))
(filter (lambda (statistic)
(and (>= statistic p)
(<= statistic r)))
statistics)))
(define (kth-quantiles! A k)
(let ((quantiles '()))
(let continue ((p 0)
(r (- (vector-length A) 1)))
(let* ((statistics (quantile-statistics A p r k))
(pivot-statistic
(if (null? statistics)
0
(list-ref statistics (exact-floor (/ (length statistics) 2))))))
(if (null? statistics)
quantiles
(let ((x (randomized-select A p r (+ (- pivot-statistic p) 1))))
(set! quantiles (cons x quantiles))
(partition-k! A p r pivot-statistic)
(continue p (- pivot-statistic 1))
(continue (+ pivot-statistic 1) r)))))))
(define (k-medial-proximals! A k)
(let* ((length (vector-length A))
(medial (lower-median length))
(median (vector-ref A (- medial 1))))
(partition-median! A 0 (- length 1))
(loop continue ((until (= k 0))
(with k k)
(with i medial)
(with j (- medial 1))
(with proximals '()))
=> proximals
(let ((upper (vector-ref A i))
(lower (vector-ref A j)))
(let ((upper-delta (if (>= i length) +inf.0 (abs (- median upper))))
(lower-delta (if (<= j 0) +inf.0 (abs (- median lower)))))
(if (< upper-delta lower-delta)
(continue (=> k (- k 1))
(=> i (+ i 1))
(=> proximals (cons upper proximals)))
(continue (=> k (- k 1))
(=> j (- j 1))
(=> proximals (cons lower proximals)))))))))
(define (dual-medians A B)
(define (binary-search A B n low high)
(if (> low high)
#f
(let ((k (exact-floor (/ (+ low high) 2))))
(let ((An (list-ref A n))
(Ak (list-ref A k)))
(cond ((and (= k n) (<= An (car B))) An)
((and (< k n) (<= (list-ref B (- n k 1))
Ak
(list-ref B (- n k))))
Ak)
((> Ak (list-ref B (- n k)))
(binary-search A B n low (- k 1)))
(else (binary-search A B n (+ 1 k) high)))))))
(let* ((n (- (length A) 1))
(premedian (binary-search A B n 0 n))
(median (if premedian
premedian
(binary-search B A n 0 n))))
median))
| null | https://raw.githubusercontent.com/klutometis/clrs/f85a8f0036f0946c9e64dde3259a19acc62b74a1/9.3/quantiles.scm | scheme | (define (quantile-statistics A p r k)
(let* ((n (vector-length A))
(statistics (map (lambda (quantile)
(exact-floor (/ (* quantile n) k)))
(iota (- k 1) 1))))
(filter (lambda (statistic)
(and (>= statistic p)
(<= statistic r)))
statistics)))
(define (kth-quantiles! A k)
(let ((quantiles '()))
(let continue ((p 0)
(r (- (vector-length A) 1)))
(let* ((statistics (quantile-statistics A p r k))
(pivot-statistic
(if (null? statistics)
0
(list-ref statistics (exact-floor (/ (length statistics) 2))))))
(if (null? statistics)
quantiles
(let ((x (randomized-select A p r (+ (- pivot-statistic p) 1))))
(set! quantiles (cons x quantiles))
(partition-k! A p r pivot-statistic)
(continue p (- pivot-statistic 1))
(continue (+ pivot-statistic 1) r)))))))
(define (k-medial-proximals! A k)
(let* ((length (vector-length A))
(medial (lower-median length))
(median (vector-ref A (- medial 1))))
(partition-median! A 0 (- length 1))
(loop continue ((until (= k 0))
(with k k)
(with i medial)
(with j (- medial 1))
(with proximals '()))
=> proximals
(let ((upper (vector-ref A i))
(lower (vector-ref A j)))
(let ((upper-delta (if (>= i length) +inf.0 (abs (- median upper))))
(lower-delta (if (<= j 0) +inf.0 (abs (- median lower)))))
(if (< upper-delta lower-delta)
(continue (=> k (- k 1))
(=> i (+ i 1))
(=> proximals (cons upper proximals)))
(continue (=> k (- k 1))
(=> j (- j 1))
(=> proximals (cons lower proximals)))))))))
(define (dual-medians A B)
(define (binary-search A B n low high)
(if (> low high)
#f
(let ((k (exact-floor (/ (+ low high) 2))))
(let ((An (list-ref A n))
(Ak (list-ref A k)))
(cond ((and (= k n) (<= An (car B))) An)
((and (< k n) (<= (list-ref B (- n k 1))
Ak
(list-ref B (- n k))))
Ak)
((> Ak (list-ref B (- n k)))
(binary-search A B n low (- k 1)))
(else (binary-search A B n (+ 1 k) high)))))))
(let* ((n (- (length A) 1))
(premedian (binary-search A B n 0 n))
(median (if premedian
premedian
(binary-search B A n 0 n))))
median))
| |
b80cfe62f1bab7a381e6bb7da24668c78bf1f3ac0f2b091abc2b09b3922f7157 | OCamlPro/liquidity | liquidDot.mli | (****************************************************************************)
(* Liquidity *)
(* *)
Copyright ( C ) 2017 - 2020 OCamlPro SAS
(* *)
(* Authors: Fabrice Le Fessant *)
(* *)
(* 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 </>. *)
(****************************************************************************)
open LiquidTypes
* Generate graph representation ( in dot graphviz format ) from a
decompiled symbolic evaluated contract .
decompiled symbolic evaluated Michelson contract. *)
val to_string : node_contract -> string
| null | https://raw.githubusercontent.com/OCamlPro/liquidity/3578de34cf751f54b9e4c001a95625d2041b2962/tools/liquidity/liquidDot.mli | ocaml | **************************************************************************
Liquidity
Authors: Fabrice Le Fessant
This program is free software: you can redistribute it and/or modify
(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.
along with this program. If not, see </>.
************************************************************************** | Copyright ( C ) 2017 - 2020 OCamlPro SAS
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
open LiquidTypes
* Generate graph representation ( in dot graphviz format ) from a
decompiled symbolic evaluated contract .
decompiled symbolic evaluated Michelson contract. *)
val to_string : node_contract -> string
|
3f11145c8203d50d2496531999d002efb9bd683d875e9d176daf16a9749d4ad1 | zadean/xqerl | xqerl_mod_db.erl | Copyright ( c ) 2019 - 2020 .
SPDX - FileCopyrightText : 2022
%
SPDX - License - Identifier : Apache-2.0
@doc Implements namespace
-module(xqerl_mod_db).
-include("xqerl.hrl").
-define(NS, <<"">>).
-define(PX, <<"db">>).
-define(XL, <<"">>).
-define(ND, <<"updating">>).
-'module-namespace'({?NS, ?PX}).
-variables([]).
-functions([
{
{qname, ?NS, ?PX, <<"put">>},
{seqType, 'empty-sequence', zero},
[{annotation, {qname, ?XL, <<>>, ?ND}, []}],
{'put', 3},
2,
[
{seqType, item, one_or_many},
{seqType, 'xs:string', one}
]
},
{
{qname, ?NS, ?PX, <<"link">>},
{seqType, 'empty-sequence', zero},
[{annotation, {qname, ?XL, <<>>, ?ND}, []}],
{'link_', 3},
2,
[
{seqType, 'xs:string', one},
{seqType, 'xs:string', one}
]
},
{{qname, ?NS, ?PX, <<"get">>}, {seqType, item, one}, [], {'get_', 2}, 1, [
{seqType, 'xs:string', one}
]},
{
{qname, ?NS, ?PX, <<"delete">>},
{seqType, 'empty-sequence', zero},
[{annotation, {qname, ?XL, <<>>, ?ND}, []}],
{'delete', 2},
1,
[
{seqType, 'xs:string', one}
]
},
{
{qname, ?NS, ?PX, <<"delete-collection">>},
{seqType, 'empty-sequence', zero},
[{annotation, {qname, ?XL, <<>>, ?ND}, []}],
{'delete', 2},
1,
[
{seqType, 'xs:string', one}
]
}
]).
%% ====================================================================
%% API functions
%% ====================================================================
-export([
put/3,
link_/3,
get_/2,
delete/2,
delete_collection/2
]).
put(Ctx, [Item], Uri) ->
put(Ctx, Item, Uri);
put(Ctx, #{nk := _} = Node, Uri) ->
xqerl_mod_fn:put(Ctx, Node, Uri);
put(#{'base-uri' := BaseUri0} = Ctx, Item, Uri0) ->
Uri = xqerl_types:value(Uri0),
BaseUri = xqerl_types:value(BaseUri0),
AbsUri = resolve_uri(BaseUri, Uri),
{DbUri, Name} = xqldb_uri:split_uri(AbsUri),
DB = xqldb_db:database(DbUri),
do_put(Ctx, Item, DB, Name).
do_put(Ctx, Item, DB, Name) when is_binary(Item) ->
xqerl_update:add(Ctx, {put, text, Item, DB, Name});
do_put(Ctx, #xqAtomicValue{type = StrType, value = Item}, DB, Name) when ?xs_string(StrType) ->
xqerl_update:add(Ctx, {put, text, Item, DB, Name});
do_put(
Ctx,
#xqAtomicValue{
type = BinType,
value = Item
},
DB,
Name
) when BinType =:= 'xs:base64Binary'; BinType =:= 'xs:hexBinary' ->
xqerl_update:add(Ctx, {put, raw, Item, DB, Name});
do_put(Ctx, Items, DB, Name) when is_list(Items) ->
_ = [throw_error(node) || #{nk := _} <- Items],
xqerl_update:add(Ctx, {put, item, Items, DB, Name});
do_put(Ctx, Item, DB, Name) ->
xqerl_update:add(Ctx, {put, item, Item, DB, Name}).
link_(Ctx, [Item], Uri) ->
link_(Ctx, Item, Uri);
link_(#{'base-uri' := BaseUri0} = Ctx, Item, Uri0) ->
Uri = xqerl_types:value(Uri0),
BaseUri = xqerl_types:value(BaseUri0),
AbsUri = resolve_uri(BaseUri, Uri),
{DbUri, Name} = xqldb_uri:split_uri(AbsUri),
DB = xqldb_db:database(DbUri),
do_link(Ctx, Item, DB, Name).
do_link(Ctx, Filename, DB, Name) ->
xqerl_update:add(Ctx, {put, link, Filename, DB, Name}).
get_(#{'base-uri' := BaseUri0} = Ctx, Uri0) ->
Uri = xqerl_types:value(Uri0),
BaseUri = xqerl_types:value(BaseUri0),
AbsUri = resolve_uri(BaseUri, Uri),
xqldb_dml:select(Ctx, AbsUri).
delete(
#{
'base-uri' := BaseUri0,
trans := _Agent
} = Ctx,
Uri0
) ->
Uri = xqerl_types:value(Uri0),
BaseUri = xqerl_types:value(BaseUri0),
AbsUri = resolve_uri(BaseUri, Uri),
{DbUri, Name} = xqldb_uri:split_uri(AbsUri),
#{db_name := _DbPid} = DB = xqldb_db:database(DbUri),
xqerl_update:add(Ctx, {delete, item, {DB, Name}}).
delete_collection(
#{
'base-uri' := BaseUri0,
trans := Agent
} = Ctx,
Uri0
) ->
Uri = xqerl_types:value(Uri0),
BaseUri = xqerl_types:value(BaseUri0),
AbsUri = resolve_uri(BaseUri, Uri),
DBs = xqldb_db:databases(AbsUri),
Locks = [
{[DbPid, write], write}
|| #{db_name := DbPid} <- DBs
],
locks:lock_objects(Agent, Locks),
F = fun(DB) ->
xqerl_update:add(Ctx, {delete, all, DB})
end,
ok = lists:foreach(F, DBs),
[].
resolve_uri(BaseUri, Uri) ->
try
xqerl_lib:resolve_against_base_uri(BaseUri, Uri)
catch
_:_ ->
throw_error(bad_uri, Uri)
end.
throw_error(bad_uri, Uri) ->
E = #xqError{
name = #qname{
namespace = ?NS,
prefix = ?PX,
local_name = <<"invalid-uri">>
},
description = <<"Not a valid lexical representation of the xs:anyURI type">>,
value = Uri
},
?err(E).
throw_error(node) ->
E = #xqError{
name = #qname{
namespace = ?NS,
prefix = ?PX,
local_name = <<"node-sequence">>
},
description = <<"Nodes are not allowed in mixed sequences.">>
},
?err(E).
| null | https://raw.githubusercontent.com/zadean/xqerl/06c651ec832d0ac2b77bef92c1b4ab14d8da8883/src/xqerl_mod_db.erl | erlang |
====================================================================
API functions
==================================================================== | Copyright ( c ) 2019 - 2020 .
SPDX - FileCopyrightText : 2022
SPDX - License - Identifier : Apache-2.0
@doc Implements namespace
-module(xqerl_mod_db).
-include("xqerl.hrl").
-define(NS, <<"">>).
-define(PX, <<"db">>).
-define(XL, <<"">>).
-define(ND, <<"updating">>).
-'module-namespace'({?NS, ?PX}).
-variables([]).
-functions([
{
{qname, ?NS, ?PX, <<"put">>},
{seqType, 'empty-sequence', zero},
[{annotation, {qname, ?XL, <<>>, ?ND}, []}],
{'put', 3},
2,
[
{seqType, item, one_or_many},
{seqType, 'xs:string', one}
]
},
{
{qname, ?NS, ?PX, <<"link">>},
{seqType, 'empty-sequence', zero},
[{annotation, {qname, ?XL, <<>>, ?ND}, []}],
{'link_', 3},
2,
[
{seqType, 'xs:string', one},
{seqType, 'xs:string', one}
]
},
{{qname, ?NS, ?PX, <<"get">>}, {seqType, item, one}, [], {'get_', 2}, 1, [
{seqType, 'xs:string', one}
]},
{
{qname, ?NS, ?PX, <<"delete">>},
{seqType, 'empty-sequence', zero},
[{annotation, {qname, ?XL, <<>>, ?ND}, []}],
{'delete', 2},
1,
[
{seqType, 'xs:string', one}
]
},
{
{qname, ?NS, ?PX, <<"delete-collection">>},
{seqType, 'empty-sequence', zero},
[{annotation, {qname, ?XL, <<>>, ?ND}, []}],
{'delete', 2},
1,
[
{seqType, 'xs:string', one}
]
}
]).
-export([
put/3,
link_/3,
get_/2,
delete/2,
delete_collection/2
]).
put(Ctx, [Item], Uri) ->
put(Ctx, Item, Uri);
put(Ctx, #{nk := _} = Node, Uri) ->
xqerl_mod_fn:put(Ctx, Node, Uri);
put(#{'base-uri' := BaseUri0} = Ctx, Item, Uri0) ->
Uri = xqerl_types:value(Uri0),
BaseUri = xqerl_types:value(BaseUri0),
AbsUri = resolve_uri(BaseUri, Uri),
{DbUri, Name} = xqldb_uri:split_uri(AbsUri),
DB = xqldb_db:database(DbUri),
do_put(Ctx, Item, DB, Name).
do_put(Ctx, Item, DB, Name) when is_binary(Item) ->
xqerl_update:add(Ctx, {put, text, Item, DB, Name});
do_put(Ctx, #xqAtomicValue{type = StrType, value = Item}, DB, Name) when ?xs_string(StrType) ->
xqerl_update:add(Ctx, {put, text, Item, DB, Name});
do_put(
Ctx,
#xqAtomicValue{
type = BinType,
value = Item
},
DB,
Name
) when BinType =:= 'xs:base64Binary'; BinType =:= 'xs:hexBinary' ->
xqerl_update:add(Ctx, {put, raw, Item, DB, Name});
do_put(Ctx, Items, DB, Name) when is_list(Items) ->
_ = [throw_error(node) || #{nk := _} <- Items],
xqerl_update:add(Ctx, {put, item, Items, DB, Name});
do_put(Ctx, Item, DB, Name) ->
xqerl_update:add(Ctx, {put, item, Item, DB, Name}).
link_(Ctx, [Item], Uri) ->
link_(Ctx, Item, Uri);
link_(#{'base-uri' := BaseUri0} = Ctx, Item, Uri0) ->
Uri = xqerl_types:value(Uri0),
BaseUri = xqerl_types:value(BaseUri0),
AbsUri = resolve_uri(BaseUri, Uri),
{DbUri, Name} = xqldb_uri:split_uri(AbsUri),
DB = xqldb_db:database(DbUri),
do_link(Ctx, Item, DB, Name).
do_link(Ctx, Filename, DB, Name) ->
xqerl_update:add(Ctx, {put, link, Filename, DB, Name}).
get_(#{'base-uri' := BaseUri0} = Ctx, Uri0) ->
Uri = xqerl_types:value(Uri0),
BaseUri = xqerl_types:value(BaseUri0),
AbsUri = resolve_uri(BaseUri, Uri),
xqldb_dml:select(Ctx, AbsUri).
delete(
#{
'base-uri' := BaseUri0,
trans := _Agent
} = Ctx,
Uri0
) ->
Uri = xqerl_types:value(Uri0),
BaseUri = xqerl_types:value(BaseUri0),
AbsUri = resolve_uri(BaseUri, Uri),
{DbUri, Name} = xqldb_uri:split_uri(AbsUri),
#{db_name := _DbPid} = DB = xqldb_db:database(DbUri),
xqerl_update:add(Ctx, {delete, item, {DB, Name}}).
delete_collection(
#{
'base-uri' := BaseUri0,
trans := Agent
} = Ctx,
Uri0
) ->
Uri = xqerl_types:value(Uri0),
BaseUri = xqerl_types:value(BaseUri0),
AbsUri = resolve_uri(BaseUri, Uri),
DBs = xqldb_db:databases(AbsUri),
Locks = [
{[DbPid, write], write}
|| #{db_name := DbPid} <- DBs
],
locks:lock_objects(Agent, Locks),
F = fun(DB) ->
xqerl_update:add(Ctx, {delete, all, DB})
end,
ok = lists:foreach(F, DBs),
[].
resolve_uri(BaseUri, Uri) ->
try
xqerl_lib:resolve_against_base_uri(BaseUri, Uri)
catch
_:_ ->
throw_error(bad_uri, Uri)
end.
throw_error(bad_uri, Uri) ->
E = #xqError{
name = #qname{
namespace = ?NS,
prefix = ?PX,
local_name = <<"invalid-uri">>
},
description = <<"Not a valid lexical representation of the xs:anyURI type">>,
value = Uri
},
?err(E).
throw_error(node) ->
E = #xqError{
name = #qname{
namespace = ?NS,
prefix = ?PX,
local_name = <<"node-sequence">>
},
description = <<"Nodes are not allowed in mixed sequences.">>
},
?err(E).
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.