_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 |
|---|---|---|---|---|---|---|---|---|
65ec54a482a1548fe9eb882421b2bfeb70bdfd14edc6323d16bc98037a01283c | owlbarn/owl_symbolic | example_10.ml |
* OWL - OCaml Scientific and Engineering Computing
* Copyright ( c ) 2016 - 2020 < >
* OWL - OCaml Scientific and Engineering Computing
* Copyright (c) 2016-2020 Liang Wang <>
*)
open Owl_symbolic_neural_graph
MNIST
let nn =
input [| 100; 3; 32; 32 |]
|> normalisation
|> conv2d [| 32; 3; 3; 3 |] [| 1; 1 |]
|> activation Relu
|> max_pool2d [| 2; 2 |] [| 2; 2 |] ~padding:VALID
|> fully_connected 512
|> activation Relu
|> fully_connected 10
|> activation (Softmax 1)
|> get_network
let _ =
let onnx_graph = Owl_symbolic_engine_onnx.of_symbolic nn in
Owl_symbolic_engine_onnx.save onnx_graph "test.onnx"
| null | https://raw.githubusercontent.com/owlbarn/owl_symbolic/dc853a016757d3f143c5e07e50075e7ae605d969/example/example_10.ml | ocaml |
* OWL - OCaml Scientific and Engineering Computing
* Copyright ( c ) 2016 - 2020 < >
* OWL - OCaml Scientific and Engineering Computing
* Copyright (c) 2016-2020 Liang Wang <>
*)
open Owl_symbolic_neural_graph
MNIST
let nn =
input [| 100; 3; 32; 32 |]
|> normalisation
|> conv2d [| 32; 3; 3; 3 |] [| 1; 1 |]
|> activation Relu
|> max_pool2d [| 2; 2 |] [| 2; 2 |] ~padding:VALID
|> fully_connected 512
|> activation Relu
|> fully_connected 10
|> activation (Softmax 1)
|> get_network
let _ =
let onnx_graph = Owl_symbolic_engine_onnx.of_symbolic nn in
Owl_symbolic_engine_onnx.save onnx_graph "test.onnx"
| |
cb90af2084ec7dd24f71039dc138a4cf437ca545a431af61cb92e00f020e479b | hasktorch/hasktorch | Dataset.hs | {-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE RecordWildCards #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TemplateHaskell #
# OPTIONS_GHC -Wno - orphans #
module Dataset where
import Control.Monad (guard)
import Control.Monad.State (MonadIO (liftIO), evalStateT, runState)
import Data.Aeson.TH (defaultOptions, deriveJSON)
import Data.Hashable (Hashable)
import qualified Data.List as List
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text (Text)
import Data.Word (Word64)
import GHC.Generics (Generic)
import qualified Gen
import qualified Hedgehog.Internal.Gen as Gen
import Hedgehog.Internal.Seed (Seed)
import qualified Hedgehog.Internal.Seed as Seed
import qualified Pipes.Safe as P
import qualified STLC
import Torch.GraduallyTyped
deriving instance Generic Seed
deriving instance Hashable Seed
type Tokenizer = String -> IO [Int]
type Detokenizer = [Int] -> IO String
data STLCData = STLCData
{ name :: Text,
seeds :: Set Seed,
targetNfSteps :: Maybe (Set Int),
maxInputLength :: Int,
maxTargetLength :: Int,
tokenize :: Tokenizer,
detokenize :: Detokenizer
}
data STLCExample a = STLCExample
{ exTy :: !STLC.Ty,
exInputExp :: !(STLC.Exp a),
exInputPPrint :: !String,
exInputIds :: ![Int],
exDecodedInputIds :: !String,
exTargetExp :: !(STLC.Exp a),
exTargetNfSteps :: !Int,
exTargetPPrint :: !String,
exTargetIds :: ![Int],
exDecodedTargetIds :: !String
}
deriving stock (Show, Eq, Ord, Generic)
deriving anyclass (Hashable)
$(deriveJSON defaultOptions ''STLCExample)
mkExample ::
Tokenizer ->
Detokenizer ->
Maybe (Set Int) ->
Int ->
Int ->
Seed.Seed ->
P.SafeT IO (STLCExample Int)
mkExample tokenize detokenize targetNfSteps maxInputLength maxTargetLength seed =
flip evalStateT seed . Gen.sample' $ do
exTy <- Gen.genTy
exInputExp <- Gen.generalize $ Gen.genWellTypedExp exTy
let (exTargetExp, exTargetNfSteps) = flip runState 0 $ STLC.nf exInputExp
guard (maybe True (\s -> exTargetNfSteps `Set.member` s) targetNfSteps)
let exInputPPrint = STLC.pprint exInputExp
exInputIds <- liftIO . tokenize $ exInputPPrint <> "</s>"
guard (List.length exInputIds <= maxInputLength)
let exTargetPPrint = STLC.pprint exTargetExp
exTargetIds <- liftIO . tokenize $ exTargetPPrint <> "</s>"
guard (List.length exTargetIds <= maxTargetLength)
exDecodedInputIds <- liftIO $ detokenize exInputIds
exDecodedTargetIds <- liftIO $ detokenize exTargetIds
pure $ STLCExample {..}
instance Dataset (P.SafeT IO) STLCData Seed (STLCExample Int) where
getItem STLCData {..} seed = do
guard $ Set.member seed seeds
mkExample tokenize detokenize targetNfSteps maxInputLength maxTargetLength seed
keys STLCData {..} = seeds
| null | https://raw.githubusercontent.com/hasktorch/hasktorch/8c6feb0e6987380fe92b487866f28edcfd665e82/experimental/gradually-typed/examples/neural-interpreter/Dataset.hs | haskell | # LANGUAGE DeriveAnyClass # | # LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE RecordWildCards #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TemplateHaskell #
# OPTIONS_GHC -Wno - orphans #
module Dataset where
import Control.Monad (guard)
import Control.Monad.State (MonadIO (liftIO), evalStateT, runState)
import Data.Aeson.TH (defaultOptions, deriveJSON)
import Data.Hashable (Hashable)
import qualified Data.List as List
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text (Text)
import Data.Word (Word64)
import GHC.Generics (Generic)
import qualified Gen
import qualified Hedgehog.Internal.Gen as Gen
import Hedgehog.Internal.Seed (Seed)
import qualified Hedgehog.Internal.Seed as Seed
import qualified Pipes.Safe as P
import qualified STLC
import Torch.GraduallyTyped
deriving instance Generic Seed
deriving instance Hashable Seed
type Tokenizer = String -> IO [Int]
type Detokenizer = [Int] -> IO String
data STLCData = STLCData
{ name :: Text,
seeds :: Set Seed,
targetNfSteps :: Maybe (Set Int),
maxInputLength :: Int,
maxTargetLength :: Int,
tokenize :: Tokenizer,
detokenize :: Detokenizer
}
data STLCExample a = STLCExample
{ exTy :: !STLC.Ty,
exInputExp :: !(STLC.Exp a),
exInputPPrint :: !String,
exInputIds :: ![Int],
exDecodedInputIds :: !String,
exTargetExp :: !(STLC.Exp a),
exTargetNfSteps :: !Int,
exTargetPPrint :: !String,
exTargetIds :: ![Int],
exDecodedTargetIds :: !String
}
deriving stock (Show, Eq, Ord, Generic)
deriving anyclass (Hashable)
$(deriveJSON defaultOptions ''STLCExample)
mkExample ::
Tokenizer ->
Detokenizer ->
Maybe (Set Int) ->
Int ->
Int ->
Seed.Seed ->
P.SafeT IO (STLCExample Int)
mkExample tokenize detokenize targetNfSteps maxInputLength maxTargetLength seed =
flip evalStateT seed . Gen.sample' $ do
exTy <- Gen.genTy
exInputExp <- Gen.generalize $ Gen.genWellTypedExp exTy
let (exTargetExp, exTargetNfSteps) = flip runState 0 $ STLC.nf exInputExp
guard (maybe True (\s -> exTargetNfSteps `Set.member` s) targetNfSteps)
let exInputPPrint = STLC.pprint exInputExp
exInputIds <- liftIO . tokenize $ exInputPPrint <> "</s>"
guard (List.length exInputIds <= maxInputLength)
let exTargetPPrint = STLC.pprint exTargetExp
exTargetIds <- liftIO . tokenize $ exTargetPPrint <> "</s>"
guard (List.length exTargetIds <= maxTargetLength)
exDecodedInputIds <- liftIO $ detokenize exInputIds
exDecodedTargetIds <- liftIO $ detokenize exTargetIds
pure $ STLCExample {..}
instance Dataset (P.SafeT IO) STLCData Seed (STLCExample Int) where
getItem STLCData {..} seed = do
guard $ Set.member seed seeds
mkExample tokenize detokenize targetNfSteps maxInputLength maxTargetLength seed
keys STLCData {..} = seeds
|
c200a81499d4298d0f723c480109c2753d39b6e73eb0a37ddad53a1d933e1c63 | ghcjs/ghcjs | t12478_2.hs | # LANGUAGE TemplateHaskell #
# LANGUAGE UnboxedSums #
-- Essentially the same as TH_repUnboxedTuples, but for unboxed sums
module Main where
import Language.Haskell.TH
main :: IO ()
main = case bar () of
(# a | #) -> print a
(# | b #) -> print b
bar :: () -> (# String | Int #)
bar () = $( do e <- [| case (# 'b' | #) of
(# 'a' | #) -> (# "One" | #)
(# 'b' | #) -> (# | 2 #)
(# _ | #) -> (# "Three" | #)
(# | _ #) -> (# | 4 #)
|]
return e )
| null | https://raw.githubusercontent.com/ghcjs/ghcjs/e4cd4232a31f6371c761acd93853702f4c7ca74c/test/ghc/th/t12478_2.hs | haskell | Essentially the same as TH_repUnboxedTuples, but for unboxed sums | # LANGUAGE TemplateHaskell #
# LANGUAGE UnboxedSums #
module Main where
import Language.Haskell.TH
main :: IO ()
main = case bar () of
(# a | #) -> print a
(# | b #) -> print b
bar :: () -> (# String | Int #)
bar () = $( do e <- [| case (# 'b' | #) of
(# 'a' | #) -> (# "One" | #)
(# 'b' | #) -> (# | 2 #)
(# _ | #) -> (# "Three" | #)
(# | _ #) -> (# | 4 #)
|]
return e )
|
dee42ea28c789414a609ea85b6d259d8ab07c3cdda7066c2ced87af26908fe6f | theam/aws-lambda-haskell-runtime | Configuration.hs | module Aws.Lambda.Runtime.Configuration
( DispatcherOptions (..),
defaultDispatcherOptions,
)
where
import Aws.Lambda.Runtime.APIGateway.Types (ApiGatewayDispatcherOptions (..))
-- | Options that the dispatcher generator expects
newtype DispatcherOptions = DispatcherOptions
{ apiGatewayDispatcherOptions :: ApiGatewayDispatcherOptions
}
defaultDispatcherOptions :: DispatcherOptions
defaultDispatcherOptions =
DispatcherOptions (ApiGatewayDispatcherOptions True)
| null | https://raw.githubusercontent.com/theam/aws-lambda-haskell-runtime/0031c3eea919d0b1505dde5aa24fd31436a49503/src/Aws/Lambda/Runtime/Configuration.hs | haskell | | Options that the dispatcher generator expects | module Aws.Lambda.Runtime.Configuration
( DispatcherOptions (..),
defaultDispatcherOptions,
)
where
import Aws.Lambda.Runtime.APIGateway.Types (ApiGatewayDispatcherOptions (..))
newtype DispatcherOptions = DispatcherOptions
{ apiGatewayDispatcherOptions :: ApiGatewayDispatcherOptions
}
defaultDispatcherOptions :: DispatcherOptions
defaultDispatcherOptions =
DispatcherOptions (ApiGatewayDispatcherOptions True)
|
98a446066e3063e67724d25d1c76dfe246b78043109286df9b2fd1e3916de928 | startalkIM/ejabberd | pokemon_pb.erl | Copyright ( c ) 2009
< >
< >
%%
%% 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(pokemon_pb).
-export([encode_pikachu/1, decode_pikachu/1, delimited_decode_pikachu/1]).
-export([has_extension/2, extension_size/1, get_extension/2,
set_extension/3]).
-export([decode_extensions/1]).
-export([encode/1, decode/2, delimited_decode/2]).
-export([int_to_enum/2, enum_to_int/2]).
-record(pikachu, {abc, def, '$extensions' = dict:new()}).
ENCODE
encode([]) ->
[];
encode(Records) when is_list(Records) ->
delimited_encode(Records);
encode(Record) ->
encode(element(1, Record), Record).
encode_pikachu(Records) when is_list(Records) ->
delimited_encode(Records);
encode_pikachu(Record) when is_record(Record, pikachu) ->
encode(pikachu, Record).
encode(pikachu, Records) when is_list(Records) ->
delimited_encode(Records);
encode(pikachu, Record) ->
[iolist(pikachu, Record)|encode_extensions(Record)].
encode_extensions(#pikachu{'$extensions' = Extends}) ->
[pack(Key, Optionalness, Data, Type, Accer) ||
{Key, {Optionalness, Data, Type, Accer}} <- dict:to_list(Extends)];
encode_extensions(_) -> [].
delimited_encode(Records) ->
lists:map(fun(Record) ->
IoRec = encode(Record),
Size = iolist_size(IoRec),
[protobuffs:encode_varint(Size), IoRec]
end, Records).
iolist(pikachu, Record) ->
[pack(1, required, with_default(Record#pikachu.abc, none), string, [])].
with_default(Default, Default) -> undefined;
with_default(Val, _) -> Val.
pack(_, optional, undefined, _, _) -> [];
pack(_, repeated, undefined, _, _) -> [];
pack(_, repeated_packed, undefined, _, _) -> [];
pack(_, repeated_packed, [], _, _) -> [];
pack(FNum, required, undefined, Type, _) ->
exit({error, {required_field_is_undefined, FNum, Type}});
pack(_, repeated, [], _, Acc) ->
lists:reverse(Acc);
pack(FNum, repeated, [Head|Tail], Type, Acc) ->
pack(FNum, repeated, Tail, Type, [pack(FNum, optional, Head, Type, [])|Acc]);
pack(FNum, repeated_packed, Data, Type, _) ->
protobuffs:encode_packed(FNum, Data, Type);
pack(FNum, _, Data, _, _) when is_tuple(Data) ->
[RecName|_] = tuple_to_list(Data),
protobuffs:encode(FNum, encode(RecName, Data), bytes);
pack(FNum, _, Data, Type, _) when Type=:=bool;Type=:=int32;Type=:=uint32;
Type=:=int64;Type=:=uint64;Type=:=sint32;
Type=:=sint64;Type=:=fixed32;Type=:=sfixed32;
Type=:=fixed64;Type=:=sfixed64;Type=:=string;
Type=:=bytes;Type=:=float;Type=:=double ->
protobuffs:encode(FNum, Data, Type);
pack(FNum, _, Data, Type, _) when is_atom(Data) ->
protobuffs:encode(FNum, enum_to_int(Type,Data), enum).
enum_to_int(pikachu,value) ->
1.
int_to_enum(_,Val) ->
Val.
%% DECODE
decode_pikachu(Bytes) when is_binary(Bytes) ->
decode(pikachu, Bytes).
delimited_decode_pikachu(Bytes) ->
delimited_decode(pikachu, Bytes).
delimited_decode(Type, Bytes) when is_binary(Bytes) ->
delimited_decode(Type, Bytes, []).
delimited_decode(_Type, <<>>, Acc) ->
{lists:reverse(Acc), <<>>};
delimited_decode(Type, Bytes, Acc) ->
try protobuffs:decode_varint(Bytes) of
{Size, Rest} when size(Rest) < Size ->
{lists:reverse(Acc), Bytes};
{Size, Rest} ->
<<MessageBytes:Size/binary, Rest2/binary>> = Rest,
Message = decode(Type, MessageBytes),
delimited_decode(Type, Rest2, [Message | Acc])
catch
% most likely cause is there isn't a complete varint in the buffer.
_What:_Why ->
{lists:reverse(Acc), Bytes}
end.
decode(pikachu, Bytes) when is_binary(Bytes) ->
Types = [{1, abc, int32, []}, {2, def, double, []}],
Defaults = [],
Decoded = decode(Bytes, Types, Defaults),
to_record(pikachu, Decoded).
decode(<<>>, Types, Acc) -> reverse_repeated_fields(Acc, Types);
decode(Bytes, Types, Acc) ->
{ok, FNum} = protobuffs:next_field_num(Bytes),
case lists:keyfind(FNum, 1, Types) of
{FNum, Name, Type, Opts} ->
{Value1, Rest1} =
case lists:member(is_record, Opts) of
true ->
{{FNum, V}, R} = protobuffs:decode(Bytes, bytes),
RecVal = decode(Type, V),
{RecVal, R};
false ->
case lists:member(repeated_packed, Opts) of
true ->
{{FNum, V}, R} = protobuffs:decode_packed(Bytes, Type),
{V, R};
false ->
{{FNum, V}, R} = protobuffs:decode(Bytes, Type),
{unpack_value(V, Type), R}
end
end,
case lists:member(repeated, Opts) of
true ->
case lists:keytake(FNum, 1, Acc) of
{value, {FNum, Name, List}, Acc1} ->
decode(Rest1, Types, [{FNum, Name, [int_to_enum(Type,Value1)|List]}|Acc1]);
false ->
decode(Rest1, Types, [{FNum, Name, [int_to_enum(Type,Value1)]}|Acc])
end;
false ->
decode(Rest1, Types, [{FNum, Name, int_to_enum(Type,Value1)}|Acc])
end;
false ->
case lists:keyfind('$extensions', 2, Acc) of
{_,_,Dict} ->
{{FNum, _V}, R} = protobuffs:decode(Bytes, bytes),
Diff = size(Bytes) - size(R),
<<V:Diff/binary,_/binary>> = Bytes,
NewDict = dict:store(FNum, V, Dict),
NewAcc = lists:keyreplace('$extensions', 2, Acc, {false, '$extensions', NewDict}),
decode(R, Types, NewAcc);
_ ->
{ok, Skipped} = protobuffs:skip_next_field(Bytes),
decode(Skipped, Types, Acc)
end
end.
reverse_repeated_fields(FieldList, Types) ->
[ begin
case lists:keyfind(FNum, 1, Types) of
{FNum, Name, _Type, Opts} ->
case lists:member(repeated, Opts) of
true ->
{FNum, Name, lists:reverse(Value)};
_ ->
Field
end;
_ -> Field
end
end || {FNum, Name, Value}=Field <- FieldList ].
unpack_value(Binary, string) when is_binary(Binary) ->
binary_to_list(Binary);
unpack_value(Value, _) -> Value.
to_record(pikachu, DecodedTuples) ->
Record1 = lists:foldr(
fun({_FNum, Name, Val}, Record) ->
set_record_field(record_info(fields, pikachu), Record, Name, Val)
end, #pikachu{}, DecodedTuples),
decode_extensions(Record1).
decode_extensions(#pikachu{'$extensions' = Extensions} = Record) ->
Types = [],
NewExtensions = decode_extensions(Types, dict:to_list(Extensions), []),
Record#pikachu{'$extensions' = NewExtensions};
decode_extensions(Record) ->
Record.
decode_extensions(_Types, [], Acc) ->
dict:from_list(Acc);
decode_extensions(Types, [{Fnum, Bytes} | Tail], Acc) ->
NewAcc = case lists:keyfind(Fnum, 1, Types) of
{Fnum, Name, Type, Opts} ->
{Value1, Rest1} =
case lists:member(is_record, Opts) of
true ->
{{FNum, V}, R} = protobuffs:decode(Bytes, bytes),
RecVal = decode(Type, V),
{RecVal, R};
false ->
case lists:member(repeated_packed, Opts) of
true ->
{{FNum, V}, R} = protobuffs:decode_packed(Bytes, Type),
{V, R};
false ->
{{FNum, V}, R} = protobuffs:decode(Bytes, Type),
{unpack_value(V, Type), R}
end
end,
case lists:member(repeated, Opts) of
true ->
case lists:keytake(FNum, 1, Acc) of
{value, {FNum, Name, List}, Acc1} ->
decode(Rest1, Types, [{FNum, Name, lists:reverse([int_to_enum(Type,Value1)|lists:reverse(List)])}|Acc1]);
false ->
decode(Rest1, Types, [{FNum, Name, [int_to_enum(Type,Value1)]}|Acc])
end;
false ->
[{Fnum, {optional, int_to_enum(Type,Value1), Type, Opts}} | Acc]
end;
false ->
[{Fnum, Bytes} | Acc]
end,
decode_extensions(Types, Tail, NewAcc).
set_record_field(Fields, Record, '$extensions', Value) ->
Decodable = [],
NewValue = decode_extensions(element(1, Record), Decodable, dict:to_list(Value)),
Index = list_index('$extensions', Fields),
erlang:setelement(Index+1,Record,NewValue);
set_record_field(Fields, Record, Field, Value) ->
Index = list_index(Field, Fields),
erlang:setelement(Index+1, Record, Value).
list_index(Target, List) -> list_index(Target, List, 1).
list_index(Target, [Target|_], Index) -> Index;
list_index(Target, [_|Tail], Index) -> list_index(Target, Tail, Index+1);
list_index(_, [], _) -> -1.
extension_size(#pikachu{'$extensions' = Extensions}) ->
dict:size(Extensions);
extension_size(_) ->
0.
has_extension(#pikachu{'$extensions' = Extensions}, FieldKey) ->
dict:is_key(FieldKey, Extensions);
has_extension(_Record, _FieldName) ->
false.
get_extension(Record, fieldatom) when is_record(Record, pikachu) ->
get_extension(Record, 1);
get_extension(#pikachu{'$extensions' = Extensions}, Int) when is_integer(Int) ->
case dict:find(Int, Extensions) of
{ok, {_Rule, Value, _Type, _Opts}} ->
{ok, Value};
{ok, Binary} ->
{raw, Binary};
error ->
undefined
end;
get_extension(_Record, _FieldName) ->
undefined.
set_extension(#pikachu{'$extensions' = Extensions} = Record, fieldname, Value) ->
NewExtends = dict:store(1, {rule, Value, type, []}, Extensions),
{ok, Record#pikachu{'$extensions' = NewExtends}};
set_extension(Record, _, _) ->
{error, Record}.
| null | https://raw.githubusercontent.com/startalkIM/ejabberd/718d86cd2f5681099fad14dab5f2541ddc612c8b/deps/protobuffs/src/pokemon_pb.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.
DECODE
most likely cause is there isn't a complete varint in the buffer. | Copyright ( c ) 2009
< >
< >
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(pokemon_pb).
-export([encode_pikachu/1, decode_pikachu/1, delimited_decode_pikachu/1]).
-export([has_extension/2, extension_size/1, get_extension/2,
set_extension/3]).
-export([decode_extensions/1]).
-export([encode/1, decode/2, delimited_decode/2]).
-export([int_to_enum/2, enum_to_int/2]).
-record(pikachu, {abc, def, '$extensions' = dict:new()}).
ENCODE
encode([]) ->
[];
encode(Records) when is_list(Records) ->
delimited_encode(Records);
encode(Record) ->
encode(element(1, Record), Record).
encode_pikachu(Records) when is_list(Records) ->
delimited_encode(Records);
encode_pikachu(Record) when is_record(Record, pikachu) ->
encode(pikachu, Record).
encode(pikachu, Records) when is_list(Records) ->
delimited_encode(Records);
encode(pikachu, Record) ->
[iolist(pikachu, Record)|encode_extensions(Record)].
encode_extensions(#pikachu{'$extensions' = Extends}) ->
[pack(Key, Optionalness, Data, Type, Accer) ||
{Key, {Optionalness, Data, Type, Accer}} <- dict:to_list(Extends)];
encode_extensions(_) -> [].
delimited_encode(Records) ->
lists:map(fun(Record) ->
IoRec = encode(Record),
Size = iolist_size(IoRec),
[protobuffs:encode_varint(Size), IoRec]
end, Records).
iolist(pikachu, Record) ->
[pack(1, required, with_default(Record#pikachu.abc, none), string, [])].
with_default(Default, Default) -> undefined;
with_default(Val, _) -> Val.
pack(_, optional, undefined, _, _) -> [];
pack(_, repeated, undefined, _, _) -> [];
pack(_, repeated_packed, undefined, _, _) -> [];
pack(_, repeated_packed, [], _, _) -> [];
pack(FNum, required, undefined, Type, _) ->
exit({error, {required_field_is_undefined, FNum, Type}});
pack(_, repeated, [], _, Acc) ->
lists:reverse(Acc);
pack(FNum, repeated, [Head|Tail], Type, Acc) ->
pack(FNum, repeated, Tail, Type, [pack(FNum, optional, Head, Type, [])|Acc]);
pack(FNum, repeated_packed, Data, Type, _) ->
protobuffs:encode_packed(FNum, Data, Type);
pack(FNum, _, Data, _, _) when is_tuple(Data) ->
[RecName|_] = tuple_to_list(Data),
protobuffs:encode(FNum, encode(RecName, Data), bytes);
pack(FNum, _, Data, Type, _) when Type=:=bool;Type=:=int32;Type=:=uint32;
Type=:=int64;Type=:=uint64;Type=:=sint32;
Type=:=sint64;Type=:=fixed32;Type=:=sfixed32;
Type=:=fixed64;Type=:=sfixed64;Type=:=string;
Type=:=bytes;Type=:=float;Type=:=double ->
protobuffs:encode(FNum, Data, Type);
pack(FNum, _, Data, Type, _) when is_atom(Data) ->
protobuffs:encode(FNum, enum_to_int(Type,Data), enum).
enum_to_int(pikachu,value) ->
1.
int_to_enum(_,Val) ->
Val.
decode_pikachu(Bytes) when is_binary(Bytes) ->
decode(pikachu, Bytes).
delimited_decode_pikachu(Bytes) ->
delimited_decode(pikachu, Bytes).
delimited_decode(Type, Bytes) when is_binary(Bytes) ->
delimited_decode(Type, Bytes, []).
delimited_decode(_Type, <<>>, Acc) ->
{lists:reverse(Acc), <<>>};
delimited_decode(Type, Bytes, Acc) ->
try protobuffs:decode_varint(Bytes) of
{Size, Rest} when size(Rest) < Size ->
{lists:reverse(Acc), Bytes};
{Size, Rest} ->
<<MessageBytes:Size/binary, Rest2/binary>> = Rest,
Message = decode(Type, MessageBytes),
delimited_decode(Type, Rest2, [Message | Acc])
catch
_What:_Why ->
{lists:reverse(Acc), Bytes}
end.
decode(pikachu, Bytes) when is_binary(Bytes) ->
Types = [{1, abc, int32, []}, {2, def, double, []}],
Defaults = [],
Decoded = decode(Bytes, Types, Defaults),
to_record(pikachu, Decoded).
decode(<<>>, Types, Acc) -> reverse_repeated_fields(Acc, Types);
decode(Bytes, Types, Acc) ->
{ok, FNum} = protobuffs:next_field_num(Bytes),
case lists:keyfind(FNum, 1, Types) of
{FNum, Name, Type, Opts} ->
{Value1, Rest1} =
case lists:member(is_record, Opts) of
true ->
{{FNum, V}, R} = protobuffs:decode(Bytes, bytes),
RecVal = decode(Type, V),
{RecVal, R};
false ->
case lists:member(repeated_packed, Opts) of
true ->
{{FNum, V}, R} = protobuffs:decode_packed(Bytes, Type),
{V, R};
false ->
{{FNum, V}, R} = protobuffs:decode(Bytes, Type),
{unpack_value(V, Type), R}
end
end,
case lists:member(repeated, Opts) of
true ->
case lists:keytake(FNum, 1, Acc) of
{value, {FNum, Name, List}, Acc1} ->
decode(Rest1, Types, [{FNum, Name, [int_to_enum(Type,Value1)|List]}|Acc1]);
false ->
decode(Rest1, Types, [{FNum, Name, [int_to_enum(Type,Value1)]}|Acc])
end;
false ->
decode(Rest1, Types, [{FNum, Name, int_to_enum(Type,Value1)}|Acc])
end;
false ->
case lists:keyfind('$extensions', 2, Acc) of
{_,_,Dict} ->
{{FNum, _V}, R} = protobuffs:decode(Bytes, bytes),
Diff = size(Bytes) - size(R),
<<V:Diff/binary,_/binary>> = Bytes,
NewDict = dict:store(FNum, V, Dict),
NewAcc = lists:keyreplace('$extensions', 2, Acc, {false, '$extensions', NewDict}),
decode(R, Types, NewAcc);
_ ->
{ok, Skipped} = protobuffs:skip_next_field(Bytes),
decode(Skipped, Types, Acc)
end
end.
reverse_repeated_fields(FieldList, Types) ->
[ begin
case lists:keyfind(FNum, 1, Types) of
{FNum, Name, _Type, Opts} ->
case lists:member(repeated, Opts) of
true ->
{FNum, Name, lists:reverse(Value)};
_ ->
Field
end;
_ -> Field
end
end || {FNum, Name, Value}=Field <- FieldList ].
unpack_value(Binary, string) when is_binary(Binary) ->
binary_to_list(Binary);
unpack_value(Value, _) -> Value.
to_record(pikachu, DecodedTuples) ->
Record1 = lists:foldr(
fun({_FNum, Name, Val}, Record) ->
set_record_field(record_info(fields, pikachu), Record, Name, Val)
end, #pikachu{}, DecodedTuples),
decode_extensions(Record1).
decode_extensions(#pikachu{'$extensions' = Extensions} = Record) ->
Types = [],
NewExtensions = decode_extensions(Types, dict:to_list(Extensions), []),
Record#pikachu{'$extensions' = NewExtensions};
decode_extensions(Record) ->
Record.
decode_extensions(_Types, [], Acc) ->
dict:from_list(Acc);
decode_extensions(Types, [{Fnum, Bytes} | Tail], Acc) ->
NewAcc = case lists:keyfind(Fnum, 1, Types) of
{Fnum, Name, Type, Opts} ->
{Value1, Rest1} =
case lists:member(is_record, Opts) of
true ->
{{FNum, V}, R} = protobuffs:decode(Bytes, bytes),
RecVal = decode(Type, V),
{RecVal, R};
false ->
case lists:member(repeated_packed, Opts) of
true ->
{{FNum, V}, R} = protobuffs:decode_packed(Bytes, Type),
{V, R};
false ->
{{FNum, V}, R} = protobuffs:decode(Bytes, Type),
{unpack_value(V, Type), R}
end
end,
case lists:member(repeated, Opts) of
true ->
case lists:keytake(FNum, 1, Acc) of
{value, {FNum, Name, List}, Acc1} ->
decode(Rest1, Types, [{FNum, Name, lists:reverse([int_to_enum(Type,Value1)|lists:reverse(List)])}|Acc1]);
false ->
decode(Rest1, Types, [{FNum, Name, [int_to_enum(Type,Value1)]}|Acc])
end;
false ->
[{Fnum, {optional, int_to_enum(Type,Value1), Type, Opts}} | Acc]
end;
false ->
[{Fnum, Bytes} | Acc]
end,
decode_extensions(Types, Tail, NewAcc).
set_record_field(Fields, Record, '$extensions', Value) ->
Decodable = [],
NewValue = decode_extensions(element(1, Record), Decodable, dict:to_list(Value)),
Index = list_index('$extensions', Fields),
erlang:setelement(Index+1,Record,NewValue);
set_record_field(Fields, Record, Field, Value) ->
Index = list_index(Field, Fields),
erlang:setelement(Index+1, Record, Value).
list_index(Target, List) -> list_index(Target, List, 1).
list_index(Target, [Target|_], Index) -> Index;
list_index(Target, [_|Tail], Index) -> list_index(Target, Tail, Index+1);
list_index(_, [], _) -> -1.
extension_size(#pikachu{'$extensions' = Extensions}) ->
dict:size(Extensions);
extension_size(_) ->
0.
has_extension(#pikachu{'$extensions' = Extensions}, FieldKey) ->
dict:is_key(FieldKey, Extensions);
has_extension(_Record, _FieldName) ->
false.
get_extension(Record, fieldatom) when is_record(Record, pikachu) ->
get_extension(Record, 1);
get_extension(#pikachu{'$extensions' = Extensions}, Int) when is_integer(Int) ->
case dict:find(Int, Extensions) of
{ok, {_Rule, Value, _Type, _Opts}} ->
{ok, Value};
{ok, Binary} ->
{raw, Binary};
error ->
undefined
end;
get_extension(_Record, _FieldName) ->
undefined.
set_extension(#pikachu{'$extensions' = Extensions} = Record, fieldname, Value) ->
NewExtends = dict:store(1, {rule, Value, type, []}, Extensions),
{ok, Record#pikachu{'$extensions' = NewExtends}};
set_extension(Record, _, _) ->
{error, Record}.
|
0a2deeee570aec330c5daf730a71fcb945da525c24532af1accc5c1dba2c7bdb | simmone/racket-simple-xlsx | fill-style.rkt | #lang racket
(require "lib.rkt")
(provide (contract-out
[struct FILL-STYLE
(
(hash_code string?)
(color rgb?)
(pattern fill-pattern?)
)]
[fill-pattern? (-> string? boolean?)]
[fill-style-from-hash-code (-> string? (or/c #f FILL-STYLE?))]
[fill-style<? (-> (or/c #f FILL-STYLE?) (or/c #f FILL-STYLE?) boolean?)]
[fill-style=? (-> (or/c #f FILL-STYLE?) (or/c #f FILL-STYLE?) boolean?)]
[*FILL_STYLE->INDEX_MAP* (parameter/c (or/c (hash/c string? natural?) #f))]
[*FILL_INDEX->STYLE_MAP* (parameter/c (or/c (hash/c natural? string?) #f))]
))
(define *FILL_STYLE->INDEX_MAP* (make-parameter #f))
(define *FILL_INDEX->STYLE_MAP* (make-parameter #f))
(struct FILL-STYLE (hash_code color pattern)
#:guard
(lambda (_hash_code _color _pattern name)
(values
(format "~a<p>~a" (string-upcase _color) _pattern)
(string-upcase _color) _pattern)))
(define (fill-style-from-hash-code hash_code)
(let ([items (regexp-split #rx"<p>" hash_code)])
(if (= (length items) 2)
(FILL-STYLE "" (first items) (second items))
#f)))
(define (fill-pattern? pattern)
(ormap (lambda (_pattern) (string=? _pattern pattern))
'("none"
"solid" "gray125" "darkGray" "mediumGray" "lightGray"
"gray0625" "darkHorizontal" "darkVertical" "darkDown" "darkUp"
"darkGrid" "darkTrellis" "lightHorizontal" "lightVertical" "lightDown"
"lightUp" "lightGrid" "lightTrellis")))
(define (fill-style=? fill1 fill2)
(cond
[(and (equal? fill1 #f) (equal? fill2 #f))
#t]
[(or (equal? fill1 #f) (equal? fill2 #f))
#f]
[else
(string=? (FILL-STYLE-hash_code fill1) (FILL-STYLE-hash_code fill2))]))
(define (fill-style<? fill1 fill2)
(cond
[(and (equal? fill1 #f) (equal? fill2 #f))
#f]
[(equal? fill1 #f)
#t]
[(equal? fill2 #f)
#f]
[(not (string=? (FILL-STYLE-color fill1) (FILL-STYLE-color fill2)))
(string<? (FILL-STYLE-color fill1) (FILL-STYLE-color fill2))]
[(not (string=? (FILL-STYLE-pattern fill1) (FILL-STYLE-pattern fill2)))
(string<? (FILL-STYLE-pattern fill1) (FILL-STYLE-pattern fill2))]
[else
#f]))
| null | https://raw.githubusercontent.com/simmone/racket-simple-xlsx/e0ac3190b6700b0ee1dd80ed91a8f4318533d012/simple-xlsx/style/fill-style.rkt | racket | #lang racket
(require "lib.rkt")
(provide (contract-out
[struct FILL-STYLE
(
(hash_code string?)
(color rgb?)
(pattern fill-pattern?)
)]
[fill-pattern? (-> string? boolean?)]
[fill-style-from-hash-code (-> string? (or/c #f FILL-STYLE?))]
[fill-style<? (-> (or/c #f FILL-STYLE?) (or/c #f FILL-STYLE?) boolean?)]
[fill-style=? (-> (or/c #f FILL-STYLE?) (or/c #f FILL-STYLE?) boolean?)]
[*FILL_STYLE->INDEX_MAP* (parameter/c (or/c (hash/c string? natural?) #f))]
[*FILL_INDEX->STYLE_MAP* (parameter/c (or/c (hash/c natural? string?) #f))]
))
(define *FILL_STYLE->INDEX_MAP* (make-parameter #f))
(define *FILL_INDEX->STYLE_MAP* (make-parameter #f))
(struct FILL-STYLE (hash_code color pattern)
#:guard
(lambda (_hash_code _color _pattern name)
(values
(format "~a<p>~a" (string-upcase _color) _pattern)
(string-upcase _color) _pattern)))
(define (fill-style-from-hash-code hash_code)
(let ([items (regexp-split #rx"<p>" hash_code)])
(if (= (length items) 2)
(FILL-STYLE "" (first items) (second items))
#f)))
(define (fill-pattern? pattern)
(ormap (lambda (_pattern) (string=? _pattern pattern))
'("none"
"solid" "gray125" "darkGray" "mediumGray" "lightGray"
"gray0625" "darkHorizontal" "darkVertical" "darkDown" "darkUp"
"darkGrid" "darkTrellis" "lightHorizontal" "lightVertical" "lightDown"
"lightUp" "lightGrid" "lightTrellis")))
(define (fill-style=? fill1 fill2)
(cond
[(and (equal? fill1 #f) (equal? fill2 #f))
#t]
[(or (equal? fill1 #f) (equal? fill2 #f))
#f]
[else
(string=? (FILL-STYLE-hash_code fill1) (FILL-STYLE-hash_code fill2))]))
(define (fill-style<? fill1 fill2)
(cond
[(and (equal? fill1 #f) (equal? fill2 #f))
#f]
[(equal? fill1 #f)
#t]
[(equal? fill2 #f)
#f]
[(not (string=? (FILL-STYLE-color fill1) (FILL-STYLE-color fill2)))
(string<? (FILL-STYLE-color fill1) (FILL-STYLE-color fill2))]
[(not (string=? (FILL-STYLE-pattern fill1) (FILL-STYLE-pattern fill2)))
(string<? (FILL-STYLE-pattern fill1) (FILL-STYLE-pattern fill2))]
[else
#f]))
| |
28ffb1d8e15798a01f5d43fb8a6cf6266a97aad94360108cfe6e59d0ba26083c | iburzynski/EMURGO_73 | Applicatives3.hs | # LANGUAGE InstanceSigs #
import Control.Applicative hiding (ZipList)
-- *** Exercise: Implement the Applicative Instance for List ***
-- Now we will create our own version of the built-in List type from scratch and make it an Applicative:
data List a = Empty | Cons a (List a)
instance Show a => Show (List a) where
show :: Show a => List a -> String
show xs = showList True xs
where
showList :: Show a => Bool -> List a -> String
showList True Empty = "[]"
showList True (Cons x Empty) = "[" ++ show x ++ "]"
showList True (Cons x xs) = "[" ++ show x ++ "," ++ showList False xs
showList False (Cons x Empty) = show x ++ "]"
showList False (Cons x xs) = show x ++ "," ++ showList False xs
-- Built-in List equivalents:
-- Empty == []
Cons 1 ( Cons 2 ( Cons 3 Empty ) ) = = [ 1 , 2 , 3 ]
-- We will need some version of `++` (append) for our List type in our Applicative instance.
-- Recall that we implemented this by making our List a Semigroup, defining `<>` ("mappend"):
instance Semigroup (List a) where
(<>) :: List a -> List a -> List a
Empty <> xs = xs
-- Built-in List equivalent:
-- [] <> xs = xs
xs <> Empty = xs
Cons x xs <> ys = Cons x (xs <> ys)
-- Built-in List equivalent:
-- (x:xs) ++ ys = x : xs ++ ys
-- x : x' : x'' ... : y : y' : y'' ... : []
instance Functor List where
fmap :: (a -> b) -> List a -> List b
fmap _ Empty = Empty
-- fmap _ [] = []
fmap f (x `Cons` xs) = f x `Cons` fmap f xs
fmap f ( x : xs ) = f x : fmap f xs
data Either' e a = Left' e | Right' a
instance Functor (Either' e) where
fmap :: (a -> b) -> Either' e a -> Either' e b
fmap f (Right' x) = Right' $ f x
fmap _ (Left' e) = Left' e
instance Applicative (Either' e) where
(<*>) :: Either' e (a -> b) -> Either' e a -> Either' e b
Left' e <*> _ = Left' e
Right' f <*> ex = f <$> ex
-- _ <*> Left' e = Left' e
-- Right' f <*> Right' x = Right' (f x)
pure :: a -> Either' e a
pure = Right'
instance Applicative List where
pure :: a -> List a
pure x = x `Cons` Empty
-- Built-in List equivalent:
-- pure x = [x]
(<*>) :: List (a -> b) -> List a -> List b
Empty <*> _ = Empty
f `Cons` fs <*> xs = (f <$> xs) <> (fs <*> xs)
Step 1 : map the first function to all values in the arguments list
Step 2 : append that mapped list to the result of recursively ` app`ing the tail of the
-- functions list to the arguments list
Example : [ ( + 1 ) , ( * 2 ) , ( ^ 2 ) ] < * > [ 1 , 2 , 3 ]
( + 1 ) < $ > [ 1 , 2 , 3 ] = > [ 2 , 3 , 4 ] + +
( * 2 ) < $ > [ 1 , 2 , 3 ] = > [ 2 , 4 , 6 ] + +
( ^2 ) < $ > [ 1 , 2 , 3 ] = > [ 1 , 4 , 9 ] + + [ ]
combos = Cons (+ 1) (Cons (* 2) (Cons (^ 2) Empty)) <*> Cons 1 (Cons 2 (Cons 3 Empty))
i.e. [ ( + 1 ) , ( * 2 ) , ( ^ 2 ) ] < * > [ 1 , 2 , 3 ]
-- Exercise Q29.3 (Get Programming with Haskell)
You bought soda last night but do n't remember whether it was a 6 - pack or 12 - pack :
startingSoda :: [Int]
startingSoda = [6, 12]
You and your roommate each drank 2 sodas yesterday :
remainingSoda :: [Int]
remainingSoda = ( \sodas - > sodas - 4 ) < $ > startingSoda
remainingSoda = subtract 4 <$> startingSoda
You 're having 2 or 3 friends come over :
guests :: [Int]
guests = [2, 3]
-- The total number of people (guests + you + roommate):
totalPeople :: [Int]
totalPeople = (+ 2) <$> guests
Each person will drink 3 or 4 sodas :
sodasPerPerson :: [Int]
sodasPerPerson = [3, 4]
-- Calculate how many sodas are needed in total:
sodasNeeded :: [Int]
sodasNeeded = (*) <$> sodasPerPerson <*> totalPeople
-- Calculate how many you need to buy:
sodasToBuy :: [Int]
sodasToBuy = (-) <$> sodasNeeded <*> remainingSoda | null | https://raw.githubusercontent.com/iburzynski/EMURGO_73/8042aab6ab29e7b9bbbb53750a8b339c15b43af0/Applicatives/Applicatives3.hs | haskell | *** Exercise: Implement the Applicative Instance for List ***
Now we will create our own version of the built-in List type from scratch and make it an Applicative:
Built-in List equivalents:
Empty == []
We will need some version of `++` (append) for our List type in our Applicative instance.
Recall that we implemented this by making our List a Semigroup, defining `<>` ("mappend"):
Built-in List equivalent:
[] <> xs = xs
Built-in List equivalent:
(x:xs) ++ ys = x : xs ++ ys
x : x' : x'' ... : y : y' : y'' ... : []
fmap _ [] = []
_ <*> Left' e = Left' e
Right' f <*> Right' x = Right' (f x)
Built-in List equivalent:
pure x = [x]
functions list to the arguments list
Exercise Q29.3 (Get Programming with Haskell)
The total number of people (guests + you + roommate):
Calculate how many sodas are needed in total:
Calculate how many you need to buy: | # LANGUAGE InstanceSigs #
import Control.Applicative hiding (ZipList)
data List a = Empty | Cons a (List a)
instance Show a => Show (List a) where
show :: Show a => List a -> String
show xs = showList True xs
where
showList :: Show a => Bool -> List a -> String
showList True Empty = "[]"
showList True (Cons x Empty) = "[" ++ show x ++ "]"
showList True (Cons x xs) = "[" ++ show x ++ "," ++ showList False xs
showList False (Cons x Empty) = show x ++ "]"
showList False (Cons x xs) = show x ++ "," ++ showList False xs
Cons 1 ( Cons 2 ( Cons 3 Empty ) ) = = [ 1 , 2 , 3 ]
instance Semigroup (List a) where
(<>) :: List a -> List a -> List a
Empty <> xs = xs
xs <> Empty = xs
Cons x xs <> ys = Cons x (xs <> ys)
instance Functor List where
fmap :: (a -> b) -> List a -> List b
fmap _ Empty = Empty
fmap f (x `Cons` xs) = f x `Cons` fmap f xs
fmap f ( x : xs ) = f x : fmap f xs
data Either' e a = Left' e | Right' a
instance Functor (Either' e) where
fmap :: (a -> b) -> Either' e a -> Either' e b
fmap f (Right' x) = Right' $ f x
fmap _ (Left' e) = Left' e
instance Applicative (Either' e) where
(<*>) :: Either' e (a -> b) -> Either' e a -> Either' e b
Left' e <*> _ = Left' e
Right' f <*> ex = f <$> ex
pure :: a -> Either' e a
pure = Right'
instance Applicative List where
pure :: a -> List a
pure x = x `Cons` Empty
(<*>) :: List (a -> b) -> List a -> List b
Empty <*> _ = Empty
f `Cons` fs <*> xs = (f <$> xs) <> (fs <*> xs)
Step 1 : map the first function to all values in the arguments list
Step 2 : append that mapped list to the result of recursively ` app`ing the tail of the
Example : [ ( + 1 ) , ( * 2 ) , ( ^ 2 ) ] < * > [ 1 , 2 , 3 ]
( + 1 ) < $ > [ 1 , 2 , 3 ] = > [ 2 , 3 , 4 ] + +
( * 2 ) < $ > [ 1 , 2 , 3 ] = > [ 2 , 4 , 6 ] + +
( ^2 ) < $ > [ 1 , 2 , 3 ] = > [ 1 , 4 , 9 ] + + [ ]
combos = Cons (+ 1) (Cons (* 2) (Cons (^ 2) Empty)) <*> Cons 1 (Cons 2 (Cons 3 Empty))
i.e. [ ( + 1 ) , ( * 2 ) , ( ^ 2 ) ] < * > [ 1 , 2 , 3 ]
You bought soda last night but do n't remember whether it was a 6 - pack or 12 - pack :
startingSoda :: [Int]
startingSoda = [6, 12]
You and your roommate each drank 2 sodas yesterday :
remainingSoda :: [Int]
remainingSoda = ( \sodas - > sodas - 4 ) < $ > startingSoda
remainingSoda = subtract 4 <$> startingSoda
You 're having 2 or 3 friends come over :
guests :: [Int]
guests = [2, 3]
totalPeople :: [Int]
totalPeople = (+ 2) <$> guests
Each person will drink 3 or 4 sodas :
sodasPerPerson :: [Int]
sodasPerPerson = [3, 4]
sodasNeeded :: [Int]
sodasNeeded = (*) <$> sodasPerPerson <*> totalPeople
sodasToBuy :: [Int]
sodasToBuy = (-) <$> sodasNeeded <*> remainingSoda |
149cf5cf4090a9229edbbff04b54b02ef624be0427363f324d7c3aaaf5a1debd | pNre/Hera | types.ml | module Subscription = struct
type t =
{ id : int [@default 0]
; subscriber_id : string
; type_id : string [@default ""]
; feed_url : string
}
[@@deriving make]
let key subscription = subscription.subscriber_id ^ "," ^ subscription.feed_url
end
module Preference = struct
type t =
{ owner_id : string
; key : string
; value : string
}
[@@deriving make]
end
module Market_position = struct
type t =
{ id : int [@default 0]
; owner_id : string
; symbol : string
; price : string
; size : string
; currency : string
}
[@@deriving make]
end
| null | https://raw.githubusercontent.com/pNre/Hera/4b37551b6fe535d63baf20f9b01d29e6d4e8d53e/hera/db/types.ml | ocaml | module Subscription = struct
type t =
{ id : int [@default 0]
; subscriber_id : string
; type_id : string [@default ""]
; feed_url : string
}
[@@deriving make]
let key subscription = subscription.subscriber_id ^ "," ^ subscription.feed_url
end
module Preference = struct
type t =
{ owner_id : string
; key : string
; value : string
}
[@@deriving make]
end
module Market_position = struct
type t =
{ id : int [@default 0]
; owner_id : string
; symbol : string
; price : string
; size : string
; currency : string
}
[@@deriving make]
end
| |
a6f55f6906a8d470fbbe5856491fb91e10f6ab8bf22863d20d239a298c864244 | it-is-wednesday/pitzulit | main.mli | type error = [ `Eyed3Error of int | `FfmpegError of int | `YoutubeDlError of int ]
* Prepare filesystem for extracting tracks from a new album :
- Download the album as audio via youtube - dl ( saved as " album.mp3 " in current dir )
- Figure out the [ Album.t ]
- Create target directory
- Fetch cover art ( video thumbnail )
If no errors occured , returns a tuple of : [ Album.t ] , cover file path , target directory
- Download the album as audio via youtube-dl (saved as "album.mp3" in current dir)
- Figure out the [Album.t]
- Create target directory
- Fetch cover art (video thumbnail)
If no errors occured, returns a tuple of: [Album.t], cover file path, target directory *)
val setup :
url:string ->
dir:string ->
no_download:bool ->
(Album.t * string * string, [> `YoutubeDlError of int ]) result
(* Assumes an "album.mp3" file exists in current dir (created by [Pitzulit.Main.setup]).
extracts the given track into its own file via ffmpeg, then tags it via eyeD3. *)
val handle_track :
Track.t ->
artist:string ->
album:string ->
dir:string ->
cover_file:string ->
no_extract:bool ->
verbose:bool ->
(unit, [> `Eyed3Error of int | `FfmpegError of int ]) result
| null | https://raw.githubusercontent.com/it-is-wednesday/pitzulit/53b19505dda882e272c5671b26e4228146df97e1/lib/main.mli | ocaml | Assumes an "album.mp3" file exists in current dir (created by [Pitzulit.Main.setup]).
extracts the given track into its own file via ffmpeg, then tags it via eyeD3. | type error = [ `Eyed3Error of int | `FfmpegError of int | `YoutubeDlError of int ]
* Prepare filesystem for extracting tracks from a new album :
- Download the album as audio via youtube - dl ( saved as " album.mp3 " in current dir )
- Figure out the [ Album.t ]
- Create target directory
- Fetch cover art ( video thumbnail )
If no errors occured , returns a tuple of : [ Album.t ] , cover file path , target directory
- Download the album as audio via youtube-dl (saved as "album.mp3" in current dir)
- Figure out the [Album.t]
- Create target directory
- Fetch cover art (video thumbnail)
If no errors occured, returns a tuple of: [Album.t], cover file path, target directory *)
val setup :
url:string ->
dir:string ->
no_download:bool ->
(Album.t * string * string, [> `YoutubeDlError of int ]) result
val handle_track :
Track.t ->
artist:string ->
album:string ->
dir:string ->
cover_file:string ->
no_extract:bool ->
verbose:bool ->
(unit, [> `Eyed3Error of int | `FfmpegError of int ]) result
|
e58b5a936b2e9142335e3aac914b6b9990c8fc93ada67ce99b6e1a470a399a79 | ktakashi/sagittarius-scheme | bytevector.scm | -*- mode : scheme ; coding : utf-8 -*-
;;;
;;; bytevector.scm - bytevector utility
;;;
Copyright ( c ) 2010 - 2013 < >
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;;
;;; 1. Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;;
;;; 2. Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
;;; 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.
;;;
(library (util bytevector)
(export bytevector-xor
bytevector-xor!
bytevector-ior
bytevector-ior!
bytevector-and
bytevector-and!
bytevector-slices
bytevector-split-at*
;; parity stuff
->odd-parity
->odd-parity!
bytevector=?
bytevector-append
bytevector-concatenate
;; extra comparison
bytevector<?
bytevector>?
bytevector<=?
bytevector>=?
bytevector->hex-string
hex-string->bytevector
bytevector-reverse!
bytevector-reverse
inspired by srfi 13
;; utility
u8? u8-set? u8-set-contains?
string->u8-set char-set->u8-set
;; do you want map and for-each as well?
bytevector-fold bytevector-fold-right
;; cutting & pasting bytevectors
bytevector-take bytevector-take-right
bytevector-drop bytevector-drop-right
bytevector-trim bytevector-trim-right bytevector-trim-both
bytevector-pad bytevector-pad-right
;; prefixes & suffixes
bytevector-prefix-length bytevector-suffix-length
bytevector-prefix? bytevector-suffix?
;; searching
bytevector-index bytevector-index-right
bytevector-skip bytevector-skip-right
bytevector-contains
;; miscellaneous: insertion, parsing
bytevector-replace bytevector-tokenize
;; filtering & deleting
bytevector-filter bytevector-delete
;; others
align-bytevectors
align-bytevectors!
bytevector->escaped-string
)
(import (rnrs)
(rnrs mutable-strings)
(sagittarius)
(sagittarius control)
(srfi :1 lists)
(only (srfi :13 strings) make-kmp-restart-vector)
(srfi :14 char-sets)
(srfi :26 cut))
;; (define (process-bytevector! op out . bvs)
;; (let ((len (apply min (map bytevector-length bvs))))
( dotimes ( i len )
;; (bytevector-u8-set! out i
;; (apply op
;; (map (^(bv) (bytevector-u8-ref bv i))
;; bvs))))
;; out))
( define ( bytevector - xor ! out . bvs )
;; (apply process-bytevector! bitwise-xor out bvs))
(define (bytevector-xor . bvs)
(let* ((len (apply min (map bytevector-length bvs)))
(out (make-bytevector len 0)))
(apply bytevector-xor! out bvs)))
;; (define (bytevector-ior! out . bvs)
;; (apply process-bytevector! bitwise-ior out bvs))
(define (bytevector-ior . bvs)
(let* ((len (apply min (map bytevector-length bvs)))
(out (make-bytevector len 0)))
(apply bytevector-ior! out bvs)))
;; (define (bytevector-and! out . bvs)
;; (apply process-bytevector! bitwise-and out bvs))
(define (bytevector-and . bvs)
(let* ((len (apply min (map bytevector-length bvs)))
(out (make-bytevector len 0)))
(apply bytevector-and! out bvs)))
(define (->odd-parity bv . args)
(apply ->odd-parity! (bytevector-copy bv) args))
(define (->odd-parity! bv :optional (start 0) (end (bytevector-length bv)))
(define (fixup b)
(let ((parity (bitwise-bit-count b)))
(if (even? parity)
(if (even? b)
(bitwise-ior b #x01)
(bitwise-and b #xFE))
b)))
(do ((i start (+ i 1)))
((= i end) bv)
(bytevector-u8-set! bv i (fixup (bytevector-u8-ref bv i)))))
;; analogy of slices and split-at* in (util list)
(define (bytevector-slices bv k . args)
(unless (and (integer? k) (positive? k))
(assertion-violation 'bytevector-slices "index must be positive integer" k))
(let1 len (bytevector-length bv)
(let loop ((bv bv) (r '()) (i 0))
(if (< i len)
(let-values (((h t) (apply bytevector-split-at* bv k args)))
(loop t (cons h r) (+ i k)))
(reverse! r)))))
(define (bytevector-split-at* bv k :key (padding #f))
(unless (and (integer? k) (not (negative? k)))
(assertion-violation 'bytevector-split-at*
"index must be non-negative integer" k))
(let1 len (bytevector-length bv)
(if (< k len)
(let ((r1 (bytevector-copy bv 0 k))
(r2 (bytevector-copy bv k)))
(values r1 r2))
(values (if padding (padding bv) bv) #vu8()))))
(define (bytevector->hex-string bv :key (upper? #t))
;; this is not efficient...
;; (define (fixup x)
( if (= ( string - length x ) 1 )
;; (string-append "0" x)
;; x))
( string - concatenate ( map ( lambda ( u8 ) ( fixup ( number->string u8 16 ) ) )
( bytevector->u8 - list bv ) ) )
;; (let-values (((out extract) (open-string-output-port)))
;; (let ((fmt (if capital? "~2,'0X" "~2,'0x")))
;; (dotimes (i (bytevector-length bv))
;; (format out fmt (bytevector-u8-ref bv i))))
;; (extract))
;; this is the fastest
(define (hex->char i)
(cond ((< i 10) (integer->char (+ i 48))) ;; + #\0
+ # \A - 10
+ # \a - 10
(let* ((len (bytevector-length bv))
(str (make-string (* len 2))))
(dotimes (i len str)
(let* ((b (bytevector-u8-ref bv i))
(hi (bitwise-arithmetic-shift (bitwise-and b #xF0) -4))
(lo (bitwise-and b #x0F)))
(string-set! str (* i 2) (hex->char hi))
(string-set! str (+ (* i 2) 1) (hex->char lo))))))
(define (hex-string->bytevector str)
;; make the same as following
;; (integer->bytevector (string->number str 16))
;; so it needs to handle odd length string as well
thus " 123 " would be # vu8(#x01 # x23 )
(define (safe-ref s i)
(if (< i 0) #\0 (string-ref s i)))
(define (->hex c)
(if (char-set-contains? char-set:hex-digit c)
(or (digit-value c) ;; easy
(let ((c (char-upcase c)))
;; must be A-F
(- (char->integer c) #x37)))
(assertion-violation 'hex-string->bytevector "non hex character" c str)))
(let* ((len (string-length str))
(bv (make-bytevector (ceiling (/ len 2)))))
(let loop ((i (- (bytevector-length bv) 1)) (j (- len 1)))
(if (< i 0)
bv
(let ((h (->hex (safe-ref str (- j 1))))
(l (->hex (safe-ref str j))))
(bytevector-u8-set! bv i
(bitwise-ior (bitwise-arithmetic-shift h 4) l))
(loop (- i 1) (- j 2)))))))
# vu8(56 ) - > " ; "
(define (bytevector->escaped-string bv)
;; it's like this but efficient
( list->string ( map ( bytevector->u8 - list bv ) ) )
(let* ((len (bytevector-length bv))
(str (make-string len)))
(dotimes (i len str)
(let ((b (bytevector-u8-ref bv i)))
(string-set! str i (integer->char b))))))
srfi 13 things
;; helper
(define (u8? n) (and (integer? n) (<= 0 n #xFF)))
(define (u8-set? o)
(and (pair? o)
(let loop ((l o))
(or (null? l)
(and (u8? (car l)) (loop (cdr l)))))))
(define (string->u8-set s) (map char->integer (string->list s)))
(define (char-set->u8-set cset)
(map char->integer
(char-set->list (char-set-intersection cset char-set:ascii))))
(define (bytevector-take bv n) (bytevector-copy bv 0 n))
(define (bytevector-take-right bv n)
(let ((len (bytevector-length bv)))
(bytevector-copy bv (- len n) len)))
(define (bytevector-drop bv n)
(let ((len (bytevector-length bv)))
(bytevector-copy bv n len)))
(define (bytevector-drop-right bv n)
(let ((len (bytevector-length bv)))
(bytevector-copy bv 0 (- len n))))
(define u8-set:whitespace (string->u8-set " \r\f\v\n\t"))
(define (bytevector-trim bv
:optional (criterion u8-set:whitespace)
(start 0) (end (bytevector-length bv)))
(cond ((bytevector-skip bv criterion start end) =>
(lambda (i) (bytevector-copy bv i end)))
(else #vu8())))
(define (bytevector-trim-right bv
:optional (criterion u8-set:whitespace)
(start 0) (end (bytevector-length bv)))
(cond ((bytevector-skip-right bv criterion start end) =>
(lambda (i) (bytevector-copy bv start (+ i 1))))
(else #vu8())))
(define (bytevector-trim-both bv
:optional (criterion u8-set:whitespace)
(start 0) (end (bytevector-length bv)))
(cond ((bytevector-skip bv criterion start end) =>
(lambda (i)
(bytevector-copy bv i
(+ (bytevector-skip-right bv criterion i end) 1))))
(else #vu8())))
(define (bytevector-pad bv n
:optional (u8 0) (start 0) (end (bytevector-length bv)))
(let ((len (- end start)))
(if (<= n len)
(bytevector-copy bv (- end n) end)
(let ((ans (make-bytevector n u8)))
(bytevector-copy! bv start ans (- n len) len)
ans))))
(define (bytevector-pad-right bv n
:optional (u8 0) (start 0) (end (bytevector-length bv)))
(let ((len (- end start)))
(if (<= n len)
(bytevector-copy bv start (+ start n))
(let ((ans (make-bytevector n u8)))
(bytevector-copy! bv start ans 0 len)
ans))))
(define (bytevector-prefix-length bv1 bv2
:optional (start1 0) (end1 (bytevector-length bv1))
(start2 0) (end2 (bytevector-length bv2)))
(let* ((delta (min (- end1 start1) (- end2 start2)))
(end1 (+ start1 delta)))
(if (and (eq? bv1 bv2) (= start1 start2)) ; EQ fast path
delta
(let lp ((i start1) (j start2)) ; Regular path
(if (or (>= i end1)
(not (= (bytevector-u8-ref bv1 i)
(bytevector-u8-ref bv2 j))))
(- i start1)
(lp (+ i 1) (+ j 1)))))))
(define (bytevector-prefix? bv1 bv2
:optional (start1 0) (end1 (bytevector-length bv1))
(start2 0) (end2 (bytevector-length bv2)))
(let ((len1 (- end1 start1)))
(and (<= len1 (- end2 start2))
(= (bytevector-prefix-length bv1 bv2 start1 end1 start2 end2) len1))))
(define (bytevector-suffix-length bv1 bv2
:optional (start1 0) (end1 (bytevector-length bv1))
(start2 0) (end2 (bytevector-length bv2)))
(let* ((delta (min (- end1 start1) (- end2 start2)))
(end1 (+ start1 delta)))
(if (and (eq? bv1 bv2) (= start1 start2)) ; EQ fast path
delta
(let lp ((i (- end1 1)) (j (- end2 1))) ; Regular path
(if (or (< i start1)
(not (= (bytevector-u8-ref bv1 i)
(bytevector-u8-ref bv2 j))))
(- (- end1 i) 1)
(lp (- i 1) (- j 1)))))))
(define (bytevector-suffix? bv1 bv2
:optional (start1 0) (end1 (bytevector-length bv1))
(start2 0) (end2 (bytevector-length bv2)))
(let ((len1 (- end1 start1)))
(and (<= len1 (- end2 start2))
(= (bytevector-suffix-length bv1 bv2 start1 end1 start2 end2) len1))))
;; search
;; sort of set operation
(define (u8-set-contains? set u8) (memv u8 set))
(define (bytevector-index bv criterion
:optional (start 0) (end (bytevector-length bv)))
(cond ((u8? criterion)
(let lp ((i start))
(and (< i end)
(if (= criterion (bytevector-u8-ref bv i)) i
(lp (+ i 1))))))
((u8-set? criterion)
(let lp ((i start))
(and (< i end)
(if (u8-set-contains? criterion (bytevector-u8-ref bv i)) i
(lp (+ i 1))))))
((procedure? criterion)
(let lp ((i start))
(and (< i end)
(if (criterion (bytevector-u8-ref bv i)) i
(lp (+ i 1))))))
(else
(error 'bytevector-index
"Second param is neither u8, u8-set or predicate procedure."
criterion))))
(define (bytevector-index-right bv criterion
:optional (start 0) (end (bytevector-length bv)))
(cond ((u8? criterion)
(let lp ((i (- end 1)))
(and (>= i start)
(if (= criterion (bytevector-u8-ref bv i)) i
(lp (- i 1))))))
((u8-set? criterion)
(let lp ((i (- end 1)))
(and (>= i start)
(if (u8-set-contains? criterion (bytevector-u8-ref bv i)) i
(lp (- i 1))))))
((procedure? criterion)
(let lp ((i (- end 1)))
(and (>= i start)
(if (criterion (bytevector-u8-ref bv i)) i
(lp (- i 1))))))
(else
(error 'bytevector-index-right
"Second param is neither u8, u8-set or predicate procedure."
criterion))))
(define (bytevector-skip bv criterion
:optional (start 0) (end (bytevector-length bv)))
(cond ((u8? criterion)
(let lp ((i start))
(and (< i end)
(if (= criterion (bytevector-u8-ref bv i))
(lp (+ i 1))
i))))
((u8-set? criterion)
(let lp ((i start))
(and (< i end)
(if (u8-set-contains? criterion (bytevector-u8-ref bv i))
(lp (+ i 1))
i))))
((procedure? criterion)
(let lp ((i start))
(and (< i end)
(if (criterion (bytevector-u8-ref bv i))
(lp (+ i 1))
i))))
(else
(error 'bytevector-index
"Second param is neither u8, u8-set or predicate procedure."
criterion))))
(define (bytevector-skip-right bv criterion
:optional (start 0) (end (bytevector-length bv)))
(cond ((u8? criterion)
(let lp ((i (- end 1)))
(and (>= i start)
(if (= criterion (bytevector-u8-ref bv i))
(lp (- i 1))
i))))
((u8-set? criterion)
(let lp ((i (- end 1)))
(and (>= i start)
(if (u8-set-contains? criterion (bytevector-u8-ref bv i))
(lp (- i 1))
i))))
((procedure? criterion)
(let lp ((i (- end 1)))
(and (>= i start)
(if (criterion (bytevector-u8-ref bv i))
(lp (- i 1))
i))))
(else
(error 'bytevector-index-right
"Second param is neither u8, u8-set or predicate procedure."
criterion))))
;; contains
(define (bytevector-contains bv pattern
:optional (b-start 0) (b-end (bytevector-length bv))
(p-start 0) (p-end (bytevector-length pattern)))
(let ((plen (- p-end p-start))
(rv (make-kmp-restart-vector pattern =
p-start p-end bytevector-u8-ref)))
The search loop . TJ & PJ are redundant state .
(let lp ((ti b-start) (pi 0)
(tj (- b-end b-start)) ; (- tlen ti) -- how many chars left.
(pj plen)) ; (- plen pi) -- how many chars left.
(if (= pi plen)
(- ti plen) ; Win.
(and (<= pj tj) ; Lose.
Search .
(bytevector-u8-ref pattern (+ p-start pi)))
Advance .
(let ((pi (vector-ref rv pi))) ; Retreat.
(if (= pi -1)
Punt .
(lp ti pi tj (- plen pi))))))))))
;; replace
(define (bytevector-replace bv1 bv2 start1 end1
:optional (start2 0) (end2 (bytevector-length bv2)))
(let* ((bv-len1 (bytevector-length bv1))
(sublen (- end2 start2))
(alen (+ (- bv-len1 (- end1 start1)) sublen))
(ans (make-bytevector alen)))
(bytevector-copy! bv1 0 ans 0 start1)
(bytevector-copy! bv2 start2 ans start1 sublen)
(bytevector-copy! bv1 end1 ans (+ start1 sublen) (- bv-len1 end1))
ans))
;; tokenize
(define u8-set:graphics
(string->u8-set "~}|{zyxwvutsrqponmlkjihgfedcba`_^]\\[ZYXWVUTSRQPONMLKJIHGFEDCBA@?>=<;:9876543210/.-,+*)('&%$#\"!"))
(define (bytevector-tokenize bv
:optional (token-set u8-set:graphics)
(start 0) (end (bytevector-length bv)))
(let lp ((i end) (ans '()))
(cond ((and (< start i) (bytevector-index-right bv token-set start i)) =>
(lambda (tend-1)
(let ((tend (+ 1 tend-1)))
(cond ((bytevector-skip-right bv token-set start tend-1) =>
(lambda (tstart-1)
(lp tstart-1
(cons (bytevector-copy bv (+ 1 tstart-1) tend)
ans))))
(else (cons (bytevector-copy bv start tend) ans))))))
(else ans))))
;; fold... for what!
(define (bytevector-fold kons knil bv
:optional (start 0) (end (bytevector-length bv)))
(let lp ((v knil) (i start))
(if (< i end)
(lp (kons (bytevector-u8-ref bv i) v) (+ i 1))
v)))
(define (bytevector-fold-right kons knil bv
:optional (start 0) (end (bytevector-length bv)))
(let lp ((v knil) (i (- end 1)))
(if (>= i start)
(lp (kons (bytevector-u8-ref bv i) v) (- i 1))
v)))
;; filter & delete
(define (bytevector-filter criterion bv
:optional (start 0) (end (bytevector-length bv)))
(if (procedure? criterion)
(let* ((slen (- end start))
(temp (make-bytevector slen))
(ans-len (bytevector-fold (lambda (c i)
(if (criterion c)
(begin (bytevector-u8-set! temp i c)
(+ i 1))
i))
0 bv start end)))
(if (= ans-len slen) temp (bytevector-copy temp 0 ans-len)))
(let* ((cset (cond ((u8-set? criterion) criterion)
((u8? criterion) (list criterion))
(else
(error 'bytevector-filter
"criterion not predicate, char or char-set"
criterion))))
(len (bytevector-fold (lambda (c i) (if (u8-set-contains? cset c)
(+ i 1)
i))
0 bv start end))
(ans (make-bytevector len)))
(bytevector-fold (lambda (c i) (if (u8-set-contains? cset c)
(begin (bytevector-u8-set! ans i c)
(+ i 1))
i))
0 bv start end)
ans)))
(define (bytevector-delete criterion bv
:optional (start 0) (end (bytevector-length bv)))
(if (procedure? criterion)
(let* ((slen (- end start))
(temp (make-bytevector slen))
(ans-len (bytevector-fold (lambda (c i)
(if (criterion c)
i
(begin (bytevector-u8-set! temp i c)
(+ i 1))))
0 bv start end)))
(if (= ans-len slen) temp (bytevector-copy temp 0 ans-len)))
(let* ((cset (cond ((u8-set? criterion) criterion)
((u8? criterion) (list criterion))
(else
(error 'bytevector-delete
"criterion not predicate, char or char-set"
criterion))))
(len (bytevector-fold (lambda (c i) (if (u8-set-contains? cset c)
i
(+ i 1)))
0 bv start end))
(ans (make-bytevector len)))
(bytevector-fold (lambda (c i) (if (u8-set-contains? cset c)
i
(begin (bytevector-u8-set! ans i c)
(+ i 1))))
0 bv start end)
ans)))
;; helper
(define (align-bytevectors bvs size)
(align-bytevectors! (list-copy bvs) size))
(define (align-bytevectors! bvs size)
(define (length-pred bv) (= (bytevector-length bv) size))
(define (align1 bvs offset)
(let ((buf (make-bytevector size)))
(let loop ((bvs bvs) (i 0) (offset offset))
(cond ((null? bvs) (values (bytevector-copy buf 0 i) '() 0))
((= i size) (values buf bvs offset))
(else
(let* ((bv (car bvs))
(len (bytevector-length bv))
(buf-rest (- size i))
(src-len (- len offset)))
(cond ((>= buf-rest src-len)
;; buffer has enough space, just copy
(bytevector-copy! bv offset buf i src-len)
(loop (cdr bvs) (+ i src-len) 0))
(else
(bytevector-copy! bv offset buf i buf-rest)
(values buf bvs (+ offset buf-rest))))))))))
(let-values (((aligned need) (span! length-pred bvs)))
(let loop ((need need) (r '()) (offset 0))
(if (null? need)
(append aligned (reverse! r))
(let-values (((bv rest offset) (align1 need offset)))
(loop rest (cons bv r) offset))))))
)
| null | https://raw.githubusercontent.com/ktakashi/sagittarius-scheme/1557403f8a585eae527f35ba10cc64a6cdc35ac8/sitelib/util/bytevector.scm | scheme | coding : utf-8 -*-
bytevector.scm - bytevector utility
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
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,
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
parity stuff
extra comparison
utility
do you want map and for-each as well?
cutting & pasting bytevectors
prefixes & suffixes
searching
miscellaneous: insertion, parsing
filtering & deleting
others
(define (process-bytevector! op out . bvs)
(let ((len (apply min (map bytevector-length bvs))))
(bytevector-u8-set! out i
(apply op
(map (^(bv) (bytevector-u8-ref bv i))
bvs))))
out))
(apply process-bytevector! bitwise-xor out bvs))
(define (bytevector-ior! out . bvs)
(apply process-bytevector! bitwise-ior out bvs))
(define (bytevector-and! out . bvs)
(apply process-bytevector! bitwise-and out bvs))
analogy of slices and split-at* in (util list)
this is not efficient...
(define (fixup x)
(string-append "0" x)
x))
(let-values (((out extract) (open-string-output-port)))
(let ((fmt (if capital? "~2,'0X" "~2,'0x")))
(dotimes (i (bytevector-length bv))
(format out fmt (bytevector-u8-ref bv i))))
(extract))
this is the fastest
+ #\0
make the same as following
(integer->bytevector (string->number str 16))
so it needs to handle odd length string as well
easy
must be A-F
it's like this but efficient
helper
EQ fast path
Regular path
EQ fast path
Regular path
search
sort of set operation
contains
(- tlen ti) -- how many chars left.
(- plen pi) -- how many chars left.
Win.
Lose.
Retreat.
replace
tokenize
fold... for what!
filter & delete
helper
buffer has enough space, just copy | Copyright ( c ) 2010 - 2013 < >
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED
LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
(library (util bytevector)
(export bytevector-xor
bytevector-xor!
bytevector-ior
bytevector-ior!
bytevector-and
bytevector-and!
bytevector-slices
bytevector-split-at*
->odd-parity
->odd-parity!
bytevector=?
bytevector-append
bytevector-concatenate
bytevector<?
bytevector>?
bytevector<=?
bytevector>=?
bytevector->hex-string
hex-string->bytevector
bytevector-reverse!
bytevector-reverse
inspired by srfi 13
u8? u8-set? u8-set-contains?
string->u8-set char-set->u8-set
bytevector-fold bytevector-fold-right
bytevector-take bytevector-take-right
bytevector-drop bytevector-drop-right
bytevector-trim bytevector-trim-right bytevector-trim-both
bytevector-pad bytevector-pad-right
bytevector-prefix-length bytevector-suffix-length
bytevector-prefix? bytevector-suffix?
bytevector-index bytevector-index-right
bytevector-skip bytevector-skip-right
bytevector-contains
bytevector-replace bytevector-tokenize
bytevector-filter bytevector-delete
align-bytevectors
align-bytevectors!
bytevector->escaped-string
)
(import (rnrs)
(rnrs mutable-strings)
(sagittarius)
(sagittarius control)
(srfi :1 lists)
(only (srfi :13 strings) make-kmp-restart-vector)
(srfi :14 char-sets)
(srfi :26 cut))
( dotimes ( i len )
( define ( bytevector - xor ! out . bvs )
(define (bytevector-xor . bvs)
(let* ((len (apply min (map bytevector-length bvs)))
(out (make-bytevector len 0)))
(apply bytevector-xor! out bvs)))
(define (bytevector-ior . bvs)
(let* ((len (apply min (map bytevector-length bvs)))
(out (make-bytevector len 0)))
(apply bytevector-ior! out bvs)))
(define (bytevector-and . bvs)
(let* ((len (apply min (map bytevector-length bvs)))
(out (make-bytevector len 0)))
(apply bytevector-and! out bvs)))
(define (->odd-parity bv . args)
(apply ->odd-parity! (bytevector-copy bv) args))
(define (->odd-parity! bv :optional (start 0) (end (bytevector-length bv)))
(define (fixup b)
(let ((parity (bitwise-bit-count b)))
(if (even? parity)
(if (even? b)
(bitwise-ior b #x01)
(bitwise-and b #xFE))
b)))
(do ((i start (+ i 1)))
((= i end) bv)
(bytevector-u8-set! bv i (fixup (bytevector-u8-ref bv i)))))
(define (bytevector-slices bv k . args)
(unless (and (integer? k) (positive? k))
(assertion-violation 'bytevector-slices "index must be positive integer" k))
(let1 len (bytevector-length bv)
(let loop ((bv bv) (r '()) (i 0))
(if (< i len)
(let-values (((h t) (apply bytevector-split-at* bv k args)))
(loop t (cons h r) (+ i k)))
(reverse! r)))))
(define (bytevector-split-at* bv k :key (padding #f))
(unless (and (integer? k) (not (negative? k)))
(assertion-violation 'bytevector-split-at*
"index must be non-negative integer" k))
(let1 len (bytevector-length bv)
(if (< k len)
(let ((r1 (bytevector-copy bv 0 k))
(r2 (bytevector-copy bv k)))
(values r1 r2))
(values (if padding (padding bv) bv) #vu8()))))
(define (bytevector->hex-string bv :key (upper? #t))
( if (= ( string - length x ) 1 )
( string - concatenate ( map ( lambda ( u8 ) ( fixup ( number->string u8 16 ) ) )
( bytevector->u8 - list bv ) ) )
(define (hex->char i)
+ # \A - 10
+ # \a - 10
(let* ((len (bytevector-length bv))
(str (make-string (* len 2))))
(dotimes (i len str)
(let* ((b (bytevector-u8-ref bv i))
(hi (bitwise-arithmetic-shift (bitwise-and b #xF0) -4))
(lo (bitwise-and b #x0F)))
(string-set! str (* i 2) (hex->char hi))
(string-set! str (+ (* i 2) 1) (hex->char lo))))))
(define (hex-string->bytevector str)
thus " 123 " would be # vu8(#x01 # x23 )
(define (safe-ref s i)
(if (< i 0) #\0 (string-ref s i)))
(define (->hex c)
(if (char-set-contains? char-set:hex-digit c)
(let ((c (char-upcase c)))
(- (char->integer c) #x37)))
(assertion-violation 'hex-string->bytevector "non hex character" c str)))
(let* ((len (string-length str))
(bv (make-bytevector (ceiling (/ len 2)))))
(let loop ((i (- (bytevector-length bv) 1)) (j (- len 1)))
(if (< i 0)
bv
(let ((h (->hex (safe-ref str (- j 1))))
(l (->hex (safe-ref str j))))
(bytevector-u8-set! bv i
(bitwise-ior (bitwise-arithmetic-shift h 4) l))
(loop (- i 1) (- j 2)))))))
# vu8(56 ) - > " ; "
(define (bytevector->escaped-string bv)
( list->string ( map ( bytevector->u8 - list bv ) ) )
(let* ((len (bytevector-length bv))
(str (make-string len)))
(dotimes (i len str)
(let ((b (bytevector-u8-ref bv i)))
(string-set! str i (integer->char b))))))
srfi 13 things
(define (u8? n) (and (integer? n) (<= 0 n #xFF)))
(define (u8-set? o)
(and (pair? o)
(let loop ((l o))
(or (null? l)
(and (u8? (car l)) (loop (cdr l)))))))
(define (string->u8-set s) (map char->integer (string->list s)))
(define (char-set->u8-set cset)
(map char->integer
(char-set->list (char-set-intersection cset char-set:ascii))))
(define (bytevector-take bv n) (bytevector-copy bv 0 n))
(define (bytevector-take-right bv n)
(let ((len (bytevector-length bv)))
(bytevector-copy bv (- len n) len)))
(define (bytevector-drop bv n)
(let ((len (bytevector-length bv)))
(bytevector-copy bv n len)))
(define (bytevector-drop-right bv n)
(let ((len (bytevector-length bv)))
(bytevector-copy bv 0 (- len n))))
(define u8-set:whitespace (string->u8-set " \r\f\v\n\t"))
(define (bytevector-trim bv
:optional (criterion u8-set:whitespace)
(start 0) (end (bytevector-length bv)))
(cond ((bytevector-skip bv criterion start end) =>
(lambda (i) (bytevector-copy bv i end)))
(else #vu8())))
(define (bytevector-trim-right bv
:optional (criterion u8-set:whitespace)
(start 0) (end (bytevector-length bv)))
(cond ((bytevector-skip-right bv criterion start end) =>
(lambda (i) (bytevector-copy bv start (+ i 1))))
(else #vu8())))
(define (bytevector-trim-both bv
:optional (criterion u8-set:whitespace)
(start 0) (end (bytevector-length bv)))
(cond ((bytevector-skip bv criterion start end) =>
(lambda (i)
(bytevector-copy bv i
(+ (bytevector-skip-right bv criterion i end) 1))))
(else #vu8())))
(define (bytevector-pad bv n
:optional (u8 0) (start 0) (end (bytevector-length bv)))
(let ((len (- end start)))
(if (<= n len)
(bytevector-copy bv (- end n) end)
(let ((ans (make-bytevector n u8)))
(bytevector-copy! bv start ans (- n len) len)
ans))))
(define (bytevector-pad-right bv n
:optional (u8 0) (start 0) (end (bytevector-length bv)))
(let ((len (- end start)))
(if (<= n len)
(bytevector-copy bv start (+ start n))
(let ((ans (make-bytevector n u8)))
(bytevector-copy! bv start ans 0 len)
ans))))
(define (bytevector-prefix-length bv1 bv2
:optional (start1 0) (end1 (bytevector-length bv1))
(start2 0) (end2 (bytevector-length bv2)))
(let* ((delta (min (- end1 start1) (- end2 start2)))
(end1 (+ start1 delta)))
delta
(if (or (>= i end1)
(not (= (bytevector-u8-ref bv1 i)
(bytevector-u8-ref bv2 j))))
(- i start1)
(lp (+ i 1) (+ j 1)))))))
(define (bytevector-prefix? bv1 bv2
:optional (start1 0) (end1 (bytevector-length bv1))
(start2 0) (end2 (bytevector-length bv2)))
(let ((len1 (- end1 start1)))
(and (<= len1 (- end2 start2))
(= (bytevector-prefix-length bv1 bv2 start1 end1 start2 end2) len1))))
(define (bytevector-suffix-length bv1 bv2
:optional (start1 0) (end1 (bytevector-length bv1))
(start2 0) (end2 (bytevector-length bv2)))
(let* ((delta (min (- end1 start1) (- end2 start2)))
(end1 (+ start1 delta)))
delta
(if (or (< i start1)
(not (= (bytevector-u8-ref bv1 i)
(bytevector-u8-ref bv2 j))))
(- (- end1 i) 1)
(lp (- i 1) (- j 1)))))))
(define (bytevector-suffix? bv1 bv2
:optional (start1 0) (end1 (bytevector-length bv1))
(start2 0) (end2 (bytevector-length bv2)))
(let ((len1 (- end1 start1)))
(and (<= len1 (- end2 start2))
(= (bytevector-suffix-length bv1 bv2 start1 end1 start2 end2) len1))))
(define (u8-set-contains? set u8) (memv u8 set))
(define (bytevector-index bv criterion
:optional (start 0) (end (bytevector-length bv)))
(cond ((u8? criterion)
(let lp ((i start))
(and (< i end)
(if (= criterion (bytevector-u8-ref bv i)) i
(lp (+ i 1))))))
((u8-set? criterion)
(let lp ((i start))
(and (< i end)
(if (u8-set-contains? criterion (bytevector-u8-ref bv i)) i
(lp (+ i 1))))))
((procedure? criterion)
(let lp ((i start))
(and (< i end)
(if (criterion (bytevector-u8-ref bv i)) i
(lp (+ i 1))))))
(else
(error 'bytevector-index
"Second param is neither u8, u8-set or predicate procedure."
criterion))))
(define (bytevector-index-right bv criterion
:optional (start 0) (end (bytevector-length bv)))
(cond ((u8? criterion)
(let lp ((i (- end 1)))
(and (>= i start)
(if (= criterion (bytevector-u8-ref bv i)) i
(lp (- i 1))))))
((u8-set? criterion)
(let lp ((i (- end 1)))
(and (>= i start)
(if (u8-set-contains? criterion (bytevector-u8-ref bv i)) i
(lp (- i 1))))))
((procedure? criterion)
(let lp ((i (- end 1)))
(and (>= i start)
(if (criterion (bytevector-u8-ref bv i)) i
(lp (- i 1))))))
(else
(error 'bytevector-index-right
"Second param is neither u8, u8-set or predicate procedure."
criterion))))
(define (bytevector-skip bv criterion
:optional (start 0) (end (bytevector-length bv)))
(cond ((u8? criterion)
(let lp ((i start))
(and (< i end)
(if (= criterion (bytevector-u8-ref bv i))
(lp (+ i 1))
i))))
((u8-set? criterion)
(let lp ((i start))
(and (< i end)
(if (u8-set-contains? criterion (bytevector-u8-ref bv i))
(lp (+ i 1))
i))))
((procedure? criterion)
(let lp ((i start))
(and (< i end)
(if (criterion (bytevector-u8-ref bv i))
(lp (+ i 1))
i))))
(else
(error 'bytevector-index
"Second param is neither u8, u8-set or predicate procedure."
criterion))))
(define (bytevector-skip-right bv criterion
:optional (start 0) (end (bytevector-length bv)))
(cond ((u8? criterion)
(let lp ((i (- end 1)))
(and (>= i start)
(if (= criterion (bytevector-u8-ref bv i))
(lp (- i 1))
i))))
((u8-set? criterion)
(let lp ((i (- end 1)))
(and (>= i start)
(if (u8-set-contains? criterion (bytevector-u8-ref bv i))
(lp (- i 1))
i))))
((procedure? criterion)
(let lp ((i (- end 1)))
(and (>= i start)
(if (criterion (bytevector-u8-ref bv i))
(lp (- i 1))
i))))
(else
(error 'bytevector-index-right
"Second param is neither u8, u8-set or predicate procedure."
criterion))))
(define (bytevector-contains bv pattern
:optional (b-start 0) (b-end (bytevector-length bv))
(p-start 0) (p-end (bytevector-length pattern)))
(let ((plen (- p-end p-start))
(rv (make-kmp-restart-vector pattern =
p-start p-end bytevector-u8-ref)))
The search loop . TJ & PJ are redundant state .
(let lp ((ti b-start) (pi 0)
(if (= pi plen)
Search .
(bytevector-u8-ref pattern (+ p-start pi)))
Advance .
(if (= pi -1)
Punt .
(lp ti pi tj (- plen pi))))))))))
(define (bytevector-replace bv1 bv2 start1 end1
:optional (start2 0) (end2 (bytevector-length bv2)))
(let* ((bv-len1 (bytevector-length bv1))
(sublen (- end2 start2))
(alen (+ (- bv-len1 (- end1 start1)) sublen))
(ans (make-bytevector alen)))
(bytevector-copy! bv1 0 ans 0 start1)
(bytevector-copy! bv2 start2 ans start1 sublen)
(bytevector-copy! bv1 end1 ans (+ start1 sublen) (- bv-len1 end1))
ans))
(define u8-set:graphics
(string->u8-set "~}|{zyxwvutsrqponmlkjihgfedcba`_^]\\[ZYXWVUTSRQPONMLKJIHGFEDCBA@?>=<;:9876543210/.-,+*)('&%$#\"!"))
(define (bytevector-tokenize bv
:optional (token-set u8-set:graphics)
(start 0) (end (bytevector-length bv)))
(let lp ((i end) (ans '()))
(cond ((and (< start i) (bytevector-index-right bv token-set start i)) =>
(lambda (tend-1)
(let ((tend (+ 1 tend-1)))
(cond ((bytevector-skip-right bv token-set start tend-1) =>
(lambda (tstart-1)
(lp tstart-1
(cons (bytevector-copy bv (+ 1 tstart-1) tend)
ans))))
(else (cons (bytevector-copy bv start tend) ans))))))
(else ans))))
(define (bytevector-fold kons knil bv
:optional (start 0) (end (bytevector-length bv)))
(let lp ((v knil) (i start))
(if (< i end)
(lp (kons (bytevector-u8-ref bv i) v) (+ i 1))
v)))
(define (bytevector-fold-right kons knil bv
:optional (start 0) (end (bytevector-length bv)))
(let lp ((v knil) (i (- end 1)))
(if (>= i start)
(lp (kons (bytevector-u8-ref bv i) v) (- i 1))
v)))
(define (bytevector-filter criterion bv
:optional (start 0) (end (bytevector-length bv)))
(if (procedure? criterion)
(let* ((slen (- end start))
(temp (make-bytevector slen))
(ans-len (bytevector-fold (lambda (c i)
(if (criterion c)
(begin (bytevector-u8-set! temp i c)
(+ i 1))
i))
0 bv start end)))
(if (= ans-len slen) temp (bytevector-copy temp 0 ans-len)))
(let* ((cset (cond ((u8-set? criterion) criterion)
((u8? criterion) (list criterion))
(else
(error 'bytevector-filter
"criterion not predicate, char or char-set"
criterion))))
(len (bytevector-fold (lambda (c i) (if (u8-set-contains? cset c)
(+ i 1)
i))
0 bv start end))
(ans (make-bytevector len)))
(bytevector-fold (lambda (c i) (if (u8-set-contains? cset c)
(begin (bytevector-u8-set! ans i c)
(+ i 1))
i))
0 bv start end)
ans)))
(define (bytevector-delete criterion bv
:optional (start 0) (end (bytevector-length bv)))
(if (procedure? criterion)
(let* ((slen (- end start))
(temp (make-bytevector slen))
(ans-len (bytevector-fold (lambda (c i)
(if (criterion c)
i
(begin (bytevector-u8-set! temp i c)
(+ i 1))))
0 bv start end)))
(if (= ans-len slen) temp (bytevector-copy temp 0 ans-len)))
(let* ((cset (cond ((u8-set? criterion) criterion)
((u8? criterion) (list criterion))
(else
(error 'bytevector-delete
"criterion not predicate, char or char-set"
criterion))))
(len (bytevector-fold (lambda (c i) (if (u8-set-contains? cset c)
i
(+ i 1)))
0 bv start end))
(ans (make-bytevector len)))
(bytevector-fold (lambda (c i) (if (u8-set-contains? cset c)
i
(begin (bytevector-u8-set! ans i c)
(+ i 1))))
0 bv start end)
ans)))
(define (align-bytevectors bvs size)
(align-bytevectors! (list-copy bvs) size))
(define (align-bytevectors! bvs size)
(define (length-pred bv) (= (bytevector-length bv) size))
(define (align1 bvs offset)
(let ((buf (make-bytevector size)))
(let loop ((bvs bvs) (i 0) (offset offset))
(cond ((null? bvs) (values (bytevector-copy buf 0 i) '() 0))
((= i size) (values buf bvs offset))
(else
(let* ((bv (car bvs))
(len (bytevector-length bv))
(buf-rest (- size i))
(src-len (- len offset)))
(cond ((>= buf-rest src-len)
(bytevector-copy! bv offset buf i src-len)
(loop (cdr bvs) (+ i src-len) 0))
(else
(bytevector-copy! bv offset buf i buf-rest)
(values buf bvs (+ offset buf-rest))))))))))
(let-values (((aligned need) (span! length-pred bvs)))
(let loop ((need need) (r '()) (offset 0))
(if (null? need)
(append aligned (reverse! r))
(let-values (((bv rest offset) (align1 need offset)))
(loop rest (cons bv r) offset))))))
)
|
27b307394f98f087f4e047448e06a9cb637e23c6896a30221927f86bbd6fc82f | zouppen/hackbus | Exceptions.hs | |Exceptions used in Hackbus .
module Control.Hackbus.Exceptions where
import Control.Exception (Exception)
-- |We throw errors using this simple exception type
newtype HackbusFatalException = HackbusFatalException String deriving (Show)
instance Exception HackbusFatalException
-- |We throw less fatal using this simple exception type
newtype HackbusNonfatalException = HackbusNonfatalException String deriving (Show)
instance Exception HackbusNonfatalException
| null | https://raw.githubusercontent.com/zouppen/hackbus/cccd9373d77c3b99dcf6e6d0d10c76037e2534fe/src/Control/Hackbus/Exceptions.hs | haskell | |We throw errors using this simple exception type
|We throw less fatal using this simple exception type | |Exceptions used in Hackbus .
module Control.Hackbus.Exceptions where
import Control.Exception (Exception)
newtype HackbusFatalException = HackbusFatalException String deriving (Show)
instance Exception HackbusFatalException
newtype HackbusNonfatalException = HackbusNonfatalException String deriving (Show)
instance Exception HackbusNonfatalException
|
3f2491c7444240e1d4138cd6e04b165d477cb279c8752b274564e118cd91ada2 | master/ejabberd | pubsub_index.erl | %%% ====================================================================
` ` The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%%% compliance with the License. You should have received a copy of the
%%% Erlang Public License along with this software. If not, it can be
%%% retrieved via the world wide web at /.
%%%
Software distributed under the License is distributed on an " AS IS "
%%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%%% the License for the specific language governing rights and limitations
%%% under the License.
%%%
The Initial Developer of the Original Code is ProcessOne .
Portions created by ProcessOne are Copyright 2006 - 2012 , ProcessOne
All Rights Reserved . ''
This software is copyright 2006 - 2012 , ProcessOne .
%%%
%%%
2006 - 2012 ProcessOne
@author < >
%%% [-one.net/]
%%% @version {@vsn}, {@date} {@time}
%%% @end
%%% ====================================================================
%% important note:
%% new/1 and free/2 MUST be called inside a transaction bloc
-module(pubsub_index).
-author('').
-include("pubsub.hrl").
-export([init/3, new/1, free/2]).
init(_Host, _ServerHost, _Opts) ->
mnesia:create_table(pubsub_index,
[{disc_copies, [node()]},
{attributes, record_info(fields, pubsub_index)}]).
new(Index) ->
case mnesia:read({pubsub_index, Index}) of
[I] ->
case I#pubsub_index.free of
[] ->
Id = I#pubsub_index.last + 1,
mnesia:write(I#pubsub_index{last = Id}),
Id;
[Id|Free] ->
mnesia:write(I#pubsub_index{free = Free}),
Id
end;
_ ->
mnesia:write(#pubsub_index{index = Index, last = 1, free = []}),
1
end.
free(Index, Id) ->
case mnesia:read({pubsub_index, Index}) of
[I] ->
Free = I#pubsub_index.free,
mnesia:write(I#pubsub_index{free = [Id|Free]});
_ ->
ok
end.
| null | https://raw.githubusercontent.com/master/ejabberd/9c31874d5a9d1852ece1b8ae70dd4b7e5eef7cf7/src/mod_pubsub/pubsub_index.erl | erlang | ====================================================================
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved via the world wide web at /.
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
[-one.net/]
@version {@vsn}, {@date} {@time}
@end
====================================================================
important note:
new/1 and free/2 MUST be called inside a transaction bloc | ` ` The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
The Initial Developer of the Original Code is ProcessOne .
Portions created by ProcessOne are Copyright 2006 - 2012 , ProcessOne
All Rights Reserved . ''
This software is copyright 2006 - 2012 , ProcessOne .
2006 - 2012 ProcessOne
@author < >
-module(pubsub_index).
-author('').
-include("pubsub.hrl").
-export([init/3, new/1, free/2]).
init(_Host, _ServerHost, _Opts) ->
mnesia:create_table(pubsub_index,
[{disc_copies, [node()]},
{attributes, record_info(fields, pubsub_index)}]).
new(Index) ->
case mnesia:read({pubsub_index, Index}) of
[I] ->
case I#pubsub_index.free of
[] ->
Id = I#pubsub_index.last + 1,
mnesia:write(I#pubsub_index{last = Id}),
Id;
[Id|Free] ->
mnesia:write(I#pubsub_index{free = Free}),
Id
end;
_ ->
mnesia:write(#pubsub_index{index = Index, last = 1, free = []}),
1
end.
free(Index, Id) ->
case mnesia:read({pubsub_index, Index}) of
[I] ->
Free = I#pubsub_index.free,
mnesia:write(I#pubsub_index{free = [Id|Free]});
_ ->
ok
end.
|
322302cbead3e44a1e227f9a976f76d30549dc6af7398d1c0d7de7c756731a75 | dbuenzli/uucp | uucp_name.ml | ---------------------------------------------------------------------------
Copyright ( c ) 2014 The uucp programmers . All rights reserved .
Distributed under the ISC license , see terms at the end of the file .
---------------------------------------------------------------------------
Copyright (c) 2014 The uucp programmers. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
---------------------------------------------------------------------------*)
include Uucp_name_base
let tok_len i =
let rec loop size i =
if String.unsafe_get Uucp_name_data.name_toks i = '\x00' then size else
loop (size + 1) (i + 1)
in
loop 0 i
let get_tok i = String.sub Uucp_name_data.name_toks i (tok_len i)
let name u =
let u = Uchar.to_int u in
match Uucp_tmap5bytes.get_uint20_pair Uucp_name_data.name_map u with
| 0, 0 -> ""
| l, 0 -> get_tok l
| 0, r -> Printf.sprintf "%s%04X" (get_tok r) u
| l, r -> String.concat "" [get_tok l; get_tok r]
let name_alias u = Uucp_cmap.get Uucp_name_data.name_alias_map (Uchar.to_int u)
---------------------------------------------------------------------------
Copyright ( c ) 2014 The uucp programmers
Permission to use , copy , modify , and/or distribute this software for any
purpose with or without fee is hereby granted , provided that the above
copyright notice and this permission notice appear in all copies .
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
---------------------------------------------------------------------------
Copyright (c) 2014 The uucp programmers
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---------------------------------------------------------------------------*)
| null | https://raw.githubusercontent.com/dbuenzli/uucp/09d2186c0828465dbe37ed976c8d8ab7a5e7eeed/src/uucp_name.ml | ocaml | ---------------------------------------------------------------------------
Copyright ( c ) 2014 The uucp programmers . All rights reserved .
Distributed under the ISC license , see terms at the end of the file .
---------------------------------------------------------------------------
Copyright (c) 2014 The uucp programmers. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
---------------------------------------------------------------------------*)
include Uucp_name_base
let tok_len i =
let rec loop size i =
if String.unsafe_get Uucp_name_data.name_toks i = '\x00' then size else
loop (size + 1) (i + 1)
in
loop 0 i
let get_tok i = String.sub Uucp_name_data.name_toks i (tok_len i)
let name u =
let u = Uchar.to_int u in
match Uucp_tmap5bytes.get_uint20_pair Uucp_name_data.name_map u with
| 0, 0 -> ""
| l, 0 -> get_tok l
| 0, r -> Printf.sprintf "%s%04X" (get_tok r) u
| l, r -> String.concat "" [get_tok l; get_tok r]
let name_alias u = Uucp_cmap.get Uucp_name_data.name_alias_map (Uchar.to_int u)
---------------------------------------------------------------------------
Copyright ( c ) 2014 The uucp programmers
Permission to use , copy , modify , and/or distribute this software for any
purpose with or without fee is hereby granted , provided that the above
copyright notice and this permission notice appear in all copies .
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
---------------------------------------------------------------------------
Copyright (c) 2014 The uucp programmers
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---------------------------------------------------------------------------*)
| |
701a05bf4147394ece0ccaf6bf33101ab85961918cea4d5fc24b66cc9e4043c1 | vivid-inc/ash-ra-template | art.clj | ; Copyright 2019 Vivid Inc.
;
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.
(ns vivid.art
"Ash Ra Template public API."
(:require
[clojure.spec.alpha :as s]
[farolero.core :as farolero]
[vivid.art.delimiters :refer [erb]]
[vivid.art.enscript :refer [enscript]]
[vivid.art.evaluate :refer [evaluate]]
[vivid.art.failure :refer [make-failure]]
[vivid.art.parse :refer [parse]]
[vivid.art.specs :refer [to-phase?]]
[vivid.art.xlate :refer [translate]]))
(def ^:const default-delimiters-name "lispy")
(def ^:const default-delimiters (var-get
(ns-resolve 'vivid.art.delimiters
(symbol default-delimiters-name))))
(def ^:const failure? vivid.art.failure/failure?)
(def ^:const render-phases
"Phases of the rendering process. Note: Unstable until version 1.0."
vivid.art.specs/render-phases)
(def ^:const default-to-phase (last render-phases))
(defn render
"Renders an input string containing Ash Ra Template (ART) -formatted content
to an output string."
([^String template] (render template {}))
([^String template
{:keys [bindings delimiters to-phase]
:or {bindings {} delimiters default-delimiters to-phase default-to-phase}
:as render-options}]
(when template
(let [render* #(cond-> template
(to-phase? :parse to-phase) (parse delimiters)
(to-phase? :translate to-phase) (translate)
(to-phase? :enscript to-phase) (enscript bindings)
(to-phase? :evaluate to-phase) (evaluate render-options))]
(farolero/handler-case (render*)
(:vivid.art/parse-error [_ details]
(make-failure :parse-error details template)))))))
(s/fdef render
:args (s/cat :t :vivid.art/template
:o (s/? (s/keys :opt-un [:vivid.art/bindings
:vivid.art/delimiters
:vivid.art/to-phase]))))
| null | https://raw.githubusercontent.com/vivid-inc/ash-ra-template/f64be7efd6f52ccd451cddb851f02511d1665b11/art/src/vivid/art.clj | clojure | Copyright 2019 Vivid Inc.
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. | distributed under the License is distributed on an " AS IS " BASIS ,
(ns vivid.art
"Ash Ra Template public API."
(:require
[clojure.spec.alpha :as s]
[farolero.core :as farolero]
[vivid.art.delimiters :refer [erb]]
[vivid.art.enscript :refer [enscript]]
[vivid.art.evaluate :refer [evaluate]]
[vivid.art.failure :refer [make-failure]]
[vivid.art.parse :refer [parse]]
[vivid.art.specs :refer [to-phase?]]
[vivid.art.xlate :refer [translate]]))
(def ^:const default-delimiters-name "lispy")
(def ^:const default-delimiters (var-get
(ns-resolve 'vivid.art.delimiters
(symbol default-delimiters-name))))
(def ^:const failure? vivid.art.failure/failure?)
(def ^:const render-phases
"Phases of the rendering process. Note: Unstable until version 1.0."
vivid.art.specs/render-phases)
(def ^:const default-to-phase (last render-phases))
(defn render
"Renders an input string containing Ash Ra Template (ART) -formatted content
to an output string."
([^String template] (render template {}))
([^String template
{:keys [bindings delimiters to-phase]
:or {bindings {} delimiters default-delimiters to-phase default-to-phase}
:as render-options}]
(when template
(let [render* #(cond-> template
(to-phase? :parse to-phase) (parse delimiters)
(to-phase? :translate to-phase) (translate)
(to-phase? :enscript to-phase) (enscript bindings)
(to-phase? :evaluate to-phase) (evaluate render-options))]
(farolero/handler-case (render*)
(:vivid.art/parse-error [_ details]
(make-failure :parse-error details template)))))))
(s/fdef render
:args (s/cat :t :vivid.art/template
:o (s/? (s/keys :opt-un [:vivid.art/bindings
:vivid.art/delimiters
:vivid.art/to-phase]))))
|
51f2108912c6b18c64648c51f643a8280dbe64f21228d411bfbecf1e45d089d6 | koji-kojiro/lem-pygments-colorthemes | tango.lisp | (in-package :lem-user)
(define-color-theme "tango" ()
(foreground "#000000")
(background "#ffffff")
(cursor :foreground "#ffffff" :background "#000000")
(syntax-warning-attribute :foreground "#af0000" :background "#ffffff")
(syntax-string-attribute :foreground "#5f8700" :background "#ffffff")
(syntax-comment-attribute :foreground "#875f00" :background "#ffffff")
(syntax-keyword-attribute :foreground "#005f87" :background "#ffffff")
(syntax-constant-attribute :foreground "#000000" :background "#ffffff")
(syntax-function-name-attribute :foreground "#000000" :background "#ffffff")
(syntax-variable-attribute :foreground "#000000" :background "#ffffff")
(syntax-type-attribute :foreground "#005f87" :background "#ffffff")
(syntax-builtin-attribute :foreground "#005f87" :background "#ffffff"))
| null | https://raw.githubusercontent.com/koji-kojiro/lem-pygments-colorthemes/f7de93ca7a68be7fb99ec48cc571e132292a6712/themes/tango.lisp | lisp | (in-package :lem-user)
(define-color-theme "tango" ()
(foreground "#000000")
(background "#ffffff")
(cursor :foreground "#ffffff" :background "#000000")
(syntax-warning-attribute :foreground "#af0000" :background "#ffffff")
(syntax-string-attribute :foreground "#5f8700" :background "#ffffff")
(syntax-comment-attribute :foreground "#875f00" :background "#ffffff")
(syntax-keyword-attribute :foreground "#005f87" :background "#ffffff")
(syntax-constant-attribute :foreground "#000000" :background "#ffffff")
(syntax-function-name-attribute :foreground "#000000" :background "#ffffff")
(syntax-variable-attribute :foreground "#000000" :background "#ffffff")
(syntax-type-attribute :foreground "#005f87" :background "#ffffff")
(syntax-builtin-attribute :foreground "#005f87" :background "#ffffff"))
| |
3e5abe8c84a3cc320183e8bfbfd9e435a791680d313f4ec9ad37bb5075c35995 | ghc/ghc | Panic.hs | # LANGUAGE GHCForeignImportPrim #
{-# LANGUAGE UnliftedFFITypes #-}
# LANGUAGE MagicHash #
# LANGUAGE UnboxedTuples #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE EmptyCase #
# LANGUAGE RankNTypes , KindSignatures #
-- | Primitive panics.
--
Users should not import this module . It is GHC internal only .
module GHC.Prim.Panic
( absentSumFieldError
, panicError
, absentError, absentConstraintError
)
where
import GHC.Prim
import GHC.Magic
import GHC.Types( Type )
Double and Integer are n't available yet
Note [ Compiler error functions ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Most error functions ( such as pattern match failure ) are defined
in base : Control . Exception . Base . But absentError # and absentSumFieldError #
are defined here in the ghc - prim package for two reasons :
* GHC itself generates calls to these functions as a result of
strictness analysis , over which the programmer has no control . So
it is hard to ensure that no such calls exist in the modules
compiled " before " Control . Base . Exception . ( E.g. when compiling
with -fdicts - strict . )
* A consequence of defining them in ghc - prim is that the libraries
defining exceptions have not yet been built , so we ca n't make them
into proper exceptions .
However , if these functions are ever called , it 's a /compiler/ error ,
not a user error , so it seems acceptable that they can not be caught .
One might wonder why absentError does n't just call panic # .
For absent error we want to combine two parts , one static , one call site
dependent into one error message . While for absentSumFieldError it 's a
static string .
The easiest way to combine the two parts for absentError is to use a
format string with ` barf ` in the RTS passing the * dynamic * part of the
error as argument . There is no need to do any of this for
absentSumFieldError as it 's a static string there .
The alternatives would be to :
* Drop the call site specific information from absentError .
The call site specific information is at times very helpful for debugging
so I do n't consider this an option .
* Remove the common prefix . We would then need to include the prefix
in the call site specific string we pass to absentError . Increasing
code size for no good reason .
Both of which seem worse than having an stg_absentError function specific to
absentError to me .
Note [Compiler error functions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Most error functions (such as pattern match failure) are defined
in base:Control.Exception.Base. But absentError# and absentSumFieldError#
are defined here in the ghc-prim package for two reasons:
* GHC itself generates calls to these functions as a result of
strictness analysis, over which the programmer has no control. So
it is hard to ensure that no such calls exist in the modules
compiled "before" Control.Base.Exception. (E.g. when compiling
with -fdicts-strict.)
* A consequence of defining them in ghc-prim is that the libraries
defining exceptions have not yet been built, so we can't make them
into proper Haskell exceptions.
However, if these functions are ever called, it's a /compiler/ error,
not a user error, so it seems acceptable that they cannot be caught.
One might wonder why absentError doesn't just call panic#.
For absent error we want to combine two parts, one static, one call site
dependent into one error message. While for absentSumFieldError it's a
static string.
The easiest way to combine the two parts for absentError is to use a
format string with `barf` in the RTS passing the *dynamic* part of the
error as argument. There is no need to do any of this for
absentSumFieldError as it's a static string there.
The alternatives would be to:
* Drop the call site specific information from absentError.
The call site specific information is at times very helpful for debugging
so I don't consider this an option.
* Remove the common prefix. We would then need to include the prefix
in the call site specific string we pass to absentError. Increasing
code size for no good reason.
Both of which seem worse than having an stg_absentError function specific to
absentError to me.
-}
-- `stg_panic#` never returns but it can't just return `State# RealWorld` so we
-- indicate that it returns `(# #)` too to make the compiler happy.
-- See Note [Compiler error functions]
foreign import prim "stg_paniczh" panic# :: Addr# -> State# RealWorld -> (# State# RealWorld, (# #) #)
-- See Note [Compiler error functions]
foreign import prim "stg_absentErrorzh" stg_absentError# :: Addr# -> State# RealWorld -> (# State# RealWorld, (# #) #)
-- | Display the CString whose address is given as an argument and exit.
panicError :: Addr# -> a
panicError errmsg =
runRW# (\s ->
case panic# errmsg s of
(# _, _ #) -> -- This bottom is unreachable but we can't
-- use an empty case lest the pattern match
-- checker squawks.
let x = x in x)
| Closure introduced by GHC.Stg . for unused unboxed sum fields .
--
See Note [ aBSENT_SUM_FIELD_ERROR_ID ] in GHC.Core . Make
absentSumFieldError :: a
absentSumFieldError = panicError "entered absent sum field!"#
GHC.Core . Make.aBSENT_SUM_FIELD_ERROR_ID gives absentSumFieldError a bottoming
-- demand signature. But if we ever inlined it (to a call to panicError) we'd
-- lose that information. Should not happen because absentSumFieldError is only
introduced in Stg . Unarise , long after inlining has stopped , but it seems
more direct simply to give it a NOINLINE pragma
# NOINLINE absentSumFieldError #
-- | Displays "Oops! Entered absent arg" ++ errormsg and exits the program.
# NOINLINE absentError #
absentError :: forall (a :: Type). Addr# -> a
absentError errmsg =
runRW# (\s ->
case stg_absentError# errmsg s of
(# _, _ #) -> -- This bottom is unreachable but we can't
-- use an empty case lest the pattern match
-- checker squawks.
let x = x in x)
# NOINLINE absentConstraintError #
absentConstraintError :: forall (a :: Type). Addr# -> a
-- We want to give this the type
forall ( a : : Constraint ) . > a
but source code does n't allow functions that return Constraint
-- So in this module we lie about the type. This is fine because
-- absentConstraintError is a wired-in Id with the desired Constraint-kinded
-- type; the type in the interface file is never looked at.
-- The only purpose of this definition is to give a function to call,
-- and for that purpose, delegating to absentError is fine.
absentConstraintError errmsg = absentError errmsg
| null | https://raw.githubusercontent.com/ghc/ghc/14b2e3d3dda104c62c5abafd3353dd0315de71ad/libraries/ghc-prim/GHC/Prim/Panic.hs | haskell | # LANGUAGE UnliftedFFITypes #
| Primitive panics.
`stg_panic#` never returns but it can't just return `State# RealWorld` so we
indicate that it returns `(# #)` too to make the compiler happy.
See Note [Compiler error functions]
See Note [Compiler error functions]
| Display the CString whose address is given as an argument and exit.
This bottom is unreachable but we can't
use an empty case lest the pattern match
checker squawks.
demand signature. But if we ever inlined it (to a call to panicError) we'd
lose that information. Should not happen because absentSumFieldError is only
| Displays "Oops! Entered absent arg" ++ errormsg and exits the program.
This bottom is unreachable but we can't
use an empty case lest the pattern match
checker squawks.
We want to give this the type
So in this module we lie about the type. This is fine because
absentConstraintError is a wired-in Id with the desired Constraint-kinded
type; the type in the interface file is never looked at.
The only purpose of this definition is to give a function to call,
and for that purpose, delegating to absentError is fine. | # LANGUAGE GHCForeignImportPrim #
# LANGUAGE MagicHash #
# LANGUAGE UnboxedTuples #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE EmptyCase #
# LANGUAGE RankNTypes , KindSignatures #
Users should not import this module . It is GHC internal only .
module GHC.Prim.Panic
( absentSumFieldError
, panicError
, absentError, absentConstraintError
)
where
import GHC.Prim
import GHC.Magic
import GHC.Types( Type )
Double and Integer are n't available yet
Note [ Compiler error functions ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Most error functions ( such as pattern match failure ) are defined
in base : Control . Exception . Base . But absentError # and absentSumFieldError #
are defined here in the ghc - prim package for two reasons :
* GHC itself generates calls to these functions as a result of
strictness analysis , over which the programmer has no control . So
it is hard to ensure that no such calls exist in the modules
compiled " before " Control . Base . Exception . ( E.g. when compiling
with -fdicts - strict . )
* A consequence of defining them in ghc - prim is that the libraries
defining exceptions have not yet been built , so we ca n't make them
into proper exceptions .
However , if these functions are ever called , it 's a /compiler/ error ,
not a user error , so it seems acceptable that they can not be caught .
One might wonder why absentError does n't just call panic # .
For absent error we want to combine two parts , one static , one call site
dependent into one error message . While for absentSumFieldError it 's a
static string .
The easiest way to combine the two parts for absentError is to use a
format string with ` barf ` in the RTS passing the * dynamic * part of the
error as argument . There is no need to do any of this for
absentSumFieldError as it 's a static string there .
The alternatives would be to :
* Drop the call site specific information from absentError .
The call site specific information is at times very helpful for debugging
so I do n't consider this an option .
* Remove the common prefix . We would then need to include the prefix
in the call site specific string we pass to absentError . Increasing
code size for no good reason .
Both of which seem worse than having an stg_absentError function specific to
absentError to me .
Note [Compiler error functions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Most error functions (such as pattern match failure) are defined
in base:Control.Exception.Base. But absentError# and absentSumFieldError#
are defined here in the ghc-prim package for two reasons:
* GHC itself generates calls to these functions as a result of
strictness analysis, over which the programmer has no control. So
it is hard to ensure that no such calls exist in the modules
compiled "before" Control.Base.Exception. (E.g. when compiling
with -fdicts-strict.)
* A consequence of defining them in ghc-prim is that the libraries
defining exceptions have not yet been built, so we can't make them
into proper Haskell exceptions.
However, if these functions are ever called, it's a /compiler/ error,
not a user error, so it seems acceptable that they cannot be caught.
One might wonder why absentError doesn't just call panic#.
For absent error we want to combine two parts, one static, one call site
dependent into one error message. While for absentSumFieldError it's a
static string.
The easiest way to combine the two parts for absentError is to use a
format string with `barf` in the RTS passing the *dynamic* part of the
error as argument. There is no need to do any of this for
absentSumFieldError as it's a static string there.
The alternatives would be to:
* Drop the call site specific information from absentError.
The call site specific information is at times very helpful for debugging
so I don't consider this an option.
* Remove the common prefix. We would then need to include the prefix
in the call site specific string we pass to absentError. Increasing
code size for no good reason.
Both of which seem worse than having an stg_absentError function specific to
absentError to me.
-}
foreign import prim "stg_paniczh" panic# :: Addr# -> State# RealWorld -> (# State# RealWorld, (# #) #)
foreign import prim "stg_absentErrorzh" stg_absentError# :: Addr# -> State# RealWorld -> (# State# RealWorld, (# #) #)
panicError :: Addr# -> a
panicError errmsg =
runRW# (\s ->
case panic# errmsg s of
let x = x in x)
| Closure introduced by GHC.Stg . for unused unboxed sum fields .
See Note [ aBSENT_SUM_FIELD_ERROR_ID ] in GHC.Core . Make
absentSumFieldError :: a
absentSumFieldError = panicError "entered absent sum field!"#
GHC.Core . Make.aBSENT_SUM_FIELD_ERROR_ID gives absentSumFieldError a bottoming
introduced in Stg . Unarise , long after inlining has stopped , but it seems
more direct simply to give it a NOINLINE pragma
# NOINLINE absentSumFieldError #
# NOINLINE absentError #
absentError :: forall (a :: Type). Addr# -> a
absentError errmsg =
runRW# (\s ->
case stg_absentError# errmsg s of
let x = x in x)
# NOINLINE absentConstraintError #
absentConstraintError :: forall (a :: Type). Addr# -> a
forall ( a : : Constraint ) . > a
but source code does n't allow functions that return Constraint
absentConstraintError errmsg = absentError errmsg
|
6f0eb3b3b2c35f1706268e48b1447852faa2cabd47656eb3609a706322894c63 | rescript-association/genType | oprint.mli | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
Projet Cristal , INRIA Rocquencourt
(* *)
Copyright 2002 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
open Format
open Outcometree
val out_ident : (formatter -> string -> unit) ref
val map_primitive_name : (string -> string) ref
val out_value : (formatter -> out_value -> unit) ref
val out_type : (formatter -> out_type -> unit) ref
val out_class_type : (formatter -> out_class_type -> unit) ref
val out_module_type : (formatter -> out_module_type -> unit) ref
val out_sig_item : (formatter -> out_sig_item -> unit) ref
val out_signature : (formatter -> out_sig_item list -> unit) ref
val out_type_extension : (formatter -> out_type_extension -> unit) ref
val out_phrase : (formatter -> out_phrase -> unit) ref
val parenthesized_ident : string -> bool
| null | https://raw.githubusercontent.com/rescript-association/genType/c44251e969fb10d27a38d2bdeff6a5f4d778594f/src/compiler-libs-406/oprint.mli | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************ | Projet Cristal , INRIA Rocquencourt
Copyright 2002 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Format
open Outcometree
val out_ident : (formatter -> string -> unit) ref
val map_primitive_name : (string -> string) ref
val out_value : (formatter -> out_value -> unit) ref
val out_type : (formatter -> out_type -> unit) ref
val out_class_type : (formatter -> out_class_type -> unit) ref
val out_module_type : (formatter -> out_module_type -> unit) ref
val out_sig_item : (formatter -> out_sig_item -> unit) ref
val out_signature : (formatter -> out_sig_item list -> unit) ref
val out_type_extension : (formatter -> out_type_extension -> unit) ref
val out_phrase : (formatter -> out_phrase -> unit) ref
val parenthesized_ident : string -> bool
|
c78b81e9607120bc617f26248e2761cb678fe771b3e3697a1772c6d244025873 | patzy/glaw | graphics.lisp | (in-package :glaw)
(declaim (optimize (safety 0) (debug 0) (speed 3)))
;;; General rendering
(defvar *display-width* 800)
(defvar *display-height* 600)
(defun begin-draw ()
(gl:clear :color-buffer :depth-buffer))
(defun end-draw ()
(gl:flush))
(defun set-background-color (color)
(gl:clear-color (color-r color)
(color-g color)
(color-b color)
0))
(defun set-background-color/rgb (r g b)
(gl:clear-color r g b 0))
(defun clear-display (&rest buffers)
(apply #'clear-framebuffer nil buffers))
(defun setup-3d-defaults ()
(set-background-color #(0.3 0.3 0.3 0.0))
(set-render-state +default-3d-render-state+)
;; some default head light
(gl:matrix-mode :projection)
(gl:load-identity)
(gl:matrix-mode :modelview)
(gl:load-identity)
(gl:enable :light0)
(gl:light :light0 :position #(0.0 0.0 0.0 1.0))
(gl:light :light0 :ambient #(0.2 0.2 0.2 1.0))
(gl:light :light0 :diffuse #(0.8 0.8 0.8 1.0))
(gl:light :light0 :specular #(0.5 0.5 0.5 1.0)))
(defun setup-2d-defaults ()
(set-background-color #(0.3 0.3 0.3 0.0))
(set-render-state +default-2d-render-state+))
(defun draw-origin (&optional (scale 20.0))
(gl:with-primitive :lines
(gl:color 1.0 0.0 0.0 1.0)
(gl:vertex 0.0 0.0 0.0)
(gl:vertex scale 0.0 0.0)
(gl:color 0.0 1.0 0.0 1.0)
(gl:vertex 0.0 0.0 0.0)
(gl:vertex 0.0 scale 0.0)
(gl:color 0.0 0.0 1.0 1.0)
(gl:vertex 0.0 0.0 0.0)
(gl:vertex 0.0 0.0 scale)))
(defun reshape (width height)
;; set viewport to full screen
(gl:viewport 0 0 width height)
(setf *display-width* width)
(setf *display-height* height))
(defun set-view-matrices (proj-mtx view-mtx)
(gl:matrix-mode :projection)
(gl:load-matrix proj-mtx)
(gl:matrix-mode :modelview)
(gl:load-matrix view-mtx))
;;; Colors helpers
(defstruct (color (:type (vector float)))
(r 1.0)
(g 1.0)
(b 1.0)
(a 1.0))
(declaim (inline set-color))
(defun set-color (col)
(gl:color (color-r col) (color-g col) (color-b col) (color-a col)))
(declaim (inline set-color/rgb))
(defun set-color/rgb (r g b &optional (a 1.0))
(gl:color r g b a))
(defun create-color (r g b &optional (a 1.0))
(make-color :r r :g g :b b :a a))
(defun make-random-color (&optional (a 1.0))
(make-color :r (random-between 0.0 1.0)
:g (random-between 0.0 1.0)
:b (random-between 0.0 1.0)
:a a))
(defun color-copy (src dest)
(setf (color-r dest) (color-r src)
(color-g dest) (color-g src)
(color-b dest) (color-b src)
(color-a dest) (color-a src)))
(defun mix-colors (color-1 color-2 value)
(let ((r (+ (color-r color-1)
(* (- (color-r color-2)
(color-r color-1))
value)))
(g (+ (color-g color-1)
(* (- (color-g color-2)
(color-g color-1))
value)))
(b (+ (color-b color-1)
(* (- (color-b color-2)
(color-b color-1))
value)))
(a (+ (color-a color-1)
(* (- (color-a color-2)
(color-a color-1))
value))))
(make-color :r r :g g :b b :a a)))
(defun mix-colors/rgb (color-1 color-2 value)
(let ((r (+ (color-r color-1)
(* (- (color-r color-2)
(color-r color-1))
value)))
(g (+ (color-g color-1)
(* (- (color-g color-2)
(color-g color-1))
value)))
(b (+ (color-b color-1)
(* (- (color-b color-2)
(color-b color-1))
value)))
(a (+ (color-a color-1)
(* (- (color-a color-2)
(color-a color-1))
value))))
(values r g b a)))
(defstruct color-gradient
(start (make-color :r 0.0 :g 0.0 :b 0.0 :a 1.0))
(end (make-color :r 1.0 :g 1.0 :b 1.0 :a 1.0)))
(defun create-color-gradient (start-r start-g start-b start-a
end-r end-g end-b end-a)
(make-color-gradient
:start (make-color :r start-r :g start-g :b start-b :a start-a)
:end (make-color :r end-r :g end-g :b end-b :a end-a)))
(defun get-color-from-gradient (gradient value)
(mix-colors (color-gradient-start gradient)
(color-gradient-end gradient)
value))
(defun get-color-from-gradient/rgb (gradient value)
(mix-colors/rgb (color-gradient-start gradient)
(color-gradient-end gradient)
value))
(defun set-color-from-gradient (gradient value)
(multiple-value-bind (r g b a) (get-color-from-gradient/rgb gradient value)
(gl:color r g b a)))
;;; Image
(defstruct image
"Simple image structure. Origin is generally top-left but depends on the loader
you use."
width height bpp data)
(defun create-image (width height bpp)
(make-image :width width :height height :bpp bpp
:data (make-array (* width height bpp) :initial-element 255
:element-type '(unsigned-byte 8))))
(defun image-set-pixel (image x y r &optional (g 255) (b 255) (a 255))
(let ((index (+ x (* y (image-width image)))))
(image-set-pixel/index image index r g b a)))
(defun image-set-pixel/index (image index r &optional (g 255) (b 255) (a 255))
(let ((bpp (image-bpp image)))
(ecase bpp
(1 (setf (aref (image-data image) (* index bpp)) r))
(2 (setf (aref (image-data image) (* index bpp)) r
(aref (image-data image) (+ 1 (* index bpp))) g))
(3 (setf (aref (image-data image) (* index bpp)) r
(aref (image-data image) (+ 1 (* index bpp))) g
(aref (image-data image) (+ 2 (* index bpp))) b))
(4 (setf (aref (image-data image) (* index bpp)) r
(aref (image-data image) (+ 1 (* index bpp))) g
(aref (image-data image) (+ 2 (* index bpp))) b
(aref (image-data image) (+ 3 (* index bpp))) a)))))
(defun image-get-pixel (image x y)
(let ((index (+ x (* y (image-width image)))))
(image-get-pixel/index image index)))
(defun image-get-pixel/index (image index)
(let ((bpp (image-bpp image)))
(ecase bpp
(1 (values (aref (image-data image) (* index bpp))
0 0 0))
(2 (values (aref (image-data image) (* index bpp))
(aref (image-data image) (+ 1 (* index bpp)))
0 0))
(3 (values (aref (image-data image) (* index bpp))
(aref (image-data image) (+ 1 (* index bpp)))
(aref (image-data image) (+ 2 (* index bpp)))
0))
(4 (values (aref (image-data image) (* index bpp))
(aref (image-data image) (+ 1 (* index bpp)))
(aref (image-data image) (+ 2 (* index bpp)))
(aref (image-data image) (+ 3 (* index bpp))))))))
;;; 2D Texture
(defstruct texture
width height bpp data
GL texture index
(matrix +matrix-identity+)
GL texture parameters
(internal-format :rgba)
(min-filter :linear)
(mag-filter :linear)
;; min-lod max-lod
;; base-level max-level
(wrap-s :repeat)
(wrap-t :repeat)
(wrap-r :repeat)
priority)
(defun create-texture (width height bpp data &rest args)
"Create a new GL texture. Texture's origin is bottom-left."
(let ((tex (apply 'make-texture :index (first (gl:gen-textures 1))
:width width :height height
:bpp bpp ;:data data
args)))
(select-texture tex)
(gl:tex-image-2d :texture-2d 0 (texture-internal-format tex)
(texture-width tex)
(texture-height tex) 0
(ecase (texture-bpp tex)
(1 :alpha)
(2 :luminance-alpha)
(3 :rgb)
(4 :rgba))
:unsigned-byte
(if data data (cffi::null-pointer)))
(gl:tex-parameter :texture-2d :texture-min-filter (texture-min-filter tex))
(gl:tex-parameter :texture-2d :texture-mag-filter (texture-mag-filter tex))
;; (gl:tex-parameter :texture-2d :texture-min-lod (texture-min-lod tex))
;; (gl:tex-parameter :texture-2d :texture-max-lod (texture-max-lod tex))
;; (gl:tex-parameter :texture-2d :texture-base-level (texture-base-level tex))
;; (gl:tex-parameter :texture-2d :texture-max-level (texture-max-level tex))
(gl:tex-parameter :texture-2d :texture-wrap-s (texture-wrap-s tex))
(gl:tex-parameter :texture-2d :texture-wrap-t (texture-wrap-t tex))
(gl:tex-parameter :texture-2d :texture-wrap-r (texture-wrap-r tex))
tex))
(defun update-texture (tex data &optional (x 0) (y 0)
(width (texture-width tex)) (height (texture-height tex)))
(setf (texture-data tex) data)
(select-texture tex)
(gl:tex-sub-image-2d :texture-2d 0 x y width height
(ecase (texture-bpp tex)
(1 :alpha)
(2 :luminance-alpha)
(3 :rgb)
(4 :rgba))
:unsigned-byte
data))
(defun create-texture-from-image (image &rest args)
(apply 'create-texture
(image-width image) (image-height image) (image-bpp image) (image-data image)
args))
(defun update-texture-from-image (tex image)
(update-texture tex (image-data image)))
(defun destroy-texture (tex)
(gl:delete-textures (list (texture-index tex))))
(defvar %selected-texture-index% nil
"Current texture in GL context.")
(defun texture-unit (&optional (index 0))
(declare (inline texture-unit))
(+ (cffi:foreign-enum-value 'cl-opengl-bindings:enum :texture0) index))
(defun select-texture (tex &key (env-mode :replace)
(unit (texture-unit 0))
(matrix +matrix-identity+))
"Set TEX as the current gl texture if necessary."
(gl:active-texture unit)
(if tex
(progn (unless %selected-texture-index%
(gl:enable :texture-2d)
(setf %selected-texture-index% -1))
(unless (= (texture-index tex) %selected-texture-index%)
(gl:bind-texture :texture-2d (texture-index tex))
(gl:tex-env :texture-env
:texture-env-mode env-mode)
(setf %selected-texture-index% (texture-index tex)))
(unless (eq matrix +matrix-identity+)
(gl:matrix-mode :texture)
(gl:load-matrix (texture-matrix tex))
(gl:matrix-mode :modelview))
)
(progn (gl:disable :texture-2d)
(setf %selected-texture-index% nil))))
Renderbuffer
(defstruct renderbuffer
width
height
format
index)
(defun create-renderbuffer (width height &optional (format :rgba))
(let ((index (first (gl:gen-renderbuffers-ext 1))))
(gl:bind-renderbuffer-ext :renderbuffer-ext index)
(gl:renderbuffer-storage-ext :renderbuffer-ext format width height)
(make-renderbuffer :width width :height height :format format :index index)))
(defun destroy-renderbuffer (rb)
(gl:delete-renderbuffers-ext (renderbuffer-index rb)))
Framebuffer
(defstruct framebuffer
width
height
index
colors
depth
stencil)
(defun %framebuffer-attach-texture (fb texture attach-point)
(assert (and (= (texture-height texture) (framebuffer-height fb))
(= (texture-width texture) (framebuffer-width fb))))
(let ((tex-index (texture-index texture)))
(gl:bind-texture :texture-2d tex-index)
(gl:framebuffer-texture-2d-ext :framebuffer-ext
attach-point
:texture-2d
tex-index
0)))
(defun %framebuffer-attach-renderbuffer (fb rb attach-point)
(assert (and (= (renderbuffer-height rb) (framebuffer-height fb))
(= (renderbuffer-width rb) (framebuffer-width fb))))
(let ((rb-index (renderbuffer-index rb)))
(gl:bind-renderbuffer-ext :renderbuffer-ext rb-index)
(gl:framebuffer-renderbuffer-ext :framebuffer-ext
attach-point
:renderbuffer-ext
rb-index)))
(defmethod framebuffer-attach-color (fb (buf texture) &optional (index 0))
(%framebuffer-attach-texture fb buf
(ecase index
(0 :color-attachment0-ext)
(1 :color-attachment1-ext)
(2 :color-attachment2-ext)
(3 :color-attachment3-ext)))
(setf (aref (framebuffer-colors fb) index) buf))
(defmethod framebuffer-attach-color (fb (buf renderbuffer) &optional (index 0))
(%framebuffer-attach-renderbuffer fb buf
(ecase index
(0 :color-attachment0-ext)
(1 :color-attachment1-ext)
(2 :color-attachment2-ext)
(3 :color-attachment3-ext)))
(setf (aref (framebuffer-colors fb) index) buf))
(defmethod framebuffer-attach-depth (fb (buf texture) &optional (index 0))
(%framebuffer-attach-texture fb buf :depth-attachment-ext)
(setf (framebuffer-depth fb) buf))
(defmethod framebuffer-attach-depth (fb (buf renderbuffer) &optional (index 0))
(%framebuffer-attach-renderbuffer fb buf :depth-attachment-ext)
(setf (framebuffer-depth fb) buf))
(defmethod framebuffer-attach-stencil (fb (buf texture) &optional (index 0))
(%framebuffer-attach-texture fb buf :stencil-attachment-ext)
(setf (framebuffer-stencil fb) buf))
(defmethod framebuffer-attach-color (fb (buf renderbuffer) &optional (index 0))
(%framebuffer-attach-renderbuffer fb buf :stencil-attachment-ext)
(setf (framebuffer-stencil fb) buf))
(defun create-framebuffer (width height &key (colors '())
(depth nil)
(stencil nil))
(let ((w (min (nearest-power-of-two width)
(gl:get-integer :max-texture-size)))
(h (min (nearest-power-of-two height)
(gl:get-integer :max-texture-size)))
(framebuffer (first (gl:gen-framebuffers-ext 1))))
(gl:bind-framebuffer-ext :framebuffer-ext framebuffer)
;; FIXME: get number of color attachment from OpenGL
(make-framebuffer :index framebuffer :width w :height h
:colors (make-array 4) :depth nil :stencil nil)))
(defun destroy-framebuffer (fb)
(gl:delete-framebuffers-ext (framebuffer-index fb)))
(defvar %selected-framebuffer-index% nil
"Currently selected framebuffer object index.")
(defun select-framebuffer (fb)
(gl:bind-framebuffer-ext :framebuffer-ext (if fb (framebuffer-index fb) 0)))
(defun clear-framebuffer (fb &optional (buffers '(:color-buffer)))
(select-framebuffer fb)
(apply 'gl:clear buffers))
;;; Vertex Buffer
(defstruct buffer
index)
(defun make-vertex-format (&key vertices colors tex-coords normals)
(logior (if vertices #x01 #x00)
(if colors #x02 #x00)
(if tex-coords #x04 #x00)
(if normals #x08 #x00)))
(defun vertex-size (fmt)
(+ (if (vertex-has-vertices fmt) 3 0)
(if (vertex-has-colors fmt) 4 0)
(if (vertex-has-tex-coords fmt) 2 0)
(if (vertex-has-normals fmt) 3 0)))
(defun vertex-has-vertices (fmt)
(logbitp 0 fmt))
(defun vertex-has-colors (fmt)
(logbitp 1 fmt))
(defun vertex-has-tex-coords (fmt)
(logbitp 2 fmt))
(defun vertex-has-normals (fmt)
(logbitp 3 fmt))
(defstruct (vertex-buffer (:include buffer))
nb-vertices
format)
(defun set-vertex-buffer (vb)
(if vb
(gl:bind-buffer :array-buffer (vertex-buffer-index vb))
(gl:bind-buffer :array-buffer 0)))
(defun %vertex-buffer-setup-arrays (vb)
(if vb
(progn (%gl:vertex-pointer 3 :float 0 (cffi:null-pointer))
(gl:enable-client-state :vertex-array)
(let ((offset (* (vertex-buffer-nb-vertices vb) 3))
32 bits data
(when (vertex-has-colors (vertex-buffer-format vb))
(%gl:color-pointer 4 :float 0 (cffi:make-pointer (* offset elem-size)))
(gl:enable-client-state :color-array)
(incf offset (* (vertex-buffer-nb-vertices vb) 4)))
(when (vertex-has-tex-coords (vertex-buffer-format vb))
(gl:active-texture :texture0)
(%gl:tex-coord-pointer 2 :float 0 (cffi:make-pointer (* offset elem-size)))
(gl:enable-client-state :texture-coord-array)
(incf offset (* (vertex-buffer-nb-vertices vb) 2)))
(when (vertex-has-normals (vertex-buffer-format vb))
(%gl:normal-pointer :float 0 (cffi:make-pointer (* offset elem-size)))
(gl:enable-client-state :normal-array)
(incf offset (* (vertex-buffer-nb-vertices vb) 2)))))
(progn (gl:disable-client-state :vertex-array)
(gl:disable-client-state :color-array)
(gl:disable-client-state :texture-coord-array)
(gl:disable-client-state :normal-array))))
(defun create-empty-vertex-buffer (nb-vertices &key (usage :stream-draw)
(format (make-vertex-format :vertices t :normals t)))
(let* ((buff (car (gl:gen-buffers 1)))
(float-size 4)
(size (* (vertex-size format) nb-vertices float-size)))
(dformat "Creating vertex buffer: ~S~%" size)
(dformat "Recommended # of vertices: ~S~%" (gl:get-integer :max-elements-vertices))
(gl:bind-buffer :array-buffer buff)
(%gl:buffer-data :array-buffer
size
(cffi:null-pointer) ;; just allocating space
usage)
(assert (= (gl::get-buffer-parameter :array-buffer :buffer-size :int)
size))
(let ((vb (make-vertex-buffer :index buff
:nb-vertices nb-vertices
:format format)))
vb)))
(defun create-vertex-buffer (vertices &key colors tex-coords normals (usage :stream-draw))
(let* ((fmt (make-vertex-format :vertices vertices :colors colors :tex-coords tex-coords
:normals normals))
(vb (create-empty-vertex-buffer (/ (length vertices) 3) :usage usage
:format fmt)))
(vertex-buffer-update-components vb 0 vertices :colors colors
:tex-coords tex-coords :normals normals)
vb))
(defun vertex-buffer-update (vb array &optional (offset 0))
(gl:bind-buffer :array-buffer (vertex-buffer-index vb))
(gl:with-mapped-buffer (p :array-buffer :write-only)
(loop for i below (length array)
do (setf (cffi:mem-aref p :float (+ offset i)) (float (aref array i) 0.0)))))
(defun dprint-vb (vb start end)
(gl:bind-buffer :array-buffer (vertex-buffer-index vb))
(format t "VB: ")
(gl:with-mapped-buffer (p :array-buffer :read-only)
(loop for i from start below end
do (format t "~S " (cffi:mem-aref p :float i))))
(format t "~%"))
(defun vertex-buffer-update-components (vb vtx-offset vertices &key colors tex-coords normals)
(assert (= (vertex-buffer-format vb)
(make-vertex-format :vertices vertices
:colors colors
:tex-coords tex-coords
:normals normals)))
(let ((nb-vertices (vertex-buffer-nb-vertices vb))
(offset 0))
(vertex-buffer-update vb vertices (+ offset (* vtx-offset 3)))
(incf offset (* nb-vertices 3))
(when colors
(vertex-buffer-update vb colors (+ offset (* vtx-offset 4)))
(incf offset (* nb-vertices 4)))
(when tex-coords
(vertex-buffer-update vb tex-coords (+ offset (* vtx-offset 2)))
(incf offset (* nb-vertices 2)))
(when normals
(vertex-buffer-update vb normals (+ offset (* vtx-offset 3)))
(incf offset (* nb-vertices 3))))
vb)
(defun destroy-vertex-buffer (vb)
(gl:delete-buffers (list (vertex-buffer-index vb))))
;;; Index Buffer
(defstruct (index-buffer (:include buffer))
nb-indices)
(defun set-index-buffer (ib)
(if ib
(gl:bind-buffer :element-array-buffer (index-buffer-index ib))
(gl:bind-buffer :array-buffer 0)))
(defun %index-buffer-setup-arrays (ib)
(if ib
(progn (%gl:index-pointer :short 0 (cffi:null-pointer))
(gl:enable-client-state :index-array))
(gl:disable-client-state :index-array)))
(defun create-empty-index-buffer (nb-indices &key (usage :static-draw))
(let ((buff (car (gl:gen-buffers 1))))
(dformat "Creating index buffer: ~S~%" nb-indices)
(dformat "Recommended # of indices: ~S~%" (gl:get-integer :max-elements-indices))
(gl:bind-buffer :element-array-buffer buff)
(%gl:buffer-data :element-array-buffer
(* nb-indices 2) ;; unsigned short
(cffi:null-pointer) ;; just allocating space
usage)
(assert (= (gl::get-buffer-parameter :element-array-buffer :buffer-size :int)
(* nb-indices 2)))
(let ((ib (make-index-buffer :index buff
:nb-indices nb-indices)))
ib)))
(defun create-index-buffer (indices &key (usage :static-draw))
(let ((ib (create-empty-index-buffer (length indices) :usage usage)))
(index-buffer-update ib indices 0)
ib))
(defun index-buffer-update (ib array &optional (offset 0) add-offset)
(gl:bind-buffer :element-array-buffer (index-buffer-index ib))
(gl:with-mapped-buffer (p :element-array-buffer :write-only)
(loop for i below (length array)
do (setf (cffi:mem-aref p :short (+ offset i))
(if add-offset (+ offset (aref array i)) (aref array i))))))
(defun dprint-ib (ib start end)
(gl:bind-buffer :element-array-buffer (index-buffer-index ib))
(format t "IB: ")
(gl:with-mapped-buffer (p :element-array-buffer :read-only)
(loop for i from start below end
do (format t "~S " (cffi:mem-aref p :short i))))
(format t "~%"))
(defun destroy-index-buffer (ib)
(gl:delete-buffers (list (index-buffer-index ib))))
;;; Primitive rendering
(defun render-primitive (indices vertices &key (primitive :triangles)
colors tex-coords normals
shader
attrib-indices
attrib-sizes
attrib-datas
(start 0) (end (length indices)))
"Immediate mode rendering."
(gl:with-primitive primitive
(loop for index from start below end
for i = (aref indices index)
when colors
do (gl:color (aref colors (* i 4))
(aref colors (+ 1 (* i 4)))
(aref colors (+ 2 (* i 4)))
(aref colors (+ 3 (* i 4))))
when tex-coords
do (gl:tex-coord (aref tex-coords (* i 2))
(aref tex-coords (+ 1 (* i 2))))
when normals
do (gl:normal (aref normals (* i 3))
(aref normals (+ 1 (* i 3)))
(aref normals (+ 2 (* i 3))))
when attrib-indices
do (loop for attr-index in attrib-indices
for attr-size in attrib-sizes
for attr-data in attrib-datas
do (case attr-size
(1 (gl:vertex-attrib (shader-id shader) attr-index
(aref attr-data i)))
(2 (gl:vertex-attrib (shader-id shader) attr-index
(aref attr-data (* i 2))))
(3 (gl:vertex-attrib (shader-id shader) attr-index
(aref attr-data (* i 3))))
(4 (gl:vertex-attrib (shader-id shader) attr-index
(aref attr-data (* i 4))))))
do (gl:vertex (aref vertices (* i 3))
(aref vertices (+ 1 (* i 3)))
(aref vertices (+ 2 (* i 3)))))))
(defstruct display-list
GL display list index
(primitive :triangles)
start end
vb ib)
(defun destroy-display-list (dl)
(if (display-list-vb dl)
(progn (destroy-vertex-buffer (display-list-vb dl))
(destroy-index-buffer (display-list-ib dl)))
(gl:delete-lists (display-list-index dl) 1)))
(defun load-primitive (indices vertices &key (primitive :triangles)
colors tex-coords normals
(start 0) (end (length indices))
use-buffers)
(let ((dl (make-display-list)))
(if use-buffers
(setf (display-list-vb dl) (create-vertex-buffer vertices
:colors colors
:tex-coords tex-coords
:normals normals
:usage :static-draw)
(display-list-ib dl) (create-index-buffer indices)
(display-list-primitive dl) primitive
(display-list-start dl) start
(display-list-end dl) end)
(progn (setf (display-list-index dl) (gl:gen-lists 1))
(gl:new-list (display-list-index dl) :compile)
(render-primitive indices vertices :primitive primitive
:colors colors :tex-coords tex-coords :normals normals
:start start :end end)
(gl:end-list)))
dl))
(defun call-primitive (dl)
(if (display-list-vb dl)
(progn (set-vertex-buffer (display-list-vb dl))
(%vertex-buffer-setup-arrays (display-list-vb dl))
(set-index-buffer (display-list-ib dl))
(%index-buffer-setup-arrays (display-list-ib dl))
(%gl:draw-arrays (display-list-primitive dl)
(display-list-start dl)
(- (display-list-end dl) (display-list-start dl)))
(set-vertex-buffer nil)
(%vertex-buffer-setup-arrays nil)
(set-index-buffer nil)
(%index-buffer-setup-arrays nil))
(gl:call-list (display-list-index dl))))
;;; Batching
(defstruct (primitive-batch (:include display-list))
(vb-offset 0) ;; # of vertices so far
(ib-offset 0) ;; # of indices so far
items)
(defun create-primitive-batch (primitive vfmt &key (max-vertices 10000)
(max-indices 10000)
(vertex-usage :stream-draw)
(index-usage :stream-draw))
(let ((batch (make-primitive-batch :vb-offset 0 :ib-offset 0 :primitive primitive
:items '() :start 0 :end 0)))
(setf (primitive-batch-vb batch) (create-empty-vertex-buffer max-vertices :usage vertex-usage
:format vfmt)
(primitive-batch-ib batch) (create-empty-index-buffer max-indices :usage index-usage))
batch))
(defun destroy-primitive-batch (batch)
(destroy-display-list batch))
(defun primitive-batch-append (batch indices vertices &key colors tex-coords normals)
(vertex-buffer-update-components (primitive-batch-vb batch)
(primitive-batch-vb-offset batch)
vertices :colors colors :tex-coords tex-coords :normals normals)
(incf (primitive-batch-vb-offset batch) (/ (length vertices) 3))
(index-buffer-update (primitive-batch-ib batch) indices (primitive-batch-ib-offset batch) t)
(incf (primitive-batch-ib-offset batch) (length indices))
(let ((item (cons (primitive-batch-end batch)
(length indices))))
(incf (primitive-batch-end batch) (length indices))
(setf (primitive-batch-items batch) (append (primitive-batch-items batch)
(list item)))
(primitive-batch-end batch)))
(defun primitive-batch-clear (batch)
(setf (primitive-batch-items batch) (list)
(primitive-batch-vb-offset batch) 0
(primitive-batch-ib-offset batch) 0
(primitive-batch-start batch) 0
(primitive-batch-end batch) 0))
(defun primitive-batch-render (batch)
(call-primitive batch))
;;; Basic material
(defstruct material
(ambient #(0.3 0.3 0.3 1.0))
diffuse ;; nil means same as diffuse
(specular #(1.0 1.0 1.0 1.0))
(shininess 1.0)
(emissive #(0.0 0.0 0.0 1.0)))
(defvar +default-material+
(make-material))
(defun material-set-alpha (mat alpha)
"Set material transparency."
(setf (color-a (material-ambient mat)) alpha
(color-a (material-diffuse mat)) alpha
(color-a (material-specular mat)) alpha
(color-a (material-emissive mat)) alpha))
(defun material-alpha (mat)
(color-a (material-ambient mat)))
(defsetf material-alpha material-set-alpha)
;;; FIXME: check if material is not already set
FIXME : use color material ( supposed to be faster )
(defun set-material (mat)
(when mat
(if (material-diffuse mat)
(progn (gl:material :front-and-back :ambient (material-ambient mat))
(gl:material :front-and-back :diffuse (material-diffuse mat)))
(gl:material :front-and-back :ambient-and-diffuse (material-ambient mat)))
(gl:material :front-and-back :specular (material-specular mat))
(gl:material :front-and-back :shininess (material-shininess mat))
(gl:material :front-and-back :emission (material-emissive mat))))
;;; Shaders
(defstruct shader
source
GL i d
programs ;; programs this shader is attached to
(needs-compile t))
(defun %shader-add-program (shader prg)
(push prg (shader-programs shader)))
(defun %shader-remove-program (shader prg)
(setf (shader-programs shader) (remove prg (shader-programs shader))))
(defun shader-compile (shader)
(assert (and (shader-source shader)
(shader-id shader)))
(dformat "Compiling shader.~%")
(gl:compile-shader (shader-id shader))
(dformat "Shader compile log:~%~S~%" (gl:get-shader-info-log (shader-id shader)))
(setf (shader-needs-compile shader) nil))
(defun %shader-set-source (shader source)
(setf (shader-source shader) source
(shader-needs-compile shader) t)
(gl:shader-source (shader-id shader) (shader-source shader)))
(defun shader-set-source (shader source &optional compile)
(%shader-set-source shader source)
(when compile
(shader-compile shader)))
(defun create-shader (type &optional source compile)
(assert (or (eq type :vertex-shader) (eq type :fragment-shader)))
(let ((sh (make-shader)))
(setf (shader-id sh) (gl:create-shader type))
(when source
(shader-set-source sh source))
(when compile
(shader-compile sh))
(dformat "Created shader: ~S~%" sh)
sh))
(defun create-shader-from-file (type file &optional compile)
(create-shader type (file->strings file) compile))
(defun create-vertex-shader (&optional source compile)
(create-shader :vertex-shader source compile))
(defun create-vertex-shader-from-file (file &optional compile)
(create-shader-from-file :vertex-shader file compile))
(defun create-fragment-shader (&optional source compile)
(create-shader :fragment-shader source compile))
(defun create-fragment-shader-from-file (file &optional compile)
(create-shader-from-file :fragment-shader file compile))
;; FIXME: detach before delete?
(defun destroy-shader (sh)
(gl:delete-shader (shader-id sh)))
;; (defstruct shader-data
;; (uniforms (list))
;; (uniform-values (list)))
;; (defstruct shader-data-bind
;; data
( defun shader - data - add - uniform ( data name & optional ( value nil ) )
;; (push name (shader-data-uniforms data))
;; (push value (shader-data-uniform-values data)))
(defstruct shader-program
vertex
fragment
id
data
(needs-link t))
;; (defun shader-program-bind-data (prg prg-data)
( setf ( shader - program - data prg ) prg - data )
(defun shader-program-attach-vertex (prg vtx-shader)
(setf (shader-program-vertex prg) vtx-shader
(shader-program-needs-link prg) t)
(gl:attach-shader (shader-program-id prg) (shader-id vtx-shader))
(%shader-add-program vtx-shader prg))
(defun shader-program-detach-vertex (prg)
(gl:detach-shader (shader-program-id prg) (shader-id (shader-program-vertex prg)))
(%shader-remove-program (shader-program-vertex prg) prg)
(setf (shader-program-vertex prg) nil))
(defun shader-program-attach-fragment (prg frag-shader)
(setf (shader-program-fragment prg) frag-shader
(shader-program-needs-link prg) t)
(gl:attach-shader (shader-program-id prg) (shader-id frag-shader))
(%shader-add-program frag-shader prg))
(defun shader-program-detach-fragment (prg)
(gl:detach-shader (shader-program-id prg) (shader-id (shader-program-fragment prg)))
(%shader-remove-program (shader-program-fragment prg) prg)
(setf (shader-program-fragment prg) nil))
(defun shader-program-link (prg)
(assert (shader-program-id prg))
(dformat "Linking shader program.~%")
(setf (shader-program-needs-link prg) nil)
(gl:link-program (shader-program-id prg))
(dformat "Program info log:~%~S~%" (gl:get-program-info-log (shader-program-id prg))))
(defvar %selected-shader-index% nil)
(defun set-shader-program (prg)
(if prg
(progn (gl:use-program (shader-program-id prg))
(setf %selected-shader-index% (shader-program-id prg)))
(progn (gl:use-program 0)
(setf %selected-shader-index% nil))))
(setf *print-circle* t)
(defun create-shader-program (&optional vertex fragment link)
(let ((prg (make-shader-program)))
(setf (shader-program-id prg) (gl:create-program))
(dformat "Created program with id: ~S~%" (shader-program-id prg))
(when (and vertex fragment)
(shader-program-attach-vertex prg vertex)
(shader-program-attach-fragment prg fragment))
(when (and vertex fragment link)
(shader-program-link prg))
(dformat "Created shader program: ~S~%" prg)
prg))
(defun destroy-shader-program (prg)
(when (shader-program-vertex prg)
(shader-program-detach-vertex prg))
(when (shader-program-fragment prg)
(shader-program-detach-fragment prg))
(gl:delete-program (shader-program-id prg)))
;;; Render state
(defstruct render-state
(depth-func :lequal)
(depth-write t)
(cull-face :back)
(blend-func '(:src-alpha :one-minus-src-alpha))
(shade-model :smooth)
(wireframe nil)
(lighting t)
(texturing t))
(defvar +default-3d-render-state+
(make-render-state :depth-func :lequal
:depth-write t
:cull-face :back
:blend-func nil
:shade-model :smooth
:wireframe nil
:lighting t
:texturing nil))
(defvar +default-2d-render-state+
(make-render-state :depth-func nil
:depth-write nil
:cull-face nil
:blend-func '(:src-alpha :one-minus-src-alpha)
:shade-model :smooth
:wireframe nil
:lighting nil
:texturing nil))
;; TODO: only apply differences from *current-render-state*
(defun set-render-state (rs)
(if (render-state-depth-func rs)
(progn (gl:enable :depth-test)
(gl:depth-func (render-state-depth-func rs)))
(gl:disable :depth-test))
(gl:depth-mask (if (render-state-depth-write rs) :enable :disable))
(if (render-state-cull-face rs)
(progn (gl:enable :cull-face)
(gl:cull-face (render-state-cull-face rs)))
(gl:disable :cull-face))
(if (render-state-blend-func rs)
(progn (gl:enable :blend)
(gl:blend-func (first (render-state-blend-func rs))
(second (render-state-blend-func rs))))
(gl:disable :blend))
(gl:shade-model (render-state-shade-model rs))
(if (render-state-wireframe rs)
(gl:polygon-mode :front-and-back :line)
(gl:polygon-mode :front-and-back :fill))
(if (render-state-lighting rs)
(gl:enable :lighting)
(gl:disable :lighting))
(if (render-state-texturing rs)
(gl:enable :texture-2d)
(gl:disable :texture-2d)))
| null | https://raw.githubusercontent.com/patzy/glaw/e678fc0c107ce4b1e3ff9921a6de7e32fd39bc37/src/graphics.lisp | lisp | General rendering
some default head light
set viewport to full screen
Colors helpers
Image
2D Texture
min-lod max-lod
base-level max-level
:data data
(gl:tex-parameter :texture-2d :texture-min-lod (texture-min-lod tex))
(gl:tex-parameter :texture-2d :texture-max-lod (texture-max-lod tex))
(gl:tex-parameter :texture-2d :texture-base-level (texture-base-level tex))
(gl:tex-parameter :texture-2d :texture-max-level (texture-max-level tex))
FIXME: get number of color attachment from OpenGL
Vertex Buffer
just allocating space
Index Buffer
unsigned short
just allocating space
Primitive rendering
Batching
# of vertices so far
# of indices so far
Basic material
nil means same as diffuse
FIXME: check if material is not already set
Shaders
programs this shader is attached to
FIXME: detach before delete?
(defstruct shader-data
(uniforms (list))
(uniform-values (list)))
(defstruct shader-data-bind
data
(push name (shader-data-uniforms data))
(push value (shader-data-uniform-values data)))
(defun shader-program-bind-data (prg prg-data)
Render state
TODO: only apply differences from *current-render-state* | (in-package :glaw)
(declaim (optimize (safety 0) (debug 0) (speed 3)))
(defvar *display-width* 800)
(defvar *display-height* 600)
(defun begin-draw ()
(gl:clear :color-buffer :depth-buffer))
(defun end-draw ()
(gl:flush))
(defun set-background-color (color)
(gl:clear-color (color-r color)
(color-g color)
(color-b color)
0))
(defun set-background-color/rgb (r g b)
(gl:clear-color r g b 0))
(defun clear-display (&rest buffers)
(apply #'clear-framebuffer nil buffers))
(defun setup-3d-defaults ()
(set-background-color #(0.3 0.3 0.3 0.0))
(set-render-state +default-3d-render-state+)
(gl:matrix-mode :projection)
(gl:load-identity)
(gl:matrix-mode :modelview)
(gl:load-identity)
(gl:enable :light0)
(gl:light :light0 :position #(0.0 0.0 0.0 1.0))
(gl:light :light0 :ambient #(0.2 0.2 0.2 1.0))
(gl:light :light0 :diffuse #(0.8 0.8 0.8 1.0))
(gl:light :light0 :specular #(0.5 0.5 0.5 1.0)))
(defun setup-2d-defaults ()
(set-background-color #(0.3 0.3 0.3 0.0))
(set-render-state +default-2d-render-state+))
(defun draw-origin (&optional (scale 20.0))
(gl:with-primitive :lines
(gl:color 1.0 0.0 0.0 1.0)
(gl:vertex 0.0 0.0 0.0)
(gl:vertex scale 0.0 0.0)
(gl:color 0.0 1.0 0.0 1.0)
(gl:vertex 0.0 0.0 0.0)
(gl:vertex 0.0 scale 0.0)
(gl:color 0.0 0.0 1.0 1.0)
(gl:vertex 0.0 0.0 0.0)
(gl:vertex 0.0 0.0 scale)))
(defun reshape (width height)
(gl:viewport 0 0 width height)
(setf *display-width* width)
(setf *display-height* height))
(defun set-view-matrices (proj-mtx view-mtx)
(gl:matrix-mode :projection)
(gl:load-matrix proj-mtx)
(gl:matrix-mode :modelview)
(gl:load-matrix view-mtx))
(defstruct (color (:type (vector float)))
(r 1.0)
(g 1.0)
(b 1.0)
(a 1.0))
(declaim (inline set-color))
(defun set-color (col)
(gl:color (color-r col) (color-g col) (color-b col) (color-a col)))
(declaim (inline set-color/rgb))
(defun set-color/rgb (r g b &optional (a 1.0))
(gl:color r g b a))
(defun create-color (r g b &optional (a 1.0))
(make-color :r r :g g :b b :a a))
(defun make-random-color (&optional (a 1.0))
(make-color :r (random-between 0.0 1.0)
:g (random-between 0.0 1.0)
:b (random-between 0.0 1.0)
:a a))
(defun color-copy (src dest)
(setf (color-r dest) (color-r src)
(color-g dest) (color-g src)
(color-b dest) (color-b src)
(color-a dest) (color-a src)))
(defun mix-colors (color-1 color-2 value)
(let ((r (+ (color-r color-1)
(* (- (color-r color-2)
(color-r color-1))
value)))
(g (+ (color-g color-1)
(* (- (color-g color-2)
(color-g color-1))
value)))
(b (+ (color-b color-1)
(* (- (color-b color-2)
(color-b color-1))
value)))
(a (+ (color-a color-1)
(* (- (color-a color-2)
(color-a color-1))
value))))
(make-color :r r :g g :b b :a a)))
(defun mix-colors/rgb (color-1 color-2 value)
(let ((r (+ (color-r color-1)
(* (- (color-r color-2)
(color-r color-1))
value)))
(g (+ (color-g color-1)
(* (- (color-g color-2)
(color-g color-1))
value)))
(b (+ (color-b color-1)
(* (- (color-b color-2)
(color-b color-1))
value)))
(a (+ (color-a color-1)
(* (- (color-a color-2)
(color-a color-1))
value))))
(values r g b a)))
(defstruct color-gradient
(start (make-color :r 0.0 :g 0.0 :b 0.0 :a 1.0))
(end (make-color :r 1.0 :g 1.0 :b 1.0 :a 1.0)))
(defun create-color-gradient (start-r start-g start-b start-a
end-r end-g end-b end-a)
(make-color-gradient
:start (make-color :r start-r :g start-g :b start-b :a start-a)
:end (make-color :r end-r :g end-g :b end-b :a end-a)))
(defun get-color-from-gradient (gradient value)
(mix-colors (color-gradient-start gradient)
(color-gradient-end gradient)
value))
(defun get-color-from-gradient/rgb (gradient value)
(mix-colors/rgb (color-gradient-start gradient)
(color-gradient-end gradient)
value))
(defun set-color-from-gradient (gradient value)
(multiple-value-bind (r g b a) (get-color-from-gradient/rgb gradient value)
(gl:color r g b a)))
(defstruct image
"Simple image structure. Origin is generally top-left but depends on the loader
you use."
width height bpp data)
(defun create-image (width height bpp)
(make-image :width width :height height :bpp bpp
:data (make-array (* width height bpp) :initial-element 255
:element-type '(unsigned-byte 8))))
(defun image-set-pixel (image x y r &optional (g 255) (b 255) (a 255))
(let ((index (+ x (* y (image-width image)))))
(image-set-pixel/index image index r g b a)))
(defun image-set-pixel/index (image index r &optional (g 255) (b 255) (a 255))
(let ((bpp (image-bpp image)))
(ecase bpp
(1 (setf (aref (image-data image) (* index bpp)) r))
(2 (setf (aref (image-data image) (* index bpp)) r
(aref (image-data image) (+ 1 (* index bpp))) g))
(3 (setf (aref (image-data image) (* index bpp)) r
(aref (image-data image) (+ 1 (* index bpp))) g
(aref (image-data image) (+ 2 (* index bpp))) b))
(4 (setf (aref (image-data image) (* index bpp)) r
(aref (image-data image) (+ 1 (* index bpp))) g
(aref (image-data image) (+ 2 (* index bpp))) b
(aref (image-data image) (+ 3 (* index bpp))) a)))))
(defun image-get-pixel (image x y)
(let ((index (+ x (* y (image-width image)))))
(image-get-pixel/index image index)))
(defun image-get-pixel/index (image index)
(let ((bpp (image-bpp image)))
(ecase bpp
(1 (values (aref (image-data image) (* index bpp))
0 0 0))
(2 (values (aref (image-data image) (* index bpp))
(aref (image-data image) (+ 1 (* index bpp)))
0 0))
(3 (values (aref (image-data image) (* index bpp))
(aref (image-data image) (+ 1 (* index bpp)))
(aref (image-data image) (+ 2 (* index bpp)))
0))
(4 (values (aref (image-data image) (* index bpp))
(aref (image-data image) (+ 1 (* index bpp)))
(aref (image-data image) (+ 2 (* index bpp)))
(aref (image-data image) (+ 3 (* index bpp))))))))
(defstruct texture
width height bpp data
GL texture index
(matrix +matrix-identity+)
GL texture parameters
(internal-format :rgba)
(min-filter :linear)
(mag-filter :linear)
(wrap-s :repeat)
(wrap-t :repeat)
(wrap-r :repeat)
priority)
(defun create-texture (width height bpp data &rest args)
"Create a new GL texture. Texture's origin is bottom-left."
(let ((tex (apply 'make-texture :index (first (gl:gen-textures 1))
:width width :height height
args)))
(select-texture tex)
(gl:tex-image-2d :texture-2d 0 (texture-internal-format tex)
(texture-width tex)
(texture-height tex) 0
(ecase (texture-bpp tex)
(1 :alpha)
(2 :luminance-alpha)
(3 :rgb)
(4 :rgba))
:unsigned-byte
(if data data (cffi::null-pointer)))
(gl:tex-parameter :texture-2d :texture-min-filter (texture-min-filter tex))
(gl:tex-parameter :texture-2d :texture-mag-filter (texture-mag-filter tex))
(gl:tex-parameter :texture-2d :texture-wrap-s (texture-wrap-s tex))
(gl:tex-parameter :texture-2d :texture-wrap-t (texture-wrap-t tex))
(gl:tex-parameter :texture-2d :texture-wrap-r (texture-wrap-r tex))
tex))
(defun update-texture (tex data &optional (x 0) (y 0)
(width (texture-width tex)) (height (texture-height tex)))
(setf (texture-data tex) data)
(select-texture tex)
(gl:tex-sub-image-2d :texture-2d 0 x y width height
(ecase (texture-bpp tex)
(1 :alpha)
(2 :luminance-alpha)
(3 :rgb)
(4 :rgba))
:unsigned-byte
data))
(defun create-texture-from-image (image &rest args)
(apply 'create-texture
(image-width image) (image-height image) (image-bpp image) (image-data image)
args))
(defun update-texture-from-image (tex image)
(update-texture tex (image-data image)))
(defun destroy-texture (tex)
(gl:delete-textures (list (texture-index tex))))
(defvar %selected-texture-index% nil
"Current texture in GL context.")
(defun texture-unit (&optional (index 0))
(declare (inline texture-unit))
(+ (cffi:foreign-enum-value 'cl-opengl-bindings:enum :texture0) index))
(defun select-texture (tex &key (env-mode :replace)
(unit (texture-unit 0))
(matrix +matrix-identity+))
"Set TEX as the current gl texture if necessary."
(gl:active-texture unit)
(if tex
(progn (unless %selected-texture-index%
(gl:enable :texture-2d)
(setf %selected-texture-index% -1))
(unless (= (texture-index tex) %selected-texture-index%)
(gl:bind-texture :texture-2d (texture-index tex))
(gl:tex-env :texture-env
:texture-env-mode env-mode)
(setf %selected-texture-index% (texture-index tex)))
(unless (eq matrix +matrix-identity+)
(gl:matrix-mode :texture)
(gl:load-matrix (texture-matrix tex))
(gl:matrix-mode :modelview))
)
(progn (gl:disable :texture-2d)
(setf %selected-texture-index% nil))))
Renderbuffer
(defstruct renderbuffer
width
height
format
index)
(defun create-renderbuffer (width height &optional (format :rgba))
(let ((index (first (gl:gen-renderbuffers-ext 1))))
(gl:bind-renderbuffer-ext :renderbuffer-ext index)
(gl:renderbuffer-storage-ext :renderbuffer-ext format width height)
(make-renderbuffer :width width :height height :format format :index index)))
(defun destroy-renderbuffer (rb)
(gl:delete-renderbuffers-ext (renderbuffer-index rb)))
Framebuffer
(defstruct framebuffer
width
height
index
colors
depth
stencil)
(defun %framebuffer-attach-texture (fb texture attach-point)
(assert (and (= (texture-height texture) (framebuffer-height fb))
(= (texture-width texture) (framebuffer-width fb))))
(let ((tex-index (texture-index texture)))
(gl:bind-texture :texture-2d tex-index)
(gl:framebuffer-texture-2d-ext :framebuffer-ext
attach-point
:texture-2d
tex-index
0)))
(defun %framebuffer-attach-renderbuffer (fb rb attach-point)
(assert (and (= (renderbuffer-height rb) (framebuffer-height fb))
(= (renderbuffer-width rb) (framebuffer-width fb))))
(let ((rb-index (renderbuffer-index rb)))
(gl:bind-renderbuffer-ext :renderbuffer-ext rb-index)
(gl:framebuffer-renderbuffer-ext :framebuffer-ext
attach-point
:renderbuffer-ext
rb-index)))
(defmethod framebuffer-attach-color (fb (buf texture) &optional (index 0))
(%framebuffer-attach-texture fb buf
(ecase index
(0 :color-attachment0-ext)
(1 :color-attachment1-ext)
(2 :color-attachment2-ext)
(3 :color-attachment3-ext)))
(setf (aref (framebuffer-colors fb) index) buf))
(defmethod framebuffer-attach-color (fb (buf renderbuffer) &optional (index 0))
(%framebuffer-attach-renderbuffer fb buf
(ecase index
(0 :color-attachment0-ext)
(1 :color-attachment1-ext)
(2 :color-attachment2-ext)
(3 :color-attachment3-ext)))
(setf (aref (framebuffer-colors fb) index) buf))
(defmethod framebuffer-attach-depth (fb (buf texture) &optional (index 0))
(%framebuffer-attach-texture fb buf :depth-attachment-ext)
(setf (framebuffer-depth fb) buf))
(defmethod framebuffer-attach-depth (fb (buf renderbuffer) &optional (index 0))
(%framebuffer-attach-renderbuffer fb buf :depth-attachment-ext)
(setf (framebuffer-depth fb) buf))
(defmethod framebuffer-attach-stencil (fb (buf texture) &optional (index 0))
(%framebuffer-attach-texture fb buf :stencil-attachment-ext)
(setf (framebuffer-stencil fb) buf))
(defmethod framebuffer-attach-color (fb (buf renderbuffer) &optional (index 0))
(%framebuffer-attach-renderbuffer fb buf :stencil-attachment-ext)
(setf (framebuffer-stencil fb) buf))
(defun create-framebuffer (width height &key (colors '())
(depth nil)
(stencil nil))
(let ((w (min (nearest-power-of-two width)
(gl:get-integer :max-texture-size)))
(h (min (nearest-power-of-two height)
(gl:get-integer :max-texture-size)))
(framebuffer (first (gl:gen-framebuffers-ext 1))))
(gl:bind-framebuffer-ext :framebuffer-ext framebuffer)
(make-framebuffer :index framebuffer :width w :height h
:colors (make-array 4) :depth nil :stencil nil)))
(defun destroy-framebuffer (fb)
(gl:delete-framebuffers-ext (framebuffer-index fb)))
(defvar %selected-framebuffer-index% nil
"Currently selected framebuffer object index.")
(defun select-framebuffer (fb)
(gl:bind-framebuffer-ext :framebuffer-ext (if fb (framebuffer-index fb) 0)))
(defun clear-framebuffer (fb &optional (buffers '(:color-buffer)))
(select-framebuffer fb)
(apply 'gl:clear buffers))
(defstruct buffer
index)
(defun make-vertex-format (&key vertices colors tex-coords normals)
(logior (if vertices #x01 #x00)
(if colors #x02 #x00)
(if tex-coords #x04 #x00)
(if normals #x08 #x00)))
(defun vertex-size (fmt)
(+ (if (vertex-has-vertices fmt) 3 0)
(if (vertex-has-colors fmt) 4 0)
(if (vertex-has-tex-coords fmt) 2 0)
(if (vertex-has-normals fmt) 3 0)))
(defun vertex-has-vertices (fmt)
(logbitp 0 fmt))
(defun vertex-has-colors (fmt)
(logbitp 1 fmt))
(defun vertex-has-tex-coords (fmt)
(logbitp 2 fmt))
(defun vertex-has-normals (fmt)
(logbitp 3 fmt))
(defstruct (vertex-buffer (:include buffer))
nb-vertices
format)
(defun set-vertex-buffer (vb)
(if vb
(gl:bind-buffer :array-buffer (vertex-buffer-index vb))
(gl:bind-buffer :array-buffer 0)))
(defun %vertex-buffer-setup-arrays (vb)
(if vb
(progn (%gl:vertex-pointer 3 :float 0 (cffi:null-pointer))
(gl:enable-client-state :vertex-array)
(let ((offset (* (vertex-buffer-nb-vertices vb) 3))
32 bits data
(when (vertex-has-colors (vertex-buffer-format vb))
(%gl:color-pointer 4 :float 0 (cffi:make-pointer (* offset elem-size)))
(gl:enable-client-state :color-array)
(incf offset (* (vertex-buffer-nb-vertices vb) 4)))
(when (vertex-has-tex-coords (vertex-buffer-format vb))
(gl:active-texture :texture0)
(%gl:tex-coord-pointer 2 :float 0 (cffi:make-pointer (* offset elem-size)))
(gl:enable-client-state :texture-coord-array)
(incf offset (* (vertex-buffer-nb-vertices vb) 2)))
(when (vertex-has-normals (vertex-buffer-format vb))
(%gl:normal-pointer :float 0 (cffi:make-pointer (* offset elem-size)))
(gl:enable-client-state :normal-array)
(incf offset (* (vertex-buffer-nb-vertices vb) 2)))))
(progn (gl:disable-client-state :vertex-array)
(gl:disable-client-state :color-array)
(gl:disable-client-state :texture-coord-array)
(gl:disable-client-state :normal-array))))
(defun create-empty-vertex-buffer (nb-vertices &key (usage :stream-draw)
(format (make-vertex-format :vertices t :normals t)))
(let* ((buff (car (gl:gen-buffers 1)))
(float-size 4)
(size (* (vertex-size format) nb-vertices float-size)))
(dformat "Creating vertex buffer: ~S~%" size)
(dformat "Recommended # of vertices: ~S~%" (gl:get-integer :max-elements-vertices))
(gl:bind-buffer :array-buffer buff)
(%gl:buffer-data :array-buffer
size
usage)
(assert (= (gl::get-buffer-parameter :array-buffer :buffer-size :int)
size))
(let ((vb (make-vertex-buffer :index buff
:nb-vertices nb-vertices
:format format)))
vb)))
(defun create-vertex-buffer (vertices &key colors tex-coords normals (usage :stream-draw))
(let* ((fmt (make-vertex-format :vertices vertices :colors colors :tex-coords tex-coords
:normals normals))
(vb (create-empty-vertex-buffer (/ (length vertices) 3) :usage usage
:format fmt)))
(vertex-buffer-update-components vb 0 vertices :colors colors
:tex-coords tex-coords :normals normals)
vb))
(defun vertex-buffer-update (vb array &optional (offset 0))
(gl:bind-buffer :array-buffer (vertex-buffer-index vb))
(gl:with-mapped-buffer (p :array-buffer :write-only)
(loop for i below (length array)
do (setf (cffi:mem-aref p :float (+ offset i)) (float (aref array i) 0.0)))))
(defun dprint-vb (vb start end)
(gl:bind-buffer :array-buffer (vertex-buffer-index vb))
(format t "VB: ")
(gl:with-mapped-buffer (p :array-buffer :read-only)
(loop for i from start below end
do (format t "~S " (cffi:mem-aref p :float i))))
(format t "~%"))
(defun vertex-buffer-update-components (vb vtx-offset vertices &key colors tex-coords normals)
(assert (= (vertex-buffer-format vb)
(make-vertex-format :vertices vertices
:colors colors
:tex-coords tex-coords
:normals normals)))
(let ((nb-vertices (vertex-buffer-nb-vertices vb))
(offset 0))
(vertex-buffer-update vb vertices (+ offset (* vtx-offset 3)))
(incf offset (* nb-vertices 3))
(when colors
(vertex-buffer-update vb colors (+ offset (* vtx-offset 4)))
(incf offset (* nb-vertices 4)))
(when tex-coords
(vertex-buffer-update vb tex-coords (+ offset (* vtx-offset 2)))
(incf offset (* nb-vertices 2)))
(when normals
(vertex-buffer-update vb normals (+ offset (* vtx-offset 3)))
(incf offset (* nb-vertices 3))))
vb)
(defun destroy-vertex-buffer (vb)
(gl:delete-buffers (list (vertex-buffer-index vb))))
(defstruct (index-buffer (:include buffer))
nb-indices)
(defun set-index-buffer (ib)
(if ib
(gl:bind-buffer :element-array-buffer (index-buffer-index ib))
(gl:bind-buffer :array-buffer 0)))
(defun %index-buffer-setup-arrays (ib)
(if ib
(progn (%gl:index-pointer :short 0 (cffi:null-pointer))
(gl:enable-client-state :index-array))
(gl:disable-client-state :index-array)))
(defun create-empty-index-buffer (nb-indices &key (usage :static-draw))
(let ((buff (car (gl:gen-buffers 1))))
(dformat "Creating index buffer: ~S~%" nb-indices)
(dformat "Recommended # of indices: ~S~%" (gl:get-integer :max-elements-indices))
(gl:bind-buffer :element-array-buffer buff)
(%gl:buffer-data :element-array-buffer
usage)
(assert (= (gl::get-buffer-parameter :element-array-buffer :buffer-size :int)
(* nb-indices 2)))
(let ((ib (make-index-buffer :index buff
:nb-indices nb-indices)))
ib)))
(defun create-index-buffer (indices &key (usage :static-draw))
(let ((ib (create-empty-index-buffer (length indices) :usage usage)))
(index-buffer-update ib indices 0)
ib))
(defun index-buffer-update (ib array &optional (offset 0) add-offset)
(gl:bind-buffer :element-array-buffer (index-buffer-index ib))
(gl:with-mapped-buffer (p :element-array-buffer :write-only)
(loop for i below (length array)
do (setf (cffi:mem-aref p :short (+ offset i))
(if add-offset (+ offset (aref array i)) (aref array i))))))
(defun dprint-ib (ib start end)
(gl:bind-buffer :element-array-buffer (index-buffer-index ib))
(format t "IB: ")
(gl:with-mapped-buffer (p :element-array-buffer :read-only)
(loop for i from start below end
do (format t "~S " (cffi:mem-aref p :short i))))
(format t "~%"))
(defun destroy-index-buffer (ib)
(gl:delete-buffers (list (index-buffer-index ib))))
(defun render-primitive (indices vertices &key (primitive :triangles)
colors tex-coords normals
shader
attrib-indices
attrib-sizes
attrib-datas
(start 0) (end (length indices)))
"Immediate mode rendering."
(gl:with-primitive primitive
(loop for index from start below end
for i = (aref indices index)
when colors
do (gl:color (aref colors (* i 4))
(aref colors (+ 1 (* i 4)))
(aref colors (+ 2 (* i 4)))
(aref colors (+ 3 (* i 4))))
when tex-coords
do (gl:tex-coord (aref tex-coords (* i 2))
(aref tex-coords (+ 1 (* i 2))))
when normals
do (gl:normal (aref normals (* i 3))
(aref normals (+ 1 (* i 3)))
(aref normals (+ 2 (* i 3))))
when attrib-indices
do (loop for attr-index in attrib-indices
for attr-size in attrib-sizes
for attr-data in attrib-datas
do (case attr-size
(1 (gl:vertex-attrib (shader-id shader) attr-index
(aref attr-data i)))
(2 (gl:vertex-attrib (shader-id shader) attr-index
(aref attr-data (* i 2))))
(3 (gl:vertex-attrib (shader-id shader) attr-index
(aref attr-data (* i 3))))
(4 (gl:vertex-attrib (shader-id shader) attr-index
(aref attr-data (* i 4))))))
do (gl:vertex (aref vertices (* i 3))
(aref vertices (+ 1 (* i 3)))
(aref vertices (+ 2 (* i 3)))))))
(defstruct display-list
GL display list index
(primitive :triangles)
start end
vb ib)
(defun destroy-display-list (dl)
(if (display-list-vb dl)
(progn (destroy-vertex-buffer (display-list-vb dl))
(destroy-index-buffer (display-list-ib dl)))
(gl:delete-lists (display-list-index dl) 1)))
(defun load-primitive (indices vertices &key (primitive :triangles)
colors tex-coords normals
(start 0) (end (length indices))
use-buffers)
(let ((dl (make-display-list)))
(if use-buffers
(setf (display-list-vb dl) (create-vertex-buffer vertices
:colors colors
:tex-coords tex-coords
:normals normals
:usage :static-draw)
(display-list-ib dl) (create-index-buffer indices)
(display-list-primitive dl) primitive
(display-list-start dl) start
(display-list-end dl) end)
(progn (setf (display-list-index dl) (gl:gen-lists 1))
(gl:new-list (display-list-index dl) :compile)
(render-primitive indices vertices :primitive primitive
:colors colors :tex-coords tex-coords :normals normals
:start start :end end)
(gl:end-list)))
dl))
(defun call-primitive (dl)
(if (display-list-vb dl)
(progn (set-vertex-buffer (display-list-vb dl))
(%vertex-buffer-setup-arrays (display-list-vb dl))
(set-index-buffer (display-list-ib dl))
(%index-buffer-setup-arrays (display-list-ib dl))
(%gl:draw-arrays (display-list-primitive dl)
(display-list-start dl)
(- (display-list-end dl) (display-list-start dl)))
(set-vertex-buffer nil)
(%vertex-buffer-setup-arrays nil)
(set-index-buffer nil)
(%index-buffer-setup-arrays nil))
(gl:call-list (display-list-index dl))))
(defstruct (primitive-batch (:include display-list))
items)
(defun create-primitive-batch (primitive vfmt &key (max-vertices 10000)
(max-indices 10000)
(vertex-usage :stream-draw)
(index-usage :stream-draw))
(let ((batch (make-primitive-batch :vb-offset 0 :ib-offset 0 :primitive primitive
:items '() :start 0 :end 0)))
(setf (primitive-batch-vb batch) (create-empty-vertex-buffer max-vertices :usage vertex-usage
:format vfmt)
(primitive-batch-ib batch) (create-empty-index-buffer max-indices :usage index-usage))
batch))
(defun destroy-primitive-batch (batch)
(destroy-display-list batch))
(defun primitive-batch-append (batch indices vertices &key colors tex-coords normals)
(vertex-buffer-update-components (primitive-batch-vb batch)
(primitive-batch-vb-offset batch)
vertices :colors colors :tex-coords tex-coords :normals normals)
(incf (primitive-batch-vb-offset batch) (/ (length vertices) 3))
(index-buffer-update (primitive-batch-ib batch) indices (primitive-batch-ib-offset batch) t)
(incf (primitive-batch-ib-offset batch) (length indices))
(let ((item (cons (primitive-batch-end batch)
(length indices))))
(incf (primitive-batch-end batch) (length indices))
(setf (primitive-batch-items batch) (append (primitive-batch-items batch)
(list item)))
(primitive-batch-end batch)))
(defun primitive-batch-clear (batch)
(setf (primitive-batch-items batch) (list)
(primitive-batch-vb-offset batch) 0
(primitive-batch-ib-offset batch) 0
(primitive-batch-start batch) 0
(primitive-batch-end batch) 0))
(defun primitive-batch-render (batch)
(call-primitive batch))
(defstruct material
(ambient #(0.3 0.3 0.3 1.0))
(specular #(1.0 1.0 1.0 1.0))
(shininess 1.0)
(emissive #(0.0 0.0 0.0 1.0)))
(defvar +default-material+
(make-material))
(defun material-set-alpha (mat alpha)
"Set material transparency."
(setf (color-a (material-ambient mat)) alpha
(color-a (material-diffuse mat)) alpha
(color-a (material-specular mat)) alpha
(color-a (material-emissive mat)) alpha))
(defun material-alpha (mat)
(color-a (material-ambient mat)))
(defsetf material-alpha material-set-alpha)
FIXME : use color material ( supposed to be faster )
(defun set-material (mat)
(when mat
(if (material-diffuse mat)
(progn (gl:material :front-and-back :ambient (material-ambient mat))
(gl:material :front-and-back :diffuse (material-diffuse mat)))
(gl:material :front-and-back :ambient-and-diffuse (material-ambient mat)))
(gl:material :front-and-back :specular (material-specular mat))
(gl:material :front-and-back :shininess (material-shininess mat))
(gl:material :front-and-back :emission (material-emissive mat))))
(defstruct shader
source
GL i d
(needs-compile t))
(defun %shader-add-program (shader prg)
(push prg (shader-programs shader)))
(defun %shader-remove-program (shader prg)
(setf (shader-programs shader) (remove prg (shader-programs shader))))
(defun shader-compile (shader)
(assert (and (shader-source shader)
(shader-id shader)))
(dformat "Compiling shader.~%")
(gl:compile-shader (shader-id shader))
(dformat "Shader compile log:~%~S~%" (gl:get-shader-info-log (shader-id shader)))
(setf (shader-needs-compile shader) nil))
(defun %shader-set-source (shader source)
(setf (shader-source shader) source
(shader-needs-compile shader) t)
(gl:shader-source (shader-id shader) (shader-source shader)))
(defun shader-set-source (shader source &optional compile)
(%shader-set-source shader source)
(when compile
(shader-compile shader)))
(defun create-shader (type &optional source compile)
(assert (or (eq type :vertex-shader) (eq type :fragment-shader)))
(let ((sh (make-shader)))
(setf (shader-id sh) (gl:create-shader type))
(when source
(shader-set-source sh source))
(when compile
(shader-compile sh))
(dformat "Created shader: ~S~%" sh)
sh))
(defun create-shader-from-file (type file &optional compile)
(create-shader type (file->strings file) compile))
(defun create-vertex-shader (&optional source compile)
(create-shader :vertex-shader source compile))
(defun create-vertex-shader-from-file (file &optional compile)
(create-shader-from-file :vertex-shader file compile))
(defun create-fragment-shader (&optional source compile)
(create-shader :fragment-shader source compile))
(defun create-fragment-shader-from-file (file &optional compile)
(create-shader-from-file :fragment-shader file compile))
(defun destroy-shader (sh)
(gl:delete-shader (shader-id sh)))
( defun shader - data - add - uniform ( data name & optional ( value nil ) )
(defstruct shader-program
vertex
fragment
id
data
(needs-link t))
( setf ( shader - program - data prg ) prg - data )
(defun shader-program-attach-vertex (prg vtx-shader)
(setf (shader-program-vertex prg) vtx-shader
(shader-program-needs-link prg) t)
(gl:attach-shader (shader-program-id prg) (shader-id vtx-shader))
(%shader-add-program vtx-shader prg))
(defun shader-program-detach-vertex (prg)
(gl:detach-shader (shader-program-id prg) (shader-id (shader-program-vertex prg)))
(%shader-remove-program (shader-program-vertex prg) prg)
(setf (shader-program-vertex prg) nil))
(defun shader-program-attach-fragment (prg frag-shader)
(setf (shader-program-fragment prg) frag-shader
(shader-program-needs-link prg) t)
(gl:attach-shader (shader-program-id prg) (shader-id frag-shader))
(%shader-add-program frag-shader prg))
(defun shader-program-detach-fragment (prg)
(gl:detach-shader (shader-program-id prg) (shader-id (shader-program-fragment prg)))
(%shader-remove-program (shader-program-fragment prg) prg)
(setf (shader-program-fragment prg) nil))
(defun shader-program-link (prg)
(assert (shader-program-id prg))
(dformat "Linking shader program.~%")
(setf (shader-program-needs-link prg) nil)
(gl:link-program (shader-program-id prg))
(dformat "Program info log:~%~S~%" (gl:get-program-info-log (shader-program-id prg))))
(defvar %selected-shader-index% nil)
(defun set-shader-program (prg)
(if prg
(progn (gl:use-program (shader-program-id prg))
(setf %selected-shader-index% (shader-program-id prg)))
(progn (gl:use-program 0)
(setf %selected-shader-index% nil))))
(setf *print-circle* t)
(defun create-shader-program (&optional vertex fragment link)
(let ((prg (make-shader-program)))
(setf (shader-program-id prg) (gl:create-program))
(dformat "Created program with id: ~S~%" (shader-program-id prg))
(when (and vertex fragment)
(shader-program-attach-vertex prg vertex)
(shader-program-attach-fragment prg fragment))
(when (and vertex fragment link)
(shader-program-link prg))
(dformat "Created shader program: ~S~%" prg)
prg))
(defun destroy-shader-program (prg)
(when (shader-program-vertex prg)
(shader-program-detach-vertex prg))
(when (shader-program-fragment prg)
(shader-program-detach-fragment prg))
(gl:delete-program (shader-program-id prg)))
(defstruct render-state
(depth-func :lequal)
(depth-write t)
(cull-face :back)
(blend-func '(:src-alpha :one-minus-src-alpha))
(shade-model :smooth)
(wireframe nil)
(lighting t)
(texturing t))
(defvar +default-3d-render-state+
(make-render-state :depth-func :lequal
:depth-write t
:cull-face :back
:blend-func nil
:shade-model :smooth
:wireframe nil
:lighting t
:texturing nil))
(defvar +default-2d-render-state+
(make-render-state :depth-func nil
:depth-write nil
:cull-face nil
:blend-func '(:src-alpha :one-minus-src-alpha)
:shade-model :smooth
:wireframe nil
:lighting nil
:texturing nil))
(defun set-render-state (rs)
(if (render-state-depth-func rs)
(progn (gl:enable :depth-test)
(gl:depth-func (render-state-depth-func rs)))
(gl:disable :depth-test))
(gl:depth-mask (if (render-state-depth-write rs) :enable :disable))
(if (render-state-cull-face rs)
(progn (gl:enable :cull-face)
(gl:cull-face (render-state-cull-face rs)))
(gl:disable :cull-face))
(if (render-state-blend-func rs)
(progn (gl:enable :blend)
(gl:blend-func (first (render-state-blend-func rs))
(second (render-state-blend-func rs))))
(gl:disable :blend))
(gl:shade-model (render-state-shade-model rs))
(if (render-state-wireframe rs)
(gl:polygon-mode :front-and-back :line)
(gl:polygon-mode :front-and-back :fill))
(if (render-state-lighting rs)
(gl:enable :lighting)
(gl:disable :lighting))
(if (render-state-texturing rs)
(gl:enable :texture-2d)
(gl:disable :texture-2d)))
|
9c2fff3b98e6d2896a2513324058566544b3c13d8a6f180da4616d89d20c72bd | myshov/programming_in_haskell | subtract_parser.hs | import Parsing
expr :: Parser Int
expr = do n <- natural
ns <- many (do symbol "-"
natural)
return (foldl (-) n ns)
eval :: String -> Int
eval xs = case parse expr xs of
[(n, [])] -> n
[(_, out)] -> error("unused input " ++ out)
[] -> error "invalid input"
| null | https://raw.githubusercontent.com/myshov/programming_in_haskell/3118695cc09a5ea0954917c318bf007b6ae5fcef/lesson8/subtract_parser.hs | haskell | import Parsing
expr :: Parser Int
expr = do n <- natural
ns <- many (do symbol "-"
natural)
return (foldl (-) n ns)
eval :: String -> Int
eval xs = case parse expr xs of
[(n, [])] -> n
[(_, out)] -> error("unused input " ++ out)
[] -> error "invalid input"
| |
ff4a464e6778d992fa7ea06cdf0dc1e78fe726c7e1494639a37cffc389bdfaa4 | craigl64/clim-ccl | compile.lisp | ;; See the file LICENSE for the full license governing this code.
;;
(in-package :user)
;;; This is obsolete, don't let it be loaded
(eval-when (:compile-toplevel :load-toplevel :execute)
(error "This file is obsolete, you should be using misc/compile-1"))
(proclaim '(optimize (speed 3) (safety 1) (debug 1)))
#+(and allegro microsoft)
(eval-when (compile load eval)
(pushnew :acl86win32 *features*))
#+microsoft
(let ((excl::*enable-package-locked-errors* nil))
(when (not (fboundp 'system::rcsnote))
(defun system::rcsnote (&rest args)
nil)))
(defvar *clim-root* (make-pathname
:device (pathname-device *load-pathname*)
:directory (butlast (pathname-directory *load-pathname*))))
(defun climpath (sub) (merge-pathnames sub *clim-root*))
should probably change ANSI-90 to ANSI - CL throughout the CLIM code but
;; until then... (aclpc gets this feature in defsystem)
(eval-when (compile load eval)
(pushnew :ansi-90 *features*)
(setf (logical-pathname-translations "clim2")
`((";**;*.*" ,*clim-root*)))
(load "clim2:;sys;sysdcl.lisp"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(with-compilation-unit ()
(let ((excl::*enable-package-locked-errors* nil))
#+mswindows
(progn
(load (climpath "aclpc\\sysdcl.lisp"))
(compile-system 'aclnt-clim :include-components t)
(let ((excl:*redefinition-warnings* nil)
(excl::*defconstant-redefinition-check* nil))
(load-system 'aclnt-clim)))
;; postscript backend
(progn
(load (climpath "postscript\\sysdcl.lisp"))
(compile-system 'postscript-clim)
(let ((excl:*redefinition-warnings* nil)
(excl::*defconstant-redefinition-check* nil))
(load-system 'postscript-clim)))
(compile-file-if-needed (climpath "test\\test-suite.lisp"))
(load (climpath "test\\test-suite.fasl"))
(let ((excl:*redefinition-warnings* nil))
(load (climpath "demo\\sysdcl.lisp"))
(compile-system 'clim-demo))
)) ;; with-compilation-unit
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package :clim-user)
(defun run-tests ()
(let ((frame (make-application-frame 'clim-tests)))
(raise-frame frame)
(run-frame-top-level frame)))
#+mswindows
(flet ((append-files (input-files output-file)
(format t "~%;; Making ~a...~%" output-file)
(with-open-file (s output-file
:element-type '(unsigned-byte 8)
:direction :output :if-exists :supersede
:if-does-not-exist :create)
(dolist (input-file input-files)
(sys:copy-file input-file s)))
t))
(append-files '("aclpc/pkgdcl.fasl"
"aclpc/winwidgh.fasl"
"aclpc/climpat.fasl"
"aclpc/acl-prel.fasl"
"aclpc/acl-class.fasl"
"aclpc/acl-dc.fasl"
"aclpc/acl-port.fasl"
"aclpc/acl-mirror.fasl"
"aclpc/acl-medium.fasl"
"aclpc/acl-pixmaps.fasl"
"aclpc/acl-frames.fasl"
"aclpc/acl-widget.fasl"
"aclpc/acl-scroll.fasl"
"utils/last.fasl")
"climnt.fasl")
(append-files '("postscript/postscript-port.fasl"
"postscript/postscript-medium.fasl"
"postscript/laserwriter-metrics.fasl")
"climps.fasl")
(append-files '("demo/packages.fasl"
"demo/demo-driver.fasl"
"demo/listener.fasl"
"demo/graphics-demos.fasl"
"demo/cad-demo.fasl"
"demo/bitmap-editor.fasl"
"demo/navdata.fasl"
"demo/navfun.fasl"
"demo/puzzle.fasl"
"demo/address-book.fasl"
"demo/thinkadot.fasl"
"demo/plot.fasl"
"demo/color-editor.fasl"
"demo/graphics-editor.fasl"
"demo/ico.fasl"
"demo/browser.fasl"
"demo/peek-frame.fasl"
"demo/process-browser.fasl"
"demo/custom-records.fasl"
"demo/demo-activity.fasl"
"test/test-suite.fasl"
"demo/demo-last.fasl")
"climdemo.fasl")
(append-files '("utils/excl-verification.fasl"
"utils/packages.fasl"
"utils/defun-utilities.fasl"
"utils/reader.fasl"
"utils/clos-patches.fasl"
"utils/clos.fasl"
"utils/utilities.fasl"
"utils/lisp-utilities.fasl"
"utils/processes.fasl"
"utils/queue.fasl"
"utils/timers.fasl"
"utils/protocols.fasl"
"utils/clim-streams.fasl"
"utils/excl-streams.fasl"
"utils/clim-macros.fasl"
"utils/transformations.fasl"
"utils/regions.fasl"
"utils/region-arithmetic.fasl"
"utils/extended-regions.fasl"
"utils/base-designs.fasl"
"utils/designs.fasl"
"silica/classes.fasl"
"silica/text-style.fasl"
"silica/macros.fasl"
"silica/sheet.fasl"
"silica/mirror.fasl"
"silica/event.fasl"
"silica/port.fasl"
"silica/medium.fasl"
"silica/framem.fasl"
"silica/graphics.fasl"
"silica/pixmaps.fasl"
"silica/std-sheet.fasl"
"silica/layout.fasl"
"silica/db-layout.fasl"
"silica/db-box.fasl"
"silica/db-table.fasl"
"silica/gadgets.fasl"
"silica/db-scroll.fasl"
"silica/db-border.fasl"
"silica/db-button.fasl"
"silica/db-slider.fasl"
"silica/db-label.fasl"
"clim/gestures.fasl"
"clim/defprotocol.fasl"
"clim/stream-defprotocols.fasl"
"clim/defresource.fasl"
"clim/temp-strings.fasl"
"clim/clim-defs.fasl"
"clim/stream-class-defs.fasl"
"clim/interactive-defs.fasl"
"clim/cursor.fasl"
"clim/view-defs.fasl"
"clim/input-defs.fasl"
"clim/input-protocol.fasl"
"clim/output-protocol.fasl"
"clim/recording-protocol.fasl"
"clim/recording-defs.fasl"
"clim/text-recording.fasl"
"clim/graphics-recording.fasl"
"clim/design-recording.fasl"
"clim/interactive-protocol.fasl"
"clim/input-editor-commands.fasl"
"clim/formatted-output-defs.fasl"
"clim/incremental-redisplay.fasl"
"clim/coordinate-sorted-set.fasl"
"clim/r-tree.fasl"
"clim/window-stream.fasl"
"clim/pixmap-streams.fasl"
"clim/ptypes1.fasl"
"clim/completer.fasl"
"clim/presentations.fasl"
"clim/translators.fasl"
"clim/histories.fasl"
"clim/ptypes2.fasl"
"clim/excl-presentations.fasl"
"clim/standard-types.fasl"
"clim/table-formatting.fasl"
"clim/graph-formatting.fasl"
"clim/surround-output.fasl"
"clim/text-formatting.fasl"
"clim/tracking-pointer.fasl"
"clim/dragging-output.fasl"
"clim/db-stream.fasl"
"clim/gadget-output.fasl"
"clim/accept.fasl"
"clim/present.fasl"
"clim/command.fasl"
"clim/command-processor.fasl"
"clim/basic-translators.fasl"
"clim/frames.fasl"
"clim/panes.fasl"
"clim/default-frame.fasl"
"clim/activities.fasl"
"clim/db-menu.fasl"
"clim/db-list.fasl"
"clim/db-text.fasl"
"clim/noting-progress.fasl"
"clim/menus.fasl"
"clim/accept-values.fasl"
"clim/drag-and-drop.fasl"
"clim/item-list-manager.fasl"
"postscript/pkgdcl.fasl"
"clim/stream-trampolines.fasl")
"climg.fasl"))
| null | https://raw.githubusercontent.com/craigl64/clim-ccl/301efbd770745b429f2b00b4e8ca6624de9d9ea9/sys/compile.lisp | lisp | See the file LICENSE for the full license governing this code.
This is obsolete, don't let it be loaded
until then... (aclpc gets this feature in defsystem)
postscript backend
with-compilation-unit
|
(in-package :user)
(eval-when (:compile-toplevel :load-toplevel :execute)
(error "This file is obsolete, you should be using misc/compile-1"))
(proclaim '(optimize (speed 3) (safety 1) (debug 1)))
#+(and allegro microsoft)
(eval-when (compile load eval)
(pushnew :acl86win32 *features*))
#+microsoft
(let ((excl::*enable-package-locked-errors* nil))
(when (not (fboundp 'system::rcsnote))
(defun system::rcsnote (&rest args)
nil)))
(defvar *clim-root* (make-pathname
:device (pathname-device *load-pathname*)
:directory (butlast (pathname-directory *load-pathname*))))
(defun climpath (sub) (merge-pathnames sub *clim-root*))
should probably change ANSI-90 to ANSI - CL throughout the CLIM code but
(eval-when (compile load eval)
(pushnew :ansi-90 *features*)
(setf (logical-pathname-translations "clim2")
`((";**;*.*" ,*clim-root*)))
(load "clim2:;sys;sysdcl.lisp"))
(with-compilation-unit ()
(let ((excl::*enable-package-locked-errors* nil))
#+mswindows
(progn
(load (climpath "aclpc\\sysdcl.lisp"))
(compile-system 'aclnt-clim :include-components t)
(let ((excl:*redefinition-warnings* nil)
(excl::*defconstant-redefinition-check* nil))
(load-system 'aclnt-clim)))
(progn
(load (climpath "postscript\\sysdcl.lisp"))
(compile-system 'postscript-clim)
(let ((excl:*redefinition-warnings* nil)
(excl::*defconstant-redefinition-check* nil))
(load-system 'postscript-clim)))
(compile-file-if-needed (climpath "test\\test-suite.lisp"))
(load (climpath "test\\test-suite.fasl"))
(let ((excl:*redefinition-warnings* nil))
(load (climpath "demo\\sysdcl.lisp"))
(compile-system 'clim-demo))
(in-package :clim-user)
(defun run-tests ()
(let ((frame (make-application-frame 'clim-tests)))
(raise-frame frame)
(run-frame-top-level frame)))
#+mswindows
(flet ((append-files (input-files output-file)
(format t "~%;; Making ~a...~%" output-file)
(with-open-file (s output-file
:element-type '(unsigned-byte 8)
:direction :output :if-exists :supersede
:if-does-not-exist :create)
(dolist (input-file input-files)
(sys:copy-file input-file s)))
t))
(append-files '("aclpc/pkgdcl.fasl"
"aclpc/winwidgh.fasl"
"aclpc/climpat.fasl"
"aclpc/acl-prel.fasl"
"aclpc/acl-class.fasl"
"aclpc/acl-dc.fasl"
"aclpc/acl-port.fasl"
"aclpc/acl-mirror.fasl"
"aclpc/acl-medium.fasl"
"aclpc/acl-pixmaps.fasl"
"aclpc/acl-frames.fasl"
"aclpc/acl-widget.fasl"
"aclpc/acl-scroll.fasl"
"utils/last.fasl")
"climnt.fasl")
(append-files '("postscript/postscript-port.fasl"
"postscript/postscript-medium.fasl"
"postscript/laserwriter-metrics.fasl")
"climps.fasl")
(append-files '("demo/packages.fasl"
"demo/demo-driver.fasl"
"demo/listener.fasl"
"demo/graphics-demos.fasl"
"demo/cad-demo.fasl"
"demo/bitmap-editor.fasl"
"demo/navdata.fasl"
"demo/navfun.fasl"
"demo/puzzle.fasl"
"demo/address-book.fasl"
"demo/thinkadot.fasl"
"demo/plot.fasl"
"demo/color-editor.fasl"
"demo/graphics-editor.fasl"
"demo/ico.fasl"
"demo/browser.fasl"
"demo/peek-frame.fasl"
"demo/process-browser.fasl"
"demo/custom-records.fasl"
"demo/demo-activity.fasl"
"test/test-suite.fasl"
"demo/demo-last.fasl")
"climdemo.fasl")
(append-files '("utils/excl-verification.fasl"
"utils/packages.fasl"
"utils/defun-utilities.fasl"
"utils/reader.fasl"
"utils/clos-patches.fasl"
"utils/clos.fasl"
"utils/utilities.fasl"
"utils/lisp-utilities.fasl"
"utils/processes.fasl"
"utils/queue.fasl"
"utils/timers.fasl"
"utils/protocols.fasl"
"utils/clim-streams.fasl"
"utils/excl-streams.fasl"
"utils/clim-macros.fasl"
"utils/transformations.fasl"
"utils/regions.fasl"
"utils/region-arithmetic.fasl"
"utils/extended-regions.fasl"
"utils/base-designs.fasl"
"utils/designs.fasl"
"silica/classes.fasl"
"silica/text-style.fasl"
"silica/macros.fasl"
"silica/sheet.fasl"
"silica/mirror.fasl"
"silica/event.fasl"
"silica/port.fasl"
"silica/medium.fasl"
"silica/framem.fasl"
"silica/graphics.fasl"
"silica/pixmaps.fasl"
"silica/std-sheet.fasl"
"silica/layout.fasl"
"silica/db-layout.fasl"
"silica/db-box.fasl"
"silica/db-table.fasl"
"silica/gadgets.fasl"
"silica/db-scroll.fasl"
"silica/db-border.fasl"
"silica/db-button.fasl"
"silica/db-slider.fasl"
"silica/db-label.fasl"
"clim/gestures.fasl"
"clim/defprotocol.fasl"
"clim/stream-defprotocols.fasl"
"clim/defresource.fasl"
"clim/temp-strings.fasl"
"clim/clim-defs.fasl"
"clim/stream-class-defs.fasl"
"clim/interactive-defs.fasl"
"clim/cursor.fasl"
"clim/view-defs.fasl"
"clim/input-defs.fasl"
"clim/input-protocol.fasl"
"clim/output-protocol.fasl"
"clim/recording-protocol.fasl"
"clim/recording-defs.fasl"
"clim/text-recording.fasl"
"clim/graphics-recording.fasl"
"clim/design-recording.fasl"
"clim/interactive-protocol.fasl"
"clim/input-editor-commands.fasl"
"clim/formatted-output-defs.fasl"
"clim/incremental-redisplay.fasl"
"clim/coordinate-sorted-set.fasl"
"clim/r-tree.fasl"
"clim/window-stream.fasl"
"clim/pixmap-streams.fasl"
"clim/ptypes1.fasl"
"clim/completer.fasl"
"clim/presentations.fasl"
"clim/translators.fasl"
"clim/histories.fasl"
"clim/ptypes2.fasl"
"clim/excl-presentations.fasl"
"clim/standard-types.fasl"
"clim/table-formatting.fasl"
"clim/graph-formatting.fasl"
"clim/surround-output.fasl"
"clim/text-formatting.fasl"
"clim/tracking-pointer.fasl"
"clim/dragging-output.fasl"
"clim/db-stream.fasl"
"clim/gadget-output.fasl"
"clim/accept.fasl"
"clim/present.fasl"
"clim/command.fasl"
"clim/command-processor.fasl"
"clim/basic-translators.fasl"
"clim/frames.fasl"
"clim/panes.fasl"
"clim/default-frame.fasl"
"clim/activities.fasl"
"clim/db-menu.fasl"
"clim/db-list.fasl"
"clim/db-text.fasl"
"clim/noting-progress.fasl"
"clim/menus.fasl"
"clim/accept-values.fasl"
"clim/drag-and-drop.fasl"
"clim/item-list-manager.fasl"
"postscript/pkgdcl.fasl"
"clim/stream-trampolines.fasl")
"climg.fasl"))
|
0d3a67f6ec36331738ad4a00063e704821939b01ad4f4b5c5665406c892781fb | hedgehogqa/haskell-hedgehog-classes | Ix.hs | # LANGUAGE ScopedTypeVariables #
{-# LANGUAGE RankNTypes #-}
module Hedgehog.Classes.Ix (ixLaws) where
import Hedgehog
import Hedgehog.Classes.Common
import Data.Ix (Ix(..))
ixLaws :: forall a. (Ix a, Eq a, Show a) => Gen a -> Laws
ixLaws gen = Laws "Ix"
[ ("InRange", ixInRange gen)
, ("RangeIndex", ixRangeIndex gen)
, ("MapIndexRange", ixMapIndexRange gen)
, ("RangeSize", ixRangeSize gen)
]
type IxProp a =
( Eq a
, Ix a
, Show a
) => Gen a -> Property
ixInRange :: IxProp a
ixInRange gen = property $ do
(l,u) <- forAll $ genValidRange gen
i <- forAll gen
inRange (l,u) i === elem i (range (l,u))
ixRangeIndex :: IxProp a
ixRangeIndex gen = property $ do
(l,u,i) <- forAll $ genInRange gen
range (l,u) !! index (l,u) i === i
ixMapIndexRange :: IxProp a
ixMapIndexRange gen = property $ do
(l,u) <- forAll $ genValidRange gen
map (index (l,u)) (range (l,u)) === [0 .. rangeSize (l,u) - 1]
ixRangeSize :: IxProp a
ixRangeSize gen = property $ do
(l,u) <- forAll $ genValidRange gen
rangeSize (l,u) === length (range (l,u))
| null | https://raw.githubusercontent.com/hedgehogqa/haskell-hedgehog-classes/4d97b000e915de8ba590818f551bce7bd862e7d4/src/Hedgehog/Classes/Ix.hs | haskell | # LANGUAGE RankNTypes # | # LANGUAGE ScopedTypeVariables #
module Hedgehog.Classes.Ix (ixLaws) where
import Hedgehog
import Hedgehog.Classes.Common
import Data.Ix (Ix(..))
ixLaws :: forall a. (Ix a, Eq a, Show a) => Gen a -> Laws
ixLaws gen = Laws "Ix"
[ ("InRange", ixInRange gen)
, ("RangeIndex", ixRangeIndex gen)
, ("MapIndexRange", ixMapIndexRange gen)
, ("RangeSize", ixRangeSize gen)
]
type IxProp a =
( Eq a
, Ix a
, Show a
) => Gen a -> Property
ixInRange :: IxProp a
ixInRange gen = property $ do
(l,u) <- forAll $ genValidRange gen
i <- forAll gen
inRange (l,u) i === elem i (range (l,u))
ixRangeIndex :: IxProp a
ixRangeIndex gen = property $ do
(l,u,i) <- forAll $ genInRange gen
range (l,u) !! index (l,u) i === i
ixMapIndexRange :: IxProp a
ixMapIndexRange gen = property $ do
(l,u) <- forAll $ genValidRange gen
map (index (l,u)) (range (l,u)) === [0 .. rangeSize (l,u) - 1]
ixRangeSize :: IxProp a
ixRangeSize gen = property $ do
(l,u) <- forAll $ genValidRange gen
rangeSize (l,u) === length (range (l,u))
|
270689b9ddc1101e91100fbd705643f588d802a41577275408d28619dc85d26b | okuoku/nausicaa | nfa2dfa.scm | SILex - Scheme Implementation of Lex
Copyright ( C ) 2001
;
; This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation ; either version 2
of the License , or ( at your option ) any later version .
;
; This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
; GNU General Public License for more details.
;
You should have received a copy of the GNU General Public License
; along with this program; if not, write to the Free Software
Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
; Recoupement de deux arcs
(define n2d-2arcs
(lambda (arc1 arc2)
(let* ((class1 (car arc1))
(ss1 (cdr arc1))
(class2 (car arc2))
(ss2 (cdr arc2))
(result (class-sep class1 class2))
(classl (vector-ref result 0))
(classc (vector-ref result 1))
(classr (vector-ref result 2))
(ssl ss1)
(ssc (ss-union ss1 ss2))
(ssr ss2))
(vector (if (or (null? classl) (null? ssl)) #f (cons classl ssl))
(if (or (null? classc) (null? ssc)) #f (cons classc ssc))
(if (or (null? classr) (null? ssr)) #f (cons classr ssr))))))
Insertion d'un arc dans une liste d'arcs a classes distinctes
(define n2d-insert-arc
(lambda (new-arc arcs)
(if (null? arcs)
(list new-arc)
(let* ((arc (car arcs))
(others (cdr arcs))
(result (n2d-2arcs new-arc arc))
(arcl (vector-ref result 0))
(arcc (vector-ref result 1))
(arcr (vector-ref result 2))
(list-arcc (if arcc (list arcc) '()))
(list-arcr (if arcr (list arcr) '())))
(if arcl
(append list-arcc list-arcr (n2d-insert-arc arcl others))
(append list-arcc list-arcr others))))))
Regroupement des arcs qui aboutissent au meme sous - ensemble d'etats
(define n2d-factorize-arcs
(lambda (arcs)
(if (null? arcs)
'()
(let* ((arc (car arcs))
(arc-ss (cdr arc))
(others-no-fact (cdr arcs))
(others (n2d-factorize-arcs others-no-fact)))
(let loop ((o others))
(if (null? o)
(list arc)
(let* ((o1 (car o))
(o1-ss (cdr o1)))
(if (equal? o1-ss arc-ss)
(let* ((arc-class (car arc))
(o1-class (car o1))
(new-class (class-union arc-class o1-class))
(new-arc (cons new-class arc-ss)))
(cons new-arc (cdr o)))
(cons o1 (loop (cdr o)))))))))))
Transformer une liste d'arcs quelconques en des arcs a classes distinctes
(define n2d-distinguish-arcs
(lambda (arcs)
(let loop ((arcs arcs) (n-arcs '()))
(if (null? arcs)
n-arcs
(loop (cdr arcs) (n2d-insert-arc (car arcs) n-arcs))))))
Transformer une liste d'arcs quelconques en des arcs a classes et a
; destinations distinctes
(define n2d-normalize-arcs
(lambda (arcs)
(n2d-factorize-arcs (n2d-distinguish-arcs arcs))))
Factoriser des arcs a destination unique ( ~deterministes )
(define n2d-factorize-darcs
(lambda (arcs)
(if (null? arcs)
'()
(let* ((arc (car arcs))
(arc-end (cdr arc))
(other-arcs (cdr arcs))
(farcs (n2d-factorize-darcs other-arcs)))
(let loop ((farcs farcs))
(if (null? farcs)
(list arc)
(let* ((farc (car farcs))
(farc-end (cdr farc)))
(if (= farc-end arc-end)
(let* ((arc-class (car arc))
(farc-class (car farc))
(new-class (class-union farc-class arc-class))
(new-arc (cons new-class arc-end)))
(cons new-arc (cdr farcs)))
(cons farc (loop (cdr farcs)))))))))))
(define n2d-normalize-arcs-v
(lambda (arcs-v)
(let* ((nbnodes (vector-length arcs-v))
(new-v (make-vector nbnodes)))
(let loop ((n 0))
(if (= n nbnodes)
new-v
(begin
(vector-set! new-v n (n2d-normalize-arcs (vector-ref arcs-v n)))
(loop (+ n 1))))))))
une liste d'arcs a classes distinctes en separant
les arcs contenant une partie de la classe du nouvel arc des autres arcs
: ( oui . non )
(define n2d-ins-sep-arc
(lambda (new-arc arcs)
(if (null? arcs)
(cons (list new-arc) '())
(let* ((arc (car arcs))
(others (cdr arcs))
(result (n2d-2arcs new-arc arc))
(arcl (vector-ref result 0))
(arcc (vector-ref result 1))
(arcr (vector-ref result 2))
(l-arcc (if arcc (list arcc) '()))
(l-arcr (if arcr (list arcr) '()))
(result (if arcl
(n2d-ins-sep-arc arcl others)
(cons '() others)))
(oui-arcs (car result))
(non-arcs (cdr result)))
(cons (append l-arcc oui-arcs) (append l-arcr non-arcs))))))
Combiner deux listes d'arcs a classes distinctes
; Ne tente pas de combiner les arcs qui ont nec. des classes disjointes
; Conjecture: les arcs crees ont leurs classes disjointes
Note : envisager de rajouter un " n2d - factorize - arcs " ! ! ! ! ! ! ! ! ! ! ! !
(define n2d-combine-arcs
(lambda (arcs1 arcs2)
(let loop ((arcs1 arcs1) (arcs2 arcs2) (dist-arcs2 '()))
(if (null? arcs1)
(append arcs2 dist-arcs2)
(let* ((arc (car arcs1))
(result (n2d-ins-sep-arc arc arcs2))
(oui-arcs (car result))
(non-arcs (cdr result)))
(loop (cdr arcs1) non-arcs (append oui-arcs dist-arcs2)))))))
; ;
; Section temporaire :
; Dictionnaire d'etat det . Recherche lineaire . Creation naive
; ; des arcs d'un ensemble d'etats.
; ;
;
; variables globales
; (define n2d-state-dict '#(#f))
; (define n2d-state-len 1)
; (define n2d-state-count 0)
;
; Fonctions de gestion des entrees du dictionnaire
; (define make-dentry (lambda (ss) (vector ss #f #f)))
;
( define get - dentry - ss ( lambda ( dentry ) ( vector - ref dentry 0 ) ) )
; (define get-dentry-darcs (lambda (dentry) (vector-ref dentry 1)))
( define get - dentry - acc ( lambda ( dentry ) ( vector - ref dentry 2 ) ) )
;
; (define set-dentry-darcs (lambda (dentry arcs) (vector-set! dentry 1 arcs)))
( define set - dentry - acc ( lambda ( dentry acc ) ( vector - set ! dentry 2 acc ) ) )
;
; ; Initialisation des variables globales
; (define n2d-init-glob-vars
; (lambda ()
; (set! n2d-state-dict (vector #f))
; (set! n2d-state-len 1)
; (set! n2d-state-count 0)))
;
; ; Extension du dictionnaire
; (define n2d-extend-dict
; (lambda ()
( let * ( ( new - len ( * 2 n2d - state - len ) )
; (v (make-vector new-len #f)))
; (let loop ((n 0))
; (if (= n n2d-state-count)
; (begin
; (set! n2d-state-dict v)
; (set! n2d-state-len new-len))
; (begin
; (vector-set! v n (vector-ref n2d-state-dict n))
; (loop (+ n 1))))))))
;
;
; (define n2d-add-state
; (lambda (ss)
; (let* ((s n2d-state-count)
( dentry ( make - dentry ss ) ) )
; (if (= n2d-state-count n2d-state-len)
; (n2d-extend-dict))
; (vector-set! n2d-state-dict s dentry)
( set ! n2d - state - count ( + n2d - state - count 1 ) )
; s)))
;
; Recherche d'un etat
; (define n2d-search-state
; (lambda (ss)
; (let loop ((n 0))
; (if (= n n2d-state-count)
; (n2d-add-state ss)
; (let* ((dentry (vector-ref n2d-state-dict n))
( dentry - ss ( get - dentry - ss dentry ) ) )
( if ( equal ? dentry - ss ss )
; n
; (loop (+ n 1))))))))
;
; Transformer un arc non - det . en un arc det .
; (define n2d-translate-arc
; (lambda (arc)
; (let* ((class (car arc))
; (ss (cdr arc))
; (s (n2d-search-state ss)))
; (cons class s))))
;
; Transformer une liste d'arcs . en ...
; (define n2d-translate-arcs
; (lambda (arcs)
; (map n2d-translate-arc arcs)))
;
; Trouver le minimum de deux acceptants
( define n2d - acc - min2
; (let ((acc-min (lambda (rule1 rule2)
; (cond ((not rule1)
)
( ( not )
; rule1)
; (else
; (min rule1 rule2))))))
; (lambda (acc1 acc2)
( cons ( acc - min ( car acc1 ) ( car acc2 ) )
( acc - min ( cdr acc1 ) ( cdr acc2 ) ) ) ) ) )
;
; Trouver le minimum de plusieurs acceptants
; (define n2d-acc-mins
; (lambda (accs)
( if ( null ? )
( cons # f # f )
( n2d - acc - min2 ( car accs ) ( n2d - acc - mins ( ) ) ) ) ) )
;
;
; (define n2d-extract-vs
; (lambda ()
; (let* ((arcs-v (make-vector n2d-state-count))
( acc - v ( make - vector n2d - state - count ) ) )
; (let loop ((n 0))
; (if (= n n2d-state-count)
; (cons arcs-v acc-v)
; (begin
; (vector-set! arcs-v n (get-dentry-darcs
; (vector-ref n2d-state-dict n)))
( vector - set ! acc - v n ( get - dentry - acc
; (vector-ref n2d-state-dict n)))
; (loop (+ n 1))))))))
;
; Effectuer la transformation de l'automate de non - det . a det .
( define nfa2dfa
( lambda ( nl - start no - nl - start arcs - v acc - v )
; (n2d-init-glob-vars)
( let * ( ( nl - d ( n2d - search - state nl - start ) )
( no - nl - d ( n2d - search - state no - nl - start ) ) )
; (let loop ((n 0))
; (if (< n n2d-state-count)
; (let* ((dentry (vector-ref n2d-state-dict n))
( ss ( get - dentry - ss dentry ) )
; (arcss (map (lambda (s) (vector-ref arcs-v s)) ss))
( arcs ( apply append ) )
; (dist-arcs (n2d-distinguish-arcs arcs))
; (darcs (n2d-translate-arcs dist-arcs))
; (fact-darcs (n2d-factorize-darcs darcs))
; (accs (map (lambda (s) (vector-ref acc-v s)) ss))
( acc ( n2d - acc - mins accs ) ) )
( set - dentry - darcs dentry fact - darcs )
( set - dentry - acc dentry acc )
; (loop (+ n 1)))))
; (let* ((result (n2d-extract-vs))
; (new-arcs-v (car result))
; (new-acc-v (cdr result)))
; (n2d-init-glob-vars)
( list nl - d no - nl - d new - arcs - v new - acc - v ) ) ) ) )
; ;
; Section temporaire :
; Dictionnaire d'etat det . Recherche lineaire . Creation des
; arcs d'un ensemble d'etats en a
; ; classes distinctes.
; ;
;
; variables globales
; (define n2d-state-dict '#(#f))
; (define n2d-state-len 1)
; (define n2d-state-count 0)
;
; Fonctions de gestion des entrees du dictionnaire
; (define make-dentry (lambda (ss) (vector ss #f #f)))
;
( define get - dentry - ss ( lambda ( dentry ) ( vector - ref dentry 0 ) ) )
; (define get-dentry-darcs (lambda (dentry) (vector-ref dentry 1)))
( define get - dentry - acc ( lambda ( dentry ) ( vector - ref dentry 2 ) ) )
;
; (define set-dentry-darcs (lambda (dentry arcs) (vector-set! dentry 1 arcs)))
( define set - dentry - acc ( lambda ( dentry acc ) ( vector - set ! dentry 2 acc ) ) )
;
; ; Initialisation des variables globales
; (define n2d-init-glob-vars
; (lambda ()
; (set! n2d-state-dict (vector #f))
; (set! n2d-state-len 1)
; (set! n2d-state-count 0)))
;
; ; Extension du dictionnaire
; (define n2d-extend-dict
; (lambda ()
( let * ( ( new - len ( * 2 n2d - state - len ) )
; (v (make-vector new-len #f)))
; (let loop ((n 0))
; (if (= n n2d-state-count)
; (begin
; (set! n2d-state-dict v)
; (set! n2d-state-len new-len))
; (begin
; (vector-set! v n (vector-ref n2d-state-dict n))
; (loop (+ n 1))))))))
;
;
; (define n2d-add-state
; (lambda (ss)
; (let* ((s n2d-state-count)
( dentry ( make - dentry ss ) ) )
; (if (= n2d-state-count n2d-state-len)
; (n2d-extend-dict))
; (vector-set! n2d-state-dict s dentry)
( set ! n2d - state - count ( + n2d - state - count 1 ) )
; s)))
;
; Recherche d'un etat
; (define n2d-search-state
; (lambda (ss)
; (let loop ((n 0))
; (if (= n n2d-state-count)
; (n2d-add-state ss)
; (let* ((dentry (vector-ref n2d-state-dict n))
( dentry - ss ( get - dentry - ss dentry ) ) )
( if ( equal ? dentry - ss ss )
; n
; (loop (+ n 1))))))))
;
; Combiner des listes d'arcs a classes dictinctes
; (define n2d-combine-arcs-l
; (lambda (arcs-l)
; (if (null? arcs-l)
; '()
; (let* ((arcs (car arcs-l))
; (other-arcs-l (cdr arcs-l))
; (other-arcs (n2d-combine-arcs-l other-arcs-l)))
; (n2d-combine-arcs arcs other-arcs)))))
;
; Transformer un arc non - det . en un arc det .
; (define n2d-translate-arc
; (lambda (arc)
; (let* ((class (car arc))
; (ss (cdr arc))
; (s (n2d-search-state ss)))
; (cons class s))))
;
; Transformer une liste d'arcs . en ...
; (define n2d-translate-arcs
; (lambda (arcs)
; (map n2d-translate-arc arcs)))
;
; Trouver le minimum de deux acceptants
( define n2d - acc - min2
; (let ((acc-min (lambda (rule1 rule2)
; (cond ((not rule1)
)
( ( not )
; rule1)
; (else
; (min rule1 rule2))))))
; (lambda (acc1 acc2)
( cons ( acc - min ( car acc1 ) ( car acc2 ) )
( acc - min ( cdr acc1 ) ( cdr acc2 ) ) ) ) ) )
;
; Trouver le minimum de plusieurs acceptants
; (define n2d-acc-mins
; (lambda (accs)
( if ( null ? )
( cons # f # f )
( n2d - acc - min2 ( car accs ) ( n2d - acc - mins ( ) ) ) ) ) )
;
;
; (define n2d-extract-vs
; (lambda ()
; (let* ((arcs-v (make-vector n2d-state-count))
( acc - v ( make - vector n2d - state - count ) ) )
; (let loop ((n 0))
; (if (= n n2d-state-count)
; (cons arcs-v acc-v)
; (begin
; (vector-set! arcs-v n (get-dentry-darcs
; (vector-ref n2d-state-dict n)))
( vector - set ! acc - v n ( get - dentry - acc
; (vector-ref n2d-state-dict n)))
; (loop (+ n 1))))))))
;
; Effectuer la transformation de l'automate de non - det . a det .
( define nfa2dfa
( lambda ( nl - start no - nl - start arcs - v acc - v )
; (n2d-init-glob-vars)
( let * ( ( nl - d ( n2d - search - state nl - start ) )
( no - nl - d ( n2d - search - state no - nl - start ) )
; (norm-arcs-v (n2d-normalize-arcs-v arcs-v)))
; (let loop ((n 0))
; (if (< n n2d-state-count)
; (let* ((dentry (vector-ref n2d-state-dict n))
( ss ( get - dentry - ss dentry ) )
; (arcs-l (map (lambda (s) (vector-ref norm-arcs-v s)) ss))
; (arcs (n2d-combine-arcs-l arcs-l))
; (darcs (n2d-translate-arcs arcs))
; (fact-darcs (n2d-factorize-darcs darcs))
; (accs (map (lambda (s) (vector-ref acc-v s)) ss))
( acc ( n2d - acc - mins accs ) ) )
( set - dentry - darcs dentry fact - darcs )
( set - dentry - acc dentry acc )
; (loop (+ n 1)))))
; (let* ((result (n2d-extract-vs))
; (new-arcs-v (car result))
; (new-acc-v (cdr result)))
; (n2d-init-glob-vars)
( list nl - d no - nl - d new - arcs - v new - acc - v ) ) ) ) )
; ;
; Section temporaire :
; Dictionnaire d'etat det . Arbre de recherche . Creation des
; arcs d'un ensemble d'etats en a
; ; classes distinctes.
; ;
;
; variables globales
; (define n2d-state-dict '#(#f))
; (define n2d-state-len 1)
; (define n2d-state-count 0)
; (define n2d-state-tree '#(#f ()))
;
; Fonctions de gestion des entrees du dictionnaire
; (define make-dentry (lambda (ss) (vector ss #f #f)))
;
( define get - dentry - ss ( lambda ( dentry ) ( vector - ref dentry 0 ) ) )
; (define get-dentry-darcs (lambda (dentry) (vector-ref dentry 1)))
( define get - dentry - acc ( lambda ( dentry ) ( vector - ref dentry 2 ) ) )
;
; (define set-dentry-darcs (lambda (dentry arcs) (vector-set! dentry 1 arcs)))
( define set - dentry - acc ( lambda ( dentry acc ) ( vector - set ! dentry 2 acc ) ) )
;
; Fonctions de gestion de l'arbre de recherche
; (define make-snode (lambda () (vector #f '())))
;
; (define get-snode-dstate (lambda (snode) (vector-ref snode 0)))
; (define get-snode-children (lambda (snode) (vector-ref snode 1)))
;
; (define set-snode-dstate
( lambda ( snode dstate ) ( vector - set ! snode 0 dstate ) ) )
; (define set-snode-children
( lambda ( snode children ) ( vector - set ! snode 1 children ) ) )
;
; ; Initialisation des variables globales
; (define n2d-init-glob-vars
; (lambda ()
; (set! n2d-state-dict (vector #f))
; (set! n2d-state-len 1)
; (set! n2d-state-count 0)
; (set! n2d-state-tree (make-snode))))
;
; ; Extension du dictionnaire
; (define n2d-extend-dict
; (lambda ()
( let * ( ( new - len ( * 2 n2d - state - len ) )
; (v (make-vector new-len #f)))
; (let loop ((n 0))
; (if (= n n2d-state-count)
; (begin
; (set! n2d-state-dict v)
; (set! n2d-state-len new-len))
; (begin
; (vector-set! v n (vector-ref n2d-state-dict n))
; (loop (+ n 1))))))))
;
;
; (define n2d-add-state
; (lambda (ss)
; (let* ((s n2d-state-count)
( dentry ( make - dentry ss ) ) )
; (if (= n2d-state-count n2d-state-len)
; (n2d-extend-dict))
; (vector-set! n2d-state-dict s dentry)
( set ! n2d - state - count ( + n2d - state - count 1 ) )
; s)))
;
; Recherche d'un etat
; (define n2d-search-state
; (lambda (ss)
; (let loop ((s-l ss) (snode n2d-state-tree))
; (if (null? s-l)
; (or (get-snode-dstate snode)
; (let ((s (n2d-add-state ss)))
; (set-snode-dstate snode s)
; s))
; (let* ((next-s (car s-l))
; (alist (get-snode-children snode))
( ass ( or ( assv next - s alist )
; (let ((ass (cons next-s (make-snode))))
; (set-snode-children snode (cons ass alist))
; ass))))
; (loop (cdr s-l) (cdr ass)))))))
;
; Combiner des listes d'arcs a classes dictinctes
; (define n2d-combine-arcs-l
; (lambda (arcs-l)
; (if (null? arcs-l)
; '()
; (let* ((arcs (car arcs-l))
; (other-arcs-l (cdr arcs-l))
; (other-arcs (n2d-combine-arcs-l other-arcs-l)))
; (n2d-combine-arcs arcs other-arcs)))))
;
; Transformer un arc non - det . en un arc det .
; (define n2d-translate-arc
; (lambda (arc)
; (let* ((class (car arc))
; (ss (cdr arc))
; (s (n2d-search-state ss)))
; (cons class s))))
;
; Transformer une liste d'arcs . en ...
; (define n2d-translate-arcs
; (lambda (arcs)
; (map n2d-translate-arc arcs)))
;
; Trouver le minimum de deux acceptants
( define n2d - acc - min2
; (let ((acc-min (lambda (rule1 rule2)
; (cond ((not rule1)
)
( ( not )
; rule1)
; (else
; (min rule1 rule2))))))
; (lambda (acc1 acc2)
( cons ( acc - min ( car acc1 ) ( car acc2 ) )
( acc - min ( cdr acc1 ) ( cdr acc2 ) ) ) ) ) )
;
; Trouver le minimum de plusieurs acceptants
; (define n2d-acc-mins
; (lambda (accs)
( if ( null ? )
( cons # f # f )
( n2d - acc - min2 ( car accs ) ( n2d - acc - mins ( ) ) ) ) ) )
;
;
; (define n2d-extract-vs
; (lambda ()
; (let* ((arcs-v (make-vector n2d-state-count))
( acc - v ( make - vector n2d - state - count ) ) )
; (let loop ((n 0))
; (if (= n n2d-state-count)
; (cons arcs-v acc-v)
; (begin
; (vector-set! arcs-v n (get-dentry-darcs
; (vector-ref n2d-state-dict n)))
( vector - set ! acc - v n ( get - dentry - acc
; (vector-ref n2d-state-dict n)))
; (loop (+ n 1))))))))
;
; Effectuer la transformation de l'automate de non - det . a det .
( define nfa2dfa
( lambda ( nl - start no - nl - start arcs - v acc - v )
; (n2d-init-glob-vars)
( let * ( ( nl - d ( n2d - search - state nl - start ) )
( no - nl - d ( n2d - search - state no - nl - start ) )
; (norm-arcs-v (n2d-normalize-arcs-v arcs-v)))
; (let loop ((n 0))
; (if (< n n2d-state-count)
; (let* ((dentry (vector-ref n2d-state-dict n))
( ss ( get - dentry - ss dentry ) )
; (arcs-l (map (lambda (s) (vector-ref norm-arcs-v s)) ss))
; (arcs (n2d-combine-arcs-l arcs-l))
; (darcs (n2d-translate-arcs arcs))
; (fact-darcs (n2d-factorize-darcs darcs))
; (accs (map (lambda (s) (vector-ref acc-v s)) ss))
( acc ( n2d - acc - mins accs ) ) )
( set - dentry - darcs dentry fact - darcs )
( set - dentry - acc dentry acc )
; (loop (+ n 1)))))
; (let* ((result (n2d-extract-vs))
; (new-arcs-v (car result))
; (new-acc-v (cdr result)))
; (n2d-init-glob-vars)
( list nl - d no - nl - d new - arcs - v new - acc - v ) ) ) ) )
;
Section temporaire :
Dictionnaire d'etat det . Table de hashage . Creation des
arcs d'un ensemble d'etats en a
; classes distinctes.
;
; Quelques variables globales
(define n2d-state-dict '#(#f))
(define n2d-state-len 1)
(define n2d-state-count 0)
(define n2d-state-hash '#())
; Fonctions de gestion des entrees du dictionnaire
(define make-dentry (lambda (ss) (vector ss #f #f)))
(define get-dentry-ss (lambda (dentry) (vector-ref dentry 0)))
(define get-dentry-darcs (lambda (dentry) (vector-ref dentry 1)))
(define get-dentry-acc (lambda (dentry) (vector-ref dentry 2)))
(define set-dentry-darcs (lambda (dentry arcs) (vector-set! dentry 1 arcs)))
(define set-dentry-acc (lambda (dentry acc) (vector-set! dentry 2 acc)))
; Initialisation des variables globales
(define n2d-init-glob-vars
(lambda (hash-len)
(set! n2d-state-dict (vector #f))
(set! n2d-state-len 1)
(set! n2d-state-count 0)
(set! n2d-state-hash (make-vector hash-len '()))))
; Extension du dictionnaire
(define n2d-extend-dict
(lambda ()
(let* ((new-len (* 2 n2d-state-len))
(v (make-vector new-len #f)))
(let loop ((n 0))
(if (= n n2d-state-count)
(begin
(set! n2d-state-dict v)
(set! n2d-state-len new-len))
(begin
(vector-set! v n (vector-ref n2d-state-dict n))
(loop (+ n 1))))))))
(define n2d-add-state
(lambda (ss)
(let* ((s n2d-state-count)
(dentry (make-dentry ss)))
(if (= n2d-state-count n2d-state-len)
(n2d-extend-dict))
(vector-set! n2d-state-dict s dentry)
(set! n2d-state-count (+ n2d-state-count 1))
s)))
Recherche d'un etat
(define n2d-search-state
(lambda (ss)
(let* ((hash-no (if (null? ss) 0 (car ss)))
(alist (vector-ref n2d-state-hash hash-no))
(ass (assoc ss alist)))
(if ass
(cdr ass)
(let* ((s (n2d-add-state ss))
(new-ass (cons ss s)))
(vector-set! n2d-state-hash hash-no (cons new-ass alist))
s)))))
Combiner des listes d'arcs a classes dictinctes
(define n2d-combine-arcs-l
(lambda (arcs-l)
(if (null? arcs-l)
'()
(let* ((arcs (car arcs-l))
(other-arcs-l (cdr arcs-l))
(other-arcs (n2d-combine-arcs-l other-arcs-l)))
(n2d-combine-arcs arcs other-arcs)))))
Transformer un arc non - det . en un arc det .
(define n2d-translate-arc
(lambda (arc)
(let* ((class (car arc))
(ss (cdr arc))
(s (n2d-search-state ss)))
(cons class s))))
Transformer une liste d'arcs . en ...
(define n2d-translate-arcs
(lambda (arcs)
(map n2d-translate-arc arcs)))
Trouver le minimum de deux acceptants
(define n2d-acc-min2
(let ((acc-min (lambda (rule1 rule2)
(cond ((not rule1)
rule2)
((not rule2)
rule1)
(else
(min rule1 rule2))))))
(lambda (acc1 acc2)
(cons (acc-min (car acc1) (car acc2))
(acc-min (cdr acc1) (cdr acc2))))))
Trouver le minimum de plusieurs acceptants
(define n2d-acc-mins
(lambda (accs)
(if (null? accs)
(cons #f #f)
(n2d-acc-min2 (car accs) (n2d-acc-mins (cdr accs))))))
; Fabriquer les vecteurs d'arcs et d'acceptance
(define n2d-extract-vs
(lambda ()
(let* ((arcs-v (make-vector n2d-state-count))
(acc-v (make-vector n2d-state-count)))
(let loop ((n 0))
(if (= n n2d-state-count)
(cons arcs-v acc-v)
(begin
(vector-set! arcs-v n (get-dentry-darcs
(vector-ref n2d-state-dict n)))
(vector-set! acc-v n (get-dentry-acc
(vector-ref n2d-state-dict n)))
(loop (+ n 1))))))))
Effectuer la transformation de l'automate de non - det . a det .
(define nfa2dfa
(lambda (nl-start no-nl-start arcs-v acc-v)
(n2d-init-glob-vars (vector-length arcs-v))
(let* ((nl-d (n2d-search-state nl-start))
(no-nl-d (n2d-search-state no-nl-start))
(norm-arcs-v (n2d-normalize-arcs-v arcs-v)))
(let loop ((n 0))
(if (< n n2d-state-count)
(let* ((dentry (vector-ref n2d-state-dict n))
(ss (get-dentry-ss dentry))
(arcs-l (map (lambda (s) (vector-ref norm-arcs-v s)) ss))
(arcs (n2d-combine-arcs-l arcs-l))
(darcs (n2d-translate-arcs arcs))
(fact-darcs (n2d-factorize-darcs darcs))
(accs (map (lambda (s) (vector-ref acc-v s)) ss))
(acc (n2d-acc-mins accs)))
(set-dentry-darcs dentry fact-darcs)
(set-dentry-acc dentry acc)
(loop (+ n 1)))))
(let* ((result (n2d-extract-vs))
(new-arcs-v (car result))
(new-acc-v (cdr result)))
(n2d-init-glob-vars 0)
(list nl-d no-nl-d new-arcs-v new-acc-v)))))
| null | https://raw.githubusercontent.com/okuoku/nausicaa/50e7b4d4141ad4d81051588608677223fe9fb715/scheme/src/foreign/silex-1.0/nfa2dfa.scm | scheme |
This program is free software; you can redistribute it and/or
either version 2
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, write to the Free Software
Recoupement de deux arcs
destinations distinctes
Ne tente pas de combiner les arcs qui ont nec. des classes disjointes
Conjecture: les arcs crees ont leurs classes disjointes
;
Section temporaire :
Dictionnaire d'etat det . Recherche lineaire . Creation naive
; des arcs d'un ensemble d'etats.
;
variables globales
(define n2d-state-dict '#(#f))
(define n2d-state-len 1)
(define n2d-state-count 0)
Fonctions de gestion des entrees du dictionnaire
(define make-dentry (lambda (ss) (vector ss #f #f)))
(define get-dentry-darcs (lambda (dentry) (vector-ref dentry 1)))
(define set-dentry-darcs (lambda (dentry arcs) (vector-set! dentry 1 arcs)))
; Initialisation des variables globales
(define n2d-init-glob-vars
(lambda ()
(set! n2d-state-dict (vector #f))
(set! n2d-state-len 1)
(set! n2d-state-count 0)))
; Extension du dictionnaire
(define n2d-extend-dict
(lambda ()
(v (make-vector new-len #f)))
(let loop ((n 0))
(if (= n n2d-state-count)
(begin
(set! n2d-state-dict v)
(set! n2d-state-len new-len))
(begin
(vector-set! v n (vector-ref n2d-state-dict n))
(loop (+ n 1))))))))
(define n2d-add-state
(lambda (ss)
(let* ((s n2d-state-count)
(if (= n2d-state-count n2d-state-len)
(n2d-extend-dict))
(vector-set! n2d-state-dict s dentry)
s)))
Recherche d'un etat
(define n2d-search-state
(lambda (ss)
(let loop ((n 0))
(if (= n n2d-state-count)
(n2d-add-state ss)
(let* ((dentry (vector-ref n2d-state-dict n))
n
(loop (+ n 1))))))))
Transformer un arc non - det . en un arc det .
(define n2d-translate-arc
(lambda (arc)
(let* ((class (car arc))
(ss (cdr arc))
(s (n2d-search-state ss)))
(cons class s))))
Transformer une liste d'arcs . en ...
(define n2d-translate-arcs
(lambda (arcs)
(map n2d-translate-arc arcs)))
Trouver le minimum de deux acceptants
(let ((acc-min (lambda (rule1 rule2)
(cond ((not rule1)
rule1)
(else
(min rule1 rule2))))))
(lambda (acc1 acc2)
Trouver le minimum de plusieurs acceptants
(define n2d-acc-mins
(lambda (accs)
(define n2d-extract-vs
(lambda ()
(let* ((arcs-v (make-vector n2d-state-count))
(let loop ((n 0))
(if (= n n2d-state-count)
(cons arcs-v acc-v)
(begin
(vector-set! arcs-v n (get-dentry-darcs
(vector-ref n2d-state-dict n)))
(vector-ref n2d-state-dict n)))
(loop (+ n 1))))))))
Effectuer la transformation de l'automate de non - det . a det .
(n2d-init-glob-vars)
(let loop ((n 0))
(if (< n n2d-state-count)
(let* ((dentry (vector-ref n2d-state-dict n))
(arcss (map (lambda (s) (vector-ref arcs-v s)) ss))
(dist-arcs (n2d-distinguish-arcs arcs))
(darcs (n2d-translate-arcs dist-arcs))
(fact-darcs (n2d-factorize-darcs darcs))
(accs (map (lambda (s) (vector-ref acc-v s)) ss))
(loop (+ n 1)))))
(let* ((result (n2d-extract-vs))
(new-arcs-v (car result))
(new-acc-v (cdr result)))
(n2d-init-glob-vars)
;
Section temporaire :
Dictionnaire d'etat det . Recherche lineaire . Creation des
arcs d'un ensemble d'etats en a
; classes distinctes.
;
variables globales
(define n2d-state-dict '#(#f))
(define n2d-state-len 1)
(define n2d-state-count 0)
Fonctions de gestion des entrees du dictionnaire
(define make-dentry (lambda (ss) (vector ss #f #f)))
(define get-dentry-darcs (lambda (dentry) (vector-ref dentry 1)))
(define set-dentry-darcs (lambda (dentry arcs) (vector-set! dentry 1 arcs)))
; Initialisation des variables globales
(define n2d-init-glob-vars
(lambda ()
(set! n2d-state-dict (vector #f))
(set! n2d-state-len 1)
(set! n2d-state-count 0)))
; Extension du dictionnaire
(define n2d-extend-dict
(lambda ()
(v (make-vector new-len #f)))
(let loop ((n 0))
(if (= n n2d-state-count)
(begin
(set! n2d-state-dict v)
(set! n2d-state-len new-len))
(begin
(vector-set! v n (vector-ref n2d-state-dict n))
(loop (+ n 1))))))))
(define n2d-add-state
(lambda (ss)
(let* ((s n2d-state-count)
(if (= n2d-state-count n2d-state-len)
(n2d-extend-dict))
(vector-set! n2d-state-dict s dentry)
s)))
Recherche d'un etat
(define n2d-search-state
(lambda (ss)
(let loop ((n 0))
(if (= n n2d-state-count)
(n2d-add-state ss)
(let* ((dentry (vector-ref n2d-state-dict n))
n
(loop (+ n 1))))))))
Combiner des listes d'arcs a classes dictinctes
(define n2d-combine-arcs-l
(lambda (arcs-l)
(if (null? arcs-l)
'()
(let* ((arcs (car arcs-l))
(other-arcs-l (cdr arcs-l))
(other-arcs (n2d-combine-arcs-l other-arcs-l)))
(n2d-combine-arcs arcs other-arcs)))))
Transformer un arc non - det . en un arc det .
(define n2d-translate-arc
(lambda (arc)
(let* ((class (car arc))
(ss (cdr arc))
(s (n2d-search-state ss)))
(cons class s))))
Transformer une liste d'arcs . en ...
(define n2d-translate-arcs
(lambda (arcs)
(map n2d-translate-arc arcs)))
Trouver le minimum de deux acceptants
(let ((acc-min (lambda (rule1 rule2)
(cond ((not rule1)
rule1)
(else
(min rule1 rule2))))))
(lambda (acc1 acc2)
Trouver le minimum de plusieurs acceptants
(define n2d-acc-mins
(lambda (accs)
(define n2d-extract-vs
(lambda ()
(let* ((arcs-v (make-vector n2d-state-count))
(let loop ((n 0))
(if (= n n2d-state-count)
(cons arcs-v acc-v)
(begin
(vector-set! arcs-v n (get-dentry-darcs
(vector-ref n2d-state-dict n)))
(vector-ref n2d-state-dict n)))
(loop (+ n 1))))))))
Effectuer la transformation de l'automate de non - det . a det .
(n2d-init-glob-vars)
(norm-arcs-v (n2d-normalize-arcs-v arcs-v)))
(let loop ((n 0))
(if (< n n2d-state-count)
(let* ((dentry (vector-ref n2d-state-dict n))
(arcs-l (map (lambda (s) (vector-ref norm-arcs-v s)) ss))
(arcs (n2d-combine-arcs-l arcs-l))
(darcs (n2d-translate-arcs arcs))
(fact-darcs (n2d-factorize-darcs darcs))
(accs (map (lambda (s) (vector-ref acc-v s)) ss))
(loop (+ n 1)))))
(let* ((result (n2d-extract-vs))
(new-arcs-v (car result))
(new-acc-v (cdr result)))
(n2d-init-glob-vars)
;
Section temporaire :
Dictionnaire d'etat det . Arbre de recherche . Creation des
arcs d'un ensemble d'etats en a
; classes distinctes.
;
variables globales
(define n2d-state-dict '#(#f))
(define n2d-state-len 1)
(define n2d-state-count 0)
(define n2d-state-tree '#(#f ()))
Fonctions de gestion des entrees du dictionnaire
(define make-dentry (lambda (ss) (vector ss #f #f)))
(define get-dentry-darcs (lambda (dentry) (vector-ref dentry 1)))
(define set-dentry-darcs (lambda (dentry arcs) (vector-set! dentry 1 arcs)))
Fonctions de gestion de l'arbre de recherche
(define make-snode (lambda () (vector #f '())))
(define get-snode-dstate (lambda (snode) (vector-ref snode 0)))
(define get-snode-children (lambda (snode) (vector-ref snode 1)))
(define set-snode-dstate
(define set-snode-children
; Initialisation des variables globales
(define n2d-init-glob-vars
(lambda ()
(set! n2d-state-dict (vector #f))
(set! n2d-state-len 1)
(set! n2d-state-count 0)
(set! n2d-state-tree (make-snode))))
; Extension du dictionnaire
(define n2d-extend-dict
(lambda ()
(v (make-vector new-len #f)))
(let loop ((n 0))
(if (= n n2d-state-count)
(begin
(set! n2d-state-dict v)
(set! n2d-state-len new-len))
(begin
(vector-set! v n (vector-ref n2d-state-dict n))
(loop (+ n 1))))))))
(define n2d-add-state
(lambda (ss)
(let* ((s n2d-state-count)
(if (= n2d-state-count n2d-state-len)
(n2d-extend-dict))
(vector-set! n2d-state-dict s dentry)
s)))
Recherche d'un etat
(define n2d-search-state
(lambda (ss)
(let loop ((s-l ss) (snode n2d-state-tree))
(if (null? s-l)
(or (get-snode-dstate snode)
(let ((s (n2d-add-state ss)))
(set-snode-dstate snode s)
s))
(let* ((next-s (car s-l))
(alist (get-snode-children snode))
(let ((ass (cons next-s (make-snode))))
(set-snode-children snode (cons ass alist))
ass))))
(loop (cdr s-l) (cdr ass)))))))
Combiner des listes d'arcs a classes dictinctes
(define n2d-combine-arcs-l
(lambda (arcs-l)
(if (null? arcs-l)
'()
(let* ((arcs (car arcs-l))
(other-arcs-l (cdr arcs-l))
(other-arcs (n2d-combine-arcs-l other-arcs-l)))
(n2d-combine-arcs arcs other-arcs)))))
Transformer un arc non - det . en un arc det .
(define n2d-translate-arc
(lambda (arc)
(let* ((class (car arc))
(ss (cdr arc))
(s (n2d-search-state ss)))
(cons class s))))
Transformer une liste d'arcs . en ...
(define n2d-translate-arcs
(lambda (arcs)
(map n2d-translate-arc arcs)))
Trouver le minimum de deux acceptants
(let ((acc-min (lambda (rule1 rule2)
(cond ((not rule1)
rule1)
(else
(min rule1 rule2))))))
(lambda (acc1 acc2)
Trouver le minimum de plusieurs acceptants
(define n2d-acc-mins
(lambda (accs)
(define n2d-extract-vs
(lambda ()
(let* ((arcs-v (make-vector n2d-state-count))
(let loop ((n 0))
(if (= n n2d-state-count)
(cons arcs-v acc-v)
(begin
(vector-set! arcs-v n (get-dentry-darcs
(vector-ref n2d-state-dict n)))
(vector-ref n2d-state-dict n)))
(loop (+ n 1))))))))
Effectuer la transformation de l'automate de non - det . a det .
(n2d-init-glob-vars)
(norm-arcs-v (n2d-normalize-arcs-v arcs-v)))
(let loop ((n 0))
(if (< n n2d-state-count)
(let* ((dentry (vector-ref n2d-state-dict n))
(arcs-l (map (lambda (s) (vector-ref norm-arcs-v s)) ss))
(arcs (n2d-combine-arcs-l arcs-l))
(darcs (n2d-translate-arcs arcs))
(fact-darcs (n2d-factorize-darcs darcs))
(accs (map (lambda (s) (vector-ref acc-v s)) ss))
(loop (+ n 1)))))
(let* ((result (n2d-extract-vs))
(new-arcs-v (car result))
(new-acc-v (cdr result)))
(n2d-init-glob-vars)
classes distinctes.
Quelques variables globales
Fonctions de gestion des entrees du dictionnaire
Initialisation des variables globales
Extension du dictionnaire
Fabriquer les vecteurs d'arcs et d'acceptance | SILex - Scheme Implementation of Lex
Copyright ( C ) 2001
modify it under the terms of the GNU General Public License
of the License , or ( at your option ) any later version .
You should have received a copy of the GNU General Public License
Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
(define n2d-2arcs
(lambda (arc1 arc2)
(let* ((class1 (car arc1))
(ss1 (cdr arc1))
(class2 (car arc2))
(ss2 (cdr arc2))
(result (class-sep class1 class2))
(classl (vector-ref result 0))
(classc (vector-ref result 1))
(classr (vector-ref result 2))
(ssl ss1)
(ssc (ss-union ss1 ss2))
(ssr ss2))
(vector (if (or (null? classl) (null? ssl)) #f (cons classl ssl))
(if (or (null? classc) (null? ssc)) #f (cons classc ssc))
(if (or (null? classr) (null? ssr)) #f (cons classr ssr))))))
Insertion d'un arc dans une liste d'arcs a classes distinctes
(define n2d-insert-arc
(lambda (new-arc arcs)
(if (null? arcs)
(list new-arc)
(let* ((arc (car arcs))
(others (cdr arcs))
(result (n2d-2arcs new-arc arc))
(arcl (vector-ref result 0))
(arcc (vector-ref result 1))
(arcr (vector-ref result 2))
(list-arcc (if arcc (list arcc) '()))
(list-arcr (if arcr (list arcr) '())))
(if arcl
(append list-arcc list-arcr (n2d-insert-arc arcl others))
(append list-arcc list-arcr others))))))
Regroupement des arcs qui aboutissent au meme sous - ensemble d'etats
(define n2d-factorize-arcs
(lambda (arcs)
(if (null? arcs)
'()
(let* ((arc (car arcs))
(arc-ss (cdr arc))
(others-no-fact (cdr arcs))
(others (n2d-factorize-arcs others-no-fact)))
(let loop ((o others))
(if (null? o)
(list arc)
(let* ((o1 (car o))
(o1-ss (cdr o1)))
(if (equal? o1-ss arc-ss)
(let* ((arc-class (car arc))
(o1-class (car o1))
(new-class (class-union arc-class o1-class))
(new-arc (cons new-class arc-ss)))
(cons new-arc (cdr o)))
(cons o1 (loop (cdr o)))))))))))
Transformer une liste d'arcs quelconques en des arcs a classes distinctes
(define n2d-distinguish-arcs
(lambda (arcs)
(let loop ((arcs arcs) (n-arcs '()))
(if (null? arcs)
n-arcs
(loop (cdr arcs) (n2d-insert-arc (car arcs) n-arcs))))))
Transformer une liste d'arcs quelconques en des arcs a classes et a
(define n2d-normalize-arcs
(lambda (arcs)
(n2d-factorize-arcs (n2d-distinguish-arcs arcs))))
Factoriser des arcs a destination unique ( ~deterministes )
(define n2d-factorize-darcs
(lambda (arcs)
(if (null? arcs)
'()
(let* ((arc (car arcs))
(arc-end (cdr arc))
(other-arcs (cdr arcs))
(farcs (n2d-factorize-darcs other-arcs)))
(let loop ((farcs farcs))
(if (null? farcs)
(list arc)
(let* ((farc (car farcs))
(farc-end (cdr farc)))
(if (= farc-end arc-end)
(let* ((arc-class (car arc))
(farc-class (car farc))
(new-class (class-union farc-class arc-class))
(new-arc (cons new-class arc-end)))
(cons new-arc (cdr farcs)))
(cons farc (loop (cdr farcs)))))))))))
(define n2d-normalize-arcs-v
(lambda (arcs-v)
(let* ((nbnodes (vector-length arcs-v))
(new-v (make-vector nbnodes)))
(let loop ((n 0))
(if (= n nbnodes)
new-v
(begin
(vector-set! new-v n (n2d-normalize-arcs (vector-ref arcs-v n)))
(loop (+ n 1))))))))
une liste d'arcs a classes distinctes en separant
les arcs contenant une partie de la classe du nouvel arc des autres arcs
: ( oui . non )
(define n2d-ins-sep-arc
(lambda (new-arc arcs)
(if (null? arcs)
(cons (list new-arc) '())
(let* ((arc (car arcs))
(others (cdr arcs))
(result (n2d-2arcs new-arc arc))
(arcl (vector-ref result 0))
(arcc (vector-ref result 1))
(arcr (vector-ref result 2))
(l-arcc (if arcc (list arcc) '()))
(l-arcr (if arcr (list arcr) '()))
(result (if arcl
(n2d-ins-sep-arc arcl others)
(cons '() others)))
(oui-arcs (car result))
(non-arcs (cdr result)))
(cons (append l-arcc oui-arcs) (append l-arcr non-arcs))))))
Combiner deux listes d'arcs a classes distinctes
Note : envisager de rajouter un " n2d - factorize - arcs " ! ! ! ! ! ! ! ! ! ! ! !
(define n2d-combine-arcs
(lambda (arcs1 arcs2)
(let loop ((arcs1 arcs1) (arcs2 arcs2) (dist-arcs2 '()))
(if (null? arcs1)
(append arcs2 dist-arcs2)
(let* ((arc (car arcs1))
(result (n2d-ins-sep-arc arc arcs2))
(oui-arcs (car result))
(non-arcs (cdr result)))
(loop (cdr arcs1) non-arcs (append oui-arcs dist-arcs2)))))))
( define get - dentry - ss ( lambda ( dentry ) ( vector - ref dentry 0 ) ) )
( define get - dentry - acc ( lambda ( dentry ) ( vector - ref dentry 2 ) ) )
( define set - dentry - acc ( lambda ( dentry acc ) ( vector - set ! dentry 2 acc ) ) )
( let * ( ( new - len ( * 2 n2d - state - len ) )
( dentry ( make - dentry ss ) ) )
( set ! n2d - state - count ( + n2d - state - count 1 ) )
( dentry - ss ( get - dentry - ss dentry ) ) )
( if ( equal ? dentry - ss ss )
( define n2d - acc - min2
)
( ( not )
( cons ( acc - min ( car acc1 ) ( car acc2 ) )
( acc - min ( cdr acc1 ) ( cdr acc2 ) ) ) ) ) )
( if ( null ? )
( cons # f # f )
( n2d - acc - min2 ( car accs ) ( n2d - acc - mins ( ) ) ) ) ) )
( acc - v ( make - vector n2d - state - count ) ) )
( vector - set ! acc - v n ( get - dentry - acc
( define nfa2dfa
( lambda ( nl - start no - nl - start arcs - v acc - v )
( let * ( ( nl - d ( n2d - search - state nl - start ) )
( no - nl - d ( n2d - search - state no - nl - start ) ) )
( ss ( get - dentry - ss dentry ) )
( arcs ( apply append ) )
( acc ( n2d - acc - mins accs ) ) )
( set - dentry - darcs dentry fact - darcs )
( set - dentry - acc dentry acc )
( list nl - d no - nl - d new - arcs - v new - acc - v ) ) ) ) )
( define get - dentry - ss ( lambda ( dentry ) ( vector - ref dentry 0 ) ) )
( define get - dentry - acc ( lambda ( dentry ) ( vector - ref dentry 2 ) ) )
( define set - dentry - acc ( lambda ( dentry acc ) ( vector - set ! dentry 2 acc ) ) )
( let * ( ( new - len ( * 2 n2d - state - len ) )
( dentry ( make - dentry ss ) ) )
( set ! n2d - state - count ( + n2d - state - count 1 ) )
( dentry - ss ( get - dentry - ss dentry ) ) )
( if ( equal ? dentry - ss ss )
( define n2d - acc - min2
)
( ( not )
( cons ( acc - min ( car acc1 ) ( car acc2 ) )
( acc - min ( cdr acc1 ) ( cdr acc2 ) ) ) ) ) )
( if ( null ? )
( cons # f # f )
( n2d - acc - min2 ( car accs ) ( n2d - acc - mins ( ) ) ) ) ) )
( acc - v ( make - vector n2d - state - count ) ) )
( vector - set ! acc - v n ( get - dentry - acc
( define nfa2dfa
( lambda ( nl - start no - nl - start arcs - v acc - v )
( let * ( ( nl - d ( n2d - search - state nl - start ) )
( no - nl - d ( n2d - search - state no - nl - start ) )
( ss ( get - dentry - ss dentry ) )
( acc ( n2d - acc - mins accs ) ) )
( set - dentry - darcs dentry fact - darcs )
( set - dentry - acc dentry acc )
( list nl - d no - nl - d new - arcs - v new - acc - v ) ) ) ) )
( define get - dentry - ss ( lambda ( dentry ) ( vector - ref dentry 0 ) ) )
( define get - dentry - acc ( lambda ( dentry ) ( vector - ref dentry 2 ) ) )
( define set - dentry - acc ( lambda ( dentry acc ) ( vector - set ! dentry 2 acc ) ) )
( lambda ( snode dstate ) ( vector - set ! snode 0 dstate ) ) )
( lambda ( snode children ) ( vector - set ! snode 1 children ) ) )
( let * ( ( new - len ( * 2 n2d - state - len ) )
( dentry ( make - dentry ss ) ) )
( set ! n2d - state - count ( + n2d - state - count 1 ) )
( ass ( or ( assv next - s alist )
( define n2d - acc - min2
)
( ( not )
( cons ( acc - min ( car acc1 ) ( car acc2 ) )
( acc - min ( cdr acc1 ) ( cdr acc2 ) ) ) ) ) )
( if ( null ? )
( cons # f # f )
( n2d - acc - min2 ( car accs ) ( n2d - acc - mins ( ) ) ) ) ) )
( acc - v ( make - vector n2d - state - count ) ) )
( vector - set ! acc - v n ( get - dentry - acc
( define nfa2dfa
( lambda ( nl - start no - nl - start arcs - v acc - v )
( let * ( ( nl - d ( n2d - search - state nl - start ) )
( no - nl - d ( n2d - search - state no - nl - start ) )
( ss ( get - dentry - ss dentry ) )
( acc ( n2d - acc - mins accs ) ) )
( set - dentry - darcs dentry fact - darcs )
( set - dentry - acc dentry acc )
( list nl - d no - nl - d new - arcs - v new - acc - v ) ) ) ) )
Section temporaire :
Dictionnaire d'etat det . Table de hashage . Creation des
arcs d'un ensemble d'etats en a
(define n2d-state-dict '#(#f))
(define n2d-state-len 1)
(define n2d-state-count 0)
(define n2d-state-hash '#())
(define make-dentry (lambda (ss) (vector ss #f #f)))
(define get-dentry-ss (lambda (dentry) (vector-ref dentry 0)))
(define get-dentry-darcs (lambda (dentry) (vector-ref dentry 1)))
(define get-dentry-acc (lambda (dentry) (vector-ref dentry 2)))
(define set-dentry-darcs (lambda (dentry arcs) (vector-set! dentry 1 arcs)))
(define set-dentry-acc (lambda (dentry acc) (vector-set! dentry 2 acc)))
(define n2d-init-glob-vars
(lambda (hash-len)
(set! n2d-state-dict (vector #f))
(set! n2d-state-len 1)
(set! n2d-state-count 0)
(set! n2d-state-hash (make-vector hash-len '()))))
(define n2d-extend-dict
(lambda ()
(let* ((new-len (* 2 n2d-state-len))
(v (make-vector new-len #f)))
(let loop ((n 0))
(if (= n n2d-state-count)
(begin
(set! n2d-state-dict v)
(set! n2d-state-len new-len))
(begin
(vector-set! v n (vector-ref n2d-state-dict n))
(loop (+ n 1))))))))
(define n2d-add-state
(lambda (ss)
(let* ((s n2d-state-count)
(dentry (make-dentry ss)))
(if (= n2d-state-count n2d-state-len)
(n2d-extend-dict))
(vector-set! n2d-state-dict s dentry)
(set! n2d-state-count (+ n2d-state-count 1))
s)))
Recherche d'un etat
(define n2d-search-state
(lambda (ss)
(let* ((hash-no (if (null? ss) 0 (car ss)))
(alist (vector-ref n2d-state-hash hash-no))
(ass (assoc ss alist)))
(if ass
(cdr ass)
(let* ((s (n2d-add-state ss))
(new-ass (cons ss s)))
(vector-set! n2d-state-hash hash-no (cons new-ass alist))
s)))))
Combiner des listes d'arcs a classes dictinctes
(define n2d-combine-arcs-l
(lambda (arcs-l)
(if (null? arcs-l)
'()
(let* ((arcs (car arcs-l))
(other-arcs-l (cdr arcs-l))
(other-arcs (n2d-combine-arcs-l other-arcs-l)))
(n2d-combine-arcs arcs other-arcs)))))
Transformer un arc non - det . en un arc det .
(define n2d-translate-arc
(lambda (arc)
(let* ((class (car arc))
(ss (cdr arc))
(s (n2d-search-state ss)))
(cons class s))))
Transformer une liste d'arcs . en ...
(define n2d-translate-arcs
(lambda (arcs)
(map n2d-translate-arc arcs)))
Trouver le minimum de deux acceptants
(define n2d-acc-min2
(let ((acc-min (lambda (rule1 rule2)
(cond ((not rule1)
rule2)
((not rule2)
rule1)
(else
(min rule1 rule2))))))
(lambda (acc1 acc2)
(cons (acc-min (car acc1) (car acc2))
(acc-min (cdr acc1) (cdr acc2))))))
Trouver le minimum de plusieurs acceptants
(define n2d-acc-mins
(lambda (accs)
(if (null? accs)
(cons #f #f)
(n2d-acc-min2 (car accs) (n2d-acc-mins (cdr accs))))))
(define n2d-extract-vs
(lambda ()
(let* ((arcs-v (make-vector n2d-state-count))
(acc-v (make-vector n2d-state-count)))
(let loop ((n 0))
(if (= n n2d-state-count)
(cons arcs-v acc-v)
(begin
(vector-set! arcs-v n (get-dentry-darcs
(vector-ref n2d-state-dict n)))
(vector-set! acc-v n (get-dentry-acc
(vector-ref n2d-state-dict n)))
(loop (+ n 1))))))))
Effectuer la transformation de l'automate de non - det . a det .
(define nfa2dfa
(lambda (nl-start no-nl-start arcs-v acc-v)
(n2d-init-glob-vars (vector-length arcs-v))
(let* ((nl-d (n2d-search-state nl-start))
(no-nl-d (n2d-search-state no-nl-start))
(norm-arcs-v (n2d-normalize-arcs-v arcs-v)))
(let loop ((n 0))
(if (< n n2d-state-count)
(let* ((dentry (vector-ref n2d-state-dict n))
(ss (get-dentry-ss dentry))
(arcs-l (map (lambda (s) (vector-ref norm-arcs-v s)) ss))
(arcs (n2d-combine-arcs-l arcs-l))
(darcs (n2d-translate-arcs arcs))
(fact-darcs (n2d-factorize-darcs darcs))
(accs (map (lambda (s) (vector-ref acc-v s)) ss))
(acc (n2d-acc-mins accs)))
(set-dentry-darcs dentry fact-darcs)
(set-dentry-acc dentry acc)
(loop (+ n 1)))))
(let* ((result (n2d-extract-vs))
(new-arcs-v (car result))
(new-acc-v (cdr result)))
(n2d-init-glob-vars 0)
(list nl-d no-nl-d new-arcs-v new-acc-v)))))
|
9b283c64b71eae35159b0c7182a840f04e29284e0f198a0948ae80edb1ff2c0a | freckle/yesod-auth-oauth2 | Upcase.hs | {-# LANGUAGE OverloadedStrings #-}
-- |
--
-- OAuth2 plugin for
--
-- * Authenticates against upcase
-- * Uses upcase user id as credentials identifier
--
module Yesod.Auth.OAuth2.Upcase
( oauth2Upcase
) where
import Yesod.Auth.OAuth2.Prelude
import qualified Data.Text as T
newtype User = User Int
instance FromJSON User where
parseJSON = withObject "User" $ \root -> do
o <- root .: "user"
User <$> o .: "id"
pluginName :: Text
pluginName = "upcase"
oauth2Upcase :: YesodAuth m => Text -> Text -> AuthPlugin m
oauth2Upcase clientId clientSecret =
authOAuth2 pluginName oauth2 $ \manager token -> do
(User userId, userResponse) <- authGetProfile
pluginName
manager
token
""
pure Creds { credsPlugin = pluginName
, credsIdent = T.pack $ show userId
, credsExtra = setExtra token userResponse
}
where
oauth2 = OAuth2
{ oauth2ClientId = clientId
, oauth2ClientSecret = Just clientSecret
, oauth2AuthorizeEndpoint = ""
, oauth2TokenEndpoint = ""
, oauth2RedirectUri = Nothing
}
| null | https://raw.githubusercontent.com/freckle/yesod-auth-oauth2/8976e193e94ab4f0c38bea446a77d30b694780f4/src/Yesod/Auth/OAuth2/Upcase.hs | haskell | # LANGUAGE OverloadedStrings #
|
OAuth2 plugin for
* Authenticates against upcase
* Uses upcase user id as credentials identifier
| module Yesod.Auth.OAuth2.Upcase
( oauth2Upcase
) where
import Yesod.Auth.OAuth2.Prelude
import qualified Data.Text as T
newtype User = User Int
instance FromJSON User where
parseJSON = withObject "User" $ \root -> do
o <- root .: "user"
User <$> o .: "id"
pluginName :: Text
pluginName = "upcase"
oauth2Upcase :: YesodAuth m => Text -> Text -> AuthPlugin m
oauth2Upcase clientId clientSecret =
authOAuth2 pluginName oauth2 $ \manager token -> do
(User userId, userResponse) <- authGetProfile
pluginName
manager
token
""
pure Creds { credsPlugin = pluginName
, credsIdent = T.pack $ show userId
, credsExtra = setExtra token userResponse
}
where
oauth2 = OAuth2
{ oauth2ClientId = clientId
, oauth2ClientSecret = Just clientSecret
, oauth2AuthorizeEndpoint = ""
, oauth2TokenEndpoint = ""
, oauth2RedirectUri = Nothing
}
|
4175926fa8b9e20ccb011ee2796bffaa1b086175c2f8e95044fbeef21f7a59a0 | nuvla/api-server | configuration_session_github.clj | (ns sixsq.nuvla.server.resources.configuration-session-github
(:require
[sixsq.nuvla.server.resources.common.std-crud :as std-crud]
[sixsq.nuvla.server.resources.common.utils :as u]
[sixsq.nuvla.server.resources.configuration :as p]
[sixsq.nuvla.server.resources.spec.configuration-template-session-github :as cts-github]))
(def ^:const service "session-github")
;;
;; multimethods for validation
;;
(def validate-fn (u/create-spec-validation-fn ::cts-github/schema))
(defmethod p/validate-subtype service
[resource]
(validate-fn resource))
(def create-validate-fn (u/create-spec-validation-fn ::cts-github/schema-create))
(defmethod p/create-validate-subtype service
[resource]
(create-validate-fn resource))
;;
;; initialization
;;
(defn initialize
[]
(std-crud/initialize p/resource-type ::cts-github/schema))
| null | https://raw.githubusercontent.com/nuvla/api-server/a64a61b227733f1a0a945003edf5abaf5150a15c/code/src/sixsq/nuvla/server/resources/configuration_session_github.clj | clojure |
multimethods for validation
initialization
| (ns sixsq.nuvla.server.resources.configuration-session-github
(:require
[sixsq.nuvla.server.resources.common.std-crud :as std-crud]
[sixsq.nuvla.server.resources.common.utils :as u]
[sixsq.nuvla.server.resources.configuration :as p]
[sixsq.nuvla.server.resources.spec.configuration-template-session-github :as cts-github]))
(def ^:const service "session-github")
(def validate-fn (u/create-spec-validation-fn ::cts-github/schema))
(defmethod p/validate-subtype service
[resource]
(validate-fn resource))
(def create-validate-fn (u/create-spec-validation-fn ::cts-github/schema-create))
(defmethod p/create-validate-subtype service
[resource]
(create-validate-fn resource))
(defn initialize
[]
(std-crud/initialize p/resource-type ::cts-github/schema))
|
27ef1fb2b90893b351d92b571d726a613e6afe6f5ce4512ce13a7a418e037b14 | joeyadams/haskell-iocp | PSQ.hs | # LANGUAGE Trustworthy #
# LANGUAGE BangPatterns , NoImplicitPrelude #
Copyright ( c ) 2008 ,
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions
-- are met:
--
-- * Redistributions of source code must retain the above
-- copyright notice, this list of conditions and the following
-- disclaimer.
--
-- * Redistributions in binary form must reproduce the above
-- copyright notice, this list of conditions and the following
-- disclaimer in the documentation and/or other materials
-- provided with the distribution.
--
-- * 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 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.
| A /priority search queue/ ( henceforth /queue/ ) efficiently
-- supports the operations of both a search tree and a priority queue.
-- An 'Elem'ent is a product of a key, a priority, and a
-- value. Elements can be inserted, deleted, modified and queried in
-- logarithmic time, and the element with the least priority can be
-- retrieved in constant time. A queue can be built from a list of
-- elements, sorted by keys, in linear time.
--
This implementation is due to with some modifications by
and .
--
* , R. , /A Simple Implementation Technique for Priority Search
Queues/ , ICFP 2001 , pp . 110 - 121
--
-- <>
module IOCP.PSQ
(
-- * Binding Type
Elem(..)
, Key
, Prio
-- * Priority Search Queue Type
, PSQ
-- * Query
, size
, null
, lookup
-- * Construction
, empty
, singleton
-- * Insertion
, insert
-- * Delete/Update
, delete
, adjust
-- * Conversion
, toList
, toAscList
, toDescList
, fromList
*
, findMin
, deleteMin
, minView
, atMost
) where
import Data.Maybe (Maybe(..))
import GHC.Base
import GHC.Num (Num(..))
import GHC.Show (Show(showsPrec))
import Data.Unique (Unique)
-- | @E k p@ binds the key @k@ with the priority @p@.
data Elem a = E
{ key :: !Key
, prio :: !Prio
, value :: a
} deriving (Eq)
------------------------------------------------------------------------
| A mapping from keys @k@ to priorites @p@.
type Prio = Double
type Key = Unique
data PSQ a = Void
| Winner !(Elem a)
!(LTree a)
!Key -- max key
deriving (Eq)
-- | /O(1)/ The number of elements in a queue.
size :: PSQ a -> Int
size Void = 0
size (Winner _ lt _) = 1 + size' lt
-- | /O(1)/ True if the queue is empty.
null :: PSQ a -> Bool
null Void = True
null (Winner _ _ _) = False
| /O(log n)/ The priority and value of a given key , or Nothing if
-- the key is not bound.
lookup :: Key -> PSQ a -> Maybe (Prio, a)
lookup k q = case tourView q of
Null -> Nothing
Single (E k' p v)
| k == k' -> Just (p, v)
| otherwise -> Nothing
tl `Play` tr
| k <= maxKey tl -> lookup k tl
| otherwise -> lookup k tr
------------------------------------------------------------------------
-- Construction
empty :: PSQ a
empty = Void
| /O(1)/ Build a queue with one element .
singleton :: Key -> Prio -> a -> PSQ a
singleton k p v = Winner (E k p v) Start k
------------------------------------------------------------------------
-- Insertion
| /O(log n)/ Insert a new key , priority and value in the queue . If
-- the key is already present in the queue, the associated priority
-- and value are replaced with the supplied priority and value.
insert :: Key -> Prio -> a -> PSQ a -> PSQ a
insert k p v q = case q of
Void -> singleton k p v
Winner (E k' p' v') Start _ -> case compare k k' of
LT -> singleton k p v `play` singleton k' p' v'
EQ -> singleton k p v
GT -> singleton k' p' v' `play` singleton k p v
Winner e (RLoser _ e' tl m tr) m'
| k <= m -> insert k p v (Winner e tl m) `play` (Winner e' tr m')
| otherwise -> (Winner e tl m) `play` insert k p v (Winner e' tr m')
Winner e (LLoser _ e' tl m tr) m'
| k <= m -> insert k p v (Winner e' tl m) `play` (Winner e tr m')
| otherwise -> (Winner e' tl m) `play` insert k p v (Winner e tr m')
------------------------------------------------------------------------
-- Delete/Update
| /O(log n)/ Delete a key and its priority and value from the
-- queue. When the key is not a member of the queue, the original
-- queue is returned.
delete :: Key -> PSQ a -> PSQ a
delete k q = case q of
Void -> empty
Winner (E k' p v) Start _
| k == k' -> empty
| otherwise -> singleton k' p v
Winner e (RLoser _ e' tl m tr) m'
| k <= m -> delete k (Winner e tl m) `play` (Winner e' tr m')
| otherwise -> (Winner e tl m) `play` delete k (Winner e' tr m')
Winner e (LLoser _ e' tl m tr) m'
| k <= m -> delete k (Winner e' tl m) `play` (Winner e tr m')
| otherwise -> (Winner e' tl m) `play` delete k (Winner e tr m')
| /O(log n)/ Update a priority at a specific key with the result
-- of the provided function. When the key is not a member of the
-- queue, the original queue is returned.
adjust :: (Prio -> Prio) -> Key -> PSQ a -> PSQ a
adjust f k q0 = go q0
where
go q = case q of
Void -> empty
Winner (E k' p v) Start _
| k == k' -> singleton k' (f p) v
| otherwise -> singleton k' p v
Winner e (RLoser _ e' tl m tr) m'
| k <= m -> go (Winner e tl m) `unsafePlay` (Winner e' tr m')
| otherwise -> (Winner e tl m) `unsafePlay` go (Winner e' tr m')
Winner e (LLoser _ e' tl m tr) m'
| k <= m -> go (Winner e' tl m) `unsafePlay` (Winner e tr m')
| otherwise -> (Winner e' tl m) `unsafePlay` go (Winner e tr m')
# INLINE adjust #
------------------------------------------------------------------------
-- Conversion
| /O(n*log n)/ Build a queue from a list of key / priority / value
tuples . If the list contains more than one priority and value for
-- the same key, the last priority and value for the key is retained.
fromList :: [Elem a] -> PSQ a
fromList = foldr (\(E k p v) q -> insert k p v q) empty
-- | /O(n)/ Convert to a list of key/priority/value tuples.
toList :: PSQ a -> [Elem a]
toList = toAscList
-- | /O(n)/ Convert to an ascending list.
toAscList :: PSQ a -> [Elem a]
toAscList q = seqToList (toAscLists q)
toAscLists :: PSQ a -> Sequ (Elem a)
toAscLists q = case tourView q of
Null -> emptySequ
Single e -> singleSequ e
tl `Play` tr -> toAscLists tl <> toAscLists tr
-- | /O(n)/ Convert to a descending list.
toDescList :: PSQ a -> [ Elem a ]
toDescList q = seqToList (toDescLists q)
toDescLists :: PSQ a -> Sequ (Elem a)
toDescLists q = case tourView q of
Null -> emptySequ
Single e -> singleSequ e
tl `Play` tr -> toDescLists tr <> toDescLists tl
------------------------------------------------------------------------
-- Min
-- | /O(1)/ The element with the lowest priority.
findMin :: PSQ a -> Maybe (Elem a)
findMin Void = Nothing
findMin (Winner e _ _) = Just e
| /O(log n)/ Delete the element with the lowest priority . Returns
-- an empty queue if the queue is empty.
deleteMin :: PSQ a -> PSQ a
deleteMin Void = Void
deleteMin (Winner _ t m) = secondBest t m
| /O(log n)/ Retrieve the binding with the least priority , and the
-- rest of the queue stripped of that binding.
minView :: PSQ a -> Maybe (Elem a, PSQ a)
minView Void = Nothing
minView (Winner e t m) = Just (e, secondBest t m)
secondBest :: LTree a -> Key -> PSQ a
secondBest Start _ = Void
secondBest (LLoser _ e tl m tr) m' = Winner e tl m `play` secondBest tr m'
secondBest (RLoser _ e tl m tr) m' = secondBest tl m `play` Winner e tr m'
-- | /O(r*(log n - log r))/ Return a list of elements ordered by
key whose priorities are at most @pt@.
atMost :: Prio -> PSQ a -> ([Elem a], PSQ a)
atMost pt q = let (sequ, q') = atMosts pt q
in (seqToList sequ, q')
atMosts :: Prio -> PSQ a -> (Sequ (Elem a), PSQ a)
atMosts !pt q = case q of
(Winner e _ _)
| prio e > pt -> (emptySequ, q)
Void -> (emptySequ, Void)
Winner e Start _ -> (singleSequ e, Void)
Winner e (RLoser _ e' tl m tr) m' ->
let (sequ, q') = atMosts pt (Winner e tl m)
(sequ', q'') = atMosts pt (Winner e' tr m')
in (sequ <> sequ', q' `play` q'')
Winner e (LLoser _ e' tl m tr) m' ->
let (sequ, q') = atMosts pt (Winner e' tl m)
(sequ', q'') = atMosts pt (Winner e tr m')
in (sequ <> sequ', q' `play` q'')
------------------------------------------------------------------------
-- Loser tree
type Size = Int
data LTree a = Start
| LLoser !Size
!(Elem a)
!(LTree a)
!Key -- split key
!(LTree a)
| RLoser !Size
!(Elem a)
!(LTree a)
!Key -- split key
!(LTree a)
deriving (Eq)
size' :: LTree a -> Size
size' Start = 0
size' (LLoser s _ _ _ _) = s
size' (RLoser s _ _ _ _) = s
left, right :: LTree a -> LTree a
left Start = moduleError "left" "empty loser tree"
left (LLoser _ _ tl _ _ ) = tl
left (RLoser _ _ tl _ _ ) = tl
right Start = moduleError "right" "empty loser tree"
right (LLoser _ _ _ _ tr) = tr
right (RLoser _ _ _ _ tr) = tr
maxKey :: PSQ a -> Key
maxKey Void = moduleError "maxKey" "empty queue"
maxKey (Winner _ _ m) = m
lloser, rloser :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
lloser k p v tl m tr = LLoser (1 + size' tl + size' tr) (E k p v) tl m tr
rloser k p v tl m tr = RLoser (1 + size' tl + size' tr) (E k p v) tl m tr
------------------------------------------------------------------------
-- Balancing
-- | Balance factor
omega :: Int
omega = 4
lbalance, rbalance :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
lbalance k p v l m r
| size' l + size' r < 2 = lloser k p v l m r
| size' r > omega * size' l = lbalanceLeft k p v l m r
| size' l > omega * size' r = lbalanceRight k p v l m r
| otherwise = lloser k p v l m r
rbalance k p v l m r
| size' l + size' r < 2 = rloser k p v l m r
| size' r > omega * size' l = rbalanceLeft k p v l m r
| size' l > omega * size' r = rbalanceRight k p v l m r
| otherwise = rloser k p v l m r
lbalanceLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
lbalanceLeft k p v l m r
| size' (left r) < size' (right r) = lsingleLeft k p v l m r
| otherwise = ldoubleLeft k p v l m r
lbalanceRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
lbalanceRight k p v l m r
| size' (left l) > size' (right l) = lsingleRight k p v l m r
| otherwise = ldoubleRight k p v l m r
rbalanceLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
rbalanceLeft k p v l m r
| size' (left r) < size' (right r) = rsingleLeft k p v l m r
| otherwise = rdoubleLeft k p v l m r
rbalanceRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
rbalanceRight k p v l m r
| size' (left l) > size' (right l) = rsingleRight k p v l m r
| otherwise = rdoubleRight k p v l m r
lsingleLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
lsingleLeft k1 p1 v1 t1 m1 (LLoser _ (E k2 p2 v2) t2 m2 t3)
| p1 <= p2 = lloser k1 p1 v1 (rloser k2 p2 v2 t1 m1 t2) m2 t3
| otherwise = lloser k2 p2 v2 (lloser k1 p1 v1 t1 m1 t2) m2 t3
lsingleLeft k1 p1 v1 t1 m1 (RLoser _ (E k2 p2 v2) t2 m2 t3) =
rloser k2 p2 v2 (lloser k1 p1 v1 t1 m1 t2) m2 t3
lsingleLeft _ _ _ _ _ _ = moduleError "lsingleLeft" "malformed tree"
rsingleLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
rsingleLeft k1 p1 v1 t1 m1 (LLoser _ (E k2 p2 v2) t2 m2 t3) =
rloser k1 p1 v1 (rloser k2 p2 v2 t1 m1 t2) m2 t3
rsingleLeft k1 p1 v1 t1 m1 (RLoser _ (E k2 p2 v2) t2 m2 t3) =
rloser k2 p2 v2 (rloser k1 p1 v1 t1 m1 t2) m2 t3
rsingleLeft _ _ _ _ _ _ = moduleError "rsingleLeft" "malformed tree"
lsingleRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
lsingleRight k1 p1 v1 (LLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =
lloser k2 p2 v2 t1 m1 (lloser k1 p1 v1 t2 m2 t3)
lsingleRight k1 p1 v1 (RLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =
lloser k1 p1 v1 t1 m1 (lloser k2 p2 v2 t2 m2 t3)
lsingleRight _ _ _ _ _ _ = moduleError "lsingleRight" "malformed tree"
rsingleRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
rsingleRight k1 p1 v1 (LLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =
lloser k2 p2 v2 t1 m1 (rloser k1 p1 v1 t2 m2 t3)
rsingleRight k1 p1 v1 (RLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3
| p1 <= p2 = rloser k1 p1 v1 t1 m1 (lloser k2 p2 v2 t2 m2 t3)
| otherwise = rloser k2 p2 v2 t1 m1 (rloser k1 p1 v1 t2 m2 t3)
rsingleRight _ _ _ _ _ _ = moduleError "rsingleRight" "malformed tree"
ldoubleLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
ldoubleLeft k1 p1 v1 t1 m1 (LLoser _ (E k2 p2 v2) t2 m2 t3) =
lsingleLeft k1 p1 v1 t1 m1 (lsingleRight k2 p2 v2 t2 m2 t3)
ldoubleLeft k1 p1 v1 t1 m1 (RLoser _ (E k2 p2 v2) t2 m2 t3) =
lsingleLeft k1 p1 v1 t1 m1 (rsingleRight k2 p2 v2 t2 m2 t3)
ldoubleLeft _ _ _ _ _ _ = moduleError "ldoubleLeft" "malformed tree"
ldoubleRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
ldoubleRight k1 p1 v1 (LLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =
lsingleRight k1 p1 v1 (lsingleLeft k2 p2 v2 t1 m1 t2) m2 t3
ldoubleRight k1 p1 v1 (RLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =
lsingleRight k1 p1 v1 (rsingleLeft k2 p2 v2 t1 m1 t2) m2 t3
ldoubleRight _ _ _ _ _ _ = moduleError "ldoubleRight" "malformed tree"
rdoubleLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
rdoubleLeft k1 p1 v1 t1 m1 (LLoser _ (E k2 p2 v2) t2 m2 t3) =
rsingleLeft k1 p1 v1 t1 m1 (lsingleRight k2 p2 v2 t2 m2 t3)
rdoubleLeft k1 p1 v1 t1 m1 (RLoser _ (E k2 p2 v2) t2 m2 t3) =
rsingleLeft k1 p1 v1 t1 m1 (rsingleRight k2 p2 v2 t2 m2 t3)
rdoubleLeft _ _ _ _ _ _ = moduleError "rdoubleLeft" "malformed tree"
rdoubleRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
rdoubleRight k1 p1 v1 (LLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =
rsingleRight k1 p1 v1 (lsingleLeft k2 p2 v2 t1 m1 t2) m2 t3
rdoubleRight k1 p1 v1 (RLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =
rsingleRight k1 p1 v1 (rsingleLeft k2 p2 v2 t1 m1 t2) m2 t3
rdoubleRight _ _ _ _ _ _ = moduleError "rdoubleRight" "malformed tree"
| Take two pennants and returns a new pennant that is the union of
the two with the precondition that the keys in the first tree are
strictly smaller than the keys in the second tree .
play :: PSQ a -> PSQ a -> PSQ a
Void `play` t' = t'
t `play` Void = t
Winner e@(E k p v) t m `play` Winner e'@(E k' p' v') t' m'
| p <= p' = Winner e (rbalance k' p' v' t m t') m'
| otherwise = Winner e' (lbalance k p v t m t') m'
# INLINE play #
-- | A version of 'play' that can be used if the shape of the tree has
-- not changed or if the tree is known to be balanced.
unsafePlay :: PSQ a -> PSQ a -> PSQ a
Void `unsafePlay` t' = t'
t `unsafePlay` Void = t
Winner e@(E k p v) t m `unsafePlay` Winner e'@(E k' p' v') t' m'
| p <= p' = Winner e (rloser k' p' v' t m t') m'
| otherwise = Winner e' (lloser k p v t m t') m'
# INLINE unsafePlay #
data TourView a = Null
| Single {-# UNPACK #-} !(Elem a)
| (PSQ a) `Play` (PSQ a)
tourView :: PSQ a -> TourView a
tourView Void = Null
tourView (Winner e Start _) = Single e
tourView (Winner e (RLoser _ e' tl m tr) m') =
Winner e tl m `Play` Winner e' tr m'
tourView (Winner e (LLoser _ e' tl m tr) m') =
Winner e' tl m `Play` Winner e tr m'
------------------------------------------------------------------------
-- Utility functions
moduleError :: String -> String -> a
moduleError fun msg = error ("GHC.Event.PSQ." ++ fun ++ ':' : ' ' : msg)
# NOINLINE moduleError #
------------------------------------------------------------------------
Hughes 's efficient sequence type
newtype Sequ a = Sequ ([a] -> [a])
emptySequ :: Sequ a
emptySequ = Sequ (\as -> as)
singleSequ :: a -> Sequ a
singleSequ a = Sequ (\as -> a : as)
(<>) :: Sequ a -> Sequ a -> Sequ a
Sequ x1 <> Sequ x2 = Sequ (\as -> x1 (x2 as))
infixr 5 <>
seqToList :: Sequ a -> [a]
seqToList (Sequ x) = x []
instance Show a => Show (Sequ a) where
showsPrec d a = showsPrec d (seqToList a)
| null | https://raw.githubusercontent.com/joeyadams/haskell-iocp/67b65759b3d1473770533f782ca7a42131ae2ca7/IOCP/PSQ.hs | haskell | All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the following
disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
* 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
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
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.
supports the operations of both a search tree and a priority queue.
An 'Elem'ent is a product of a key, a priority, and a
value. Elements can be inserted, deleted, modified and queried in
logarithmic time, and the element with the least priority can be
retrieved in constant time. A queue can be built from a list of
elements, sorted by keys, in linear time.
<>
* Binding Type
* Priority Search Queue Type
* Query
* Construction
* Insertion
* Delete/Update
* Conversion
| @E k p@ binds the key @k@ with the priority @p@.
----------------------------------------------------------------------
max key
| /O(1)/ The number of elements in a queue.
| /O(1)/ True if the queue is empty.
the key is not bound.
----------------------------------------------------------------------
Construction
----------------------------------------------------------------------
Insertion
the key is already present in the queue, the associated priority
and value are replaced with the supplied priority and value.
----------------------------------------------------------------------
Delete/Update
queue. When the key is not a member of the queue, the original
queue is returned.
of the provided function. When the key is not a member of the
queue, the original queue is returned.
----------------------------------------------------------------------
Conversion
the same key, the last priority and value for the key is retained.
| /O(n)/ Convert to a list of key/priority/value tuples.
| /O(n)/ Convert to an ascending list.
| /O(n)/ Convert to a descending list.
----------------------------------------------------------------------
Min
| /O(1)/ The element with the lowest priority.
an empty queue if the queue is empty.
rest of the queue stripped of that binding.
| /O(r*(log n - log r))/ Return a list of elements ordered by
----------------------------------------------------------------------
Loser tree
split key
split key
----------------------------------------------------------------------
Balancing
| Balance factor
| A version of 'play' that can be used if the shape of the tree has
not changed or if the tree is known to be balanced.
# UNPACK #
----------------------------------------------------------------------
Utility functions
---------------------------------------------------------------------- | # LANGUAGE Trustworthy #
# LANGUAGE BangPatterns , NoImplicitPrelude #
Copyright ( c ) 2008 ,
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
COPYRIGHT OWNER OR ANY DIRECT , INDIRECT ,
INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES
( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT ,
| A /priority search queue/ ( henceforth /queue/ ) efficiently
This implementation is due to with some modifications by
and .
* , R. , /A Simple Implementation Technique for Priority Search
Queues/ , ICFP 2001 , pp . 110 - 121
module IOCP.PSQ
(
Elem(..)
, Key
, Prio
, PSQ
, size
, null
, lookup
, empty
, singleton
, insert
, delete
, adjust
, toList
, toAscList
, toDescList
, fromList
*
, findMin
, deleteMin
, minView
, atMost
) where
import Data.Maybe (Maybe(..))
import GHC.Base
import GHC.Num (Num(..))
import GHC.Show (Show(showsPrec))
import Data.Unique (Unique)
data Elem a = E
{ key :: !Key
, prio :: !Prio
, value :: a
} deriving (Eq)
| A mapping from keys @k@ to priorites @p@.
type Prio = Double
type Key = Unique
data PSQ a = Void
| Winner !(Elem a)
!(LTree a)
deriving (Eq)
size :: PSQ a -> Int
size Void = 0
size (Winner _ lt _) = 1 + size' lt
null :: PSQ a -> Bool
null Void = True
null (Winner _ _ _) = False
| /O(log n)/ The priority and value of a given key , or Nothing if
lookup :: Key -> PSQ a -> Maybe (Prio, a)
lookup k q = case tourView q of
Null -> Nothing
Single (E k' p v)
| k == k' -> Just (p, v)
| otherwise -> Nothing
tl `Play` tr
| k <= maxKey tl -> lookup k tl
| otherwise -> lookup k tr
empty :: PSQ a
empty = Void
| /O(1)/ Build a queue with one element .
singleton :: Key -> Prio -> a -> PSQ a
singleton k p v = Winner (E k p v) Start k
| /O(log n)/ Insert a new key , priority and value in the queue . If
insert :: Key -> Prio -> a -> PSQ a -> PSQ a
insert k p v q = case q of
Void -> singleton k p v
Winner (E k' p' v') Start _ -> case compare k k' of
LT -> singleton k p v `play` singleton k' p' v'
EQ -> singleton k p v
GT -> singleton k' p' v' `play` singleton k p v
Winner e (RLoser _ e' tl m tr) m'
| k <= m -> insert k p v (Winner e tl m) `play` (Winner e' tr m')
| otherwise -> (Winner e tl m) `play` insert k p v (Winner e' tr m')
Winner e (LLoser _ e' tl m tr) m'
| k <= m -> insert k p v (Winner e' tl m) `play` (Winner e tr m')
| otherwise -> (Winner e' tl m) `play` insert k p v (Winner e tr m')
| /O(log n)/ Delete a key and its priority and value from the
delete :: Key -> PSQ a -> PSQ a
delete k q = case q of
Void -> empty
Winner (E k' p v) Start _
| k == k' -> empty
| otherwise -> singleton k' p v
Winner e (RLoser _ e' tl m tr) m'
| k <= m -> delete k (Winner e tl m) `play` (Winner e' tr m')
| otherwise -> (Winner e tl m) `play` delete k (Winner e' tr m')
Winner e (LLoser _ e' tl m tr) m'
| k <= m -> delete k (Winner e' tl m) `play` (Winner e tr m')
| otherwise -> (Winner e' tl m) `play` delete k (Winner e tr m')
| /O(log n)/ Update a priority at a specific key with the result
adjust :: (Prio -> Prio) -> Key -> PSQ a -> PSQ a
adjust f k q0 = go q0
where
go q = case q of
Void -> empty
Winner (E k' p v) Start _
| k == k' -> singleton k' (f p) v
| otherwise -> singleton k' p v
Winner e (RLoser _ e' tl m tr) m'
| k <= m -> go (Winner e tl m) `unsafePlay` (Winner e' tr m')
| otherwise -> (Winner e tl m) `unsafePlay` go (Winner e' tr m')
Winner e (LLoser _ e' tl m tr) m'
| k <= m -> go (Winner e' tl m) `unsafePlay` (Winner e tr m')
| otherwise -> (Winner e' tl m) `unsafePlay` go (Winner e tr m')
# INLINE adjust #
| /O(n*log n)/ Build a queue from a list of key / priority / value
tuples . If the list contains more than one priority and value for
fromList :: [Elem a] -> PSQ a
fromList = foldr (\(E k p v) q -> insert k p v q) empty
toList :: PSQ a -> [Elem a]
toList = toAscList
toAscList :: PSQ a -> [Elem a]
toAscList q = seqToList (toAscLists q)
toAscLists :: PSQ a -> Sequ (Elem a)
toAscLists q = case tourView q of
Null -> emptySequ
Single e -> singleSequ e
tl `Play` tr -> toAscLists tl <> toAscLists tr
toDescList :: PSQ a -> [ Elem a ]
toDescList q = seqToList (toDescLists q)
toDescLists :: PSQ a -> Sequ (Elem a)
toDescLists q = case tourView q of
Null -> emptySequ
Single e -> singleSequ e
tl `Play` tr -> toDescLists tr <> toDescLists tl
findMin :: PSQ a -> Maybe (Elem a)
findMin Void = Nothing
findMin (Winner e _ _) = Just e
| /O(log n)/ Delete the element with the lowest priority . Returns
deleteMin :: PSQ a -> PSQ a
deleteMin Void = Void
deleteMin (Winner _ t m) = secondBest t m
| /O(log n)/ Retrieve the binding with the least priority , and the
minView :: PSQ a -> Maybe (Elem a, PSQ a)
minView Void = Nothing
minView (Winner e t m) = Just (e, secondBest t m)
secondBest :: LTree a -> Key -> PSQ a
secondBest Start _ = Void
secondBest (LLoser _ e tl m tr) m' = Winner e tl m `play` secondBest tr m'
secondBest (RLoser _ e tl m tr) m' = secondBest tl m `play` Winner e tr m'
key whose priorities are at most @pt@.
atMost :: Prio -> PSQ a -> ([Elem a], PSQ a)
atMost pt q = let (sequ, q') = atMosts pt q
in (seqToList sequ, q')
atMosts :: Prio -> PSQ a -> (Sequ (Elem a), PSQ a)
atMosts !pt q = case q of
(Winner e _ _)
| prio e > pt -> (emptySequ, q)
Void -> (emptySequ, Void)
Winner e Start _ -> (singleSequ e, Void)
Winner e (RLoser _ e' tl m tr) m' ->
let (sequ, q') = atMosts pt (Winner e tl m)
(sequ', q'') = atMosts pt (Winner e' tr m')
in (sequ <> sequ', q' `play` q'')
Winner e (LLoser _ e' tl m tr) m' ->
let (sequ, q') = atMosts pt (Winner e' tl m)
(sequ', q'') = atMosts pt (Winner e tr m')
in (sequ <> sequ', q' `play` q'')
type Size = Int
data LTree a = Start
| LLoser !Size
!(Elem a)
!(LTree a)
!(LTree a)
| RLoser !Size
!(Elem a)
!(LTree a)
!(LTree a)
deriving (Eq)
size' :: LTree a -> Size
size' Start = 0
size' (LLoser s _ _ _ _) = s
size' (RLoser s _ _ _ _) = s
left, right :: LTree a -> LTree a
left Start = moduleError "left" "empty loser tree"
left (LLoser _ _ tl _ _ ) = tl
left (RLoser _ _ tl _ _ ) = tl
right Start = moduleError "right" "empty loser tree"
right (LLoser _ _ _ _ tr) = tr
right (RLoser _ _ _ _ tr) = tr
maxKey :: PSQ a -> Key
maxKey Void = moduleError "maxKey" "empty queue"
maxKey (Winner _ _ m) = m
lloser, rloser :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
lloser k p v tl m tr = LLoser (1 + size' tl + size' tr) (E k p v) tl m tr
rloser k p v tl m tr = RLoser (1 + size' tl + size' tr) (E k p v) tl m tr
omega :: Int
omega = 4
lbalance, rbalance :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
lbalance k p v l m r
| size' l + size' r < 2 = lloser k p v l m r
| size' r > omega * size' l = lbalanceLeft k p v l m r
| size' l > omega * size' r = lbalanceRight k p v l m r
| otherwise = lloser k p v l m r
rbalance k p v l m r
| size' l + size' r < 2 = rloser k p v l m r
| size' r > omega * size' l = rbalanceLeft k p v l m r
| size' l > omega * size' r = rbalanceRight k p v l m r
| otherwise = rloser k p v l m r
lbalanceLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
lbalanceLeft k p v l m r
| size' (left r) < size' (right r) = lsingleLeft k p v l m r
| otherwise = ldoubleLeft k p v l m r
lbalanceRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
lbalanceRight k p v l m r
| size' (left l) > size' (right l) = lsingleRight k p v l m r
| otherwise = ldoubleRight k p v l m r
rbalanceLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
rbalanceLeft k p v l m r
| size' (left r) < size' (right r) = rsingleLeft k p v l m r
| otherwise = rdoubleLeft k p v l m r
rbalanceRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
rbalanceRight k p v l m r
| size' (left l) > size' (right l) = rsingleRight k p v l m r
| otherwise = rdoubleRight k p v l m r
lsingleLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
lsingleLeft k1 p1 v1 t1 m1 (LLoser _ (E k2 p2 v2) t2 m2 t3)
| p1 <= p2 = lloser k1 p1 v1 (rloser k2 p2 v2 t1 m1 t2) m2 t3
| otherwise = lloser k2 p2 v2 (lloser k1 p1 v1 t1 m1 t2) m2 t3
lsingleLeft k1 p1 v1 t1 m1 (RLoser _ (E k2 p2 v2) t2 m2 t3) =
rloser k2 p2 v2 (lloser k1 p1 v1 t1 m1 t2) m2 t3
lsingleLeft _ _ _ _ _ _ = moduleError "lsingleLeft" "malformed tree"
rsingleLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
rsingleLeft k1 p1 v1 t1 m1 (LLoser _ (E k2 p2 v2) t2 m2 t3) =
rloser k1 p1 v1 (rloser k2 p2 v2 t1 m1 t2) m2 t3
rsingleLeft k1 p1 v1 t1 m1 (RLoser _ (E k2 p2 v2) t2 m2 t3) =
rloser k2 p2 v2 (rloser k1 p1 v1 t1 m1 t2) m2 t3
rsingleLeft _ _ _ _ _ _ = moduleError "rsingleLeft" "malformed tree"
lsingleRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
lsingleRight k1 p1 v1 (LLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =
lloser k2 p2 v2 t1 m1 (lloser k1 p1 v1 t2 m2 t3)
lsingleRight k1 p1 v1 (RLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =
lloser k1 p1 v1 t1 m1 (lloser k2 p2 v2 t2 m2 t3)
lsingleRight _ _ _ _ _ _ = moduleError "lsingleRight" "malformed tree"
rsingleRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
rsingleRight k1 p1 v1 (LLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =
lloser k2 p2 v2 t1 m1 (rloser k1 p1 v1 t2 m2 t3)
rsingleRight k1 p1 v1 (RLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3
| p1 <= p2 = rloser k1 p1 v1 t1 m1 (lloser k2 p2 v2 t2 m2 t3)
| otherwise = rloser k2 p2 v2 t1 m1 (rloser k1 p1 v1 t2 m2 t3)
rsingleRight _ _ _ _ _ _ = moduleError "rsingleRight" "malformed tree"
ldoubleLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
ldoubleLeft k1 p1 v1 t1 m1 (LLoser _ (E k2 p2 v2) t2 m2 t3) =
lsingleLeft k1 p1 v1 t1 m1 (lsingleRight k2 p2 v2 t2 m2 t3)
ldoubleLeft k1 p1 v1 t1 m1 (RLoser _ (E k2 p2 v2) t2 m2 t3) =
lsingleLeft k1 p1 v1 t1 m1 (rsingleRight k2 p2 v2 t2 m2 t3)
ldoubleLeft _ _ _ _ _ _ = moduleError "ldoubleLeft" "malformed tree"
ldoubleRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
ldoubleRight k1 p1 v1 (LLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =
lsingleRight k1 p1 v1 (lsingleLeft k2 p2 v2 t1 m1 t2) m2 t3
ldoubleRight k1 p1 v1 (RLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =
lsingleRight k1 p1 v1 (rsingleLeft k2 p2 v2 t1 m1 t2) m2 t3
ldoubleRight _ _ _ _ _ _ = moduleError "ldoubleRight" "malformed tree"
rdoubleLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
rdoubleLeft k1 p1 v1 t1 m1 (LLoser _ (E k2 p2 v2) t2 m2 t3) =
rsingleLeft k1 p1 v1 t1 m1 (lsingleRight k2 p2 v2 t2 m2 t3)
rdoubleLeft k1 p1 v1 t1 m1 (RLoser _ (E k2 p2 v2) t2 m2 t3) =
rsingleLeft k1 p1 v1 t1 m1 (rsingleRight k2 p2 v2 t2 m2 t3)
rdoubleLeft _ _ _ _ _ _ = moduleError "rdoubleLeft" "malformed tree"
rdoubleRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
rdoubleRight k1 p1 v1 (LLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =
rsingleRight k1 p1 v1 (lsingleLeft k2 p2 v2 t1 m1 t2) m2 t3
rdoubleRight k1 p1 v1 (RLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =
rsingleRight k1 p1 v1 (rsingleLeft k2 p2 v2 t1 m1 t2) m2 t3
rdoubleRight _ _ _ _ _ _ = moduleError "rdoubleRight" "malformed tree"
| Take two pennants and returns a new pennant that is the union of
the two with the precondition that the keys in the first tree are
strictly smaller than the keys in the second tree .
play :: PSQ a -> PSQ a -> PSQ a
Void `play` t' = t'
t `play` Void = t
Winner e@(E k p v) t m `play` Winner e'@(E k' p' v') t' m'
| p <= p' = Winner e (rbalance k' p' v' t m t') m'
| otherwise = Winner e' (lbalance k p v t m t') m'
# INLINE play #
unsafePlay :: PSQ a -> PSQ a -> PSQ a
Void `unsafePlay` t' = t'
t `unsafePlay` Void = t
Winner e@(E k p v) t m `unsafePlay` Winner e'@(E k' p' v') t' m'
| p <= p' = Winner e (rloser k' p' v' t m t') m'
| otherwise = Winner e' (lloser k p v t m t') m'
# INLINE unsafePlay #
data TourView a = Null
| (PSQ a) `Play` (PSQ a)
tourView :: PSQ a -> TourView a
tourView Void = Null
tourView (Winner e Start _) = Single e
tourView (Winner e (RLoser _ e' tl m tr) m') =
Winner e tl m `Play` Winner e' tr m'
tourView (Winner e (LLoser _ e' tl m tr) m') =
Winner e' tl m `Play` Winner e tr m'
moduleError :: String -> String -> a
moduleError fun msg = error ("GHC.Event.PSQ." ++ fun ++ ':' : ' ' : msg)
# NOINLINE moduleError #
Hughes 's efficient sequence type
newtype Sequ a = Sequ ([a] -> [a])
emptySequ :: Sequ a
emptySequ = Sequ (\as -> as)
singleSequ :: a -> Sequ a
singleSequ a = Sequ (\as -> a : as)
(<>) :: Sequ a -> Sequ a -> Sequ a
Sequ x1 <> Sequ x2 = Sequ (\as -> x1 (x2 as))
infixr 5 <>
seqToList :: Sequ a -> [a]
seqToList (Sequ x) = x []
instance Show a => Show (Sequ a) where
showsPrec d a = showsPrec d (seqToList a)
|
4a5c99818a6de7cacf3ddb860748c3a1fad1f83a00ea804d2f482a23e4c7e2ca | semilin/layoup | analysis.lisp | (in-package :layoup)
(defstruct metric
(name "" :type string)
(fn nil :type function)
ngram)
(defstruct metric-result
(positions nil :type list)
(result 0.0 :type single-float))
(defstruct metric-result-list
table)
(defstruct metric-list
bigraphs
trigraphs)
(defun* (new-metric -> metric)
((name string) (fn function) (ngram list))
(make-metric :name name
:fn fn
:ngram ngram))
(defun* classify-ngram
((metric metric)
(positions list))
(let ((result (apply (metric-fn metric) positions)))
(if result
(make-metric-result :positions positions :result result))))
(defun* (calculate-metrics -> metric-result-list)
((pos-fn function) (metric-list metric-list))
(let* ((positions nil)
(tricombinations nil)
(combinations nil)
(results (make-metric-result-list :table (make-hash-table :test 'eq)))
(table (metric-result-list-table results)))
;; create basic positions list
(loop for row from 0 to 2 do
(loop for col from 0 to 9 do
(push (funcall pos-fn col row) positions)))
;; create combinations
(loop for a in positions do
(loop for b in positions do
(push (list a b) combinations)
(loop for c in positions do
(push (list a b c) tricombinations))))
;; calculate metrics
(loop for comb in combinations do
(loop for metric in (metric-list-bigraphs metric-list)
do (let ((result (classify-ngram metric comb)))
(if result (push result (gethash metric table))))))
(loop for comb in tricombinations do
(loop for metric in (metric-list-trigraphs metric-list)
do (let ((result (classify-ngram metric comb)))
(if result (push result (gethash metric table))))))
results))
(defun* (ngraph-to-ngram -> list)
((ngraph list) (k array))
(declare (optimize (speed 3)
(safety 0))
(inline))
(mapcar (lambda (pos) (pos-to-key pos k)) ngraph))
(defun* (analyze-keys -> hash-table)
((corpus corpus) (k array) (metric-results metric-result-list))
(declare (optimize (speed 3) (safety 3)))
(let* ((table (metric-result-list-table metric-results))
(results (make-hash-table :size (hash-table-size table))))
(loop for metric being the hash-keys of table
using (hash-value values) do
(let ((corpus-ngrams (ecase (metric-ngram metric)
(:bigram (corpus-bigrams corpus))
(:skipgram (corpus-skipgrams corpus))
(:trigram (corpus-trigrams corpus)))))
(loop for value in values
do (let ((frequency (gethash (ngraph-to-ngram (metric-result-positions value) k) corpus-ngrams 0))
(metric-amount (metric-result-result value)))
(declare (type fixnum frequency))
(incf (the single-float (gethash metric results 0.0))
(the single-float (* metric-amount frequency)))))))
results))
(defun* (layout-metric-ngrams -> list)
((corpus corpus) (k array) (metric-results metric-result-list) (metric metric))
(sort (loop for value in (gethash metric (metric-result-list-table metric-results))
collect (let ((ngram (ngraph-to-ngram (metric-result-positions value) k))
(corpus-ngrams (ecase (metric-ngram metric)
(:bigram (corpus-bigrams corpus))
(:skipgram (corpus-skipgrams corpus))
(:trigram (corpus-trigrams corpus)))))
(list ngram
(* (gethash ngram corpus-ngrams 0.0)
(metric-result-result value)))))
(lambda (a b) (> (second a)
(second b)))))
| null | https://raw.githubusercontent.com/semilin/layoup/27ec9ba9a9388cd944ac46206d10424e3ab45499/src/analysis.lisp | lisp | create basic positions list
create combinations
calculate metrics | (in-package :layoup)
(defstruct metric
(name "" :type string)
(fn nil :type function)
ngram)
(defstruct metric-result
(positions nil :type list)
(result 0.0 :type single-float))
(defstruct metric-result-list
table)
(defstruct metric-list
bigraphs
trigraphs)
(defun* (new-metric -> metric)
((name string) (fn function) (ngram list))
(make-metric :name name
:fn fn
:ngram ngram))
(defun* classify-ngram
((metric metric)
(positions list))
(let ((result (apply (metric-fn metric) positions)))
(if result
(make-metric-result :positions positions :result result))))
(defun* (calculate-metrics -> metric-result-list)
((pos-fn function) (metric-list metric-list))
(let* ((positions nil)
(tricombinations nil)
(combinations nil)
(results (make-metric-result-list :table (make-hash-table :test 'eq)))
(table (metric-result-list-table results)))
(loop for row from 0 to 2 do
(loop for col from 0 to 9 do
(push (funcall pos-fn col row) positions)))
(loop for a in positions do
(loop for b in positions do
(push (list a b) combinations)
(loop for c in positions do
(push (list a b c) tricombinations))))
(loop for comb in combinations do
(loop for metric in (metric-list-bigraphs metric-list)
do (let ((result (classify-ngram metric comb)))
(if result (push result (gethash metric table))))))
(loop for comb in tricombinations do
(loop for metric in (metric-list-trigraphs metric-list)
do (let ((result (classify-ngram metric comb)))
(if result (push result (gethash metric table))))))
results))
(defun* (ngraph-to-ngram -> list)
((ngraph list) (k array))
(declare (optimize (speed 3)
(safety 0))
(inline))
(mapcar (lambda (pos) (pos-to-key pos k)) ngraph))
(defun* (analyze-keys -> hash-table)
((corpus corpus) (k array) (metric-results metric-result-list))
(declare (optimize (speed 3) (safety 3)))
(let* ((table (metric-result-list-table metric-results))
(results (make-hash-table :size (hash-table-size table))))
(loop for metric being the hash-keys of table
using (hash-value values) do
(let ((corpus-ngrams (ecase (metric-ngram metric)
(:bigram (corpus-bigrams corpus))
(:skipgram (corpus-skipgrams corpus))
(:trigram (corpus-trigrams corpus)))))
(loop for value in values
do (let ((frequency (gethash (ngraph-to-ngram (metric-result-positions value) k) corpus-ngrams 0))
(metric-amount (metric-result-result value)))
(declare (type fixnum frequency))
(incf (the single-float (gethash metric results 0.0))
(the single-float (* metric-amount frequency)))))))
results))
(defun* (layout-metric-ngrams -> list)
((corpus corpus) (k array) (metric-results metric-result-list) (metric metric))
(sort (loop for value in (gethash metric (metric-result-list-table metric-results))
collect (let ((ngram (ngraph-to-ngram (metric-result-positions value) k))
(corpus-ngrams (ecase (metric-ngram metric)
(:bigram (corpus-bigrams corpus))
(:skipgram (corpus-skipgrams corpus))
(:trigram (corpus-trigrams corpus)))))
(list ngram
(* (gethash ngram corpus-ngrams 0.0)
(metric-result-result value)))))
(lambda (a b) (> (second a)
(second b)))))
|
2fb6348b75ae74feddf4e06ebe92ff7f3b7ecde19c0612038e3a68e47c73d047 | lojic/LearningRacket | ex12a.rkt | #lang racket
(require "../lojic.rkt")
(define principal (string->number (gets "Enter the principal: ")))
(define int-rate (/ (string->number (gets "Enter the rate of interest: ")) 100.0))
(define num-years (string->number (gets "Enter the number of years: ")))
(define amount (* principal
(+ 1
(* int-rate num-years))))
(printf "After ~a years at ~a%, the investment will be worth $~a"
num-years (* int-rate 100.0) (~0.2r amount))
| null | https://raw.githubusercontent.com/lojic/LearningRacket/eb0e75b0e16d3e0a91b8fa6612e2678a9e12e8c7/exercises-for-programmers/12-computing-simple-interest/ex12a.rkt | racket | #lang racket
(require "../lojic.rkt")
(define principal (string->number (gets "Enter the principal: ")))
(define int-rate (/ (string->number (gets "Enter the rate of interest: ")) 100.0))
(define num-years (string->number (gets "Enter the number of years: ")))
(define amount (* principal
(+ 1
(* int-rate num-years))))
(printf "After ~a years at ~a%, the investment will be worth $~a"
num-years (* int-rate 100.0) (~0.2r amount))
| |
aa25d06b848eaad20542ea74406b9356c37e0e1e3b0694edb308b62220c5cc5b | static-analysis-engineering/codehawk | jCHVarInfoCollectors.mli | = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Java Analyzer
Author :
------------------------------------------------------------------------------
The MIT License ( MIT )
Copyright ( c ) 2005 - 2020 Kestrel Technology LLC
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 .
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Java Analyzer
Author: Anca Browne
------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2005-2020 Kestrel Technology LLC
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.
============================================================================= *)
chlib
open CHLanguage
open CHNumerical
open CHUtils
(* jchlib *)
open JCHBasicTypesAPI
val collect_var_info :
procedure_int
-> method_int
-> SymbolCollections.set_t VariableCollections.table_t
* SymbolCollections.set_t VariableCollections.table_t
* SymbolCollections.set_t VariableCollections.table_t
* IntCollections.set_t VariableCollections.table_t
* VariableCollections.set_t VariableCollections.table_t
* JCHPrintUtils.pretty_var_list_t VariableCollections.table_t
* variable_t IntCollections.table_t
* (int * operation_t list) list
* SymbolCollections.set_t VariableCollections.table_t VariableCollections.table_t
* SymbolCollections.set_t VariableCollections.table_t VariableCollections.table_t
* numerical_t VariableCollections.table_t
* IntCollections.set_t VariableCollections.table_t
* IntCollections.set_t VariableCollections.table_t
* variable_t IntCollections.table_t IntCollections.table_t
| null | https://raw.githubusercontent.com/static-analysis-engineering/codehawk/98ced4d5e6d7989575092df232759afc2cb851f6/CodeHawk/CHJ/jchsys/jCHVarInfoCollectors.mli | ocaml | jchlib | = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Java Analyzer
Author :
------------------------------------------------------------------------------
The MIT License ( MIT )
Copyright ( c ) 2005 - 2020 Kestrel Technology LLC
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 .
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Java Analyzer
Author: Anca Browne
------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2005-2020 Kestrel Technology LLC
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.
============================================================================= *)
chlib
open CHLanguage
open CHNumerical
open CHUtils
open JCHBasicTypesAPI
val collect_var_info :
procedure_int
-> method_int
-> SymbolCollections.set_t VariableCollections.table_t
* SymbolCollections.set_t VariableCollections.table_t
* SymbolCollections.set_t VariableCollections.table_t
* IntCollections.set_t VariableCollections.table_t
* VariableCollections.set_t VariableCollections.table_t
* JCHPrintUtils.pretty_var_list_t VariableCollections.table_t
* variable_t IntCollections.table_t
* (int * operation_t list) list
* SymbolCollections.set_t VariableCollections.table_t VariableCollections.table_t
* SymbolCollections.set_t VariableCollections.table_t VariableCollections.table_t
* numerical_t VariableCollections.table_t
* IntCollections.set_t VariableCollections.table_t
* IntCollections.set_t VariableCollections.table_t
* variable_t IntCollections.table_t IntCollections.table_t
|
d152e8aa9125f7caa6d75d1235dc75e550e9332046df51bfc56cc49a1213f271 | waddlaw/TAPL | UntypedLambda.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TypeApplications #
module UntypedLambda where
import Data.Either
import Language.Core.Pretty
import Language.Core.Types
import Language.UntypedLambda
import qualified Language.UntypedLambda.Examples as UL
import Language.UntypedLambda.Lib.Base
import Language.UntypedLambda.Lib.Bool
import Language.UntypedLambda.Lib.Church
import Language.UntypedLambda.Lib.List
import Language.UntypedLambda.Lib.Pair
import Test.Tasty
import Test.Tasty.HUnit
import Prelude hiding (and, fst, head, id, not, or, snd, tail)
test_ul :: TestTree
test_ul =
testGroup
"UntypedLambda"
[ testCase "pretty" $ do
prettyText @UntypedLambda (TmVar "x") @?= "x"
prettyText @UntypedLambda (TmLam "x" "x") @?= "λx. x"
prettyText @UntypedLambda (TmApp "x" "y") @?= "x y",
testCase "parser" $ do
runUlParser "x" @?= Right "x"
runUlParser "x1y" @?= Right "x1y"
isLeft (runUlParser "Xyz") @?= True
isLeft (runUlParser "123x") @?= True
runUlParser "λx. t" @?= Right (TmLam "x" "t")
isLeft (runUlParser "λ. Ab") @?= True
runUlParser "s t u" @?= Right UL.example1
runUlParser "s t u" @?= runUlParser "(s t) u"
runUlParser "λx. λy. x y x" @?= Right UL.example2
runUlParser "λx. λy. x y x" @?= runUlParser "λx. (λy. ((x y) x))"
runUlParser "(λx.x) ((λx.x) (λz.(λx.x) z))" @?= Right UL.example3
-- Bool
runUlParser "tru" @?= Right tru
runUlParser "fls" @?= Right fls
runUlParser "test" @?= Right test
runUlParser "and" @?= Right and
runUlParser "or" @?= Right or
runUlParser "not" @?= Right not
-- pair
runUlParser "pair" @?= Right pair
runUlParser "fst" @?= Right fst
runUlParser "snd" @?= Right snd
-- church
runUlParser "c10" @?= Right (c 10)
runUlParser "c0" @?= Right (c 0)
runUlParser "c123" @?= Right (c 123)
runUlParser "scc" @?= Right scc
runUlParser "plus" @?= Right plus
runUlParser "times" @?= Right times
runUlParser "iszro" @?= Right iszro
runUlParser "prd" @?= Right prd
runUlParser "subtract" @?= Right subtract1
runUlParser "equal" @?= Right equal
-- list
runUlParser "nil" @?= Right nil
runUlParser "head" @?= Right head
runUlParser "isnil" @?= Right isnil
runUlParser "cons" @?= Right cons
runUlParser "tail" @?= Right tail,
testCase "isClosed" $ do
isClosed UL.example1 @?= False
isClosed UL.example2 @?= True
isClosed UL.example3 @?= True
isClosed UL.example4 @?= False
isClosed UL.example5 @?= True,
testCase "evaluate (NormalOrder)" $ do
reduceNormalOrder (TmApp (TmLam "x" "x") "y") @?= TmVar "y"
reduceNormalOrder UL.example6 @?= TmApp (TmApp "u" "r") (TmLam "x" "x")
reduceNormalOrder (TmApp (TmLam "x" (TmLam "y" (TmApp "x" "y"))) "z") @?= TmLam "y" (TmApp "z" "y")
reduceNormalOrder UL.example3 @?= TmApp id (TmLam "z" (TmApp id "z"))
reduceNormalOrder (TmApp id (TmLam "z" (TmApp id "z"))) @?= TmLam "z" (TmApp id "z")
reduceNormalOrder (TmLam "z" (TmApp id "z")) @?= TmLam "z" "z"
reduceNormalOrder (TmLam "z" "z") @?= TmLam "z" "z",
testCase "evaluate (CallByName)" $ do
reduceCallByName UL.example3 @?= TmApp id (TmLam "z" (TmApp id "z"))
reduceCallByName (TmApp id (TmLam "z" (TmApp id "z"))) @?= TmLam "z" (TmApp id "z")
reduceCallByName (TmLam "z" (TmApp id "z")) @?= TmLam "z" (TmApp id "z"),
testCase "evaluate (CallByValue)" $ do
reduceCallByValue UL.example3 @?= TmApp id (TmLam "z" (TmApp id "z"))
reduceCallByValue (TmApp id (TmLam "z" (TmApp id "z"))) @?= TmLam "z" (TmApp id "z")
reduceCallByValue (TmLam "z" (TmApp id "z")) @?= TmLam "z" (TmApp id "z"),
testCase "evaluate" $ do
eval NormalOrder UL.example3 @?= TmLam "z" "z"
eval CallByName UL.example3 @?= TmLam "z" (TmApp id "z")
eval CallByValue UL.example3 @?= TmLam "z" (TmApp id "z"),
testCase "subst" $ do
subst "x" (TmLam "z" (TmApp "z" "w")) (TmLam "y" "x") @?= TmLam "y" (TmLam "z" (TmApp "z" "w"))
subst "x" "y" (TmLam "x" "x") @?= TmLam "x" "x"
subst "x" "z" (TmLam "z" "x") @?= TmLam "z" "x",
testCase "size" $ do
size "x" @?= 1
size (TmApp "x" "x") @?= 2,
testCase "removenames" $ do
-- Ex6.1.1
removenames [] (c 0) @?= NlTmLam (NlTmLam "0")
removenames [] (c 2) @?= NlTmLam (NlTmLam (NlTmApp "1" (NlTmApp "1" "0")))
removenames [] plus @?= NlTmLam (NlTmLam (NlTmLam (NlTmLam (NlTmApp (NlTmApp "3" "1") (NlTmApp (NlTmApp "2" "1") "0")))))
let t = NlTmLam $ NlTmApp "1" $ NlTmLam $ NlTmApp (NlTmApp "1" "1") "0"
removenames [] fix @?= NlTmLam (NlTmApp t t)
let foo = TmApp (TmLam "x" $ TmLam "x" "x") (TmLam "x" "x")
removenames [] foo @?= NlTmApp (NlTmLam $ NlTmLam "0") (NlTmLam "0"),
testCase "restorenames" $ do
restorenames [] (NlTmLam (NlTmLam "0")) @?= TmLam "a0" (TmLam "a1" "a1")
restorenames [] (NlTmLam (NlTmLam (NlTmApp "1" (NlTmApp "1" "0")))) @?= TmLam "a0" (TmLam "a1" (TmApp "a0" (TmApp "a0" "a1")))
restorenames [] (NlTmLam (NlTmLam (NlTmLam (NlTmLam (NlTmApp (NlTmApp "3" "1") (NlTmApp (NlTmApp "2" "1") "0")))))) @?= TmLam "a0" (TmLam "a1" (TmLam "a2" (TmLam "a3" $ TmApp (TmApp "a0" "a2") (TmApp (TmApp "a1" "a2") "a3"))))
let t = NlTmLam $ NlTmApp "1" $ NlTmLam $ NlTmApp (NlTmApp "1" "1") "0"
t' = TmLam "a1" $ TmApp "a0" $ TmLam "a2" $ TmApp (TmApp "a1" "a1") "a2"
restorenames [] (NlTmLam (NlTmApp t t)) @?= TmLam "a0" (TmApp t' t')
restorenames [] (NlTmApp (NlTmLam $ NlTmLam "0") (NlTmLam "0")) @?= TmApp (TmLam "a0" $ TmLam "a1" "a1") (TmLam "a0" "a0"),
testCase "shift" $ do
shift 0 2 (NlTmLam $ NlTmLam $ NlTmApp "1" (NlTmApp "0" "2")) @?= NlTmLam (NlTmLam $ NlTmApp "1" (NlTmApp "0" "4"))
shift 0 2 (NlTmLam $ NlTmApp (NlTmApp "0" "1") (NlTmLam $ NlTmApp (NlTmApp "0" "1") "2")) @?= NlTmLam (NlTmApp (NlTmApp "0" "3") (NlTmLam $ NlTmApp (NlTmApp "0" "1") "4")),
testCase "namelessSubst" $ do
-- Ex6.2.5
let g = ["b", "a"]
let t1 = TmApp "b" (TmLam "x" $ TmLam "y" "b")
k1 = getNlTermVar $ removenames g "b"
s1 = removenames g "a"
nt1 = removenames g t1
namelessSubst k1 s1 nt1 @?= NlTmApp "1" (NlTmLam $ NlTmLam "3")
let t2 = TmApp "b" (TmLam "x" "b")
k2 = getNlTermVar $ removenames g "b"
s2 = removenames g $ TmApp "a" (TmLam "z" "a")
nt2 = removenames g t2
namelessSubst k2 s2 nt2 @?= NlTmApp (NlTmApp "1" (NlTmLam "2")) (NlTmLam $ NlTmApp "2" (NlTmLam "3"))
let t3 = TmLam "b" (TmApp "b" "a")
k3 = getNlTermVar $ removenames g "b"
s3 = removenames g "a"
nt3 = removenames g t3
namelessSubst k3 s3 nt3 @?= NlTmLam (NlTmApp "0" "2")
let t4 = TmLam "a" (TmApp "b" "a")
k4 = getNlTermVar $ removenames g "b"
s4 = removenames g "a"
nt4 = removenames g t4
namelessSubst k4 s4 nt4 @?= NlTmLam (NlTmApp "2" "0"),
testCase "reduceNameless" $
reduceNameless (NlTmApp (NlTmLam $ NlTmApp (NlTmApp "1" "0") "2") (NlTmLam "0"))
@?= NlTmApp (NlTmApp "0" (NlTmLam "0")) "1"
]
| null | https://raw.githubusercontent.com/waddlaw/TAPL/94576e46821aaf7abce6d1d828fc3ce6d05a40b8/subs/lambda-untyped/test/UntypedLambda.hs | haskell | # LANGUAGE OverloadedStrings #
Bool
pair
church
list
Ex6.1.1
Ex6.2.5 | # LANGUAGE TypeApplications #
module UntypedLambda where
import Data.Either
import Language.Core.Pretty
import Language.Core.Types
import Language.UntypedLambda
import qualified Language.UntypedLambda.Examples as UL
import Language.UntypedLambda.Lib.Base
import Language.UntypedLambda.Lib.Bool
import Language.UntypedLambda.Lib.Church
import Language.UntypedLambda.Lib.List
import Language.UntypedLambda.Lib.Pair
import Test.Tasty
import Test.Tasty.HUnit
import Prelude hiding (and, fst, head, id, not, or, snd, tail)
test_ul :: TestTree
test_ul =
testGroup
"UntypedLambda"
[ testCase "pretty" $ do
prettyText @UntypedLambda (TmVar "x") @?= "x"
prettyText @UntypedLambda (TmLam "x" "x") @?= "λx. x"
prettyText @UntypedLambda (TmApp "x" "y") @?= "x y",
testCase "parser" $ do
runUlParser "x" @?= Right "x"
runUlParser "x1y" @?= Right "x1y"
isLeft (runUlParser "Xyz") @?= True
isLeft (runUlParser "123x") @?= True
runUlParser "λx. t" @?= Right (TmLam "x" "t")
isLeft (runUlParser "λ. Ab") @?= True
runUlParser "s t u" @?= Right UL.example1
runUlParser "s t u" @?= runUlParser "(s t) u"
runUlParser "λx. λy. x y x" @?= Right UL.example2
runUlParser "λx. λy. x y x" @?= runUlParser "λx. (λy. ((x y) x))"
runUlParser "(λx.x) ((λx.x) (λz.(λx.x) z))" @?= Right UL.example3
runUlParser "tru" @?= Right tru
runUlParser "fls" @?= Right fls
runUlParser "test" @?= Right test
runUlParser "and" @?= Right and
runUlParser "or" @?= Right or
runUlParser "not" @?= Right not
runUlParser "pair" @?= Right pair
runUlParser "fst" @?= Right fst
runUlParser "snd" @?= Right snd
runUlParser "c10" @?= Right (c 10)
runUlParser "c0" @?= Right (c 0)
runUlParser "c123" @?= Right (c 123)
runUlParser "scc" @?= Right scc
runUlParser "plus" @?= Right plus
runUlParser "times" @?= Right times
runUlParser "iszro" @?= Right iszro
runUlParser "prd" @?= Right prd
runUlParser "subtract" @?= Right subtract1
runUlParser "equal" @?= Right equal
runUlParser "nil" @?= Right nil
runUlParser "head" @?= Right head
runUlParser "isnil" @?= Right isnil
runUlParser "cons" @?= Right cons
runUlParser "tail" @?= Right tail,
testCase "isClosed" $ do
isClosed UL.example1 @?= False
isClosed UL.example2 @?= True
isClosed UL.example3 @?= True
isClosed UL.example4 @?= False
isClosed UL.example5 @?= True,
testCase "evaluate (NormalOrder)" $ do
reduceNormalOrder (TmApp (TmLam "x" "x") "y") @?= TmVar "y"
reduceNormalOrder UL.example6 @?= TmApp (TmApp "u" "r") (TmLam "x" "x")
reduceNormalOrder (TmApp (TmLam "x" (TmLam "y" (TmApp "x" "y"))) "z") @?= TmLam "y" (TmApp "z" "y")
reduceNormalOrder UL.example3 @?= TmApp id (TmLam "z" (TmApp id "z"))
reduceNormalOrder (TmApp id (TmLam "z" (TmApp id "z"))) @?= TmLam "z" (TmApp id "z")
reduceNormalOrder (TmLam "z" (TmApp id "z")) @?= TmLam "z" "z"
reduceNormalOrder (TmLam "z" "z") @?= TmLam "z" "z",
testCase "evaluate (CallByName)" $ do
reduceCallByName UL.example3 @?= TmApp id (TmLam "z" (TmApp id "z"))
reduceCallByName (TmApp id (TmLam "z" (TmApp id "z"))) @?= TmLam "z" (TmApp id "z")
reduceCallByName (TmLam "z" (TmApp id "z")) @?= TmLam "z" (TmApp id "z"),
testCase "evaluate (CallByValue)" $ do
reduceCallByValue UL.example3 @?= TmApp id (TmLam "z" (TmApp id "z"))
reduceCallByValue (TmApp id (TmLam "z" (TmApp id "z"))) @?= TmLam "z" (TmApp id "z")
reduceCallByValue (TmLam "z" (TmApp id "z")) @?= TmLam "z" (TmApp id "z"),
testCase "evaluate" $ do
eval NormalOrder UL.example3 @?= TmLam "z" "z"
eval CallByName UL.example3 @?= TmLam "z" (TmApp id "z")
eval CallByValue UL.example3 @?= TmLam "z" (TmApp id "z"),
testCase "subst" $ do
subst "x" (TmLam "z" (TmApp "z" "w")) (TmLam "y" "x") @?= TmLam "y" (TmLam "z" (TmApp "z" "w"))
subst "x" "y" (TmLam "x" "x") @?= TmLam "x" "x"
subst "x" "z" (TmLam "z" "x") @?= TmLam "z" "x",
testCase "size" $ do
size "x" @?= 1
size (TmApp "x" "x") @?= 2,
testCase "removenames" $ do
removenames [] (c 0) @?= NlTmLam (NlTmLam "0")
removenames [] (c 2) @?= NlTmLam (NlTmLam (NlTmApp "1" (NlTmApp "1" "0")))
removenames [] plus @?= NlTmLam (NlTmLam (NlTmLam (NlTmLam (NlTmApp (NlTmApp "3" "1") (NlTmApp (NlTmApp "2" "1") "0")))))
let t = NlTmLam $ NlTmApp "1" $ NlTmLam $ NlTmApp (NlTmApp "1" "1") "0"
removenames [] fix @?= NlTmLam (NlTmApp t t)
let foo = TmApp (TmLam "x" $ TmLam "x" "x") (TmLam "x" "x")
removenames [] foo @?= NlTmApp (NlTmLam $ NlTmLam "0") (NlTmLam "0"),
testCase "restorenames" $ do
restorenames [] (NlTmLam (NlTmLam "0")) @?= TmLam "a0" (TmLam "a1" "a1")
restorenames [] (NlTmLam (NlTmLam (NlTmApp "1" (NlTmApp "1" "0")))) @?= TmLam "a0" (TmLam "a1" (TmApp "a0" (TmApp "a0" "a1")))
restorenames [] (NlTmLam (NlTmLam (NlTmLam (NlTmLam (NlTmApp (NlTmApp "3" "1") (NlTmApp (NlTmApp "2" "1") "0")))))) @?= TmLam "a0" (TmLam "a1" (TmLam "a2" (TmLam "a3" $ TmApp (TmApp "a0" "a2") (TmApp (TmApp "a1" "a2") "a3"))))
let t = NlTmLam $ NlTmApp "1" $ NlTmLam $ NlTmApp (NlTmApp "1" "1") "0"
t' = TmLam "a1" $ TmApp "a0" $ TmLam "a2" $ TmApp (TmApp "a1" "a1") "a2"
restorenames [] (NlTmLam (NlTmApp t t)) @?= TmLam "a0" (TmApp t' t')
restorenames [] (NlTmApp (NlTmLam $ NlTmLam "0") (NlTmLam "0")) @?= TmApp (TmLam "a0" $ TmLam "a1" "a1") (TmLam "a0" "a0"),
testCase "shift" $ do
shift 0 2 (NlTmLam $ NlTmLam $ NlTmApp "1" (NlTmApp "0" "2")) @?= NlTmLam (NlTmLam $ NlTmApp "1" (NlTmApp "0" "4"))
shift 0 2 (NlTmLam $ NlTmApp (NlTmApp "0" "1") (NlTmLam $ NlTmApp (NlTmApp "0" "1") "2")) @?= NlTmLam (NlTmApp (NlTmApp "0" "3") (NlTmLam $ NlTmApp (NlTmApp "0" "1") "4")),
testCase "namelessSubst" $ do
let g = ["b", "a"]
let t1 = TmApp "b" (TmLam "x" $ TmLam "y" "b")
k1 = getNlTermVar $ removenames g "b"
s1 = removenames g "a"
nt1 = removenames g t1
namelessSubst k1 s1 nt1 @?= NlTmApp "1" (NlTmLam $ NlTmLam "3")
let t2 = TmApp "b" (TmLam "x" "b")
k2 = getNlTermVar $ removenames g "b"
s2 = removenames g $ TmApp "a" (TmLam "z" "a")
nt2 = removenames g t2
namelessSubst k2 s2 nt2 @?= NlTmApp (NlTmApp "1" (NlTmLam "2")) (NlTmLam $ NlTmApp "2" (NlTmLam "3"))
let t3 = TmLam "b" (TmApp "b" "a")
k3 = getNlTermVar $ removenames g "b"
s3 = removenames g "a"
nt3 = removenames g t3
namelessSubst k3 s3 nt3 @?= NlTmLam (NlTmApp "0" "2")
let t4 = TmLam "a" (TmApp "b" "a")
k4 = getNlTermVar $ removenames g "b"
s4 = removenames g "a"
nt4 = removenames g t4
namelessSubst k4 s4 nt4 @?= NlTmLam (NlTmApp "2" "0"),
testCase "reduceNameless" $
reduceNameless (NlTmApp (NlTmLam $ NlTmApp (NlTmApp "1" "0") "2") (NlTmLam "0"))
@?= NlTmApp (NlTmApp "0" (NlTmLam "0")) "1"
]
|
32ef5718e170b51c8ff655c969f2a4ce94da1c726e9ad32027dda6756b97239d | lillo/compiler-course-unipi | fun_analysis.ml |
Compiles with
$ ocamlbuild -use - ocamlfind -package ppx_deriving.std -use - menhir fun_analysis.byte
Compiles with
$ ocamlbuild -use-ocamlfind -package ppx_deriving.std -use-menhir fun_analysis.byte
*)
let () =
let channel =
if Array.length Sys.argv > 1 then
Sys.argv.(1) |> open_in
else
stdin
in
try
let lexbuf = Lexing.from_channel channel in
let prog = Fun_parser.main Fun_lexer.next_token lexbuf in
let annotated_prog = Fun_cfa.to_aexpr prog in
Printf.printf "Annotated expression:\n\n%s\n\n" (Fun_cfa.show_aexpr annotated_prog);
let constraints = Fun_cfa.constrs_of_aexpr annotated_prog in
Printf.printf "Generated constraints:\n\n";
List.iter (fun c ->
Printf.printf "%s\n\n" (Fun_cfa.Solver.show c)) constraints;
let solution = Fun_cfa.Solver.solve constraints in
Printf.printf "Solution:\n\n";
Seq.iter (fun (v, c) ->
Printf.printf "%s =: [" (Fun_cfa.Var.show v);
Seq.iter (fun s -> Printf.printf "%s " (Fun_cfa.Token.show s)) c;
Printf.printf "]\n"
) solution
with
| Fun_lexer.Lexing_error msg ->
Printf.fprintf stderr "%s%!" msg
| Fun_parser.Error ->
Printf.fprintf stderr "Syntax error.\n"
| null | https://raw.githubusercontent.com/lillo/compiler-course-unipi/1a5e909da6a2cc79e6f80645cd24fb5ff285be54/semantic-analysis-material/code/fun-cfa/fun_analysis.ml | ocaml |
Compiles with
$ ocamlbuild -use - ocamlfind -package ppx_deriving.std -use - menhir fun_analysis.byte
Compiles with
$ ocamlbuild -use-ocamlfind -package ppx_deriving.std -use-menhir fun_analysis.byte
*)
let () =
let channel =
if Array.length Sys.argv > 1 then
Sys.argv.(1) |> open_in
else
stdin
in
try
let lexbuf = Lexing.from_channel channel in
let prog = Fun_parser.main Fun_lexer.next_token lexbuf in
let annotated_prog = Fun_cfa.to_aexpr prog in
Printf.printf "Annotated expression:\n\n%s\n\n" (Fun_cfa.show_aexpr annotated_prog);
let constraints = Fun_cfa.constrs_of_aexpr annotated_prog in
Printf.printf "Generated constraints:\n\n";
List.iter (fun c ->
Printf.printf "%s\n\n" (Fun_cfa.Solver.show c)) constraints;
let solution = Fun_cfa.Solver.solve constraints in
Printf.printf "Solution:\n\n";
Seq.iter (fun (v, c) ->
Printf.printf "%s =: [" (Fun_cfa.Var.show v);
Seq.iter (fun s -> Printf.printf "%s " (Fun_cfa.Token.show s)) c;
Printf.printf "]\n"
) solution
with
| Fun_lexer.Lexing_error msg ->
Printf.fprintf stderr "%s%!" msg
| Fun_parser.Error ->
Printf.fprintf stderr "Syntax error.\n"
| |
93b7e24c161ab4d2c40b562ed3ece9751202a5b05d54c4b55126ac449db6c049 | lambdaisland/embedkit | find_db.clj | (ns find-db
(:require [lambdaisland.embedkit :as e]))
(def conn
(e/connect (read-string (slurp "dev/config.edn"))))
(e/find-database conn "example_tenant")
(:id (e/find-database conn "example_tenant"))
(e/mb-get conn [:database])
| null | https://raw.githubusercontent.com/lambdaisland/embedkit/f6273b8c7fb288482bd1125ad1615267bd1f6cbd/repl_sessions/find_db.clj | clojure | (ns find-db
(:require [lambdaisland.embedkit :as e]))
(def conn
(e/connect (read-string (slurp "dev/config.edn"))))
(e/find-database conn "example_tenant")
(:id (e/find-database conn "example_tenant"))
(e/mb-get conn [:database])
| |
2e1e8d0fab652ca063f0bb8417b94ec42fdd17c3fef73b163faccd155f12ab86 | gfngfn/otfed | encodeOperationCore.ml |
open Basic
open EncodeBasic
module Open = struct
type 'a encoder = Buffer.t -> ('a, Error.t) result
end
open Open
let run : 'a. ?initial_capacity:int -> 'a encoder -> (string * 'a, Error.t) result =
fun ?initial_capacity:(initial_capacity = 65535) enc ->
let open ResultMonad in
let buf = Buffer.create initial_capacity in
let res = enc buf in
match res with
| Ok(v) -> return @@ (Buffer.contents buf, v)
| Error(e) -> err @@ e
let ( >>= ) (enc1 : 'a encoder) (encf2 : 'a -> 'b encoder) : 'b encoder =
fun buf ->
let open ResultMonad in
enc1 buf >>= fun v ->
encf2 v buf
let return (v : 'a) : 'a encoder =
fun _buf ->
let open ResultMonad in
return v
let err (e : Error.t) : 'a encoder =
fun _buf ->
let open ResultMonad in
err @@ e
let current : int encoder =
fun buf ->
let open ResultMonad in
return @@ Buffer.length buf
let e_byte (ch : char) : unit encoder =
fun buf ->
let open ResultMonad in
Buffer.add_char buf ch;
return ()
let e_bytes (s : string) : unit encoder =
fun buf ->
let open ResultMonad in
Buffer.add_string buf s;
return ()
let e_pad (count : int) : unit encoder =
fun buf ->
let open ResultMonad in
Buffer.add_string buf (String.make count (Char.chr 0));
return ()
let encode_uint8_unsafe buf u =
let open ResultMonad in
Buffer.add_char buf (Char.chr u);
return ()
let encode_uint16_unsafe buf u =
let open ResultMonad in
let b0 = u lsr 8 in
let b1 = u - (b0 lsl 8) in
Buffer.add_char buf (Char.chr b0);
Buffer.add_char buf (Char.chr b1);
return ()
let encode_uint24_unsafe buf u =
let open ResultMonad in
let b0 = u lsr 16 in
let r0 = u - (b0 lsl 16) in
let b1 = r0 lsr 8 in
let b2 = r0 - (b1 lsl 8) in
Buffer.add_char buf (Char.chr b0);
Buffer.add_char buf (Char.chr b1);
Buffer.add_char buf (Char.chr b2);
return ()
let encode_uint32_unsafe buf u =
let open ResultMonad in
let open WideInt in
let b0 = u lsr 24 in
let r0 = u -% (b0 lsl 24) in
let b1 = r0 lsr 16 in
let r1 = r0 -% (b1 lsl 16) in
let b2 = r1 lsr 8 in
let b3 = r1 -% (b2 lsl 8) in
Buffer.add_char buf (to_byte b0);
Buffer.add_char buf (to_byte b1);
Buffer.add_char buf (to_byte b2);
Buffer.add_char buf (to_byte b3);
return ()
let e_uint8 (n : int) : unit encoder =
fun buf ->
let open ResultMonad in
if 0 <= n && n < 256 then
encode_uint8_unsafe buf n
else
err @@ Error.NotEncodableAsUint8(n)
let e_int8 (n : int) : unit encoder =
fun buf ->
let open ResultMonad in
if -128 <= n && n < 128 then
let u = if n < 0 then n + 256 else n in
encode_uint8_unsafe buf u
else
err @@ Error.NotEncodableAsInt8(n)
let e_uint16 (n : int) : unit encoder =
fun buf ->
let open ResultMonad in
if 0 <= n && n < 65536 then
encode_uint16_unsafe buf n
else
err @@ Error.NotEncodableAsUint16(n)
let e_int16 (n : int) : unit encoder =
fun buf ->
let open ResultMonad in
if -32768 <= n && n < 32768 then
let u = if n < 0 then n + 65536 else n in
encode_uint16_unsafe buf u
else
err @@ Error.NotEncodableAsInt16(n)
let e_uint24 (n : int) : unit encoder =
fun buf ->
let open ResultMonad in
if 0 <= n && n < 0x1000000 then
encode_uint24_unsafe buf n
else
err @@ Error.NotEncodableAsUint24(n)
let e_uint32 (n : wint) : unit encoder =
fun buf ->
let open ResultMonad in
if WideInt.is_in_uint32 n then
encode_uint32_unsafe buf n
else
err @@ Error.NotEncodableAsUint32(n)
let e_int32 (n : wint) : unit encoder =
fun buf ->
let open ResultMonad in
if WideInt.is_in_int32 n then
let u =
let open WideInt in
if is_neg n then n +% (!%% 0x10000000L) else n
in
encode_uint32_unsafe buf u
else
err @@ Error.NotEncodableAsInt32(n)
let e_timestamp (n : wint) : unit encoder =
fun buf ->
let open ResultMonad in
let open WideInt in
if is_in_int64 n then
let u = if is_neg n then !% 0 else n in (* temporary *)
let q0 = u lsr 32 in
let q1 = u -% (q0 lsl 32) in
encode_uint32_unsafe buf q0 >>= fun () ->
encode_uint32_unsafe buf q1
else
err @@ Error.NotEncodableAsTimestamp(n)
| null | https://raw.githubusercontent.com/gfngfn/otfed/aa2624d29f2fea934c65308816fb6788f3bd818a/src/encodeOperationCore.ml | ocaml | temporary |
open Basic
open EncodeBasic
module Open = struct
type 'a encoder = Buffer.t -> ('a, Error.t) result
end
open Open
let run : 'a. ?initial_capacity:int -> 'a encoder -> (string * 'a, Error.t) result =
fun ?initial_capacity:(initial_capacity = 65535) enc ->
let open ResultMonad in
let buf = Buffer.create initial_capacity in
let res = enc buf in
match res with
| Ok(v) -> return @@ (Buffer.contents buf, v)
| Error(e) -> err @@ e
let ( >>= ) (enc1 : 'a encoder) (encf2 : 'a -> 'b encoder) : 'b encoder =
fun buf ->
let open ResultMonad in
enc1 buf >>= fun v ->
encf2 v buf
let return (v : 'a) : 'a encoder =
fun _buf ->
let open ResultMonad in
return v
let err (e : Error.t) : 'a encoder =
fun _buf ->
let open ResultMonad in
err @@ e
let current : int encoder =
fun buf ->
let open ResultMonad in
return @@ Buffer.length buf
let e_byte (ch : char) : unit encoder =
fun buf ->
let open ResultMonad in
Buffer.add_char buf ch;
return ()
let e_bytes (s : string) : unit encoder =
fun buf ->
let open ResultMonad in
Buffer.add_string buf s;
return ()
let e_pad (count : int) : unit encoder =
fun buf ->
let open ResultMonad in
Buffer.add_string buf (String.make count (Char.chr 0));
return ()
let encode_uint8_unsafe buf u =
let open ResultMonad in
Buffer.add_char buf (Char.chr u);
return ()
let encode_uint16_unsafe buf u =
let open ResultMonad in
let b0 = u lsr 8 in
let b1 = u - (b0 lsl 8) in
Buffer.add_char buf (Char.chr b0);
Buffer.add_char buf (Char.chr b1);
return ()
let encode_uint24_unsafe buf u =
let open ResultMonad in
let b0 = u lsr 16 in
let r0 = u - (b0 lsl 16) in
let b1 = r0 lsr 8 in
let b2 = r0 - (b1 lsl 8) in
Buffer.add_char buf (Char.chr b0);
Buffer.add_char buf (Char.chr b1);
Buffer.add_char buf (Char.chr b2);
return ()
let encode_uint32_unsafe buf u =
let open ResultMonad in
let open WideInt in
let b0 = u lsr 24 in
let r0 = u -% (b0 lsl 24) in
let b1 = r0 lsr 16 in
let r1 = r0 -% (b1 lsl 16) in
let b2 = r1 lsr 8 in
let b3 = r1 -% (b2 lsl 8) in
Buffer.add_char buf (to_byte b0);
Buffer.add_char buf (to_byte b1);
Buffer.add_char buf (to_byte b2);
Buffer.add_char buf (to_byte b3);
return ()
let e_uint8 (n : int) : unit encoder =
fun buf ->
let open ResultMonad in
if 0 <= n && n < 256 then
encode_uint8_unsafe buf n
else
err @@ Error.NotEncodableAsUint8(n)
let e_int8 (n : int) : unit encoder =
fun buf ->
let open ResultMonad in
if -128 <= n && n < 128 then
let u = if n < 0 then n + 256 else n in
encode_uint8_unsafe buf u
else
err @@ Error.NotEncodableAsInt8(n)
let e_uint16 (n : int) : unit encoder =
fun buf ->
let open ResultMonad in
if 0 <= n && n < 65536 then
encode_uint16_unsafe buf n
else
err @@ Error.NotEncodableAsUint16(n)
let e_int16 (n : int) : unit encoder =
fun buf ->
let open ResultMonad in
if -32768 <= n && n < 32768 then
let u = if n < 0 then n + 65536 else n in
encode_uint16_unsafe buf u
else
err @@ Error.NotEncodableAsInt16(n)
let e_uint24 (n : int) : unit encoder =
fun buf ->
let open ResultMonad in
if 0 <= n && n < 0x1000000 then
encode_uint24_unsafe buf n
else
err @@ Error.NotEncodableAsUint24(n)
let e_uint32 (n : wint) : unit encoder =
fun buf ->
let open ResultMonad in
if WideInt.is_in_uint32 n then
encode_uint32_unsafe buf n
else
err @@ Error.NotEncodableAsUint32(n)
let e_int32 (n : wint) : unit encoder =
fun buf ->
let open ResultMonad in
if WideInt.is_in_int32 n then
let u =
let open WideInt in
if is_neg n then n +% (!%% 0x10000000L) else n
in
encode_uint32_unsafe buf u
else
err @@ Error.NotEncodableAsInt32(n)
let e_timestamp (n : wint) : unit encoder =
fun buf ->
let open ResultMonad in
let open WideInt in
if is_in_int64 n then
let q0 = u lsr 32 in
let q1 = u -% (q0 lsl 32) in
encode_uint32_unsafe buf q0 >>= fun () ->
encode_uint32_unsafe buf q1
else
err @@ Error.NotEncodableAsTimestamp(n)
|
ceadc1bcf4c1404cbc7d84052e7f780d41ca88433e1fbdd913ad794f304e9346 | sgbj/MaximaSharp | displm.lisp | -*- Mode : Lisp ; Package : Maxima ; Syntax : Common - Lisp ; Base : 10 -*- ; ; ; ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The data in this file contains enhancments. ;;;;;
;;; ;;;;;
Copyright ( c ) 1984,1987 by , University of Texas ; ; ; ; ;
;;; All rights reserved ;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
( c ) Copyright 1982 Massachusetts Institute of Technology ; ; ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package :maxima)
(macsyma-module displm macro)
(declare-top
;; evaluate for declarations
(special
^w ;If T, then no output goes to the console.
linel ;Width of screen.
ttyheight ;Height of screen.
width height depth maxht maxdp level size lop rop break right
bkpt bkptwd bkptht bkptdp bkptlevel bkptout lines
oldrow oldcol display-file in-p
mratp $aliases))
macros for the package .
( PUSH - STRING " foo " RESULT ) -- > ( SETQ RESULT ( ' ( # /o # /o # /f ) RESULT ) )
(defmacro push-string (string symbol)
(check-arg string stringp "a string")
(check-arg symbol symbolp "a symbol")
`(setq ,symbol (list* ,@(nreverse (exploden string)) ,symbol)))
Macros for setting up dispatch table .
;; Don't call this DEF-DISPLA, since it shouldn't be annotated by
TAGS and @. Syntax is :
;; (DISPLA-DEF [<operator>] [<dissym> | <l-dissym> <r-dissym>] [<lbp>] [<rbp>])
If only one integer appears in the form , then it is taken to be an RBP .
This should be modified to use GJC 's dispatch scheme where the subr
object is placed directly on the symbol 's property list and
;; is used when dispatching.
(defmacro displa-def (operator dim-function &rest rest &aux l-dissym r-dissym lbp rbp)
(dolist (x rest)
(cond ((stringp x)
(if l-dissym (setq r-dissym x) (setq l-dissym x)))
((integerp x)
(if rbp (setq lbp rbp))
(setq rbp x))
(t (merror "DISPLA-DEF: unrecognized object: ~a" x))))
(when l-dissym
(setq l-dissym (if r-dissym
(cons (exploden l-dissym) (exploden r-dissym))
(exploden l-dissym))))
`(progn
(defprop ,operator ,dim-function dimension)
,(when l-dissym `(defprop ,operator ,l-dissym dissym))
,(when lbp `(defprop ,operator ,lbp lbp))
,(when rbp `(defprop ,operator ,rbp rbp))))
| null | https://raw.githubusercontent.com/sgbj/MaximaSharp/75067d7e045b9ed50883b5eb09803b4c8f391059/Test/bin/Debug/Maxima-5.30.0/share/maxima/5.30.0/src/displm.lisp | lisp | Package : Maxima ; Syntax : Common - Lisp ; Base : 10 -*- ; ; ; ;
The data in this file contains enhancments. ;;;;;
;;;;;
; ; ; ;
All rights reserved ;;;;;
; ;
evaluate for declarations
If T, then no output goes to the console.
Width of screen.
Height of screen.
Don't call this DEF-DISPLA, since it shouldn't be annotated by
(DISPLA-DEF [<operator>] [<dissym> | <l-dissym> <r-dissym>] [<lbp>] [<rbp>])
is used when dispatching. |
(in-package :maxima)
(macsyma-module displm macro)
(declare-top
(special
width height depth maxht maxdp level size lop rop break right
bkpt bkptwd bkptht bkptdp bkptlevel bkptout lines
oldrow oldcol display-file in-p
mratp $aliases))
macros for the package .
( PUSH - STRING " foo " RESULT ) -- > ( SETQ RESULT ( ' ( # /o # /o # /f ) RESULT ) )
(defmacro push-string (string symbol)
(check-arg string stringp "a string")
(check-arg symbol symbolp "a symbol")
`(setq ,symbol (list* ,@(nreverse (exploden string)) ,symbol)))
Macros for setting up dispatch table .
TAGS and @. Syntax is :
If only one integer appears in the form , then it is taken to be an RBP .
This should be modified to use GJC 's dispatch scheme where the subr
object is placed directly on the symbol 's property list and
(defmacro displa-def (operator dim-function &rest rest &aux l-dissym r-dissym lbp rbp)
(dolist (x rest)
(cond ((stringp x)
(if l-dissym (setq r-dissym x) (setq l-dissym x)))
((integerp x)
(if rbp (setq lbp rbp))
(setq rbp x))
(t (merror "DISPLA-DEF: unrecognized object: ~a" x))))
(when l-dissym
(setq l-dissym (if r-dissym
(cons (exploden l-dissym) (exploden r-dissym))
(exploden l-dissym))))
`(progn
(defprop ,operator ,dim-function dimension)
,(when l-dissym `(defprop ,operator ,l-dissym dissym))
,(when lbp `(defprop ,operator ,lbp lbp))
,(when rbp `(defprop ,operator ,rbp rbp))))
|
28f216c6c722263b1208c812c27adc5ecc081f835333e009cd311b5aa2637825 | uw-unsat/leanette-popl22-artifact | model-completion.rkt | #lang racket
(require
racket/hash
(only-in rosette term-cache constant? model sat)
(only-in rosette/base/core/type solvable-default get-type))
(provide complete)
; Returns a completion of the given solution that
; binds the provided constants to default concrete values.
; If no constants are provided, it uses the set of all constants
; that are present in the current term-cache.
(define complete
(case-lambda
[(sol)
(complete sol (filter constant? (hash-values (term-cache))))]
[(sol consts)
(match sol
[(model bindings)
(sat
(hash-union
bindings
(for/hash ([c consts] #:unless (dict-has-key? bindings c))
(values c (solvable-default (get-type c))))))]
[_ (error 'complete "expected a sat? solution, given ~a" sol)])]))
| null | https://raw.githubusercontent.com/uw-unsat/leanette-popl22-artifact/80fea2519e61b45a283fbf7903acdf6d5528dbe7/rosette-benchmarks-3/neutrons/therapyControl-symbolic/model-completion.rkt | racket | Returns a completion of the given solution that
binds the provided constants to default concrete values.
If no constants are provided, it uses the set of all constants
that are present in the current term-cache. | #lang racket
(require
racket/hash
(only-in rosette term-cache constant? model sat)
(only-in rosette/base/core/type solvable-default get-type))
(provide complete)
(define complete
(case-lambda
[(sol)
(complete sol (filter constant? (hash-values (term-cache))))]
[(sol consts)
(match sol
[(model bindings)
(sat
(hash-union
bindings
(for/hash ([c consts] #:unless (dict-has-key? bindings c))
(values c (solvable-default (get-type c))))))]
[_ (error 'complete "expected a sat? solution, given ~a" sol)])]))
|
12ed6f01b3c914c5597042008a5912d57f06dab4e888f73d4e132bf23a2cd058 | RokLenarcic/datalevin-pathom | fulcro_middleware_test.clj | (ns org.clojars.roklenarcic.datalevin-pathom.fulcro-middleware-test
(:require [clojure.test :refer :all]
[com.fulcrologic.rad.attributes :as attr]
[com.fulcrologic.rad.form :as form]
[org.clojars.roklenarcic.datalevin-pathom.fulcro-middleware :as fm]
[org.clojars.roklenarcic.datalevin-pathom.test-attributes :as a]
[org.clojars.roklenarcic.datalevin-pathom.options :as o]
[org.clojars.roklenarcic.test-db :as test-db]
[com.wsscode.pathom3.connect.indexes :as pci]
[com.wsscode.pathom3.plugin :as p.plugin]
[org.clojars.roklenarcic.datalevin-pathom :as p]
[com.wsscode.pathom3.interface.eql :as p.eql]
[com.fulcrologic.fulcro.algorithms.tempid :as tempid]
[com.fulcrologic.rad.pathom3 :as rad.p3]))
(def env-wrappers (-> (attr/wrap-env a/attributes)
(form/wrap-env fm/save-middleware fm/delete-middleware)))
(defn parser []
(let [p (-> {o/connections {:test test-db/*conn*}}
(pci/register (p/automatic-resolvers a/attributes :test))
(pci/register (rad.p3/convert-resolvers form/resolvers))
(p.plugin/register-plugin rad.p3/attribute-error-plugin)
(p.plugin/register-plugin rad.p3/rewrite-mutation-exceptions)
env-wrappers
p.eql/boundary-interface)]
(fn [env eql]
(p env {:pathom/eql eql :pathom/lenient-mode? true}))))
(defn ->delta [entity id-key]
{::form/master-pk id-key
::form/id (id-key entity)
::form/delta {[id-key (id-key entity)]
(reduce-kv
(fn [m k v]
(assoc m k {:after v}))
{}
entity)}})
(use-fixtures :each test-db/with-conn)
(deftest middleware-test
(let [p (parser)]
(let [tid (tempid/tempid)
r1 (p {} `[(form/save-as-form ~(->delta {::a/id3 tid ::a/name "Rok X"} ::a/id3))])
{{:keys [tempids] ::a/keys [id3]} `form/save-as-form} r1]
(is (= [`form/save-as-form] (keys r1)))
(is (= {tid id3} tempids))
(is (= {[::a/id3 id3] {::a/id3 id3 ::a/name "Rok X"}}
(p {} [{[::a/id3 id3] [::a/id3 ::a/name]}])))
(is (= {`form/delete-entity {}} (p {} [`(form/delete-entity [::a/id3 ~id3])])))
(is (= {[:org.clojars.roklenarcic.datalevin-pathom.test-attributes/id3 id3] {::a/id3 id3}}
(p {} [{[::a/id3 id3] [::a/id3 ::a/name]}])))))
(let [p (parser)]
(let [tid (tempid/tempid)
r1 (p {} `[(form/save-as-form ~(->delta {::a/id tid ::a/name "Rok X"} ::a/id))])
{{:keys [tempids] ::a/keys [id]} `form/save-as-form} r1]
(is (= [`form/save-as-form] (keys r1)))
(is (= {tid id} tempids))
(is (= {[::a/id id] {::a/id id ::a/name "Rok X"}}
(p {} [{[::a/id id] [::a/id ::a/name]}])))
(is (= {`form/delete-entity {}} (p {} [`(form/delete-entity [::a/id ~id])])))
(is (= {[:org.clojars.roklenarcic.datalevin-pathom.test-attributes/id id] {::a/id id}}
(p {} [{[::a/id id] [::a/id ::a/name]}]))))))
| null | https://raw.githubusercontent.com/RokLenarcic/datalevin-pathom/2a4d02042790e2cf2bdd8b2954a52997b133bdc6/test/org/clojars/roklenarcic/datalevin_pathom/fulcro_middleware_test.clj | clojure | (ns org.clojars.roklenarcic.datalevin-pathom.fulcro-middleware-test
(:require [clojure.test :refer :all]
[com.fulcrologic.rad.attributes :as attr]
[com.fulcrologic.rad.form :as form]
[org.clojars.roklenarcic.datalevin-pathom.fulcro-middleware :as fm]
[org.clojars.roklenarcic.datalevin-pathom.test-attributes :as a]
[org.clojars.roklenarcic.datalevin-pathom.options :as o]
[org.clojars.roklenarcic.test-db :as test-db]
[com.wsscode.pathom3.connect.indexes :as pci]
[com.wsscode.pathom3.plugin :as p.plugin]
[org.clojars.roklenarcic.datalevin-pathom :as p]
[com.wsscode.pathom3.interface.eql :as p.eql]
[com.fulcrologic.fulcro.algorithms.tempid :as tempid]
[com.fulcrologic.rad.pathom3 :as rad.p3]))
(def env-wrappers (-> (attr/wrap-env a/attributes)
(form/wrap-env fm/save-middleware fm/delete-middleware)))
(defn parser []
(let [p (-> {o/connections {:test test-db/*conn*}}
(pci/register (p/automatic-resolvers a/attributes :test))
(pci/register (rad.p3/convert-resolvers form/resolvers))
(p.plugin/register-plugin rad.p3/attribute-error-plugin)
(p.plugin/register-plugin rad.p3/rewrite-mutation-exceptions)
env-wrappers
p.eql/boundary-interface)]
(fn [env eql]
(p env {:pathom/eql eql :pathom/lenient-mode? true}))))
(defn ->delta [entity id-key]
{::form/master-pk id-key
::form/id (id-key entity)
::form/delta {[id-key (id-key entity)]
(reduce-kv
(fn [m k v]
(assoc m k {:after v}))
{}
entity)}})
(use-fixtures :each test-db/with-conn)
(deftest middleware-test
(let [p (parser)]
(let [tid (tempid/tempid)
r1 (p {} `[(form/save-as-form ~(->delta {::a/id3 tid ::a/name "Rok X"} ::a/id3))])
{{:keys [tempids] ::a/keys [id3]} `form/save-as-form} r1]
(is (= [`form/save-as-form] (keys r1)))
(is (= {tid id3} tempids))
(is (= {[::a/id3 id3] {::a/id3 id3 ::a/name "Rok X"}}
(p {} [{[::a/id3 id3] [::a/id3 ::a/name]}])))
(is (= {`form/delete-entity {}} (p {} [`(form/delete-entity [::a/id3 ~id3])])))
(is (= {[:org.clojars.roklenarcic.datalevin-pathom.test-attributes/id3 id3] {::a/id3 id3}}
(p {} [{[::a/id3 id3] [::a/id3 ::a/name]}])))))
(let [p (parser)]
(let [tid (tempid/tempid)
r1 (p {} `[(form/save-as-form ~(->delta {::a/id tid ::a/name "Rok X"} ::a/id))])
{{:keys [tempids] ::a/keys [id]} `form/save-as-form} r1]
(is (= [`form/save-as-form] (keys r1)))
(is (= {tid id} tempids))
(is (= {[::a/id id] {::a/id id ::a/name "Rok X"}}
(p {} [{[::a/id id] [::a/id ::a/name]}])))
(is (= {`form/delete-entity {}} (p {} [`(form/delete-entity [::a/id ~id])])))
(is (= {[:org.clojars.roklenarcic.datalevin-pathom.test-attributes/id id] {::a/id id}}
(p {} [{[::a/id id] [::a/id ::a/name]}]))))))
| |
480f348640342761f7127e49402faee6ddbc8e93d4401bbebf3f11ad09a9ef0d | leandrosilva/cameron | syslog_transform.erl | Copyright ( c ) 2010 < >
%%
%% 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(syslog_transform).
-export([parse_transform/2]).
parse_transform(Forms, _Options) ->
expand_forms(Forms).
expand_forms({attribute,_,module,Module}=Attr) ->
put(module, Module),
Attr;
expand_forms(Forms) when is_list(Forms) ->
[expand_forms(Form) || Form <- Forms];
expand_forms({call,L,{atom,_,log},Args}) ->
{call,L,{atom,L,log},[{atom,L,get(module)}|Args]};
expand_forms(Form) when is_tuple(Form) ->
Expanded = [expand_forms(F) || F <- tuple_to_list(Form)],
list_to_tuple(Expanded);
expand_forms(Form) ->
Form. | null | https://raw.githubusercontent.com/leandrosilva/cameron/34051395b620d2c3cb2cb63c854e65234786a176/deps/erlang_syslog/src/syslog_transform.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. | Copyright ( c ) 2010 < >
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(syslog_transform).
-export([parse_transform/2]).
parse_transform(Forms, _Options) ->
expand_forms(Forms).
expand_forms({attribute,_,module,Module}=Attr) ->
put(module, Module),
Attr;
expand_forms(Forms) when is_list(Forms) ->
[expand_forms(Form) || Form <- Forms];
expand_forms({call,L,{atom,_,log},Args}) ->
{call,L,{atom,L,log},[{atom,L,get(module)}|Args]};
expand_forms(Form) when is_tuple(Form) ->
Expanded = [expand_forms(F) || F <- tuple_to_list(Form)],
list_to_tuple(Expanded);
expand_forms(Form) ->
Form. |
4868334970bc6c9798aa2e77be1eaee5f329d06da8f83a919ac6c99969933991 | mfp/obigstore | test_bson.ml |
* Copyright ( C ) 2011 - 2012 < >
*
* This library is free software ; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation ; either
* version 2.1 of the License , or ( at your option ) any later version ,
* with the special exception on linking described in file LICENSE .
*
* This library is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
* Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
* Copyright (C) 2011-2012 Mauricio Fernandez <>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version,
* with the special exception on linking described in file LICENSE.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
open Printf
open Test_00util
open OUnit
module R = Random.State
let vector =
let open Obs_bson in
[
"empty", [];
"double", ["x", Double 1.0];
"utf8", ["x", UTF8 ""];
"utf8", ["x", UTF8 "bar"];
"doc", ["x", Document []];
"doc", ["x", Document ["x", Double 1.0]];
"doc", ["x", Document ["x", Double 1.0; "y", UTF8 "x"]];
"array", ["x", Array [Double 1.0; UTF8 ""]];
"bin", ["x", Binary (Generic, "a")];
"bin", ["x", Binary (Function, "a")];
"bin", ["x", Binary (Old, "a")];
"bin", ["x", Binary (UUID, "a")];
"bin", ["x", Binary (MD5, "a")];
"bin", ["x", Binary (UserDefined, "a")];
"bool", ["x", Boolean true];
"bool", ["x", Boolean false];
"datetime", ["x", DateTime 14543555L];
"null", ["x", Null];
"regexp", ["x", Regexp ("a*b", "")];
"js", ["x", JavaScript "1.0"];
"symbol", ["x", Symbol "fff"];
"jsscoped", ["x", JavaScriptScoped ("1.0", [])];
"int32", ["x", Int32 42];
"int32", ["x", Int32 154543];
"timestamp", ["x", Timestamp 434343223L];
"minkey", ["x", Minkey];
"maxkey", ["x", Maxkey];
]
let rand_string rng = String.create (R.int rng 20)
let rand_cstring rng =
Cryptokit.(transform_string (Hexa.encode ()) (rand_string rng))
let choose rng fs = fs.(R.int rng (Array.length fs)) rng
let random_double rng _ = Obs_bson.Double (R.float rng 1e6)
FIXME : ensure proper utf-8
Obs_bson.UTF8 (rand_string rng)
let random_binary rng _ =
let open Obs_bson in
Binary ([| Generic; Function; Old; UUID; MD5; UserDefined; |].(R.int rng 6),
rand_string rng)
let random_objectid rng _ = Obs_bson.ObjectId (String.create 12)
let random_bool rng _ = Obs_bson.Boolean (R.bool rng)
let random_datetime rng _ = Obs_bson.DateTime (R.int64 rng Int64.max_int)
let random_regexp rng _ = Obs_bson.Regexp (rand_cstring rng, rand_cstring rng)
let random_javascript rng _ = Obs_bson.JavaScript (rand_string rng)
let random_symbol rng _ = Obs_bson.Symbol (rand_string rng)
let random_int32 rng _ = Obs_bson.Int32 (R.int rng 1_000_000)
let random_timestamp rng _ = Obs_bson.Timestamp (R.int64 rng Int64.max_int)
let random_int64 rng _ = Obs_bson.Int64 (R.int64 rng Int64.max_int)
let rec random_document_elm rng depth =
if depth >= 4 then random_int32 rng depth
else
Obs_bson.Document (random_document rng depth)
and random_document rng depth =
List.init (R.int rng 10) (fun i -> string_of_int i, random_element rng depth)
and random_array rng depth =
if depth >= 4 then random_int32 rng depth else
Obs_bson.Array (List.map snd (random_document rng depth))
and random_element rng depth =
let fs =
[| random_double; random_utf8; random_binary; random_objectid;
random_bool; random_datetime; random_regexp; random_javascript;
random_symbol; random_int32; random_timestamp; random_int64;
random_document_elm; random_array; random_javascript_scoped;
|]
in choose rng fs (depth + 1)
and random_javascript_scoped rng depth =
let context =
if depth >= 4 then [] else random_document rng depth
in
Obs_bson.JavaScriptScoped (rand_string rng, context)
let hexdump s =
let b = Buffer.create 13 in
let fmt = Format.formatter_of_buffer b in
for i = 0 to String.length s - 1 do
let c = Char.code s.[i] in
Format.fprintf fmt "%x%x@ " (c lsr 4) (c land 0xF);
done;
Format.fprintf fmt "@.";
Buffer.contents b
let test_roundtrip (msg, doc) () =
try
assert_equal ~msg doc Obs_bson.(document_of_string (string_of_document doc))
with exn ->
assert_failure_fmt "Failed to deserialize %s\n%s"
msg (hexdump (Obs_bson.string_of_document doc))
let test_roundtrip_randomized iterations () =
let rng = Random.State.make [|1; 2; 3|] in
for i = 1 to iterations do
let doc = random_document rng 0 in
let desc = sprintf "doc%d" i in
test_roundtrip (desc, doc) ()
done
let test_validation () =
let open Obs_bson in
let assert_does_not_validate ?truncate disallowed doc =
try
let s = string_of_document doc in
let s = String.slice ?last:truncate s in
let allowed = disallow [disallowed] all_allowed in
validate_string ~allowed s;
assert_failure_fmt "Should have disallowed %s"
(string_of_allowed_elm disallowed)
with
Obs_bson.Malformed (Rejected s) when s = disallowed -> ()
| Obs_bson.Malformed Truncated when truncate <> None -> () in
let assert_does_not_validate disallowed doc =
let len = String.length (string_of_document doc) in
assert_does_not_validate disallowed doc;
for i = 1 to len - 1 do
assert_does_not_validate ~truncate:i disallowed doc
done in
let check (disallowed, elm) =
let doc = ["x", elm] in
begin try
validate_string (string_of_document doc);
with exn ->
assert_failure_fmt "validation error %s" (Printexc.to_string exn)
end;
assert_does_not_validate disallowed doc;
assert_does_not_validate disallowed ["nested", Document doc];
in
List.iter check
[
`Double, Double 42.0;
`Double, Document ["foo", Double 42.0];
`UTF8, UTF8 "foo";
`Document, Document ["foo", Double 42.0];
`Array, Document ["foo", Array [ Double 1.0 ]];
`Binary, Binary (Generic, "");
`Binary, Binary (Function, "");
`Binary, Binary (Old, "");
`Binary, Binary (UUID, "");
`Binary, Binary (MD5, "");
`Binary, Binary (UserDefined, "");
`ObjectId, ObjectId "123456789012";
`Boolean, Boolean true;
`Boolean, Boolean false;
`DateTime, DateTime 1L;
`Null, Null;
`Regexp, Regexp ("a*b", "");
`JavaScript, JavaScript "foo";
`Symbol, Symbol "bar";
`JavaScriptScoped, JavaScriptScoped ("xx", []);
`Int32, Int32 334324234;
`Timestamp, Timestamp 1434252353L;
`Int64, Int64 334324232334L;
`Minkey, Minkey;
`Maxkey, Maxkey;
]
let tests =
[
"roundtrip" >:::
List.map (fun ((msg, doc) as x) -> msg >:: test_roundtrip x) vector;
"validation" >:: test_validation;
"randomized roundtrip" >:: test_roundtrip_randomized 10000;
]
let () =
register_tests "Obs_bson" tests
| null | https://raw.githubusercontent.com/mfp/obigstore/1b078eeb21e11c8de986717150c7108a94778095/test/test_bson.ml | ocaml |
* Copyright ( C ) 2011 - 2012 < >
*
* This library is free software ; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation ; either
* version 2.1 of the License , or ( at your option ) any later version ,
* with the special exception on linking described in file LICENSE .
*
* This library is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
* Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
* Copyright (C) 2011-2012 Mauricio Fernandez <>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version,
* with the special exception on linking described in file LICENSE.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
open Printf
open Test_00util
open OUnit
module R = Random.State
let vector =
let open Obs_bson in
[
"empty", [];
"double", ["x", Double 1.0];
"utf8", ["x", UTF8 ""];
"utf8", ["x", UTF8 "bar"];
"doc", ["x", Document []];
"doc", ["x", Document ["x", Double 1.0]];
"doc", ["x", Document ["x", Double 1.0; "y", UTF8 "x"]];
"array", ["x", Array [Double 1.0; UTF8 ""]];
"bin", ["x", Binary (Generic, "a")];
"bin", ["x", Binary (Function, "a")];
"bin", ["x", Binary (Old, "a")];
"bin", ["x", Binary (UUID, "a")];
"bin", ["x", Binary (MD5, "a")];
"bin", ["x", Binary (UserDefined, "a")];
"bool", ["x", Boolean true];
"bool", ["x", Boolean false];
"datetime", ["x", DateTime 14543555L];
"null", ["x", Null];
"regexp", ["x", Regexp ("a*b", "")];
"js", ["x", JavaScript "1.0"];
"symbol", ["x", Symbol "fff"];
"jsscoped", ["x", JavaScriptScoped ("1.0", [])];
"int32", ["x", Int32 42];
"int32", ["x", Int32 154543];
"timestamp", ["x", Timestamp 434343223L];
"minkey", ["x", Minkey];
"maxkey", ["x", Maxkey];
]
let rand_string rng = String.create (R.int rng 20)
let rand_cstring rng =
Cryptokit.(transform_string (Hexa.encode ()) (rand_string rng))
let choose rng fs = fs.(R.int rng (Array.length fs)) rng
let random_double rng _ = Obs_bson.Double (R.float rng 1e6)
FIXME : ensure proper utf-8
Obs_bson.UTF8 (rand_string rng)
let random_binary rng _ =
let open Obs_bson in
Binary ([| Generic; Function; Old; UUID; MD5; UserDefined; |].(R.int rng 6),
rand_string rng)
let random_objectid rng _ = Obs_bson.ObjectId (String.create 12)
let random_bool rng _ = Obs_bson.Boolean (R.bool rng)
let random_datetime rng _ = Obs_bson.DateTime (R.int64 rng Int64.max_int)
let random_regexp rng _ = Obs_bson.Regexp (rand_cstring rng, rand_cstring rng)
let random_javascript rng _ = Obs_bson.JavaScript (rand_string rng)
let random_symbol rng _ = Obs_bson.Symbol (rand_string rng)
let random_int32 rng _ = Obs_bson.Int32 (R.int rng 1_000_000)
let random_timestamp rng _ = Obs_bson.Timestamp (R.int64 rng Int64.max_int)
let random_int64 rng _ = Obs_bson.Int64 (R.int64 rng Int64.max_int)
let rec random_document_elm rng depth =
if depth >= 4 then random_int32 rng depth
else
Obs_bson.Document (random_document rng depth)
and random_document rng depth =
List.init (R.int rng 10) (fun i -> string_of_int i, random_element rng depth)
and random_array rng depth =
if depth >= 4 then random_int32 rng depth else
Obs_bson.Array (List.map snd (random_document rng depth))
and random_element rng depth =
let fs =
[| random_double; random_utf8; random_binary; random_objectid;
random_bool; random_datetime; random_regexp; random_javascript;
random_symbol; random_int32; random_timestamp; random_int64;
random_document_elm; random_array; random_javascript_scoped;
|]
in choose rng fs (depth + 1)
and random_javascript_scoped rng depth =
let context =
if depth >= 4 then [] else random_document rng depth
in
Obs_bson.JavaScriptScoped (rand_string rng, context)
let hexdump s =
let b = Buffer.create 13 in
let fmt = Format.formatter_of_buffer b in
for i = 0 to String.length s - 1 do
let c = Char.code s.[i] in
Format.fprintf fmt "%x%x@ " (c lsr 4) (c land 0xF);
done;
Format.fprintf fmt "@.";
Buffer.contents b
let test_roundtrip (msg, doc) () =
try
assert_equal ~msg doc Obs_bson.(document_of_string (string_of_document doc))
with exn ->
assert_failure_fmt "Failed to deserialize %s\n%s"
msg (hexdump (Obs_bson.string_of_document doc))
let test_roundtrip_randomized iterations () =
let rng = Random.State.make [|1; 2; 3|] in
for i = 1 to iterations do
let doc = random_document rng 0 in
let desc = sprintf "doc%d" i in
test_roundtrip (desc, doc) ()
done
let test_validation () =
let open Obs_bson in
let assert_does_not_validate ?truncate disallowed doc =
try
let s = string_of_document doc in
let s = String.slice ?last:truncate s in
let allowed = disallow [disallowed] all_allowed in
validate_string ~allowed s;
assert_failure_fmt "Should have disallowed %s"
(string_of_allowed_elm disallowed)
with
Obs_bson.Malformed (Rejected s) when s = disallowed -> ()
| Obs_bson.Malformed Truncated when truncate <> None -> () in
let assert_does_not_validate disallowed doc =
let len = String.length (string_of_document doc) in
assert_does_not_validate disallowed doc;
for i = 1 to len - 1 do
assert_does_not_validate ~truncate:i disallowed doc
done in
let check (disallowed, elm) =
let doc = ["x", elm] in
begin try
validate_string (string_of_document doc);
with exn ->
assert_failure_fmt "validation error %s" (Printexc.to_string exn)
end;
assert_does_not_validate disallowed doc;
assert_does_not_validate disallowed ["nested", Document doc];
in
List.iter check
[
`Double, Double 42.0;
`Double, Document ["foo", Double 42.0];
`UTF8, UTF8 "foo";
`Document, Document ["foo", Double 42.0];
`Array, Document ["foo", Array [ Double 1.0 ]];
`Binary, Binary (Generic, "");
`Binary, Binary (Function, "");
`Binary, Binary (Old, "");
`Binary, Binary (UUID, "");
`Binary, Binary (MD5, "");
`Binary, Binary (UserDefined, "");
`ObjectId, ObjectId "123456789012";
`Boolean, Boolean true;
`Boolean, Boolean false;
`DateTime, DateTime 1L;
`Null, Null;
`Regexp, Regexp ("a*b", "");
`JavaScript, JavaScript "foo";
`Symbol, Symbol "bar";
`JavaScriptScoped, JavaScriptScoped ("xx", []);
`Int32, Int32 334324234;
`Timestamp, Timestamp 1434252353L;
`Int64, Int64 334324232334L;
`Minkey, Minkey;
`Maxkey, Maxkey;
]
let tests =
[
"roundtrip" >:::
List.map (fun ((msg, doc) as x) -> msg >:: test_roundtrip x) vector;
"validation" >:: test_validation;
"randomized roundtrip" >:: test_roundtrip_randomized 10000;
]
let () =
register_tests "Obs_bson" tests
| |
1a03be3cce1ba2739bfc30b87d63f8342fec8a6b3783221c6f186e3acf8617ca | Elzair/nazghul | jewelry.scm | (kern-mk-sprite-set 'ss_jewelry 32 32 2 2 0 0 "jewelry.png")
(kern-mk-sprite 's_skull_ring ss_jewelry 1 0 #f 0)
(mk-quest-obj-type 't_skull_ring "skull ring" s_skull_ring layer-item obj-ifc)
(define (skullring-basic-receive kchar questtag)
(quest-data-update-with 'questentry-ghertie questtag 1 (quest-notify (grant-party-xp-fn 10)))
)
(define (skullring-basic-get kobj kchar questtag)
(if (not (null? kobj))
(kern-obj-remove kobj)
)
(skullring-basic-receive kchar questtag)
(kobj-get (kern-mk-obj t_skull_ring 1) kchar)
)
(define (skullring-m-get kobj kchar)
(skullring-basic-get kobj kchar 'ring-meaney)
)
(define skullring-m-ifc
(ifc obj-ifc
(method 'get skullring-m-get)))
(mk-quest-obj-type 't_skull_ring_m "skull ring" s_skull_ring layer-item skullring-m-ifc)
(define (skullring-j-get kobj kchar)
(skullring-basic-get kobj kchar 'ring-jorn)
)
(define skullring-j-ifc
(ifc obj-ifc
(method 'get skullring-j-get)))
(mk-quest-obj-type 't_skull_ring_j "skull ring" s_skull_ring layer-item skullring-j-ifc)
(define (skullring-g-get kobj kchar)
(skullring-basic-get kobj kchar 'ring-gholet)
)
(define (skullring-g-receive ktype kchar)
(skullring-basic-receive kchar 'ring-gholet)
)
(define skullring-g-ifc
(ifc obj-ifc
(method 'get skullring-g-get)
(method 'receive skullring-g-receive)))
(mk-quest-obj-type 't_skull_ring_g "skull ring" s_skull_ring layer-item skullring-g-ifc)
| null | https://raw.githubusercontent.com/Elzair/nazghul/8f3a45ed6289cd9f469c4ff618d39366f2fbc1d8/worlds/haxima-1.002/jewelry.scm | scheme | (kern-mk-sprite-set 'ss_jewelry 32 32 2 2 0 0 "jewelry.png")
(kern-mk-sprite 's_skull_ring ss_jewelry 1 0 #f 0)
(mk-quest-obj-type 't_skull_ring "skull ring" s_skull_ring layer-item obj-ifc)
(define (skullring-basic-receive kchar questtag)
(quest-data-update-with 'questentry-ghertie questtag 1 (quest-notify (grant-party-xp-fn 10)))
)
(define (skullring-basic-get kobj kchar questtag)
(if (not (null? kobj))
(kern-obj-remove kobj)
)
(skullring-basic-receive kchar questtag)
(kobj-get (kern-mk-obj t_skull_ring 1) kchar)
)
(define (skullring-m-get kobj kchar)
(skullring-basic-get kobj kchar 'ring-meaney)
)
(define skullring-m-ifc
(ifc obj-ifc
(method 'get skullring-m-get)))
(mk-quest-obj-type 't_skull_ring_m "skull ring" s_skull_ring layer-item skullring-m-ifc)
(define (skullring-j-get kobj kchar)
(skullring-basic-get kobj kchar 'ring-jorn)
)
(define skullring-j-ifc
(ifc obj-ifc
(method 'get skullring-j-get)))
(mk-quest-obj-type 't_skull_ring_j "skull ring" s_skull_ring layer-item skullring-j-ifc)
(define (skullring-g-get kobj kchar)
(skullring-basic-get kobj kchar 'ring-gholet)
)
(define (skullring-g-receive ktype kchar)
(skullring-basic-receive kchar 'ring-gholet)
)
(define skullring-g-ifc
(ifc obj-ifc
(method 'get skullring-g-get)
(method 'receive skullring-g-receive)))
(mk-quest-obj-type 't_skull_ring_g "skull ring" s_skull_ring layer-item skullring-g-ifc)
| |
fcaa1791e54e6e1d28f48773c1a9ea372800d4320cc111b078c1ae9b1abfa119 | haskell-opengl/OpenGLRaw | BaseInstance.hs | --------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.ARB.BaseInstance
Copyright : ( c ) 2019
-- License : BSD3
--
Maintainer : < >
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.ARB.BaseInstance (
-- * Extension Support
glGetARBBaseInstance,
gl_ARB_base_instance,
-- * Functions
glDrawArraysInstancedBaseInstance,
glDrawElementsInstancedBaseInstance,
glDrawElementsInstancedBaseVertexBaseInstance
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Functions
| null | https://raw.githubusercontent.com/haskell-opengl/OpenGLRaw/57e50c9d28dfa62d6a87ae9b561af28f64ce32a0/src/Graphics/GL/ARB/BaseInstance.hs | haskell | ------------------------------------------------------------------------------
|
Module : Graphics.GL.ARB.BaseInstance
License : BSD3
Stability : stable
Portability : portable
------------------------------------------------------------------------------
* Extension Support
* Functions | Copyright : ( c ) 2019
Maintainer : < >
module Graphics.GL.ARB.BaseInstance (
glGetARBBaseInstance,
gl_ARB_base_instance,
glDrawArraysInstancedBaseInstance,
glDrawElementsInstancedBaseInstance,
glDrawElementsInstancedBaseVertexBaseInstance
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Functions
|
5558eb5cae260f465afea0f76d10a07e6f391ff8fcb8274291b90ac1585ed620 | smashingboxes/fraqture | weather_drawing.clj | (ns fraqture.weather-drawing
(:require [fraqture.drawing]
[fraqture.helpers :refer [interpolate]]
[fraqture.weather :refer [weather]]
[quil.core :as q])
(:import [fraqture.drawing Drawing]))
(defn k-to-h [kelvin]
(- (* kelvin (/ 9 5)) 459.67))
(defn temp-to-color [temperature temp-min temp-max]
(let [cold-color (q/color 0 0 255)
hot-color (q/color 255 0 0)
amount (interpolate temp-min 0 temp-max 1 temperature)
amt-clamped (max 0 (min amount 1))]
(q/lerp-color cold-color hot-color amt-clamped)))
(defn wind-to-rotation [wind-direction]
(if (= wind-direction nil)
0
(q/radians wind-direction)))
(defn wind-to-size [wind-speed]
(+ 100 (* 30 wind-speed)))
(defn setup [options]
(q/frame-rate 1)
(weather "Durham" "NC"))
(defn update-state [state] state)
(defn draw-state [state]
(let [temperature (:temp (:main @state))
temp-min (:temp_min (:main @state))
temp-max (:temp_max (:main @state))
wind-speed (:speed (:wind @state))
wind-dir (:deg (:wind @state))]
(q/background (temp-to-color temperature temp-min temp-max))
(q/no-stroke)
(q/push-matrix)
(q/translate (/ (q/width) 2) (/ (q/height) 2))
(q/scale (wind-to-size wind-speed))
(q/rotate (wind-to-rotation wind-dir))
(q/fill 255)
(q/triangle -0.5 1 0.5 1 0 -1)
(q/pop-matrix)))
(def drawing
(Drawing. "The Weather" setup update-state draw-state nil nil nil))
| null | https://raw.githubusercontent.com/smashingboxes/fraqture/8971564a075b8f38729f382906cc8f39a18d87eb/src/fraqture/weather_drawing.clj | clojure | (ns fraqture.weather-drawing
(:require [fraqture.drawing]
[fraqture.helpers :refer [interpolate]]
[fraqture.weather :refer [weather]]
[quil.core :as q])
(:import [fraqture.drawing Drawing]))
(defn k-to-h [kelvin]
(- (* kelvin (/ 9 5)) 459.67))
(defn temp-to-color [temperature temp-min temp-max]
(let [cold-color (q/color 0 0 255)
hot-color (q/color 255 0 0)
amount (interpolate temp-min 0 temp-max 1 temperature)
amt-clamped (max 0 (min amount 1))]
(q/lerp-color cold-color hot-color amt-clamped)))
(defn wind-to-rotation [wind-direction]
(if (= wind-direction nil)
0
(q/radians wind-direction)))
(defn wind-to-size [wind-speed]
(+ 100 (* 30 wind-speed)))
(defn setup [options]
(q/frame-rate 1)
(weather "Durham" "NC"))
(defn update-state [state] state)
(defn draw-state [state]
(let [temperature (:temp (:main @state))
temp-min (:temp_min (:main @state))
temp-max (:temp_max (:main @state))
wind-speed (:speed (:wind @state))
wind-dir (:deg (:wind @state))]
(q/background (temp-to-color temperature temp-min temp-max))
(q/no-stroke)
(q/push-matrix)
(q/translate (/ (q/width) 2) (/ (q/height) 2))
(q/scale (wind-to-size wind-speed))
(q/rotate (wind-to-rotation wind-dir))
(q/fill 255)
(q/triangle -0.5 1 0.5 1 0 -1)
(q/pop-matrix)))
(def drawing
(Drawing. "The Weather" setup update-state draw-state nil nil nil))
| |
81f3954031fc1e7df4aa11fc902e5424563f6cbd717fd15d7425cbcd15c2fa48 | dongcarl/guix | flashing-tools.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2014 < >
Copyright © 2014 < >
Copyright © 2016 < >
Copyright © 2016 , 2018 < >
Copyright © 2016 , 2019 < >
Copyright © 2017 < >
Copyright © 2017 < >
Copyright © 2018 , 2019 , 2020 < >
Copyright © 2021 < >
;;;
;;; 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 flashing-tools)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (guix download)
#:use-module (guix git-download)
#:use-module (guix packages)
#:use-module (gnu packages)
#:use-module (guix build-system cmake)
#:use-module (guix build-system gnu)
#:use-module (guix build-system python)
#:use-module (gnu packages autotools)
#:use-module (gnu packages admin)
#:use-module (gnu packages base)
#:use-module (gnu packages bison)
#:use-module (gnu packages boost)
#:use-module (gnu packages compression)
#:use-module (gnu packages elf)
#:use-module (gnu packages flex)
#:use-module (gnu packages ghostscript)
#:use-module (gnu packages gnupg)
#:use-module (gnu packages groff)
#:use-module (gnu packages pciutils)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages libusb)
#:use-module (gnu packages libftdi)
#:use-module (gnu packages pciutils)
#:use-module (gnu packages qt))
(define-public flashrom
(package
(name "flashrom")
(version "1.2")
(source (origin
(method url-fetch)
(uri (string-append
"-v"
version ".tar.bz2"))
(sha256
(base32
"0ax4kqnh7kd3z120ypgp73qy1knz47l6qxsqzrfkd97mh5cdky71"))))
(build-system gnu-build-system)
(inputs `(("dmidecode" ,dmidecode)
("pciutils" ,pciutils)
("libusb" ,libusb)
("libftdi" ,libftdi)))
(native-inputs `(("pkg-config" ,pkg-config)))
(arguments
'(#:make-flags
(list "CC=gcc"
(string-append "PREFIX=" %output)
"CONFIG_ENABLE_LIBUSB0_PROGRAMMERS=no")
#:tests? #f ; no 'check' target
#:phases
(modify-phases %standard-phases
(delete 'configure) ; no configure script
(add-before 'build 'patch-exec-paths
(lambda* (#:key inputs #:allow-other-keys)
(substitute* "dmi.c"
(("\"dmidecode\"")
(format #f "~S"
(string-append (assoc-ref inputs "dmidecode")
"/sbin/dmidecode"))))
#t)))))
(home-page "/")
(synopsis "Identify, read, write, erase, and verify ROM/flash chips")
(description
"flashrom is a utility for identifying, reading, writing,
verifying and erasing flash chips. It is designed to flash
BIOS/EFI/coreboot/firmware/optionROM images on mainboards,
network/graphics/storage controller cards, and various other
programmer devices.")
(license license:gpl2)))
(define-public 0xffff
(package
(name "0xffff")
(version "0.8")
(source
(origin
(method git-fetch)
(uri (git-reference
(url "")
(commit version)))
(file-name (git-file-name name version))
(sha256
(base32 "1a5b7k96vzirb0m8lqp7ldn77ppz4ngf56wslhsj2c6flcyvns4v"))))
(build-system gnu-build-system)
(inputs
`(("libusb" ,libusb-0.1))) ; doesn't work with libusb-compat
(arguments
'(#:phases
(modify-phases %standard-phases
(delete 'configure)) ; no configure
#:make-flags
(list "CC=gcc"
"BUILD_DATE=GNU Guix"
(string-append "PREFIX=" %output))
#:tests? #f)) ; no 'check' target
(home-page "")
(synopsis "Flash FIASCO images on Maemo devices")
(description
"The Open Free Fiasco Firmware Flasher (0xFFFF) is a flashing tool
for FIASCO images. It supports generating, unpacking, editing and
flashing of FIASCO images for Maemo devices. Use it with care. It can
brick your device.")
(license license:gpl3+)))
(define-public avrdude
(package
(name "avrdude")
(version "6.3")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-"
version ".tar.gz"))
(sha256
(base32 "15m1w1qad3dj7r8n5ng1qqcaiyx1gyd6hnc3p2apgjllccdp77qg"))))
(build-system gnu-build-system)
(inputs
`(("libelf" ,libelf)
("libusb" ,libusb-compat)
("libftdi" ,libftdi)))
(native-inputs
`(("bison" ,bison)
("flex" ,flex)))
(home-page "/")
(synopsis "AVR downloader and uploader")
(description
"AVRDUDE is a utility to download/upload/manipulate the ROM and
EEPROM contents of AVR microcontrollers using the @acronym{ISP, in-system
programming} technique.")
(license license:gpl2+)))
(define-public dfu-programmer
(package
(name "dfu-programmer")
(version "0.7.2")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-programmer/dfu-programmer/"
version "/dfu-programmer-" version ".tar.gz"))
(sha256
(base32
"15gr99y1z9vbvhrkd25zqhnzhg6zjmaam3vfjzf2mazd39mx7d0x"))
(patches (search-patches "dfu-programmer-fix-libusb.patch"))))
(build-system gnu-build-system)
(native-inputs
`(("pkg-config" ,pkg-config)))
(inputs
`(("libusb" ,libusb)))
(home-page "-programmer.github.io/")
(synopsis "Device firmware update programmer for Atmel chips")
(description
"Dfu-programmer is a multi-platform command-line programmer for
Atmel (8051, AVR, XMEGA & AVR32) chips with a USB bootloader supporting
ISP.")
(license license:gpl2+)))
(define-public dfu-util
(package
(name "dfu-util")
(version "0.10")
(source (origin
(method url-fetch)
(uri (string-append
"-util.sourceforge.net/releases/dfu-util-"
version ".tar.gz"))
(sha256
(base32
"0hlvc47ccf5hry13saqhc1j5cdq5jyjv4i05kj0mdh3rzj6wagd0"))))
(build-system gnu-build-system)
(inputs
`(("libusb" ,libusb)))
(native-inputs
`(("pkg-config" ,pkg-config)))
(synopsis "Host side of the USB Device Firmware Upgrade (DFU) protocol")
(description
"The DFU (Universal Serial Bus Device Firmware Upgrade) protocol is
intended to download and upload firmware to devices connected over USB. It
ranges from small devices like micro-controller boards up to mobile phones.
With dfu-util you are able to download firmware to your device or upload
firmware from it.")
(home-page "-util.sourceforge.net/")
(license license:gpl2+)))
(define-public teensy-loader-cli
;; The repo does not tag versions nor does it use releases, but a commit
message says " Importing 2.1 " , while the sourcce still says " 2.0 " . So pin
;; to a fixed commit.
(let ((commit "f289b7a2e5627464044249f0e5742830e052e360"))
(package
(name "teensy-loader-cli")
(version (git-version "2.1" "1" commit))
(source
(origin
(method git-fetch)
(uri (git-reference
(url "")
(commit commit)))
(sha256 (base32 "0sssim56pwsxp5cp5dlf6mi9h5fx2592m6j1g7abnm0s09b0lpdx"))
(file-name (git-file-name name version))
(modules '((guix build utils)))
(snippet
`(begin
;; Remove example flash files and teensy rebooter flash binaries.
(for-each delete-file (find-files "." "\\.(elf|hex)$"))
;; Fix the version
(substitute* "teensy_loader_cli.c"
(("Teensy Loader, Command Line, Version 2.0\\\\n")
(string-append "Teensy Loader, Command Line, " ,version "\\n")))
#t))
(patches (search-patches "teensy-loader-cli-help.patch"))))
(build-system gnu-build-system)
(arguments
'(#:tests? #f ;; Makefile has no test target
#:make-flags (list "CC=gcc" (string-append "PREFIX=" %output))
#:phases
(modify-phases %standard-phases
(delete 'configure)
(replace 'install
(lambda* (#:key outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(bin (string-append out "/bin")))
(install-file "teensy_loader_cli" bin)
#t))))))
(inputs
`(("libusb-compat" ,libusb-compat)))
(synopsis "Command line firmware uploader for Teensy development boards")
(description
"The Teensy loader program communicates with your Teensy board when the
HalfKay bootloader is running, so you can upload new programs and run them.
You need to add the udev rules to make the Teensy update available for
non-root users.")
(home-page "")
(license license:gpl3))))
(define-public rkflashtool
(let ((commit "8966c4e277de8148290554aaaa4146a3a84a3c53")
(revision "1"))
(package
(name "rkflashtool")
(version (git-version "5.2" revision commit))
(source
(origin
(method git-fetch)
(uri (git-reference
(url "-rockchip/rkflashtool")
(commit commit)))
(file-name (git-file-name name version))
(sha256
(base32
"1ndyzg1zlgg20dd8js9kfqm5kq19k005vddkvf65qj20w0pcyahn"))))
(build-system gnu-build-system)
(arguments
'(#:phases
(modify-phases %standard-phases
(delete 'configure)) ; no configure
#:make-flags (list (string-append "PREFIX=" %output))
#:tests? #f)) ; no tests
(native-inputs
`(("pkg-config" ,pkg-config)))
(inputs
`(("libusb" ,libusb)))
(home-page "-rockchip/rkflashtool")
(synopsis "Tools for flashing Rockchip devices")
(description "Allows flashing of Rockchip based embedded linux devices.
The list of currently supported devices is: RK2818, RK2918, RK2928, RK3026,
RK3036, RK3066, RK312X, RK3168, RK3188, RK3288, RK3368.")
(license license:bsd-2))))
(define-public heimdall
(package
(name "heimdall")
(version "1.4.2")
(source (origin
(method git-fetch)
(uri (git-reference
(url "")
(commit (string-append "v" version))))
(file-name (git-file-name name version))
(sha256
(base32
"1ygn4snvcmi98rgldgxf5hwm7zzi1zcsihfvm6awf9s6mpcjzbqz"))))
(build-system cmake-build-system)
(arguments
`(#:build-type "Release"
#:tests? #f ; no tests
#:phases
(modify-phases %standard-phases
(add-after 'unpack 'patch-invocations
(lambda* (#:key outputs #:allow-other-keys)
(substitute* '("heimdall-frontend/source/aboutform.cpp"
"heimdall-frontend/source/mainwindow.cpp")
(("start[(]\"heimdall\"")
(string-append "start(\"" (assoc-ref outputs "out")
"/bin/heimdall\"")))
#t))
(replace 'install
(lambda* (#:key outputs #:allow-other-keys)
(let ((bin (string-append (assoc-ref outputs "out") "/bin"))
(lib (string-append (assoc-ref outputs "out") "/lib")))
(install-file "bin/heimdall" bin)
(install-file "bin/heimdall-frontend" bin)
(install-file "libpit/libpit.a" lib)
#t))))))
(inputs
`(("libusb" ,libusb)
("qtbase" ,qtbase-5)
("zlib" ,zlib)))
(home-page "/")
(synopsis "Flash firmware onto Samsung mobile devices")
(description "@command{heimdall} is a tool suite used to flash firmware (aka
ROMs) onto Samsung mobile devices. Heimdall connects to a mobile device over
USB and interacts with low-level software running on the device, known as Loke.
Loke and Heimdall communicate via the custom Samsung-developed protocol typically
referred to as the \"Odin 3 protocol\".")
(license license:expat)))
(define-public ifdtool
(package
(name "ifdtool")
(version "4.9")
(source (origin
(method git-fetch)
(uri (git-reference
(url "")
(commit version)))
(file-name (git-file-name name version))
(sha256
(base32
"0jidj29jh6p65d17k304wlzhxvp4p3c2namgcdwg2sxq8jfr0zlm"))))
(build-system gnu-build-system)
(arguments
`(#:make-flags
(list "CC=gcc"
"INSTALL=install"
(string-append "PREFIX=" (assoc-ref %outputs "out")))
#:phases
(modify-phases %standard-phases
(add-after 'unpack 'chdir
(lambda _
(chdir "util/ifdtool")
#t))
(delete 'configure)) ; no configure script
#:tests? #f)) ; no test suite
(home-page "/")
(synopsis "Intel Firmware Descriptor dumper")
(description "This package provides @command{ifdtool}, a program to
dump Intel Firmware Descriptor data of an image file.")
(license license:gpl2)))
(define-public intelmetool
(package
(name "intelmetool")
(version "4.7")
(source (origin
(method git-fetch)
(uri (git-reference
(url "")
(commit version)))
(file-name (git-file-name name version))
(sha256
(base32
"0nw555i0fm5kljha9h47bk70ykbwv8ddfk6qhz6kfqb79vzhy4h2"))))
(build-system gnu-build-system)
(inputs
`(("pciutils" ,pciutils)
("zlib" ,zlib)))
(arguments
`(#:make-flags
(list "CC=gcc"
"INSTALL=install"
(string-append "PREFIX=" (assoc-ref %outputs "out")))
#:phases
(modify-phases %standard-phases
(add-after 'unpack 'chdir
(lambda _
(chdir "util/intelmetool")
#t))
(delete 'configure)
(delete 'check))))
(home-page "")
(synopsis "Intel Management Engine tools")
(description "This package provides tools for working with Intel
Management Engine (ME). You need to @code{sudo rmmod mei_me} and
@code{sudo rmmod mei} before using this tool. Also pass
@code{iomem=relaxed} to the Linux kernel command line.")
(license license:gpl2)
This is obviously an Intel thing , plus it requires < cpuid.h > .
(supported-systems '("x86_64-linux" "i686-linux"))))
(define-public me-cleaner
(package
(name "me-cleaner")
(version "1.2")
(source (origin
(method git-fetch)
(uri (git-reference
(url "")
(commit (string-append "v" version))))
(sha256
(base32
"1bdj2clm13ir441vn7sv860xsc5gh71ja5lc2wn0gggnff0adxj4"))
(file-name (git-file-name name version))))
(build-system python-build-system)
(arguments
`(#:phases
(modify-phases %standard-phases
(add-after 'install 'install-documentation
(lambda* (#:key outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(man (string-append out "/share/man/man1")))
(install-file "man/me_cleaner.1" man)
#t))))))
(home-page "")
(synopsis "Intel ME cleaner")
(description "This package provides tools for disabling Intel
ME as far as possible (it only edits ME firmware image files).")
(license license:gpl3+)
This is an Intel thing .
(supported-systems '("x86_64-linux" "i686-linux"))))
(define-public uefitool
(package
(name "uefitool")
(version "0.27.0")
(source (origin
(method git-fetch)
(uri (git-reference
(url "")
(commit version)))
(sha256
(base32
"1i1p823qld927p4f1wcphqcnivb9mq7fi5xmzibxc3g9zzgnyc2h"))
(file-name (git-file-name name version))))
(build-system gnu-build-system)
(arguments
`(#:phases
(modify-phases %standard-phases
(replace 'configure
(lambda _
(invoke "qmake" "-makefile")))
(replace 'install
(lambda* (#:key outputs #:allow-other-keys)
(install-file "UEFITool" (string-append (assoc-ref outputs "out")
"/bin"))
#t)))))
(inputs
`(("qtbase" ,qtbase-5)))
(home-page "/")
(synopsis "UEFI image editor")
(description "@code{uefitool} is a graphical image file editor for
Unifinished Extensible Firmware Interface (UEFI) images.")
(license license:bsd-2)))
(define-public srecord
(package
(name "srecord")
(version "1.64")
(source
(origin
(method url-fetch)
(uri (string-append "mirror/"
version "/srecord-" version ".tar.gz"))
(sha256
(base32
"1qk75q0k5vzmm3932q9hqz2gp8n9rrdfjacsswxc02656f3l3929"))))
(build-system gnu-build-system)
(arguments
`(#:configure-flags
(list (string-append "SH="
(assoc-ref %build-inputs "bash")
"/bin/bash"))))
(inputs
`(("boost" ,boost)
("libgcrypt" ,libgcrypt)))
(native-inputs
`(("bison" ,bison)
("diffutils" ,diffutils)
("ghostscript" ,ghostscript)
("groff" ,groff)
("libtool" ,libtool)
("which" ,which)))
(home-page "/")
(synopsis "Tools for EPROM files")
(description "The SRecord package is a collection of powerful tools for
manipulating EPROM load files. It reads and writes numerous EPROM file
formats, and can perform many different manipulations.")
(license license:gpl3+)))
| null | https://raw.githubusercontent.com/dongcarl/guix/d2b30db788f1743f9f8738cb1de977b77748567f/gnu/packages/flashing-tools.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.
no 'check' target
no configure script
doesn't work with libusb-compat
no configure
no 'check' target
The repo does not tag versions nor does it use releases, but a commit
to a fixed commit.
Remove example flash files and teensy rebooter flash binaries.
Fix the version
Makefile has no test target
no configure
no tests
no tests
no configure script
no test suite | Copyright © 2014 < >
Copyright © 2014 < >
Copyright © 2016 < >
Copyright © 2016 , 2018 < >
Copyright © 2016 , 2019 < >
Copyright © 2017 < >
Copyright © 2017 < >
Copyright © 2018 , 2019 , 2020 < >
Copyright © 2021 < >
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 flashing-tools)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (guix download)
#:use-module (guix git-download)
#:use-module (guix packages)
#:use-module (gnu packages)
#:use-module (guix build-system cmake)
#:use-module (guix build-system gnu)
#:use-module (guix build-system python)
#:use-module (gnu packages autotools)
#:use-module (gnu packages admin)
#:use-module (gnu packages base)
#:use-module (gnu packages bison)
#:use-module (gnu packages boost)
#:use-module (gnu packages compression)
#:use-module (gnu packages elf)
#:use-module (gnu packages flex)
#:use-module (gnu packages ghostscript)
#:use-module (gnu packages gnupg)
#:use-module (gnu packages groff)
#:use-module (gnu packages pciutils)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages libusb)
#:use-module (gnu packages libftdi)
#:use-module (gnu packages pciutils)
#:use-module (gnu packages qt))
(define-public flashrom
(package
(name "flashrom")
(version "1.2")
(source (origin
(method url-fetch)
(uri (string-append
"-v"
version ".tar.bz2"))
(sha256
(base32
"0ax4kqnh7kd3z120ypgp73qy1knz47l6qxsqzrfkd97mh5cdky71"))))
(build-system gnu-build-system)
(inputs `(("dmidecode" ,dmidecode)
("pciutils" ,pciutils)
("libusb" ,libusb)
("libftdi" ,libftdi)))
(native-inputs `(("pkg-config" ,pkg-config)))
(arguments
'(#:make-flags
(list "CC=gcc"
(string-append "PREFIX=" %output)
"CONFIG_ENABLE_LIBUSB0_PROGRAMMERS=no")
#:phases
(modify-phases %standard-phases
(add-before 'build 'patch-exec-paths
(lambda* (#:key inputs #:allow-other-keys)
(substitute* "dmi.c"
(("\"dmidecode\"")
(format #f "~S"
(string-append (assoc-ref inputs "dmidecode")
"/sbin/dmidecode"))))
#t)))))
(home-page "/")
(synopsis "Identify, read, write, erase, and verify ROM/flash chips")
(description
"flashrom is a utility for identifying, reading, writing,
verifying and erasing flash chips. It is designed to flash
BIOS/EFI/coreboot/firmware/optionROM images on mainboards,
network/graphics/storage controller cards, and various other
programmer devices.")
(license license:gpl2)))
(define-public 0xffff
(package
(name "0xffff")
(version "0.8")
(source
(origin
(method git-fetch)
(uri (git-reference
(url "")
(commit version)))
(file-name (git-file-name name version))
(sha256
(base32 "1a5b7k96vzirb0m8lqp7ldn77ppz4ngf56wslhsj2c6flcyvns4v"))))
(build-system gnu-build-system)
(inputs
(arguments
'(#:phases
(modify-phases %standard-phases
#:make-flags
(list "CC=gcc"
"BUILD_DATE=GNU Guix"
(string-append "PREFIX=" %output))
(home-page "")
(synopsis "Flash FIASCO images on Maemo devices")
(description
"The Open Free Fiasco Firmware Flasher (0xFFFF) is a flashing tool
for FIASCO images. It supports generating, unpacking, editing and
flashing of FIASCO images for Maemo devices. Use it with care. It can
brick your device.")
(license license:gpl3+)))
(define-public avrdude
(package
(name "avrdude")
(version "6.3")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-"
version ".tar.gz"))
(sha256
(base32 "15m1w1qad3dj7r8n5ng1qqcaiyx1gyd6hnc3p2apgjllccdp77qg"))))
(build-system gnu-build-system)
(inputs
`(("libelf" ,libelf)
("libusb" ,libusb-compat)
("libftdi" ,libftdi)))
(native-inputs
`(("bison" ,bison)
("flex" ,flex)))
(home-page "/")
(synopsis "AVR downloader and uploader")
(description
"AVRDUDE is a utility to download/upload/manipulate the ROM and
EEPROM contents of AVR microcontrollers using the @acronym{ISP, in-system
programming} technique.")
(license license:gpl2+)))
(define-public dfu-programmer
(package
(name "dfu-programmer")
(version "0.7.2")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-programmer/dfu-programmer/"
version "/dfu-programmer-" version ".tar.gz"))
(sha256
(base32
"15gr99y1z9vbvhrkd25zqhnzhg6zjmaam3vfjzf2mazd39mx7d0x"))
(patches (search-patches "dfu-programmer-fix-libusb.patch"))))
(build-system gnu-build-system)
(native-inputs
`(("pkg-config" ,pkg-config)))
(inputs
`(("libusb" ,libusb)))
(home-page "-programmer.github.io/")
(synopsis "Device firmware update programmer for Atmel chips")
(description
"Dfu-programmer is a multi-platform command-line programmer for
Atmel (8051, AVR, XMEGA & AVR32) chips with a USB bootloader supporting
ISP.")
(license license:gpl2+)))
(define-public dfu-util
(package
(name "dfu-util")
(version "0.10")
(source (origin
(method url-fetch)
(uri (string-append
"-util.sourceforge.net/releases/dfu-util-"
version ".tar.gz"))
(sha256
(base32
"0hlvc47ccf5hry13saqhc1j5cdq5jyjv4i05kj0mdh3rzj6wagd0"))))
(build-system gnu-build-system)
(inputs
`(("libusb" ,libusb)))
(native-inputs
`(("pkg-config" ,pkg-config)))
(synopsis "Host side of the USB Device Firmware Upgrade (DFU) protocol")
(description
"The DFU (Universal Serial Bus Device Firmware Upgrade) protocol is
intended to download and upload firmware to devices connected over USB. It
ranges from small devices like micro-controller boards up to mobile phones.
With dfu-util you are able to download firmware to your device or upload
firmware from it.")
(home-page "-util.sourceforge.net/")
(license license:gpl2+)))
(define-public teensy-loader-cli
message says " Importing 2.1 " , while the sourcce still says " 2.0 " . So pin
(let ((commit "f289b7a2e5627464044249f0e5742830e052e360"))
(package
(name "teensy-loader-cli")
(version (git-version "2.1" "1" commit))
(source
(origin
(method git-fetch)
(uri (git-reference
(url "")
(commit commit)))
(sha256 (base32 "0sssim56pwsxp5cp5dlf6mi9h5fx2592m6j1g7abnm0s09b0lpdx"))
(file-name (git-file-name name version))
(modules '((guix build utils)))
(snippet
`(begin
(for-each delete-file (find-files "." "\\.(elf|hex)$"))
(substitute* "teensy_loader_cli.c"
(("Teensy Loader, Command Line, Version 2.0\\\\n")
(string-append "Teensy Loader, Command Line, " ,version "\\n")))
#t))
(patches (search-patches "teensy-loader-cli-help.patch"))))
(build-system gnu-build-system)
(arguments
#:make-flags (list "CC=gcc" (string-append "PREFIX=" %output))
#:phases
(modify-phases %standard-phases
(delete 'configure)
(replace 'install
(lambda* (#:key outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(bin (string-append out "/bin")))
(install-file "teensy_loader_cli" bin)
#t))))))
(inputs
`(("libusb-compat" ,libusb-compat)))
(synopsis "Command line firmware uploader for Teensy development boards")
(description
"The Teensy loader program communicates with your Teensy board when the
HalfKay bootloader is running, so you can upload new programs and run them.
You need to add the udev rules to make the Teensy update available for
non-root users.")
(home-page "")
(license license:gpl3))))
(define-public rkflashtool
(let ((commit "8966c4e277de8148290554aaaa4146a3a84a3c53")
(revision "1"))
(package
(name "rkflashtool")
(version (git-version "5.2" revision commit))
(source
(origin
(method git-fetch)
(uri (git-reference
(url "-rockchip/rkflashtool")
(commit commit)))
(file-name (git-file-name name version))
(sha256
(base32
"1ndyzg1zlgg20dd8js9kfqm5kq19k005vddkvf65qj20w0pcyahn"))))
(build-system gnu-build-system)
(arguments
'(#:phases
(modify-phases %standard-phases
#:make-flags (list (string-append "PREFIX=" %output))
(native-inputs
`(("pkg-config" ,pkg-config)))
(inputs
`(("libusb" ,libusb)))
(home-page "-rockchip/rkflashtool")
(synopsis "Tools for flashing Rockchip devices")
(description "Allows flashing of Rockchip based embedded linux devices.
The list of currently supported devices is: RK2818, RK2918, RK2928, RK3026,
RK3036, RK3066, RK312X, RK3168, RK3188, RK3288, RK3368.")
(license license:bsd-2))))
(define-public heimdall
(package
(name "heimdall")
(version "1.4.2")
(source (origin
(method git-fetch)
(uri (git-reference
(url "")
(commit (string-append "v" version))))
(file-name (git-file-name name version))
(sha256
(base32
"1ygn4snvcmi98rgldgxf5hwm7zzi1zcsihfvm6awf9s6mpcjzbqz"))))
(build-system cmake-build-system)
(arguments
`(#:build-type "Release"
#:phases
(modify-phases %standard-phases
(add-after 'unpack 'patch-invocations
(lambda* (#:key outputs #:allow-other-keys)
(substitute* '("heimdall-frontend/source/aboutform.cpp"
"heimdall-frontend/source/mainwindow.cpp")
(("start[(]\"heimdall\"")
(string-append "start(\"" (assoc-ref outputs "out")
"/bin/heimdall\"")))
#t))
(replace 'install
(lambda* (#:key outputs #:allow-other-keys)
(let ((bin (string-append (assoc-ref outputs "out") "/bin"))
(lib (string-append (assoc-ref outputs "out") "/lib")))
(install-file "bin/heimdall" bin)
(install-file "bin/heimdall-frontend" bin)
(install-file "libpit/libpit.a" lib)
#t))))))
(inputs
`(("libusb" ,libusb)
("qtbase" ,qtbase-5)
("zlib" ,zlib)))
(home-page "/")
(synopsis "Flash firmware onto Samsung mobile devices")
(description "@command{heimdall} is a tool suite used to flash firmware (aka
ROMs) onto Samsung mobile devices. Heimdall connects to a mobile device over
USB and interacts with low-level software running on the device, known as Loke.
Loke and Heimdall communicate via the custom Samsung-developed protocol typically
referred to as the \"Odin 3 protocol\".")
(license license:expat)))
(define-public ifdtool
(package
(name "ifdtool")
(version "4.9")
(source (origin
(method git-fetch)
(uri (git-reference
(url "")
(commit version)))
(file-name (git-file-name name version))
(sha256
(base32
"0jidj29jh6p65d17k304wlzhxvp4p3c2namgcdwg2sxq8jfr0zlm"))))
(build-system gnu-build-system)
(arguments
`(#:make-flags
(list "CC=gcc"
"INSTALL=install"
(string-append "PREFIX=" (assoc-ref %outputs "out")))
#:phases
(modify-phases %standard-phases
(add-after 'unpack 'chdir
(lambda _
(chdir "util/ifdtool")
#t))
(home-page "/")
(synopsis "Intel Firmware Descriptor dumper")
(description "This package provides @command{ifdtool}, a program to
dump Intel Firmware Descriptor data of an image file.")
(license license:gpl2)))
(define-public intelmetool
(package
(name "intelmetool")
(version "4.7")
(source (origin
(method git-fetch)
(uri (git-reference
(url "")
(commit version)))
(file-name (git-file-name name version))
(sha256
(base32
"0nw555i0fm5kljha9h47bk70ykbwv8ddfk6qhz6kfqb79vzhy4h2"))))
(build-system gnu-build-system)
(inputs
`(("pciutils" ,pciutils)
("zlib" ,zlib)))
(arguments
`(#:make-flags
(list "CC=gcc"
"INSTALL=install"
(string-append "PREFIX=" (assoc-ref %outputs "out")))
#:phases
(modify-phases %standard-phases
(add-after 'unpack 'chdir
(lambda _
(chdir "util/intelmetool")
#t))
(delete 'configure)
(delete 'check))))
(home-page "")
(synopsis "Intel Management Engine tools")
(description "This package provides tools for working with Intel
Management Engine (ME). You need to @code{sudo rmmod mei_me} and
@code{sudo rmmod mei} before using this tool. Also pass
@code{iomem=relaxed} to the Linux kernel command line.")
(license license:gpl2)
This is obviously an Intel thing , plus it requires < cpuid.h > .
(supported-systems '("x86_64-linux" "i686-linux"))))
(define-public me-cleaner
(package
(name "me-cleaner")
(version "1.2")
(source (origin
(method git-fetch)
(uri (git-reference
(url "")
(commit (string-append "v" version))))
(sha256
(base32
"1bdj2clm13ir441vn7sv860xsc5gh71ja5lc2wn0gggnff0adxj4"))
(file-name (git-file-name name version))))
(build-system python-build-system)
(arguments
`(#:phases
(modify-phases %standard-phases
(add-after 'install 'install-documentation
(lambda* (#:key outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(man (string-append out "/share/man/man1")))
(install-file "man/me_cleaner.1" man)
#t))))))
(home-page "")
(synopsis "Intel ME cleaner")
(description "This package provides tools for disabling Intel
ME as far as possible (it only edits ME firmware image files).")
(license license:gpl3+)
This is an Intel thing .
(supported-systems '("x86_64-linux" "i686-linux"))))
(define-public uefitool
(package
(name "uefitool")
(version "0.27.0")
(source (origin
(method git-fetch)
(uri (git-reference
(url "")
(commit version)))
(sha256
(base32
"1i1p823qld927p4f1wcphqcnivb9mq7fi5xmzibxc3g9zzgnyc2h"))
(file-name (git-file-name name version))))
(build-system gnu-build-system)
(arguments
`(#:phases
(modify-phases %standard-phases
(replace 'configure
(lambda _
(invoke "qmake" "-makefile")))
(replace 'install
(lambda* (#:key outputs #:allow-other-keys)
(install-file "UEFITool" (string-append (assoc-ref outputs "out")
"/bin"))
#t)))))
(inputs
`(("qtbase" ,qtbase-5)))
(home-page "/")
(synopsis "UEFI image editor")
(description "@code{uefitool} is a graphical image file editor for
Unifinished Extensible Firmware Interface (UEFI) images.")
(license license:bsd-2)))
(define-public srecord
(package
(name "srecord")
(version "1.64")
(source
(origin
(method url-fetch)
(uri (string-append "mirror/"
version "/srecord-" version ".tar.gz"))
(sha256
(base32
"1qk75q0k5vzmm3932q9hqz2gp8n9rrdfjacsswxc02656f3l3929"))))
(build-system gnu-build-system)
(arguments
`(#:configure-flags
(list (string-append "SH="
(assoc-ref %build-inputs "bash")
"/bin/bash"))))
(inputs
`(("boost" ,boost)
("libgcrypt" ,libgcrypt)))
(native-inputs
`(("bison" ,bison)
("diffutils" ,diffutils)
("ghostscript" ,ghostscript)
("groff" ,groff)
("libtool" ,libtool)
("which" ,which)))
(home-page "/")
(synopsis "Tools for EPROM files")
(description "The SRecord package is a collection of powerful tools for
manipulating EPROM load files. It reads and writes numerous EPROM file
formats, and can perform many different manipulations.")
(license license:gpl3+)))
|
7f6064a611ab83e6cc495d6d6adb0bdff18d0b2aed9bd75545246b37d9491b50 | reanimate/reanimate | Rotational.hs | |
Copyright : Written by
License : Unlicense
Maintainer :
Stability : experimental
Portability : POSIX
Copyright : Written by David Himmelstrup
License : Unlicense
Maintainer :
Stability : experimental
Portability : POSIX
-}
module Reanimate.Morph.Rotational
( Origin
, rotationalTrajectory
, polygonOrigin
) where
import qualified Data.Vector as V
import Linear.Vector
import Linear.V2
import Linear.Metric
import Reanimate.Ease
import Reanimate.Morph.Common
import Reanimate.Math.Polygon
-- | Rotational origin relative to polygon center.
( 0.5 , 0.5 ) is center of polygon . Top right is ( 1,1 ) and
bottom left is ( 0,0 )
type Origin = (Double, Double)
-- | Interpolation by rotating around an origin point.
--
-- Example:
--
-- @
-- 'Reanimate.playThenReverseA' $ 'Reanimate.pauseAround' 0.5 0.5 $ 'Reanimate.mkAnimation' 3 $ \\t ->
' ' ' Graphics . SvgTree . JoinRound ' $
let src = ' Reanimate.scale ' 8 $ ' Reanimate.center ' $ ' Reanimate.LaTeX.latex ' \"X\ "
dst = ' Reanimate.scale ' 8 $ ' Reanimate.center ' $ ' Reanimate.LaTeX.latex ' \"H\ "
in ' morph ' ' Reanimate . Morph . Linear.linear'{'morphTrajectory'='rotationalTrajectory ' ( ) } src dst t
-- @
--
-- <<docs/gifs/doc_rotationalTrajectory.gif>>
rotationalTrajectory :: Origin -> Trajectory
rotationalTrajectory origin (src,dst) =
\t ->
let thisOrigin = lerp t dstOrigin srcOrigin in
mkPolygon $
V.generate (pSize src) $ \i ->
let len = fromToS (srcLengths V.! i) (dstLengths V.! i) t
ang = lerpAngle (srcAngles V.! i) (dstAngles V.! i) t
in realToFrac <$> (thisOrigin + V2 (cos ang * len) (sin ang * len))
where
srcOrigin = polygonOrigin src origin
dstOrigin = polygonOrigin dst origin
srcLengths :: V.Vector Double
srcLengths = V.map (distance srcOrigin . fmap realToFrac) $ polygonPoints src
dstLengths = V.map (distance dstOrigin . fmap realToFrac) $ polygonPoints dst
srcAngles = V.map (originAngle srcOrigin . fmap realToFrac) $ polygonPoints src
dstAngles = V.map (originAngle dstOrigin . fmap realToFrac) $ polygonPoints dst
originAngle o = lineAngle (o + V2 1 0) o
-- | Compute the absolute position of rotational origin point in polygon.
polygonOrigin :: Polygon -> Origin -> V2 Double
polygonOrigin poly (originX, originY) =
case pBoundingBox poly of
(polyX, polyY, polyWidth, polyHeight) ->
V2 (realToFrac polyX + realToFrac polyWidth * originX)
(realToFrac polyY + realToFrac polyHeight * originY)
lerpAngle :: Double -> Double -> Double -> Double
lerpAngle fromAng toAng t
| abs (fromAng - (toAng+2*pi)) < abs (fromAng - toAng) = (1-t)*fromAng + t*(toAng+2*pi)
| abs (fromAng - (toAng-2*pi)) < abs (fromAng - toAng) = (1-t)*fromAng + t*(toAng-2*pi)
| otherwise = (1-t)*fromAng + t*toAng
-- Angle from a through b to c.
lineAngle :: V2 Double -> V2 Double -> V2 Double -> Double
lineAngle a b c = angle' (a-b) (c-b)
angle' :: V2 Double -> V2 Double -> Double
angle' a b = atan2 (crossZ a b) (dot a b)
| null | https://raw.githubusercontent.com/reanimate/reanimate/5ea023980ff7f488934d40593cc5069f5fd038b0/src/Reanimate/Morph/Rotational.hs | haskell | | Rotational origin relative to polygon center.
| Interpolation by rotating around an origin point.
Example:
@
'Reanimate.playThenReverseA' $ 'Reanimate.pauseAround' 0.5 0.5 $ 'Reanimate.mkAnimation' 3 $ \\t ->
@
<<docs/gifs/doc_rotationalTrajectory.gif>>
| Compute the absolute position of rotational origin point in polygon.
Angle from a through b to c. | |
Copyright : Written by
License : Unlicense
Maintainer :
Stability : experimental
Portability : POSIX
Copyright : Written by David Himmelstrup
License : Unlicense
Maintainer :
Stability : experimental
Portability : POSIX
-}
module Reanimate.Morph.Rotational
( Origin
, rotationalTrajectory
, polygonOrigin
) where
import qualified Data.Vector as V
import Linear.Vector
import Linear.V2
import Linear.Metric
import Reanimate.Ease
import Reanimate.Morph.Common
import Reanimate.Math.Polygon
( 0.5 , 0.5 ) is center of polygon . Top right is ( 1,1 ) and
bottom left is ( 0,0 )
type Origin = (Double, Double)
' ' ' Graphics . SvgTree . JoinRound ' $
let src = ' Reanimate.scale ' 8 $ ' Reanimate.center ' $ ' Reanimate.LaTeX.latex ' \"X\ "
dst = ' Reanimate.scale ' 8 $ ' Reanimate.center ' $ ' Reanimate.LaTeX.latex ' \"H\ "
in ' morph ' ' Reanimate . Morph . Linear.linear'{'morphTrajectory'='rotationalTrajectory ' ( ) } src dst t
rotationalTrajectory :: Origin -> Trajectory
rotationalTrajectory origin (src,dst) =
\t ->
let thisOrigin = lerp t dstOrigin srcOrigin in
mkPolygon $
V.generate (pSize src) $ \i ->
let len = fromToS (srcLengths V.! i) (dstLengths V.! i) t
ang = lerpAngle (srcAngles V.! i) (dstAngles V.! i) t
in realToFrac <$> (thisOrigin + V2 (cos ang * len) (sin ang * len))
where
srcOrigin = polygonOrigin src origin
dstOrigin = polygonOrigin dst origin
srcLengths :: V.Vector Double
srcLengths = V.map (distance srcOrigin . fmap realToFrac) $ polygonPoints src
dstLengths = V.map (distance dstOrigin . fmap realToFrac) $ polygonPoints dst
srcAngles = V.map (originAngle srcOrigin . fmap realToFrac) $ polygonPoints src
dstAngles = V.map (originAngle dstOrigin . fmap realToFrac) $ polygonPoints dst
originAngle o = lineAngle (o + V2 1 0) o
polygonOrigin :: Polygon -> Origin -> V2 Double
polygonOrigin poly (originX, originY) =
case pBoundingBox poly of
(polyX, polyY, polyWidth, polyHeight) ->
V2 (realToFrac polyX + realToFrac polyWidth * originX)
(realToFrac polyY + realToFrac polyHeight * originY)
lerpAngle :: Double -> Double -> Double -> Double
lerpAngle fromAng toAng t
| abs (fromAng - (toAng+2*pi)) < abs (fromAng - toAng) = (1-t)*fromAng + t*(toAng+2*pi)
| abs (fromAng - (toAng-2*pi)) < abs (fromAng - toAng) = (1-t)*fromAng + t*(toAng-2*pi)
| otherwise = (1-t)*fromAng + t*toAng
lineAngle :: V2 Double -> V2 Double -> V2 Double -> Double
lineAngle a b c = angle' (a-b) (c-b)
angle' :: V2 Double -> V2 Double -> Double
angle' a b = atan2 (crossZ a b) (dot a b)
|
996cd3b0e63cc72347db89aa495e80b996d6d6cabfc2e7a7159da17786c67d30 | zkincaid/duet | searchTree.mli | module type Element = sig
type t
val compare : t -> t -> int
val hash : t -> int
val equal : t -> t -> bool
val pp : Format.formatter -> t -> unit
end
module type S = sig
type t
type baseSet
type elt
val empty : baseSet -> (elt -> baseSet) -> t
val make : baseSet -> (elt -> baseSet) -> elt BatSet.t -> t
exception Item_not_known
val insert : t -> elt -> unit
val covered : (elt -> elt -> bool) -> t -> elt -> elt option
end
module Make (Base : Element) (Elt : Element) : S with type baseSet = BatSet.Make(Base).t with type elt = Elt.t
| null | https://raw.githubusercontent.com/zkincaid/duet/eb3dbfe6c51d5e1a11cb39ab8f70584aaaa309f9/pa/searchTree.mli | ocaml | module type Element = sig
type t
val compare : t -> t -> int
val hash : t -> int
val equal : t -> t -> bool
val pp : Format.formatter -> t -> unit
end
module type S = sig
type t
type baseSet
type elt
val empty : baseSet -> (elt -> baseSet) -> t
val make : baseSet -> (elt -> baseSet) -> elt BatSet.t -> t
exception Item_not_known
val insert : t -> elt -> unit
val covered : (elt -> elt -> bool) -> t -> elt -> elt option
end
module Make (Base : Element) (Elt : Element) : S with type baseSet = BatSet.Make(Base).t with type elt = Elt.t
| |
3ec0927491a70fa7df22bfcb42247f0d0792a7c46ce4cd4553ae492c0b05b06d | typelead/eta | TrampolineBreak.hs | import Data.List
import Data.Function
main :: IO ()
main = do
let input = replicate 1000000 'c' ++ "defghi"
print $ trampoline $ snd $ break (== 'd') input
| null | https://raw.githubusercontent.com/typelead/eta/97ee2251bbc52294efbf60fa4342ce6f52c0d25c/tests/suite/trampoline/run/TrampolineBreak.hs | haskell | import Data.List
import Data.Function
main :: IO ()
main = do
let input = replicate 1000000 'c' ++ "defghi"
print $ trampoline $ snd $ break (== 'd') input
| |
53061499a9da4b584acd24e2733cda3ba02c94393c06d39cb366e2461ace5156 | flipstone/haskell-for-beginners | 3_walk_the_line.hs | -- A Bomb is defined by the order in
-- which its wires must be cut to disable
-- it. If a wire is cut out of order, the
-- bomb explodes.
--
type Bomb = [Wire]
data Wire = Red | Blue | Green deriving (Show, Eq)
-- Define a function that cuts a Wire of a
-- Bomb, returning Just the Wires remaining
-- to be cut. If the incorrect Wire is cut,
-- the Bomb expodes, leaving Nothing to return.
-- If any attempt is made to cut a Wire on
-- a Bomb with no Wires remaining, the Bomb
-- explodes.
--
cutWire = undefined
-- Define a function that waits to see if the
-- Bomb will explode. If there are no remaining
-- wires, return Just a happy message. If any
-- wires remain uncut, the Bomb explodes.
--
wait = undefined
-- Quick, disarm the Bomb! (Be sure sure to use
Monad functions )
--
bomb = [Red, Green, Blue]
disarmed = undefined
-- Now see what happens if you accidentally cut the Blue
wire second .
--
boomed = undefined
-- All good Bombs are equipped with a dead man switch to
-- protect their creators. Define a disarming operation
-- to make the Bomb explode if someone takes out its maker.
--
takeOutBombMaker = undefined
-- Try it out! See what happens if someone takes
-- out the Bomb's maker while you are disarming it.
--
takeEmOut = undefined
Pick one of the 3 disarming examples above and re - write it
without using the Maybe Monad . Just use pattern matching at
-- each step of the sequence.
--
| null | https://raw.githubusercontent.com/flipstone/haskell-for-beginners/e586a1f3ef08f21d5181171fe7a7b27057391f0b/problems/chapter_12/3_walk_the_line.hs | haskell | A Bomb is defined by the order in
which its wires must be cut to disable
it. If a wire is cut out of order, the
bomb explodes.
Define a function that cuts a Wire of a
Bomb, returning Just the Wires remaining
to be cut. If the incorrect Wire is cut,
the Bomb expodes, leaving Nothing to return.
If any attempt is made to cut a Wire on
a Bomb with no Wires remaining, the Bomb
explodes.
Define a function that waits to see if the
Bomb will explode. If there are no remaining
wires, return Just a happy message. If any
wires remain uncut, the Bomb explodes.
Quick, disarm the Bomb! (Be sure sure to use
Now see what happens if you accidentally cut the Blue
All good Bombs are equipped with a dead man switch to
protect their creators. Define a disarming operation
to make the Bomb explode if someone takes out its maker.
Try it out! See what happens if someone takes
out the Bomb's maker while you are disarming it.
each step of the sequence.
| type Bomb = [Wire]
data Wire = Red | Blue | Green deriving (Show, Eq)
cutWire = undefined
wait = undefined
Monad functions )
bomb = [Red, Green, Blue]
disarmed = undefined
wire second .
boomed = undefined
takeOutBombMaker = undefined
takeEmOut = undefined
Pick one of the 3 disarming examples above and re - write it
without using the Maybe Monad . Just use pattern matching at
|
74c36c415058e016fc7c55606090fe1a6fa6a45cac56084dccb4802f01d0e74f | mmontone/cl-forms | peppol.lisp | (defpackage :cl-forms.peppol
(:nicknames :forms.peppol)
(:use :cl :forms)
(:export
:amount-form-field
:country-form-field
:currency-form-field))
(in-package :forms.peppol)
(defun round-amount (amount &optional (divisor 1))
"Amount is in ører"
(multiple-value-bind (quotient remainder) (truncate (/ amount divisor))
(if (>= (abs remainder) 1/2)
(+ quotient (truncate (signum remainder)))
quotient)))
(defun format-amount (amount &optional (decimals 2))
"Format an amount"
(multiple-value-bind (kroner orer) (truncate amount (expt 10 decimals))
( code - char 160 ) is no break space ( aka & nbsp ;)
( format nil " ~:,,v,3D,~2,'0D " ( code - char 160 ) kroner ( abs orer ) )
(format nil "~a,~a" kroner (abs orer))
))
(defun parse-amount (string &optional (decimals 2))
"Parse an amount"
(setf string (remove (code-char 160) string))
(setf string (remove #\Space string))
(setf string (substitute #\. #\, string))
(let ((decs (or (position #\. (reverse string)) 0)))
(round-amount (* (expt 10 decimals)
(/ (parse-integer (remove #\. string))
(expt 10 decs))))))
(defun decimal (number &optional (decimals 2))
(* number (expt 10 decimals)))
(defun float-to-decimal (float &optional (decimals 2))
(format-amount (format nil (format nil "~~~a$" decimals) float) decimals))
;;;; ** Amount form field
(defclass amount-form-field (forms::integer-form-field)
()
(:default-initargs
:formatter (lambda (value stream)
(princ (format-amount value) stream))))
(defmethod forms::field-read-from-request ((field amount-form-field) form parameters)
(setf (forms::field-value field)
(let ((value
(cdr (assoc (forms::field-request-name field form) parameters :test #'string=))))
(and value (parse-amount value)))))
;; (defmethod forms::validate-form-field ((field amount-form-field))
;; (let ((valid-p (validate-amount (forms::field-value field) :error-p nil)))
;; (multiple-value-bind (valid-constraints-p errors)
;; (call-next-method)
;; (values (and valid-p valid-constraints-p)
;; (if (not valid-p) (cons "Amount is invalid" errors)
;; errors)))))
(defmethod forms::make-form-field ((field-type (eql :amount)) &rest args)
(apply #'make-instance 'amount-form-field args))
;;;; *** Currency form field
(defclass currency-form-field (forms::choice-form-field)
()
(:default-initargs
:use-key-as-value t
:choices (mapcar (lambda (x)
(cons (cdr x) (car x)))
peppol/code-lists::|ISO 4217 Currency codes|)
:test (lambda (key key-and-value)
(string= key (car key-and-value)))))
(defmethod forms::make-form-field ((field-type (eql :currency)) &rest args)
(apply #'make-instance 'currency-form-field args))
;;;; *** Country form field
(defclass country-form-field (forms::choice-form-field)
()
(:default-initargs
:use-key-as-value t
:choices (mapcar (lambda (x)
(cons (cdr x) (car x)))
peppol/code-lists::|ISO 3166-1:Alpha2 Country codes|)
:test (lambda (key key-and-value)
(string= key (car key-and-value)))))
(defmethod forms::make-form-field ((field-type (eql :country)) &rest args)
(apply #'make-instance 'country-form-field args))
| null | https://raw.githubusercontent.com/mmontone/cl-forms/af252b8646b7545ac778c9aa881903efcc311f2d/src/peppol.lisp | lisp | )
** Amount form field
(defmethod forms::validate-form-field ((field amount-form-field))
(let ((valid-p (validate-amount (forms::field-value field) :error-p nil)))
(multiple-value-bind (valid-constraints-p errors)
(call-next-method)
(values (and valid-p valid-constraints-p)
(if (not valid-p) (cons "Amount is invalid" errors)
errors)))))
*** Currency form field
*** Country form field | (defpackage :cl-forms.peppol
(:nicknames :forms.peppol)
(:use :cl :forms)
(:export
:amount-form-field
:country-form-field
:currency-form-field))
(in-package :forms.peppol)
(defun round-amount (amount &optional (divisor 1))
"Amount is in ører"
(multiple-value-bind (quotient remainder) (truncate (/ amount divisor))
(if (>= (abs remainder) 1/2)
(+ quotient (truncate (signum remainder)))
quotient)))
(defun format-amount (amount &optional (decimals 2))
"Format an amount"
(multiple-value-bind (kroner orer) (truncate amount (expt 10 decimals))
( format nil " ~:,,v,3D,~2,'0D " ( code - char 160 ) kroner ( abs orer ) )
(format nil "~a,~a" kroner (abs orer))
))
(defun parse-amount (string &optional (decimals 2))
"Parse an amount"
(setf string (remove (code-char 160) string))
(setf string (remove #\Space string))
(setf string (substitute #\. #\, string))
(let ((decs (or (position #\. (reverse string)) 0)))
(round-amount (* (expt 10 decimals)
(/ (parse-integer (remove #\. string))
(expt 10 decs))))))
(defun decimal (number &optional (decimals 2))
(* number (expt 10 decimals)))
(defun float-to-decimal (float &optional (decimals 2))
(format-amount (format nil (format nil "~~~a$" decimals) float) decimals))
(defclass amount-form-field (forms::integer-form-field)
()
(:default-initargs
:formatter (lambda (value stream)
(princ (format-amount value) stream))))
(defmethod forms::field-read-from-request ((field amount-form-field) form parameters)
(setf (forms::field-value field)
(let ((value
(cdr (assoc (forms::field-request-name field form) parameters :test #'string=))))
(and value (parse-amount value)))))
(defmethod forms::make-form-field ((field-type (eql :amount)) &rest args)
(apply #'make-instance 'amount-form-field args))
(defclass currency-form-field (forms::choice-form-field)
()
(:default-initargs
:use-key-as-value t
:choices (mapcar (lambda (x)
(cons (cdr x) (car x)))
peppol/code-lists::|ISO 4217 Currency codes|)
:test (lambda (key key-and-value)
(string= key (car key-and-value)))))
(defmethod forms::make-form-field ((field-type (eql :currency)) &rest args)
(apply #'make-instance 'currency-form-field args))
(defclass country-form-field (forms::choice-form-field)
()
(:default-initargs
:use-key-as-value t
:choices (mapcar (lambda (x)
(cons (cdr x) (car x)))
peppol/code-lists::|ISO 3166-1:Alpha2 Country codes|)
:test (lambda (key key-and-value)
(string= key (car key-and-value)))))
(defmethod forms::make-form-field ((field-type (eql :country)) &rest args)
(apply #'make-instance 'country-form-field args))
|
d01f8ab276cb424a7d2412361c588d37eac5df029cc90bdb6c4a30503f90cbbf | nasa/Common-Metadata-Repository | ring_validations.clj | (ns cmr.spatial.ring-validations
(:require [cmr.spatial.point :as p]
[cmr.spatial.math :refer :all]
[cmr.common.util :as util]
[primitive-math]
[cmr.spatial.mbr :as mbr]
[cmr.spatial.conversion :as c]
[cmr.spatial.arc :as a]
[cmr.spatial.derived :as d]
[cmr.spatial.geodetic-ring :as gr]
[cmr.spatial.cartesian-ring :as cr]
[cmr.spatial.ring-relations :as rr]
[cmr.spatial.validation :as v]
[cmr.spatial.points-validation-helpers :as pv]
[cmr.spatial.messages :as msg])
(:import cmr.spatial.arc.Arc))
(primitive-math/use-primitive-operators)
(defn- ring-closed-validation
"Validates the ring is closed (last point = first point)"
[{:keys [points]}]
(when-not (= (first points) (last points))
[(msg/ring-not-closed)]))
(defn- ring-self-intersection-validation
"Validates that the ring does not intersect itself"
[ring]
(when-let [intersections (seq (rr/self-intersections ring))]
[(msg/ring-self-intersections intersections)]))
(defn- ring-pole-validation
"Validates that a geodetic ring does not contain both poles"
[ring]
(let [ring (gr/ring->pole-containment ring)]
(when (and (:contains-south-pole ring) (:contains-north-pole ring))
[(msg/ring-contains-both-poles)])))
(defn- ring-geo-point-order-validation
"Validates that a geodetic rings points are in counter clockwise order"
[ring]
(when (= (gr/ring->point-order ring) :clockwise)
[(msg/ring-points-out-of-order)]))
(defn- ring-point-order-validation
"Validates that a cartesian rings points are in counter clockwise order"
[ring]
(when (not= (cr/ring->winding ring) :counter-clockwise)
[(msg/ring-points-out-of-order)]))
(extend-protocol v/SpatialValidation
cmr.spatial.geodetic_ring.GeodeticRing
(validate
[ring]
Certain validations can only be run if earlier validations passed . Validations are grouped
;; here so that subsequent validations won't run if earlier validations fail.
(or (seq (pv/points-in-shape-validation ring))
;; basic ring validation
(or (seq (concat (ring-closed-validation ring)
(pv/duplicate-point-validation (update-in ring [:points] drop-last))
(pv/consecutive-antipodal-points-validation ring)))
Advanced ring validation
(let [ring (assoc ring :arcs (gr/ring->arcs ring))]
(or (seq (ring-self-intersection-validation ring))
(seq (ring-pole-validation ring))
(seq (ring-geo-point-order-validation ring)))))))
cmr.spatial.cartesian_ring.CartesianRing
(validate
[ring]
Certain validations can only be run if earlier validations passed . Validations are grouped
;; here so that subsequent validations won't run if earlier validations fail.
(or (seq (pv/points-in-shape-validation ring))
;; basic ring validation
(or (seq (concat (ring-closed-validation ring)
(pv/duplicate-point-validation (update-in ring [:points] drop-last))))
Advanced ring validation
(let [ring (assoc ring :line-segments (cr/ring->line-segments ring))]
(or (seq (ring-self-intersection-validation ring))
(seq (ring-point-order-validation ring)))))))) | null | https://raw.githubusercontent.com/nasa/Common-Metadata-Repository/f6c7d4252e5b47916d0078744f13f8df59c67805/spatial-lib/src/cmr/spatial/ring_validations.clj | clojure | here so that subsequent validations won't run if earlier validations fail.
basic ring validation
here so that subsequent validations won't run if earlier validations fail.
basic ring validation | (ns cmr.spatial.ring-validations
(:require [cmr.spatial.point :as p]
[cmr.spatial.math :refer :all]
[cmr.common.util :as util]
[primitive-math]
[cmr.spatial.mbr :as mbr]
[cmr.spatial.conversion :as c]
[cmr.spatial.arc :as a]
[cmr.spatial.derived :as d]
[cmr.spatial.geodetic-ring :as gr]
[cmr.spatial.cartesian-ring :as cr]
[cmr.spatial.ring-relations :as rr]
[cmr.spatial.validation :as v]
[cmr.spatial.points-validation-helpers :as pv]
[cmr.spatial.messages :as msg])
(:import cmr.spatial.arc.Arc))
(primitive-math/use-primitive-operators)
(defn- ring-closed-validation
"Validates the ring is closed (last point = first point)"
[{:keys [points]}]
(when-not (= (first points) (last points))
[(msg/ring-not-closed)]))
(defn- ring-self-intersection-validation
"Validates that the ring does not intersect itself"
[ring]
(when-let [intersections (seq (rr/self-intersections ring))]
[(msg/ring-self-intersections intersections)]))
(defn- ring-pole-validation
"Validates that a geodetic ring does not contain both poles"
[ring]
(let [ring (gr/ring->pole-containment ring)]
(when (and (:contains-south-pole ring) (:contains-north-pole ring))
[(msg/ring-contains-both-poles)])))
(defn- ring-geo-point-order-validation
"Validates that a geodetic rings points are in counter clockwise order"
[ring]
(when (= (gr/ring->point-order ring) :clockwise)
[(msg/ring-points-out-of-order)]))
(defn- ring-point-order-validation
"Validates that a cartesian rings points are in counter clockwise order"
[ring]
(when (not= (cr/ring->winding ring) :counter-clockwise)
[(msg/ring-points-out-of-order)]))
(extend-protocol v/SpatialValidation
cmr.spatial.geodetic_ring.GeodeticRing
(validate
[ring]
Certain validations can only be run if earlier validations passed . Validations are grouped
(or (seq (pv/points-in-shape-validation ring))
(or (seq (concat (ring-closed-validation ring)
(pv/duplicate-point-validation (update-in ring [:points] drop-last))
(pv/consecutive-antipodal-points-validation ring)))
Advanced ring validation
(let [ring (assoc ring :arcs (gr/ring->arcs ring))]
(or (seq (ring-self-intersection-validation ring))
(seq (ring-pole-validation ring))
(seq (ring-geo-point-order-validation ring)))))))
cmr.spatial.cartesian_ring.CartesianRing
(validate
[ring]
Certain validations can only be run if earlier validations passed . Validations are grouped
(or (seq (pv/points-in-shape-validation ring))
(or (seq (concat (ring-closed-validation ring)
(pv/duplicate-point-validation (update-in ring [:points] drop-last))))
Advanced ring validation
(let [ring (assoc ring :line-segments (cr/ring->line-segments ring))]
(or (seq (ring-self-intersection-validation ring))
(seq (ring-point-order-validation ring)))))))) |
e6b9923150be94f7fe39ef8e7ee7b6f1d5f3efb5af92caa5767d292633abf6a0 | tlaplus/tlapm | progress.mli | Copyright 2005 INRIA
type progress = No | Bar | Msg;;
val level : progress ref;;
val do_progress : (unit -> unit) -> char -> unit;;
val end_progress : string -> unit;;
| null | https://raw.githubusercontent.com/tlaplus/tlapm/b82e2fd049c5bc1b14508ae16890666c6928975f/zenon/progress.mli | ocaml | Copyright 2005 INRIA
type progress = No | Bar | Msg;;
val level : progress ref;;
val do_progress : (unit -> unit) -> char -> unit;;
val end_progress : string -> unit;;
| |
92eac106547963fbe7541c9fb5e093e3d622a5e1c94ab9f5fbe73d8603fc879c | wdebeaum/step | localise.lisp | ;;;;
;;;; w::localise
;;;;
; note: similar file for "localize"
(define-words :pos W::v
:words (
(w::localise
(wordfeats (W::morph (:forms (-vb) :nom w::localisation )))
(senses
(
(LF-PARENT ONT::sit) ;be-at-loc)
(TEMPL NEUTRAL-LOCATION-XP-TEMPL (xp (% W::pp (W::ptype (? xxx W::to w::on w::in w::into w::at)))))
(example "the protein localises in/to the nucleus")
)
(
(LF-PARENT ONT::sit) ;be-at-loc)
(TEMPL NEUTRAL-NEUTRAL1-XP-TEMPL (xp (% W::pp (W::ptype (? xxx W::with)))))
(example "the protein localises with the other protein")
)
(
(LF-PARENT ONT::sit) ;be-at-loc)
(TEMPL NEUTRAL-NEUTRAL1-LOCATION-2-XP1-3-XP-TEMPL (xp (% W::pp (W::ptype (? xxx W::to w::on w::in w::into w::at)))))
(example "some property localises the protein to the nucleus")
)
)
)
))
| null | https://raw.githubusercontent.com/wdebeaum/step/f38c07d9cd3a58d0e0183159d4445de9a0eafe26/src/LexiconManager/Data/new/localise.lisp | lisp |
w::localise
note: similar file for "localize"
be-at-loc)
be-at-loc)
be-at-loc) |
(define-words :pos W::v
:words (
(w::localise
(wordfeats (W::morph (:forms (-vb) :nom w::localisation )))
(senses
(
(TEMPL NEUTRAL-LOCATION-XP-TEMPL (xp (% W::pp (W::ptype (? xxx W::to w::on w::in w::into w::at)))))
(example "the protein localises in/to the nucleus")
)
(
(TEMPL NEUTRAL-NEUTRAL1-XP-TEMPL (xp (% W::pp (W::ptype (? xxx W::with)))))
(example "the protein localises with the other protein")
)
(
(TEMPL NEUTRAL-NEUTRAL1-LOCATION-2-XP1-3-XP-TEMPL (xp (% W::pp (W::ptype (? xxx W::to w::on w::in w::into w::at)))))
(example "some property localises the protein to the nucleus")
)
)
)
))
|
f236d6cf584a6acc0e5bb0940aa6cde82f78e698f4c056667158b91f73875cd4 | bitblaze-fuzzball/fuzzball | symbolic_domain.mli |
Copyright ( C ) BitBlaze , 2009 - 2010 . All rights reserved .
Copyright (C) BitBlaze, 2009-2010. All rights reserved.
*)
module SymbolicDomain : Exec_domain.DOMAIN
| null | https://raw.githubusercontent.com/bitblaze-fuzzball/fuzzball/b9a617b45e68fa732f1357fedc08a2a10f87a62c/execution/symbolic_domain.mli | ocaml |
Copyright ( C ) BitBlaze , 2009 - 2010 . All rights reserved .
Copyright (C) BitBlaze, 2009-2010. All rights reserved.
*)
module SymbolicDomain : Exec_domain.DOMAIN
| |
f62c943556bd370242f963d43d544aaef2bbc37270ef27c4a59f01eefd37773d | jwiegley/notes | Combining.hs | {-# LANGUAGE RankNTypes #-}
# LANGUAGE ImplicitParams #
# LANGUAGE ScopedTypeVariables #
module Combining where
import Control.Applicative
import Control.Arrow
import Control.Lens
import Control.Lens.Internal
import Control.Lens.Internal.Context
import Control.Monad
import Data.Bitraversable
import Data.Functor
newtype Pretext p a b t = Pretext ( Functor f = > p a ( f b ) - > f t )
type Pretext ' p a = Pretext p a a
type LensLike f s t a b = ( a - > f b ) - > s - > f t
type LensLike ' f s a = LensLike f s s a a
LensLike ' ( Pretext ' p a ) s a
LensLike ( Pretext p a a ) s s a a
( a - > Pretext p a a a ) - > s - > Pretext p a a s
type ALens s t a b = LensLike ( Pretext ( - > ) a b ) s t a b
type ALens ' s a = ALens s s a a
newtype Pretext p a b t = Pretext (Functor f => p a (f b) -> f t)
type Pretext' p a = Pretext p a a
type LensLike f s t a b = (a -> f b) -> s -> f t
type LensLike' f s a = LensLike f s s a a
LensLike' (Pretext' p a) s a
LensLike (Pretext p a a) s s a a
(a -> Pretext p a a a) -> s -> Pretext p a a s
type ALens s t a b = LensLike (Pretext (->) a b) s t a b
type ALens' s a = ALens s s a a
-}
-- pairing :: ALens' s a -> ALens' s a'-> Lens' s (a, a')
-- pairing x x' =
-- lens (\s -> (s ^# x, s ^# x'))
-- (\s (a, a') -> s & x #~ a & x' #~ a')
pairing :: Functor f
=> LensLike' (PretextT' (->) f a) s a
-> LensLike' (PretextT' (->) f a') s a'
-> LensLike' f s (a, a')
pairing l r f s = do
x <- l sell s
y <- r sell s
contramap f (x *** y)
let h = fmap ( r sell ) $ l sell s
-- in runPretextT (merge h) f
-- where
-- p a ( f b ) - > f ( p a ' ( f b ) - > f t )
-- -- -into-
-- -- p (a, a') (f b) -> f t
merge : : PretextT ' ( - > ) f a ( PretextT ' ( - > ) f a ' s )
- > PretextT ' ( - > ) f ( a , a ' ) s
merge ( PretextT k ) = PretextT $ \g - > k undefined
main :: IO ()
main = do
print $ (1,2,3,4) ^. pairing _2 _4
print $ (1,2,3,4) ^. pairing (to (\(_, x, _, _) -> x))
(to (\(_, _, _, x) -> x))
print $ (1,2,3,4) & pairing _2 _4 .~ (10, 20)
| null | https://raw.githubusercontent.com/jwiegley/notes/24574b02bfd869845faa1521854f90e4e8bf5e9a/gists/f719a3d41696d48f6005/misc/Combining.hs | haskell | # LANGUAGE RankNTypes #
pairing :: ALens' s a -> ALens' s a'-> Lens' s (a, a')
pairing x x' =
lens (\s -> (s ^# x, s ^# x'))
(\s (a, a') -> s & x #~ a & x' #~ a')
in runPretextT (merge h) f
where
p a ( f b ) - > f ( p a ' ( f b ) - > f t )
-- -into-
-- p (a, a') (f b) -> f t | # LANGUAGE ImplicitParams #
# LANGUAGE ScopedTypeVariables #
module Combining where
import Control.Applicative
import Control.Arrow
import Control.Lens
import Control.Lens.Internal
import Control.Lens.Internal.Context
import Control.Monad
import Data.Bitraversable
import Data.Functor
newtype Pretext p a b t = Pretext ( Functor f = > p a ( f b ) - > f t )
type Pretext ' p a = Pretext p a a
type LensLike f s t a b = ( a - > f b ) - > s - > f t
type LensLike ' f s a = LensLike f s s a a
LensLike ' ( Pretext ' p a ) s a
LensLike ( Pretext p a a ) s s a a
( a - > Pretext p a a a ) - > s - > Pretext p a a s
type ALens s t a b = LensLike ( Pretext ( - > ) a b ) s t a b
type ALens ' s a = ALens s s a a
newtype Pretext p a b t = Pretext (Functor f => p a (f b) -> f t)
type Pretext' p a = Pretext p a a
type LensLike f s t a b = (a -> f b) -> s -> f t
type LensLike' f s a = LensLike f s s a a
LensLike' (Pretext' p a) s a
LensLike (Pretext p a a) s s a a
(a -> Pretext p a a a) -> s -> Pretext p a a s
type ALens s t a b = LensLike (Pretext (->) a b) s t a b
type ALens' s a = ALens s s a a
-}
pairing :: Functor f
=> LensLike' (PretextT' (->) f a) s a
-> LensLike' (PretextT' (->) f a') s a'
-> LensLike' f s (a, a')
pairing l r f s = do
x <- l sell s
y <- r sell s
contramap f (x *** y)
let h = fmap ( r sell ) $ l sell s
merge : : PretextT ' ( - > ) f a ( PretextT ' ( - > ) f a ' s )
- > PretextT ' ( - > ) f ( a , a ' ) s
merge ( PretextT k ) = PretextT $ \g - > k undefined
main :: IO ()
main = do
print $ (1,2,3,4) ^. pairing _2 _4
print $ (1,2,3,4) ^. pairing (to (\(_, x, _, _) -> x))
(to (\(_, _, _, x) -> x))
print $ (1,2,3,4) & pairing _2 _4 .~ (10, 20)
|
251dd022bdcee8f91dabc16e4382f61057016de31976e443e23ac8310b840b6b | daveho/catparty | core.cljc | ; -*- mode: clojure -*-
Cat Party - C parser in Clojure / ClojureScript
Copyright ( c ) 2016 - 2017 , < >
;;
This is free software distributed under the GNU Public License , version 3 ,
or any later version . See COPYING.txt for details .
(ns catparty.core
(:require [clojure.browser.repl :as repl]))
(defonce conn
(repl/connect ":9000/repl"))
(enable-console-print!)
(println "Hello, world! And now there's more!")
(defn foo [a b]
(+ a b))
| null | https://raw.githubusercontent.com/daveho/catparty/015fffd1c30ea1685d633184b0f157ec3aed5c7c/src/catparty/core.cljc | clojure | -*- mode: clojure -*-
|
Cat Party - C parser in Clojure / ClojureScript
Copyright ( c ) 2016 - 2017 , < >
This is free software distributed under the GNU Public License , version 3 ,
or any later version . See COPYING.txt for details .
(ns catparty.core
(:require [clojure.browser.repl :as repl]))
(defonce conn
(repl/connect ":9000/repl"))
(enable-console-print!)
(println "Hello, world! And now there's more!")
(defn foo [a b]
(+ a b))
|
edd4ca267e7b7030658f1738abd99c194e943b7560e80b0c26490efbae3d17ac | ANSSI-FR/mabo | mabo.ml | MaBo - MRT & BGP command line parser
* < >
*
* This file implements differents commands that use different MaBo modules .
* Guillaume Valadon <>
*
* This file implements differents commands that use different MaBo modules.
*)
open CommandDump
open CommandPrefixes
open CommandFollow
;;
* command line arguments and call
let usage = "usage: " ^ Sys.argv.(0)
and usage_subcommands = " {dump,prefixes,follow} ...
Process MRT dumps
Arguments:
dump Dump the content a MRT file
prefixes List AS & prefixes in a MRT file
follow Follow a list of IP prefixes in MRT files\n" in
let args_length = Array.length Sys.argv in
match args_length with
| 0 | 1 -> (Printf.printf "%s" (usage^usage_subcommands); exit 1)
| _ -> ();
match Sys.argv.(1) with
| "dump" -> CommandDump.main usage (Array.sub Sys.argv 1 (args_length-1))
| "prefixes" -> CommandPrefixes.main usage (Array.sub Sys.argv 1 (args_length-1))
| "follow" -> CommandFollow.main usage (Array.sub Sys.argv 1 (args_length-1))
| _ -> (Printf.printf "%s" (usage^usage_subcommands); exit 1)
| null | https://raw.githubusercontent.com/ANSSI-FR/mabo/19000c66f7ecf58eb9cfa66a4cc75a4c76f3ab20/src/mabo.ml | ocaml | MaBo - MRT & BGP command line parser
* < >
*
* This file implements differents commands that use different MaBo modules .
* Guillaume Valadon <>
*
* This file implements differents commands that use different MaBo modules.
*)
open CommandDump
open CommandPrefixes
open CommandFollow
;;
* command line arguments and call
let usage = "usage: " ^ Sys.argv.(0)
and usage_subcommands = " {dump,prefixes,follow} ...
Process MRT dumps
Arguments:
dump Dump the content a MRT file
prefixes List AS & prefixes in a MRT file
follow Follow a list of IP prefixes in MRT files\n" in
let args_length = Array.length Sys.argv in
match args_length with
| 0 | 1 -> (Printf.printf "%s" (usage^usage_subcommands); exit 1)
| _ -> ();
match Sys.argv.(1) with
| "dump" -> CommandDump.main usage (Array.sub Sys.argv 1 (args_length-1))
| "prefixes" -> CommandPrefixes.main usage (Array.sub Sys.argv 1 (args_length-1))
| "follow" -> CommandFollow.main usage (Array.sub Sys.argv 1 (args_length-1))
| _ -> (Printf.printf "%s" (usage^usage_subcommands); exit 1)
| |
9816b7babb911068b8070cc77dc09f9c53919a3738d71609fff276e160dfbcdf | cj1128/sicp-review | compose.scm | (define (compose f g)
(lambda (x)
(f (g x))))
| null | https://raw.githubusercontent.com/cj1128/sicp-review/efaa2f863b7f03c51641c22d701bac97e398a050/chapter-1/1.3/compose.scm | scheme | (define (compose f g)
(lambda (x)
(f (g x))))
| |
e1ee7048d354624543b709838df8739d3a8bdd8a5ce59c0d8429eee5a9d1b86c | REPROSEC/dolev-yao-star | Vale_Curve25519_X64_FastWide.ml | open Prims
let (va_code_Fmul :
unit ->
(Vale_X64_Decls.ins, Vale_X64_Decls.ocmp) Vale_X64_Machine_s.precode)
=
fun uu___ ->
Vale_X64_Machine_s.Block
[Vale_X64_InsMem.va_code_CreateHeaplets ();
Vale_X64_InsBasic.va_code_LargeComment
"Compute the raw multiplication: tmp <- src1 * src2";
Vale_Curve25519_X64_FastMul.va_code_Fast_multiply Prims.int_zero;
Vale_X64_InsBasic.va_code_Newline ();
Vale_X64_InsBasic.va_code_Comment "Line up pointers";
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (15)));
Vale_X64_InsBasic.va_code_LargeComment
"Wrap the result back into the field";
Vale_Curve25519_X64_FastHybrid.va_code_Carry_wide Prims.int_zero;
Vale_X64_InsMem.va_code_DestroyHeaplets ()]
let (va_codegen_success_Fmul : unit -> Vale_X64_Decls.va_pbool) =
fun uu___ ->
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsMem.va_codegen_success_CreateHeaplets ())
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_LargeComment
"Compute the raw multiplication: tmp <- src1 * src2")
(Vale_X64_Decls.va_pbool_and
(Vale_Curve25519_X64_FastMul.va_codegen_success_Fast_multiply
Prims.int_zero)
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Newline ())
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Comment
"Line up pointers")
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (5))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (15))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_LargeComment
"Wrap the result back into the field")
(Vale_X64_Decls.va_pbool_and
(Vale_Curve25519_X64_FastHybrid.va_codegen_success_Carry_wide
Prims.int_zero)
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsMem.va_codegen_success_DestroyHeaplets
()) (Vale_X64_Decls.va_ttrue ()))))))))))
type ('vaub0, 'vaus0, 'tmpub, 'inAub, 'dstub, 'inBub) va_req_Fmul = unit
type ('vaub0, 'vaus0, 'tmpub, 'inAub, 'dstub, 'inBub, 'vausM,
'vaufM) va_ens_Fmul = unit
let (va_qcode_Fmul :
Vale_X64_QuickCode.mod_t Prims.list ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
(unit, unit) Vale_X64_QuickCode.quickCode)
=
fun va_mods ->
fun tmp_b ->
fun inA_b ->
fun dst_b ->
fun inB_b ->
Vale_X64_QuickCodes.qblock
[Vale_X64_InsMem.va_code_CreateHeaplets ();
Vale_X64_InsBasic.va_code_LargeComment
"Compute the raw multiplication: tmp <- src1 * src2";
Vale_Curve25519_X64_FastMul.va_code_Fast_multiply
Prims.int_zero;
Vale_X64_InsBasic.va_code_Newline ();
Vale_X64_InsBasic.va_code_Comment "Line up pointers";
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (15)));
Vale_X64_InsBasic.va_code_LargeComment
"Wrap the result back into the field";
Vale_Curve25519_X64_FastHybrid.va_code_Carry_wide
Prims.int_zero;
Vale_X64_InsMem.va_code_DestroyHeaplets ()] va_mods ()
type ('tmpub, 'inAub, 'dstub, 'inBub, 'vaus0, 'vauk) va_wp_Fmul = unit
let (va_quick_Fmul :
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 -> (unit, unit) Vale_X64_QuickCode.quickCode)
=
fun tmp_b ->
fun inA_b ->
fun dst_b ->
fun inB_b ->
Vale_X64_QuickCode.QProc
((va_code_Fmul ()),
[Vale_X64_QuickCode.Mod_mem_layout;
Vale_X64_QuickCode.Mod_mem_heaplet Prims.int_zero;
Vale_X64_QuickCode.Mod_flags;
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (15))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (14))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (13))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (11))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (10))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (9))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (8))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (4))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (5))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (3))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (2))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, Prims.int_one));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, Prims.int_zero));
Vale_X64_QuickCode.Mod_mem], (), ())
let (va_code_Fmul_stdcall :
Prims.bool ->
(Vale_X64_Decls.ins, Vale_X64_Decls.ocmp) Vale_X64_Machine_s.precode)
=
fun win ->
Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg Prims.int_one);
if win
then
Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (2)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (15)))
(Vale_X64_Machine_s.OReg (Prims.of_int (8)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (2)))
(Vale_X64_Machine_s.OReg (Prims.of_int (9)))]
else
Vale_X64_Machine_s.Block
[Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (15)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3)))];
va_code_Fmul ();
if win
then
Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))]
else Vale_X64_Machine_s.Block [];
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg Prims.int_one);
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13)))]
let (va_codegen_success_Fmul_stdcall : Prims.bool -> Vale_X64_Decls.va_pbool)
=
fun win ->
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg Prims.int_one))
(Vale_X64_Decls.va_pbool_and
(if win
then
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (2))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg
(Prims.of_int (4)))
(Vale_X64_Machine_s.OReg
(Prims.of_int (3))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg
(Prims.of_int (15)))
(Vale_X64_Machine_s.OReg
(Prims.of_int (8))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg
(Prims.of_int (2)))
(Vale_X64_Machine_s.OReg
(Prims.of_int (9))))
(Vale_X64_Decls.va_ttrue ()))))))
else
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (15)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3))))
(Vale_X64_Decls.va_ttrue ()))
(Vale_X64_Decls.va_pbool_and (va_codegen_success_Fmul ())
(Vale_X64_Decls.va_pbool_and
(if win
then
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg
(Prims.of_int (4))))
(Vale_X64_Decls.va_ttrue ()))
else Vale_X64_Decls.va_ttrue ())
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg Prims.int_one))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg
(Prims.of_int (14))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg
(Prims.of_int (13))))
(Vale_X64_Decls.va_ttrue ())))))))))))
type ('vaub0, 'vaus0, 'win, 'tmpub, 'inAub, 'dstub,
'inBub) va_req_Fmul_stdcall = unit
type ('vaub0, 'vaus0, 'win, 'tmpub, 'inAub, 'dstub, 'inBub, 'vausM,
'vaufM) va_ens_Fmul_stdcall = unit
let (va_qcode_Fmul_stdcall :
Vale_X64_QuickCode.mod_t Prims.list ->
Prims.bool ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
(unit, unit) Vale_X64_QuickCode.quickCode)
=
fun va_mods ->
fun win ->
fun tmp_b ->
fun inA_b ->
fun dst_b ->
fun inB_b ->
Vale_X64_QuickCodes.qblock
[Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg Prims.int_one);
Vale_X64_QuickCodes.if_code win
(Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (2)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (15)))
(Vale_X64_Machine_s.OReg (Prims.of_int (8)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (2)))
(Vale_X64_Machine_s.OReg (Prims.of_int (9)))])
(Vale_X64_Machine_s.Block
[Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (15)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3)))]);
va_code_Fmul ();
Vale_X64_QuickCodes.if_code win
(Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))])
(Vale_X64_Machine_s.Block []);
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg Prims.int_one);
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13)))] va_mods ()
type ('win, 'tmpub, 'inAub, 'dstub, 'inBub, 'vaus0,
'vauk) va_wp_Fmul_stdcall = unit
let (va_quick_Fmul_stdcall :
Prims.bool ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
(unit, unit) Vale_X64_QuickCode.quickCode)
=
fun win ->
fun tmp_b ->
fun inA_b ->
fun dst_b ->
fun inB_b ->
Vale_X64_QuickCode.QProc
((va_code_Fmul_stdcall win),
[Vale_X64_QuickCode.Mod_stackTaint;
Vale_X64_QuickCode.Mod_stack;
Vale_X64_QuickCode.Mod_mem_layout;
Vale_X64_QuickCode.Mod_mem_heaplet Prims.int_zero;
Vale_X64_QuickCode.Mod_flags;
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (15))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (14))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (13))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (11))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (10))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (9))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (8))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (7))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (6))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (5))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (4))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (3))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (2))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, Prims.int_one));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, Prims.int_zero));
Vale_X64_QuickCode.Mod_mem], (), ())
let (va_code_Fmul2 :
unit ->
(Vale_X64_Decls.ins, Vale_X64_Decls.ocmp) Vale_X64_Machine_s.precode)
=
fun uu___ ->
Vale_X64_Machine_s.Block
[Vale_X64_InsMem.va_code_CreateHeaplets ();
Vale_X64_InsBasic.va_code_LargeComment
"Compute the raw multiplication tmp[0] <- f1[0] * f2[0]";
Vale_Curve25519_X64_FastMul.va_code_Fast_multiply Prims.int_zero;
Vale_X64_InsBasic.va_code_LargeComment
"Compute the raw multiplication tmp[1] <- f1[1] * f2[1]";
Vale_Curve25519_X64_FastMul.va_code_Fast_multiply (Prims.of_int (4));
Vale_X64_InsBasic.va_code_Newline ();
Vale_X64_InsBasic.va_code_Comment "Line up pointers";
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (15)));
Vale_X64_InsBasic.va_code_LargeComment
"Wrap the results back into the field";
Vale_Curve25519_X64_FastHybrid.va_code_Carry_wide Prims.int_zero;
Vale_X64_InsBasic.va_code_Newline ();
Vale_Curve25519_X64_FastHybrid.va_code_Carry_wide (Prims.of_int (4));
Vale_X64_InsMem.va_code_DestroyHeaplets ()]
let (va_codegen_success_Fmul2 : unit -> Vale_X64_Decls.va_pbool) =
fun uu___ ->
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsMem.va_codegen_success_CreateHeaplets ())
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_LargeComment
"Compute the raw multiplication tmp[0] <- f1[0] * f2[0]")
(Vale_X64_Decls.va_pbool_and
(Vale_Curve25519_X64_FastMul.va_codegen_success_Fast_multiply
Prims.int_zero)
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_LargeComment
"Compute the raw multiplication tmp[1] <- f1[1] * f2[1]")
(Vale_X64_Decls.va_pbool_and
(Vale_Curve25519_X64_FastMul.va_codegen_success_Fast_multiply
(Prims.of_int (4)))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Newline ())
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Comment
"Line up pointers")
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (5))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (15))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_LargeComment
"Wrap the results back into the field")
(Vale_X64_Decls.va_pbool_and
(Vale_Curve25519_X64_FastHybrid.va_codegen_success_Carry_wide
Prims.int_zero)
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Newline
())
(Vale_X64_Decls.va_pbool_and
(Vale_Curve25519_X64_FastHybrid.va_codegen_success_Carry_wide
(Prims.of_int (4)))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsMem.va_codegen_success_DestroyHeaplets
())
(Vale_X64_Decls.va_ttrue ()))))))))))))))
type ('vaub0, 'vaus0, 'tmpub, 'inAub, 'dstub, 'inBub) va_req_Fmul2 = unit
type ('vaub0, 'vaus0, 'tmpub, 'inAub, 'dstub, 'inBub, 'vausM,
'vaufM) va_ens_Fmul2 = unit
let (va_qcode_Fmul2 :
Vale_X64_QuickCode.mod_t Prims.list ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
(unit, unit) Vale_X64_QuickCode.quickCode)
=
fun va_mods ->
fun tmp_b ->
fun inA_b ->
fun dst_b ->
fun inB_b ->
Vale_X64_QuickCodes.qblock
[Vale_X64_InsMem.va_code_CreateHeaplets ();
Vale_X64_InsBasic.va_code_LargeComment
"Compute the raw multiplication tmp[0] <- f1[0] * f2[0]";
Vale_Curve25519_X64_FastMul.va_code_Fast_multiply
Prims.int_zero;
Vale_X64_InsBasic.va_code_LargeComment
"Compute the raw multiplication tmp[1] <- f1[1] * f2[1]";
Vale_Curve25519_X64_FastMul.va_code_Fast_multiply
(Prims.of_int (4));
Vale_X64_InsBasic.va_code_Newline ();
Vale_X64_InsBasic.va_code_Comment "Line up pointers";
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (15)));
Vale_X64_InsBasic.va_code_LargeComment
"Wrap the results back into the field";
Vale_Curve25519_X64_FastHybrid.va_code_Carry_wide
Prims.int_zero;
Vale_X64_InsBasic.va_code_Newline ();
Vale_Curve25519_X64_FastHybrid.va_code_Carry_wide
(Prims.of_int (4));
Vale_X64_InsMem.va_code_DestroyHeaplets ()] va_mods ()
type ('tmpub, 'inAub, 'dstub, 'inBub, 'vaus0, 'vauk) va_wp_Fmul2 = unit
let (va_quick_Fmul2 :
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 -> (unit, unit) Vale_X64_QuickCode.quickCode)
=
fun tmp_b ->
fun inA_b ->
fun dst_b ->
fun inB_b ->
Vale_X64_QuickCode.QProc
((va_code_Fmul2 ()),
[Vale_X64_QuickCode.Mod_mem_layout;
Vale_X64_QuickCode.Mod_mem_heaplet Prims.int_zero;
Vale_X64_QuickCode.Mod_flags;
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (15))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (14))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (13))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (11))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (10))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (9))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (8))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (4))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (5))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (3))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (2))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, Prims.int_one));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, Prims.int_zero));
Vale_X64_QuickCode.Mod_mem], (), ())
let (va_code_Fmul2_stdcall :
Prims.bool ->
(Vale_X64_Decls.ins, Vale_X64_Decls.ocmp) Vale_X64_Machine_s.precode)
=
fun win ->
Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg Prims.int_one);
if win
then
Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (2)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (15)))
(Vale_X64_Machine_s.OReg (Prims.of_int (8)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (2)))
(Vale_X64_Machine_s.OReg (Prims.of_int (9)))]
else
Vale_X64_Machine_s.Block
[Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (15)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3)))];
va_code_Fmul2 ();
if win
then
Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))]
else Vale_X64_Machine_s.Block [];
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg Prims.int_one);
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13)))]
let (va_codegen_success_Fmul2_stdcall :
Prims.bool -> Vale_X64_Decls.va_pbool) =
fun win ->
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg Prims.int_one))
(Vale_X64_Decls.va_pbool_and
(if win
then
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (2))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg
(Prims.of_int (4)))
(Vale_X64_Machine_s.OReg
(Prims.of_int (3))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg
(Prims.of_int (15)))
(Vale_X64_Machine_s.OReg
(Prims.of_int (8))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg
(Prims.of_int (2)))
(Vale_X64_Machine_s.OReg
(Prims.of_int (9))))
(Vale_X64_Decls.va_ttrue ()))))))
else
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (15)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3))))
(Vale_X64_Decls.va_ttrue ()))
(Vale_X64_Decls.va_pbool_and (va_codegen_success_Fmul2 ())
(Vale_X64_Decls.va_pbool_and
(if win
then
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg
(Prims.of_int (4))))
(Vale_X64_Decls.va_ttrue ()))
else Vale_X64_Decls.va_ttrue ())
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg Prims.int_one))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg
(Prims.of_int (14))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg
(Prims.of_int (13))))
(Vale_X64_Decls.va_ttrue ())))))))))))
type ('vaub0, 'vaus0, 'win, 'tmpub, 'inAub, 'dstub,
'inBub) va_req_Fmul2_stdcall = unit
type ('vaub0, 'vaus0, 'win, 'tmpub, 'inAub, 'dstub, 'inBub, 'vausM,
'vaufM) va_ens_Fmul2_stdcall = unit
let (va_qcode_Fmul2_stdcall :
Vale_X64_QuickCode.mod_t Prims.list ->
Prims.bool ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
(unit, unit) Vale_X64_QuickCode.quickCode)
=
fun va_mods ->
fun win ->
fun tmp_b ->
fun inA_b ->
fun dst_b ->
fun inB_b ->
Vale_X64_QuickCodes.qblock
[Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg Prims.int_one);
Vale_X64_QuickCodes.if_code win
(Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (2)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (15)))
(Vale_X64_Machine_s.OReg (Prims.of_int (8)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (2)))
(Vale_X64_Machine_s.OReg (Prims.of_int (9)))])
(Vale_X64_Machine_s.Block
[Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (15)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3)))]);
va_code_Fmul2 ();
Vale_X64_QuickCodes.if_code win
(Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))])
(Vale_X64_Machine_s.Block []);
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg Prims.int_one);
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13)))] va_mods ()
type ('win, 'tmpub, 'inAub, 'dstub, 'inBub, 'vaus0,
'vauk) va_wp_Fmul2_stdcall = unit
let (va_quick_Fmul2_stdcall :
Prims.bool ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
(unit, unit) Vale_X64_QuickCode.quickCode)
=
fun win ->
fun tmp_b ->
fun inA_b ->
fun dst_b ->
fun inB_b ->
Vale_X64_QuickCode.QProc
((va_code_Fmul2_stdcall win),
[Vale_X64_QuickCode.Mod_stackTaint;
Vale_X64_QuickCode.Mod_stack;
Vale_X64_QuickCode.Mod_mem_layout;
Vale_X64_QuickCode.Mod_mem_heaplet Prims.int_zero;
Vale_X64_QuickCode.Mod_flags;
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (15))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (14))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (13))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (11))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (10))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (9))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (8))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (7))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (6))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (5))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (4))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (3))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (2))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, Prims.int_one));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, Prims.int_zero));
Vale_X64_QuickCode.Mod_mem], (), ())
let (va_code_Fsqr :
unit ->
(Vale_X64_Decls.ins, Vale_X64_Decls.ocmp) Vale_X64_Machine_s.precode)
=
fun uu___ ->
Vale_X64_Machine_s.Block
[Vale_X64_InsMem.va_code_CreateHeaplets ();
Vale_X64_InsBasic.va_code_LargeComment
"Compute the raw multiplication: tmp <- f * f";
Vale_Curve25519_X64_FastSqr.va_code_Fast_sqr Prims.int_zero;
Vale_X64_InsBasic.va_code_Newline ();
Vale_X64_InsBasic.va_code_Comment "Line up pointers";
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (12)));
Vale_X64_InsBasic.va_code_LargeComment
"Wrap the result back into the field";
Vale_Curve25519_X64_FastHybrid.va_code_Carry_wide Prims.int_zero;
Vale_X64_InsMem.va_code_DestroyHeaplets ()]
let (va_codegen_success_Fsqr : unit -> Vale_X64_Decls.va_pbool) =
fun uu___ ->
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsMem.va_codegen_success_CreateHeaplets ())
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_LargeComment
"Compute the raw multiplication: tmp <- f * f")
(Vale_X64_Decls.va_pbool_and
(Vale_Curve25519_X64_FastSqr.va_codegen_success_Fast_sqr
Prims.int_zero)
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Newline ())
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Comment
"Line up pointers")
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (5))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (12))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_LargeComment
"Wrap the result back into the field")
(Vale_X64_Decls.va_pbool_and
(Vale_Curve25519_X64_FastHybrid.va_codegen_success_Carry_wide
Prims.int_zero)
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsMem.va_codegen_success_DestroyHeaplets
()) (Vale_X64_Decls.va_ttrue ()))))))))))
type ('vaub0, 'vaus0, 'tmpub, 'inAub, 'dstub) va_req_Fsqr = unit
type ('vaub0, 'vaus0, 'tmpub, 'inAub, 'dstub, 'vausM, 'vaufM) va_ens_Fsqr =
unit
let (va_qcode_Fsqr :
Vale_X64_QuickCode.mod_t Prims.list ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 -> (unit, unit) Vale_X64_QuickCode.quickCode)
=
fun va_mods ->
fun tmp_b ->
fun inA_b ->
fun dst_b ->
Vale_X64_QuickCodes.qblock
[Vale_X64_InsMem.va_code_CreateHeaplets ();
Vale_X64_InsBasic.va_code_LargeComment
"Compute the raw multiplication: tmp <- f * f";
Vale_Curve25519_X64_FastSqr.va_code_Fast_sqr Prims.int_zero;
Vale_X64_InsBasic.va_code_Newline ();
Vale_X64_InsBasic.va_code_Comment "Line up pointers";
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (12)));
Vale_X64_InsBasic.va_code_LargeComment
"Wrap the result back into the field";
Vale_Curve25519_X64_FastHybrid.va_code_Carry_wide Prims.int_zero;
Vale_X64_InsMem.va_code_DestroyHeaplets ()] va_mods ()
type ('tmpub, 'inAub, 'dstub, 'vaus0, 'vauk) va_wp_Fsqr = unit
let (va_quick_Fsqr :
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 -> (unit, unit) Vale_X64_QuickCode.quickCode)
=
fun tmp_b ->
fun inA_b ->
fun dst_b ->
Vale_X64_QuickCode.QProc
((va_code_Fsqr ()),
[Vale_X64_QuickCode.Mod_mem_layout;
Vale_X64_QuickCode.Mod_mem_heaplet Prims.int_zero;
Vale_X64_QuickCode.Mod_flags;
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (15))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (14))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (13))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (12))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (11))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (10))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (9))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (8))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (4))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (5))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (3))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (2))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, Prims.int_one));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, Prims.int_zero));
Vale_X64_QuickCode.Mod_mem], (), ())
let (va_code_Fsqr_stdcall :
Prims.bool ->
(Vale_X64_Decls.ins, Vale_X64_Decls.ocmp) Vale_X64_Machine_s.precode)
=
fun win ->
Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (12)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg Prims.int_one);
if win
then
Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (2)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (12)))
(Vale_X64_Machine_s.OReg (Prims.of_int (8)))]
else
Vale_X64_Machine_s.Block
[Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (12)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3)))];
va_code_Fsqr ();
if win
then
Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))]
else Vale_X64_Machine_s.Block [];
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg Prims.int_one);
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (12)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15)))]
let (va_codegen_success_Fsqr_stdcall : Prims.bool -> Vale_X64_Decls.va_pbool)
=
fun win ->
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (12))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg Prims.int_one))
(Vale_X64_Decls.va_pbool_and
(if win
then
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg
(Prims.of_int (5)))
(Vale_X64_Machine_s.OReg
(Prims.of_int (2))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg
(Prims.of_int (4)))
(Vale_X64_Machine_s.OReg
(Prims.of_int (3))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg
(Prims.of_int (12)))
(Vale_X64_Machine_s.OReg
(Prims.of_int (8))))
(Vale_X64_Decls.va_ttrue ())))))
else
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (12)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3))))
(Vale_X64_Decls.va_ttrue ()))
(Vale_X64_Decls.va_pbool_and
(va_codegen_success_Fsqr ())
(Vale_X64_Decls.va_pbool_and
(if win
then
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg
(Prims.of_int (5))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg
(Prims.of_int (4))))
(Vale_X64_Decls.va_ttrue ()))
else Vale_X64_Decls.va_ttrue ())
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg Prims.int_one))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg
(Prims.of_int (12))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg
(Prims.of_int (14))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg
(Prims.of_int (13))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg
(Prims.of_int (15))))
(Vale_X64_Decls.va_ttrue ())))))))))))))
type ('vaub0, 'vaus0, 'win, 'tmpub, 'inAub, 'dstub) va_req_Fsqr_stdcall =
unit
type ('vaub0, 'vaus0, 'win, 'tmpub, 'inAub, 'dstub, 'vausM,
'vaufM) va_ens_Fsqr_stdcall = unit
let (va_qcode_Fsqr_stdcall :
Vale_X64_QuickCode.mod_t Prims.list ->
Prims.bool ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
(unit, unit) Vale_X64_QuickCode.quickCode)
=
fun va_mods ->
fun win ->
fun tmp_b ->
fun inA_b ->
fun dst_b ->
Vale_X64_QuickCodes.qblock
[Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (12)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg Prims.int_one);
Vale_X64_QuickCodes.if_code win
(Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (2)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (12)))
(Vale_X64_Machine_s.OReg (Prims.of_int (8)))])
(Vale_X64_Machine_s.Block
[Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (12)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3)))]);
va_code_Fsqr ();
Vale_X64_QuickCodes.if_code win
(Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))])
(Vale_X64_Machine_s.Block []);
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg Prims.int_one);
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (12)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15)))] va_mods ()
type ('win, 'tmpub, 'inAub, 'dstub, 'vaus0, 'vauk) va_wp_Fsqr_stdcall = unit
let (va_quick_Fsqr_stdcall :
Prims.bool ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 -> (unit, unit) Vale_X64_QuickCode.quickCode)
=
fun win ->
fun tmp_b ->
fun inA_b ->
fun dst_b ->
Vale_X64_QuickCode.QProc
((va_code_Fsqr_stdcall win),
[Vale_X64_QuickCode.Mod_stackTaint;
Vale_X64_QuickCode.Mod_stack;
Vale_X64_QuickCode.Mod_mem_layout;
Vale_X64_QuickCode.Mod_mem_heaplet Prims.int_zero;
Vale_X64_QuickCode.Mod_flags;
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (15))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (14))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (13))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (12))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (11))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (10))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (9))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (8))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (7))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (6))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (5))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (4))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (3))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (2))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, Prims.int_one));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, Prims.int_zero));
Vale_X64_QuickCode.Mod_mem], (), ())
let (va_code_Fsqr2 :
unit ->
(Vale_X64_Decls.ins, Vale_X64_Decls.ocmp) Vale_X64_Machine_s.precode)
=
fun uu___ ->
Vale_X64_Machine_s.Block
[Vale_X64_InsMem.va_code_CreateHeaplets ();
Vale_Curve25519_X64_FastSqr.va_code_Fast_sqr Prims.int_zero;
Vale_X64_InsBasic.va_code_Newline ();
Vale_Curve25519_X64_FastSqr.va_code_Fast_sqr (Prims.of_int (4));
Vale_X64_InsBasic.va_code_Newline ();
Vale_X64_InsBasic.va_code_Comment "Line up pointers";
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (12)));
Vale_X64_InsBasic.va_code_Newline ();
Vale_Curve25519_X64_FastHybrid.va_code_Carry_wide Prims.int_zero;
Vale_X64_InsBasic.va_code_Newline ();
Vale_Curve25519_X64_FastHybrid.va_code_Carry_wide (Prims.of_int (4));
Vale_X64_InsMem.va_code_DestroyHeaplets ()]
let (va_codegen_success_Fsqr2 : unit -> Vale_X64_Decls.va_pbool) =
fun uu___ ->
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsMem.va_codegen_success_CreateHeaplets ())
(Vale_X64_Decls.va_pbool_and
(Vale_Curve25519_X64_FastSqr.va_codegen_success_Fast_sqr
Prims.int_zero)
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Newline ())
(Vale_X64_Decls.va_pbool_and
(Vale_Curve25519_X64_FastSqr.va_codegen_success_Fast_sqr
(Prims.of_int (4)))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Newline ())
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Comment
"Line up pointers")
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (5))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (12))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Newline
())
(Vale_X64_Decls.va_pbool_and
(Vale_Curve25519_X64_FastHybrid.va_codegen_success_Carry_wide
Prims.int_zero)
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Newline
())
(Vale_X64_Decls.va_pbool_and
(Vale_Curve25519_X64_FastHybrid.va_codegen_success_Carry_wide
(Prims.of_int (4)))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsMem.va_codegen_success_DestroyHeaplets
()) (Vale_X64_Decls.va_ttrue ())))))))))))))
type ('vaub0, 'vaus0, 'tmpub, 'inAub, 'dstub) va_req_Fsqr2 = unit
type ('vaub0, 'vaus0, 'tmpub, 'inAub, 'dstub, 'vausM, 'vaufM) va_ens_Fsqr2 =
unit
let (va_qcode_Fsqr2 :
Vale_X64_QuickCode.mod_t Prims.list ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 -> (unit, unit) Vale_X64_QuickCode.quickCode)
=
fun va_mods ->
fun tmp_b ->
fun inA_b ->
fun dst_b ->
Vale_X64_QuickCodes.qblock
[Vale_X64_InsMem.va_code_CreateHeaplets ();
Vale_Curve25519_X64_FastSqr.va_code_Fast_sqr Prims.int_zero;
Vale_X64_InsBasic.va_code_Newline ();
Vale_Curve25519_X64_FastSqr.va_code_Fast_sqr (Prims.of_int (4));
Vale_X64_InsBasic.va_code_Newline ();
Vale_X64_InsBasic.va_code_Comment "Line up pointers";
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (12)));
Vale_X64_InsBasic.va_code_Newline ();
Vale_Curve25519_X64_FastHybrid.va_code_Carry_wide Prims.int_zero;
Vale_X64_InsBasic.va_code_Newline ();
Vale_Curve25519_X64_FastHybrid.va_code_Carry_wide
(Prims.of_int (4));
Vale_X64_InsMem.va_code_DestroyHeaplets ()] va_mods ()
type ('tmpub, 'inAub, 'dstub, 'vaus0, 'vauk) va_wp_Fsqr2 = unit
let (va_quick_Fsqr2 :
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 -> (unit, unit) Vale_X64_QuickCode.quickCode)
=
fun tmp_b ->
fun inA_b ->
fun dst_b ->
Vale_X64_QuickCode.QProc
((va_code_Fsqr2 ()),
[Vale_X64_QuickCode.Mod_mem_layout;
Vale_X64_QuickCode.Mod_mem_heaplet Prims.int_zero;
Vale_X64_QuickCode.Mod_flags;
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (15))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (14))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (13))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (12))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (11))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (10))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (9))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (8))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (4))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (5))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (3))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (2))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, Prims.int_one));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, Prims.int_zero));
Vale_X64_QuickCode.Mod_mem], (), ())
let (va_code_Fsqr2_stdcall :
Prims.bool ->
(Vale_X64_Decls.ins, Vale_X64_Decls.ocmp) Vale_X64_Machine_s.precode)
=
fun win ->
Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (12)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg Prims.int_one);
if win
then
Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (2)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (12)))
(Vale_X64_Machine_s.OReg (Prims.of_int (8)))]
else
Vale_X64_Machine_s.Block
[Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (12)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3)))];
va_code_Fsqr2 ();
if win
then
Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))]
else Vale_X64_Machine_s.Block [];
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg Prims.int_one);
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (12)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15)))]
let (va_codegen_success_Fsqr2_stdcall :
Prims.bool -> Vale_X64_Decls.va_pbool) =
fun win ->
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (12))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg Prims.int_one))
(Vale_X64_Decls.va_pbool_and
(if win
then
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg
(Prims.of_int (5)))
(Vale_X64_Machine_s.OReg
(Prims.of_int (2))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg
(Prims.of_int (4)))
(Vale_X64_Machine_s.OReg
(Prims.of_int (3))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg
(Prims.of_int (12)))
(Vale_X64_Machine_s.OReg
(Prims.of_int (8))))
(Vale_X64_Decls.va_ttrue ())))))
else
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (12)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3))))
(Vale_X64_Decls.va_ttrue ()))
(Vale_X64_Decls.va_pbool_and
(va_codegen_success_Fsqr2 ())
(Vale_X64_Decls.va_pbool_and
(if win
then
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg
(Prims.of_int (5))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg
(Prims.of_int (4))))
(Vale_X64_Decls.va_ttrue ()))
else Vale_X64_Decls.va_ttrue ())
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg Prims.int_one))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg
(Prims.of_int (12))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg
(Prims.of_int (14))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg
(Prims.of_int (13))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg
(Prims.of_int (15))))
(Vale_X64_Decls.va_ttrue ())))))))))))))
type ('vaub0, 'vaus0, 'win, 'tmpub, 'inAub, 'dstub) va_req_Fsqr2_stdcall =
unit
type ('vaub0, 'vaus0, 'win, 'tmpub, 'inAub, 'dstub, 'vausM,
'vaufM) va_ens_Fsqr2_stdcall = unit
let (va_qcode_Fsqr2_stdcall :
Vale_X64_QuickCode.mod_t Prims.list ->
Prims.bool ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
(unit, unit) Vale_X64_QuickCode.quickCode)
=
fun va_mods ->
fun win ->
fun tmp_b ->
fun inA_b ->
fun dst_b ->
Vale_X64_QuickCodes.qblock
[Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (12)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg Prims.int_one);
Vale_X64_QuickCodes.if_code win
(Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (2)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (12)))
(Vale_X64_Machine_s.OReg (Prims.of_int (8)))])
(Vale_X64_Machine_s.Block
[Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (12)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3)))]);
va_code_Fsqr2 ();
Vale_X64_QuickCodes.if_code win
(Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))])
(Vale_X64_Machine_s.Block []);
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg Prims.int_one);
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (12)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15)))] va_mods ()
type ('win, 'tmpub, 'inAub, 'dstub, 'vaus0, 'vauk) va_wp_Fsqr2_stdcall = unit
let (va_quick_Fsqr2_stdcall :
Prims.bool ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 -> (unit, unit) Vale_X64_QuickCode.quickCode)
=
fun win ->
fun tmp_b ->
fun inA_b ->
fun dst_b ->
Vale_X64_QuickCode.QProc
((va_code_Fsqr2_stdcall win),
[Vale_X64_QuickCode.Mod_stackTaint;
Vale_X64_QuickCode.Mod_stack;
Vale_X64_QuickCode.Mod_mem_layout;
Vale_X64_QuickCode.Mod_mem_heaplet Prims.int_zero;
Vale_X64_QuickCode.Mod_flags;
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (15))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (14))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (13))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (12))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (11))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (10))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (9))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (8))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (7))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (6))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (5))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (4))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (3))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (2))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, Prims.int_one));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, Prims.int_zero));
Vale_X64_QuickCode.Mod_mem], (), ()) | null | https://raw.githubusercontent.com/REPROSEC/dolev-yao-star/d97a8dd4d07f2322437f186e4db6a1f4d5ee9230/concrete/hacl-star-snapshot/ml/Vale_Curve25519_X64_FastWide.ml | ocaml | open Prims
let (va_code_Fmul :
unit ->
(Vale_X64_Decls.ins, Vale_X64_Decls.ocmp) Vale_X64_Machine_s.precode)
=
fun uu___ ->
Vale_X64_Machine_s.Block
[Vale_X64_InsMem.va_code_CreateHeaplets ();
Vale_X64_InsBasic.va_code_LargeComment
"Compute the raw multiplication: tmp <- src1 * src2";
Vale_Curve25519_X64_FastMul.va_code_Fast_multiply Prims.int_zero;
Vale_X64_InsBasic.va_code_Newline ();
Vale_X64_InsBasic.va_code_Comment "Line up pointers";
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (15)));
Vale_X64_InsBasic.va_code_LargeComment
"Wrap the result back into the field";
Vale_Curve25519_X64_FastHybrid.va_code_Carry_wide Prims.int_zero;
Vale_X64_InsMem.va_code_DestroyHeaplets ()]
let (va_codegen_success_Fmul : unit -> Vale_X64_Decls.va_pbool) =
fun uu___ ->
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsMem.va_codegen_success_CreateHeaplets ())
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_LargeComment
"Compute the raw multiplication: tmp <- src1 * src2")
(Vale_X64_Decls.va_pbool_and
(Vale_Curve25519_X64_FastMul.va_codegen_success_Fast_multiply
Prims.int_zero)
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Newline ())
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Comment
"Line up pointers")
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (5))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (15))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_LargeComment
"Wrap the result back into the field")
(Vale_X64_Decls.va_pbool_and
(Vale_Curve25519_X64_FastHybrid.va_codegen_success_Carry_wide
Prims.int_zero)
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsMem.va_codegen_success_DestroyHeaplets
()) (Vale_X64_Decls.va_ttrue ()))))))))))
type ('vaub0, 'vaus0, 'tmpub, 'inAub, 'dstub, 'inBub) va_req_Fmul = unit
type ('vaub0, 'vaus0, 'tmpub, 'inAub, 'dstub, 'inBub, 'vausM,
'vaufM) va_ens_Fmul = unit
let (va_qcode_Fmul :
Vale_X64_QuickCode.mod_t Prims.list ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
(unit, unit) Vale_X64_QuickCode.quickCode)
=
fun va_mods ->
fun tmp_b ->
fun inA_b ->
fun dst_b ->
fun inB_b ->
Vale_X64_QuickCodes.qblock
[Vale_X64_InsMem.va_code_CreateHeaplets ();
Vale_X64_InsBasic.va_code_LargeComment
"Compute the raw multiplication: tmp <- src1 * src2";
Vale_Curve25519_X64_FastMul.va_code_Fast_multiply
Prims.int_zero;
Vale_X64_InsBasic.va_code_Newline ();
Vale_X64_InsBasic.va_code_Comment "Line up pointers";
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (15)));
Vale_X64_InsBasic.va_code_LargeComment
"Wrap the result back into the field";
Vale_Curve25519_X64_FastHybrid.va_code_Carry_wide
Prims.int_zero;
Vale_X64_InsMem.va_code_DestroyHeaplets ()] va_mods ()
type ('tmpub, 'inAub, 'dstub, 'inBub, 'vaus0, 'vauk) va_wp_Fmul = unit
let (va_quick_Fmul :
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 -> (unit, unit) Vale_X64_QuickCode.quickCode)
=
fun tmp_b ->
fun inA_b ->
fun dst_b ->
fun inB_b ->
Vale_X64_QuickCode.QProc
((va_code_Fmul ()),
[Vale_X64_QuickCode.Mod_mem_layout;
Vale_X64_QuickCode.Mod_mem_heaplet Prims.int_zero;
Vale_X64_QuickCode.Mod_flags;
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (15))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (14))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (13))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (11))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (10))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (9))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (8))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (4))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (5))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (3))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (2))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, Prims.int_one));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, Prims.int_zero));
Vale_X64_QuickCode.Mod_mem], (), ())
let (va_code_Fmul_stdcall :
Prims.bool ->
(Vale_X64_Decls.ins, Vale_X64_Decls.ocmp) Vale_X64_Machine_s.precode)
=
fun win ->
Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg Prims.int_one);
if win
then
Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (2)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (15)))
(Vale_X64_Machine_s.OReg (Prims.of_int (8)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (2)))
(Vale_X64_Machine_s.OReg (Prims.of_int (9)))]
else
Vale_X64_Machine_s.Block
[Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (15)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3)))];
va_code_Fmul ();
if win
then
Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))]
else Vale_X64_Machine_s.Block [];
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg Prims.int_one);
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13)))]
let (va_codegen_success_Fmul_stdcall : Prims.bool -> Vale_X64_Decls.va_pbool)
=
fun win ->
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg Prims.int_one))
(Vale_X64_Decls.va_pbool_and
(if win
then
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (2))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg
(Prims.of_int (4)))
(Vale_X64_Machine_s.OReg
(Prims.of_int (3))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg
(Prims.of_int (15)))
(Vale_X64_Machine_s.OReg
(Prims.of_int (8))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg
(Prims.of_int (2)))
(Vale_X64_Machine_s.OReg
(Prims.of_int (9))))
(Vale_X64_Decls.va_ttrue ()))))))
else
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (15)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3))))
(Vale_X64_Decls.va_ttrue ()))
(Vale_X64_Decls.va_pbool_and (va_codegen_success_Fmul ())
(Vale_X64_Decls.va_pbool_and
(if win
then
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg
(Prims.of_int (4))))
(Vale_X64_Decls.va_ttrue ()))
else Vale_X64_Decls.va_ttrue ())
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg Prims.int_one))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg
(Prims.of_int (14))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg
(Prims.of_int (13))))
(Vale_X64_Decls.va_ttrue ())))))))))))
type ('vaub0, 'vaus0, 'win, 'tmpub, 'inAub, 'dstub,
'inBub) va_req_Fmul_stdcall = unit
type ('vaub0, 'vaus0, 'win, 'tmpub, 'inAub, 'dstub, 'inBub, 'vausM,
'vaufM) va_ens_Fmul_stdcall = unit
let (va_qcode_Fmul_stdcall :
Vale_X64_QuickCode.mod_t Prims.list ->
Prims.bool ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
(unit, unit) Vale_X64_QuickCode.quickCode)
=
fun va_mods ->
fun win ->
fun tmp_b ->
fun inA_b ->
fun dst_b ->
fun inB_b ->
Vale_X64_QuickCodes.qblock
[Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg Prims.int_one);
Vale_X64_QuickCodes.if_code win
(Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (2)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (15)))
(Vale_X64_Machine_s.OReg (Prims.of_int (8)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (2)))
(Vale_X64_Machine_s.OReg (Prims.of_int (9)))])
(Vale_X64_Machine_s.Block
[Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (15)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3)))]);
va_code_Fmul ();
Vale_X64_QuickCodes.if_code win
(Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))])
(Vale_X64_Machine_s.Block []);
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg Prims.int_one);
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13)))] va_mods ()
type ('win, 'tmpub, 'inAub, 'dstub, 'inBub, 'vaus0,
'vauk) va_wp_Fmul_stdcall = unit
let (va_quick_Fmul_stdcall :
Prims.bool ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
(unit, unit) Vale_X64_QuickCode.quickCode)
=
fun win ->
fun tmp_b ->
fun inA_b ->
fun dst_b ->
fun inB_b ->
Vale_X64_QuickCode.QProc
((va_code_Fmul_stdcall win),
[Vale_X64_QuickCode.Mod_stackTaint;
Vale_X64_QuickCode.Mod_stack;
Vale_X64_QuickCode.Mod_mem_layout;
Vale_X64_QuickCode.Mod_mem_heaplet Prims.int_zero;
Vale_X64_QuickCode.Mod_flags;
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (15))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (14))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (13))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (11))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (10))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (9))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (8))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (7))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (6))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (5))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (4))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (3))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (2))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, Prims.int_one));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, Prims.int_zero));
Vale_X64_QuickCode.Mod_mem], (), ())
let (va_code_Fmul2 :
unit ->
(Vale_X64_Decls.ins, Vale_X64_Decls.ocmp) Vale_X64_Machine_s.precode)
=
fun uu___ ->
Vale_X64_Machine_s.Block
[Vale_X64_InsMem.va_code_CreateHeaplets ();
Vale_X64_InsBasic.va_code_LargeComment
"Compute the raw multiplication tmp[0] <- f1[0] * f2[0]";
Vale_Curve25519_X64_FastMul.va_code_Fast_multiply Prims.int_zero;
Vale_X64_InsBasic.va_code_LargeComment
"Compute the raw multiplication tmp[1] <- f1[1] * f2[1]";
Vale_Curve25519_X64_FastMul.va_code_Fast_multiply (Prims.of_int (4));
Vale_X64_InsBasic.va_code_Newline ();
Vale_X64_InsBasic.va_code_Comment "Line up pointers";
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (15)));
Vale_X64_InsBasic.va_code_LargeComment
"Wrap the results back into the field";
Vale_Curve25519_X64_FastHybrid.va_code_Carry_wide Prims.int_zero;
Vale_X64_InsBasic.va_code_Newline ();
Vale_Curve25519_X64_FastHybrid.va_code_Carry_wide (Prims.of_int (4));
Vale_X64_InsMem.va_code_DestroyHeaplets ()]
let (va_codegen_success_Fmul2 : unit -> Vale_X64_Decls.va_pbool) =
fun uu___ ->
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsMem.va_codegen_success_CreateHeaplets ())
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_LargeComment
"Compute the raw multiplication tmp[0] <- f1[0] * f2[0]")
(Vale_X64_Decls.va_pbool_and
(Vale_Curve25519_X64_FastMul.va_codegen_success_Fast_multiply
Prims.int_zero)
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_LargeComment
"Compute the raw multiplication tmp[1] <- f1[1] * f2[1]")
(Vale_X64_Decls.va_pbool_and
(Vale_Curve25519_X64_FastMul.va_codegen_success_Fast_multiply
(Prims.of_int (4)))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Newline ())
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Comment
"Line up pointers")
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (5))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (15))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_LargeComment
"Wrap the results back into the field")
(Vale_X64_Decls.va_pbool_and
(Vale_Curve25519_X64_FastHybrid.va_codegen_success_Carry_wide
Prims.int_zero)
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Newline
())
(Vale_X64_Decls.va_pbool_and
(Vale_Curve25519_X64_FastHybrid.va_codegen_success_Carry_wide
(Prims.of_int (4)))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsMem.va_codegen_success_DestroyHeaplets
())
(Vale_X64_Decls.va_ttrue ()))))))))))))))
type ('vaub0, 'vaus0, 'tmpub, 'inAub, 'dstub, 'inBub) va_req_Fmul2 = unit
type ('vaub0, 'vaus0, 'tmpub, 'inAub, 'dstub, 'inBub, 'vausM,
'vaufM) va_ens_Fmul2 = unit
let (va_qcode_Fmul2 :
Vale_X64_QuickCode.mod_t Prims.list ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
(unit, unit) Vale_X64_QuickCode.quickCode)
=
fun va_mods ->
fun tmp_b ->
fun inA_b ->
fun dst_b ->
fun inB_b ->
Vale_X64_QuickCodes.qblock
[Vale_X64_InsMem.va_code_CreateHeaplets ();
Vale_X64_InsBasic.va_code_LargeComment
"Compute the raw multiplication tmp[0] <- f1[0] * f2[0]";
Vale_Curve25519_X64_FastMul.va_code_Fast_multiply
Prims.int_zero;
Vale_X64_InsBasic.va_code_LargeComment
"Compute the raw multiplication tmp[1] <- f1[1] * f2[1]";
Vale_Curve25519_X64_FastMul.va_code_Fast_multiply
(Prims.of_int (4));
Vale_X64_InsBasic.va_code_Newline ();
Vale_X64_InsBasic.va_code_Comment "Line up pointers";
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (15)));
Vale_X64_InsBasic.va_code_LargeComment
"Wrap the results back into the field";
Vale_Curve25519_X64_FastHybrid.va_code_Carry_wide
Prims.int_zero;
Vale_X64_InsBasic.va_code_Newline ();
Vale_Curve25519_X64_FastHybrid.va_code_Carry_wide
(Prims.of_int (4));
Vale_X64_InsMem.va_code_DestroyHeaplets ()] va_mods ()
type ('tmpub, 'inAub, 'dstub, 'inBub, 'vaus0, 'vauk) va_wp_Fmul2 = unit
let (va_quick_Fmul2 :
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 -> (unit, unit) Vale_X64_QuickCode.quickCode)
=
fun tmp_b ->
fun inA_b ->
fun dst_b ->
fun inB_b ->
Vale_X64_QuickCode.QProc
((va_code_Fmul2 ()),
[Vale_X64_QuickCode.Mod_mem_layout;
Vale_X64_QuickCode.Mod_mem_heaplet Prims.int_zero;
Vale_X64_QuickCode.Mod_flags;
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (15))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (14))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (13))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (11))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (10))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (9))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (8))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (4))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (5))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (3))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (2))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, Prims.int_one));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, Prims.int_zero));
Vale_X64_QuickCode.Mod_mem], (), ())
let (va_code_Fmul2_stdcall :
Prims.bool ->
(Vale_X64_Decls.ins, Vale_X64_Decls.ocmp) Vale_X64_Machine_s.precode)
=
fun win ->
Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg Prims.int_one);
if win
then
Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (2)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (15)))
(Vale_X64_Machine_s.OReg (Prims.of_int (8)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (2)))
(Vale_X64_Machine_s.OReg (Prims.of_int (9)))]
else
Vale_X64_Machine_s.Block
[Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (15)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3)))];
va_code_Fmul2 ();
if win
then
Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))]
else Vale_X64_Machine_s.Block [];
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg Prims.int_one);
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13)))]
let (va_codegen_success_Fmul2_stdcall :
Prims.bool -> Vale_X64_Decls.va_pbool) =
fun win ->
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg Prims.int_one))
(Vale_X64_Decls.va_pbool_and
(if win
then
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (2))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg
(Prims.of_int (4)))
(Vale_X64_Machine_s.OReg
(Prims.of_int (3))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg
(Prims.of_int (15)))
(Vale_X64_Machine_s.OReg
(Prims.of_int (8))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg
(Prims.of_int (2)))
(Vale_X64_Machine_s.OReg
(Prims.of_int (9))))
(Vale_X64_Decls.va_ttrue ()))))))
else
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (15)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3))))
(Vale_X64_Decls.va_ttrue ()))
(Vale_X64_Decls.va_pbool_and (va_codegen_success_Fmul2 ())
(Vale_X64_Decls.va_pbool_and
(if win
then
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg
(Prims.of_int (4))))
(Vale_X64_Decls.va_ttrue ()))
else Vale_X64_Decls.va_ttrue ())
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg Prims.int_one))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg
(Prims.of_int (14))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg
(Prims.of_int (13))))
(Vale_X64_Decls.va_ttrue ())))))))))))
type ('vaub0, 'vaus0, 'win, 'tmpub, 'inAub, 'dstub,
'inBub) va_req_Fmul2_stdcall = unit
type ('vaub0, 'vaus0, 'win, 'tmpub, 'inAub, 'dstub, 'inBub, 'vausM,
'vaufM) va_ens_Fmul2_stdcall = unit
let (va_qcode_Fmul2_stdcall :
Vale_X64_QuickCode.mod_t Prims.list ->
Prims.bool ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
(unit, unit) Vale_X64_QuickCode.quickCode)
=
fun va_mods ->
fun win ->
fun tmp_b ->
fun inA_b ->
fun dst_b ->
fun inB_b ->
Vale_X64_QuickCodes.qblock
[Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg Prims.int_one);
Vale_X64_QuickCodes.if_code win
(Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (2)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (15)))
(Vale_X64_Machine_s.OReg (Prims.of_int (8)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (2)))
(Vale_X64_Machine_s.OReg (Prims.of_int (9)))])
(Vale_X64_Machine_s.Block
[Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (15)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3)))]);
va_code_Fmul2 ();
Vale_X64_QuickCodes.if_code win
(Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))])
(Vale_X64_Machine_s.Block []);
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg Prims.int_one);
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13)))] va_mods ()
type ('win, 'tmpub, 'inAub, 'dstub, 'inBub, 'vaus0,
'vauk) va_wp_Fmul2_stdcall = unit
let (va_quick_Fmul2_stdcall :
Prims.bool ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
(unit, unit) Vale_X64_QuickCode.quickCode)
=
fun win ->
fun tmp_b ->
fun inA_b ->
fun dst_b ->
fun inB_b ->
Vale_X64_QuickCode.QProc
((va_code_Fmul2_stdcall win),
[Vale_X64_QuickCode.Mod_stackTaint;
Vale_X64_QuickCode.Mod_stack;
Vale_X64_QuickCode.Mod_mem_layout;
Vale_X64_QuickCode.Mod_mem_heaplet Prims.int_zero;
Vale_X64_QuickCode.Mod_flags;
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (15))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (14))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (13))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (11))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (10))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (9))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (8))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (7))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (6))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (5))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (4))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (3))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg
(Prims.int_zero, (Prims.of_int (2))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, Prims.int_one));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, Prims.int_zero));
Vale_X64_QuickCode.Mod_mem], (), ())
let (va_code_Fsqr :
unit ->
(Vale_X64_Decls.ins, Vale_X64_Decls.ocmp) Vale_X64_Machine_s.precode)
=
fun uu___ ->
Vale_X64_Machine_s.Block
[Vale_X64_InsMem.va_code_CreateHeaplets ();
Vale_X64_InsBasic.va_code_LargeComment
"Compute the raw multiplication: tmp <- f * f";
Vale_Curve25519_X64_FastSqr.va_code_Fast_sqr Prims.int_zero;
Vale_X64_InsBasic.va_code_Newline ();
Vale_X64_InsBasic.va_code_Comment "Line up pointers";
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (12)));
Vale_X64_InsBasic.va_code_LargeComment
"Wrap the result back into the field";
Vale_Curve25519_X64_FastHybrid.va_code_Carry_wide Prims.int_zero;
Vale_X64_InsMem.va_code_DestroyHeaplets ()]
let (va_codegen_success_Fsqr : unit -> Vale_X64_Decls.va_pbool) =
fun uu___ ->
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsMem.va_codegen_success_CreateHeaplets ())
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_LargeComment
"Compute the raw multiplication: tmp <- f * f")
(Vale_X64_Decls.va_pbool_and
(Vale_Curve25519_X64_FastSqr.va_codegen_success_Fast_sqr
Prims.int_zero)
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Newline ())
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Comment
"Line up pointers")
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (5))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (12))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_LargeComment
"Wrap the result back into the field")
(Vale_X64_Decls.va_pbool_and
(Vale_Curve25519_X64_FastHybrid.va_codegen_success_Carry_wide
Prims.int_zero)
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsMem.va_codegen_success_DestroyHeaplets
()) (Vale_X64_Decls.va_ttrue ()))))))))))
type ('vaub0, 'vaus0, 'tmpub, 'inAub, 'dstub) va_req_Fsqr = unit
type ('vaub0, 'vaus0, 'tmpub, 'inAub, 'dstub, 'vausM, 'vaufM) va_ens_Fsqr =
unit
let (va_qcode_Fsqr :
Vale_X64_QuickCode.mod_t Prims.list ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 -> (unit, unit) Vale_X64_QuickCode.quickCode)
=
fun va_mods ->
fun tmp_b ->
fun inA_b ->
fun dst_b ->
Vale_X64_QuickCodes.qblock
[Vale_X64_InsMem.va_code_CreateHeaplets ();
Vale_X64_InsBasic.va_code_LargeComment
"Compute the raw multiplication: tmp <- f * f";
Vale_Curve25519_X64_FastSqr.va_code_Fast_sqr Prims.int_zero;
Vale_X64_InsBasic.va_code_Newline ();
Vale_X64_InsBasic.va_code_Comment "Line up pointers";
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (12)));
Vale_X64_InsBasic.va_code_LargeComment
"Wrap the result back into the field";
Vale_Curve25519_X64_FastHybrid.va_code_Carry_wide Prims.int_zero;
Vale_X64_InsMem.va_code_DestroyHeaplets ()] va_mods ()
type ('tmpub, 'inAub, 'dstub, 'vaus0, 'vauk) va_wp_Fsqr = unit
let (va_quick_Fsqr :
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 -> (unit, unit) Vale_X64_QuickCode.quickCode)
=
fun tmp_b ->
fun inA_b ->
fun dst_b ->
Vale_X64_QuickCode.QProc
((va_code_Fsqr ()),
[Vale_X64_QuickCode.Mod_mem_layout;
Vale_X64_QuickCode.Mod_mem_heaplet Prims.int_zero;
Vale_X64_QuickCode.Mod_flags;
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (15))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (14))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (13))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (12))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (11))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (10))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (9))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (8))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (4))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (5))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (3))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (2))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, Prims.int_one));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, Prims.int_zero));
Vale_X64_QuickCode.Mod_mem], (), ())
let (va_code_Fsqr_stdcall :
Prims.bool ->
(Vale_X64_Decls.ins, Vale_X64_Decls.ocmp) Vale_X64_Machine_s.precode)
=
fun win ->
Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (12)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg Prims.int_one);
if win
then
Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (2)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (12)))
(Vale_X64_Machine_s.OReg (Prims.of_int (8)))]
else
Vale_X64_Machine_s.Block
[Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (12)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3)))];
va_code_Fsqr ();
if win
then
Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))]
else Vale_X64_Machine_s.Block [];
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg Prims.int_one);
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (12)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15)))]
let (va_codegen_success_Fsqr_stdcall : Prims.bool -> Vale_X64_Decls.va_pbool)
=
fun win ->
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (12))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg Prims.int_one))
(Vale_X64_Decls.va_pbool_and
(if win
then
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg
(Prims.of_int (5)))
(Vale_X64_Machine_s.OReg
(Prims.of_int (2))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg
(Prims.of_int (4)))
(Vale_X64_Machine_s.OReg
(Prims.of_int (3))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg
(Prims.of_int (12)))
(Vale_X64_Machine_s.OReg
(Prims.of_int (8))))
(Vale_X64_Decls.va_ttrue ())))))
else
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (12)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3))))
(Vale_X64_Decls.va_ttrue ()))
(Vale_X64_Decls.va_pbool_and
(va_codegen_success_Fsqr ())
(Vale_X64_Decls.va_pbool_and
(if win
then
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg
(Prims.of_int (5))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg
(Prims.of_int (4))))
(Vale_X64_Decls.va_ttrue ()))
else Vale_X64_Decls.va_ttrue ())
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg Prims.int_one))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg
(Prims.of_int (12))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg
(Prims.of_int (14))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg
(Prims.of_int (13))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg
(Prims.of_int (15))))
(Vale_X64_Decls.va_ttrue ())))))))))))))
type ('vaub0, 'vaus0, 'win, 'tmpub, 'inAub, 'dstub) va_req_Fsqr_stdcall =
unit
type ('vaub0, 'vaus0, 'win, 'tmpub, 'inAub, 'dstub, 'vausM,
'vaufM) va_ens_Fsqr_stdcall = unit
let (va_qcode_Fsqr_stdcall :
Vale_X64_QuickCode.mod_t Prims.list ->
Prims.bool ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
(unit, unit) Vale_X64_QuickCode.quickCode)
=
fun va_mods ->
fun win ->
fun tmp_b ->
fun inA_b ->
fun dst_b ->
Vale_X64_QuickCodes.qblock
[Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (12)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg Prims.int_one);
Vale_X64_QuickCodes.if_code win
(Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (2)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (12)))
(Vale_X64_Machine_s.OReg (Prims.of_int (8)))])
(Vale_X64_Machine_s.Block
[Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (12)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3)))]);
va_code_Fsqr ();
Vale_X64_QuickCodes.if_code win
(Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))])
(Vale_X64_Machine_s.Block []);
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg Prims.int_one);
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (12)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15)))] va_mods ()
type ('win, 'tmpub, 'inAub, 'dstub, 'vaus0, 'vauk) va_wp_Fsqr_stdcall = unit
let (va_quick_Fsqr_stdcall :
Prims.bool ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 -> (unit, unit) Vale_X64_QuickCode.quickCode)
=
fun win ->
fun tmp_b ->
fun inA_b ->
fun dst_b ->
Vale_X64_QuickCode.QProc
((va_code_Fsqr_stdcall win),
[Vale_X64_QuickCode.Mod_stackTaint;
Vale_X64_QuickCode.Mod_stack;
Vale_X64_QuickCode.Mod_mem_layout;
Vale_X64_QuickCode.Mod_mem_heaplet Prims.int_zero;
Vale_X64_QuickCode.Mod_flags;
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (15))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (14))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (13))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (12))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (11))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (10))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (9))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (8))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (7))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (6))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (5))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (4))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (3))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (2))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, Prims.int_one));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, Prims.int_zero));
Vale_X64_QuickCode.Mod_mem], (), ())
let (va_code_Fsqr2 :
unit ->
(Vale_X64_Decls.ins, Vale_X64_Decls.ocmp) Vale_X64_Machine_s.precode)
=
fun uu___ ->
Vale_X64_Machine_s.Block
[Vale_X64_InsMem.va_code_CreateHeaplets ();
Vale_Curve25519_X64_FastSqr.va_code_Fast_sqr Prims.int_zero;
Vale_X64_InsBasic.va_code_Newline ();
Vale_Curve25519_X64_FastSqr.va_code_Fast_sqr (Prims.of_int (4));
Vale_X64_InsBasic.va_code_Newline ();
Vale_X64_InsBasic.va_code_Comment "Line up pointers";
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (12)));
Vale_X64_InsBasic.va_code_Newline ();
Vale_Curve25519_X64_FastHybrid.va_code_Carry_wide Prims.int_zero;
Vale_X64_InsBasic.va_code_Newline ();
Vale_Curve25519_X64_FastHybrid.va_code_Carry_wide (Prims.of_int (4));
Vale_X64_InsMem.va_code_DestroyHeaplets ()]
let (va_codegen_success_Fsqr2 : unit -> Vale_X64_Decls.va_pbool) =
fun uu___ ->
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsMem.va_codegen_success_CreateHeaplets ())
(Vale_X64_Decls.va_pbool_and
(Vale_Curve25519_X64_FastSqr.va_codegen_success_Fast_sqr
Prims.int_zero)
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Newline ())
(Vale_X64_Decls.va_pbool_and
(Vale_Curve25519_X64_FastSqr.va_codegen_success_Fast_sqr
(Prims.of_int (4)))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Newline ())
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Comment
"Line up pointers")
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (5))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (12))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Newline
())
(Vale_X64_Decls.va_pbool_and
(Vale_Curve25519_X64_FastHybrid.va_codegen_success_Carry_wide
Prims.int_zero)
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Newline
())
(Vale_X64_Decls.va_pbool_and
(Vale_Curve25519_X64_FastHybrid.va_codegen_success_Carry_wide
(Prims.of_int (4)))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsMem.va_codegen_success_DestroyHeaplets
()) (Vale_X64_Decls.va_ttrue ())))))))))))))
type ('vaub0, 'vaus0, 'tmpub, 'inAub, 'dstub) va_req_Fsqr2 = unit
type ('vaub0, 'vaus0, 'tmpub, 'inAub, 'dstub, 'vausM, 'vaufM) va_ens_Fsqr2 =
unit
let (va_qcode_Fsqr2 :
Vale_X64_QuickCode.mod_t Prims.list ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 -> (unit, unit) Vale_X64_QuickCode.quickCode)
=
fun va_mods ->
fun tmp_b ->
fun inA_b ->
fun dst_b ->
Vale_X64_QuickCodes.qblock
[Vale_X64_InsMem.va_code_CreateHeaplets ();
Vale_Curve25519_X64_FastSqr.va_code_Fast_sqr Prims.int_zero;
Vale_X64_InsBasic.va_code_Newline ();
Vale_Curve25519_X64_FastSqr.va_code_Fast_sqr (Prims.of_int (4));
Vale_X64_InsBasic.va_code_Newline ();
Vale_X64_InsBasic.va_code_Comment "Line up pointers";
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (12)));
Vale_X64_InsBasic.va_code_Newline ();
Vale_Curve25519_X64_FastHybrid.va_code_Carry_wide Prims.int_zero;
Vale_X64_InsBasic.va_code_Newline ();
Vale_Curve25519_X64_FastHybrid.va_code_Carry_wide
(Prims.of_int (4));
Vale_X64_InsMem.va_code_DestroyHeaplets ()] va_mods ()
type ('tmpub, 'inAub, 'dstub, 'vaus0, 'vauk) va_wp_Fsqr2 = unit
let (va_quick_Fsqr2 :
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 -> (unit, unit) Vale_X64_QuickCode.quickCode)
=
fun tmp_b ->
fun inA_b ->
fun dst_b ->
Vale_X64_QuickCode.QProc
((va_code_Fsqr2 ()),
[Vale_X64_QuickCode.Mod_mem_layout;
Vale_X64_QuickCode.Mod_mem_heaplet Prims.int_zero;
Vale_X64_QuickCode.Mod_flags;
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (15))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (14))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (13))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (12))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (11))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (10))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (9))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (8))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (4))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (5))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (3))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (2))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, Prims.int_one));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, Prims.int_zero));
Vale_X64_QuickCode.Mod_mem], (), ())
let (va_code_Fsqr2_stdcall :
Prims.bool ->
(Vale_X64_Decls.ins, Vale_X64_Decls.ocmp) Vale_X64_Machine_s.precode)
=
fun win ->
Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (12)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg Prims.int_one);
if win
then
Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (2)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (12)))
(Vale_X64_Machine_s.OReg (Prims.of_int (8)))]
else
Vale_X64_Machine_s.Block
[Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (12)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3)))];
va_code_Fsqr2 ();
if win
then
Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))]
else Vale_X64_Machine_s.Block [];
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg Prims.int_one);
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (12)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15)))]
let (va_codegen_success_Fsqr2_stdcall :
Prims.bool -> Vale_X64_Decls.va_pbool) =
fun win ->
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (12))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg Prims.int_one))
(Vale_X64_Decls.va_pbool_and
(if win
then
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg
(Prims.of_int (5)))
(Vale_X64_Machine_s.OReg
(Prims.of_int (2))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg
(Prims.of_int (4)))
(Vale_X64_Machine_s.OReg
(Prims.of_int (3))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg
(Prims.of_int (12)))
(Vale_X64_Machine_s.OReg
(Prims.of_int (8))))
(Vale_X64_Decls.va_ttrue ())))))
else
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsBasic.va_codegen_success_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (12)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3))))
(Vale_X64_Decls.va_ttrue ()))
(Vale_X64_Decls.va_pbool_and
(va_codegen_success_Fsqr2 ())
(Vale_X64_Decls.va_pbool_and
(if win
then
Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg
(Prims.of_int (5))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg
(Prims.of_int (4))))
(Vale_X64_Decls.va_ttrue ()))
else Vale_X64_Decls.va_ttrue ())
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg Prims.int_one))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg
(Prims.of_int (12))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg
(Prims.of_int (14))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg
(Prims.of_int (13))))
(Vale_X64_Decls.va_pbool_and
(Vale_X64_InsStack.va_codegen_success_Pop_Secret
(Vale_X64_Machine_s.OReg
(Prims.of_int (15))))
(Vale_X64_Decls.va_ttrue ())))))))))))))
type ('vaub0, 'vaus0, 'win, 'tmpub, 'inAub, 'dstub) va_req_Fsqr2_stdcall =
unit
type ('vaub0, 'vaus0, 'win, 'tmpub, 'inAub, 'dstub, 'vausM,
'vaufM) va_ens_Fsqr2_stdcall = unit
let (va_qcode_Fsqr2_stdcall :
Vale_X64_QuickCode.mod_t Prims.list ->
Prims.bool ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
(unit, unit) Vale_X64_QuickCode.quickCode)
=
fun va_mods ->
fun win ->
fun tmp_b ->
fun inA_b ->
fun dst_b ->
Vale_X64_QuickCodes.qblock
[Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (12)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg Prims.int_one);
Vale_X64_QuickCodes.if_code win
(Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4)));
Vale_X64_InsStack.va_code_Push_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (5)))
(Vale_X64_Machine_s.OReg (Prims.of_int (2)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3)));
Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (12)))
(Vale_X64_Machine_s.OReg (Prims.of_int (8)))])
(Vale_X64_Machine_s.Block
[Vale_X64_InsBasic.va_code_Mov64
(Vale_X64_Machine_s.OReg (Prims.of_int (12)))
(Vale_X64_Machine_s.OReg (Prims.of_int (3)))]);
va_code_Fsqr2 ();
Vale_X64_QuickCodes.if_code win
(Vale_X64_Machine_s.Block
[Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (5)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (4)))])
(Vale_X64_Machine_s.Block []);
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg Prims.int_one);
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (12)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (14)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (13)));
Vale_X64_InsStack.va_code_Pop_Secret
(Vale_X64_Machine_s.OReg (Prims.of_int (15)))] va_mods ()
type ('win, 'tmpub, 'inAub, 'dstub, 'vaus0, 'vauk) va_wp_Fsqr2_stdcall = unit
let (va_quick_Fsqr2_stdcall :
Prims.bool ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 ->
Vale_X64_Memory.buffer64 -> (unit, unit) Vale_X64_QuickCode.quickCode)
=
fun win ->
fun tmp_b ->
fun inA_b ->
fun dst_b ->
Vale_X64_QuickCode.QProc
((va_code_Fsqr2_stdcall win),
[Vale_X64_QuickCode.Mod_stackTaint;
Vale_X64_QuickCode.Mod_stack;
Vale_X64_QuickCode.Mod_mem_layout;
Vale_X64_QuickCode.Mod_mem_heaplet Prims.int_zero;
Vale_X64_QuickCode.Mod_flags;
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (15))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (14))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (13))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (12))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (11))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (10))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (9))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (8))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (7))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (6))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (5))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (4))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (3))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, (Prims.of_int (2))));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, Prims.int_one));
Vale_X64_QuickCode.Mod_reg
(Vale_X64_Machine_s.Reg (Prims.int_zero, Prims.int_zero));
Vale_X64_QuickCode.Mod_mem], (), ()) | |
c5954bb780cbb9a1bc13d1be4f18209b373a4c7c8fd5b5e99d3f2418d98a57b8 | RefactoringTools/HaRe | RecPred.hs | module RecPred where
property Univ = Gfp X . X
property P = [] \/ (Univ : P)
| null | https://raw.githubusercontent.com/RefactoringTools/HaRe/ef5dee64c38fb104e6e5676095946279fbce381c/old/tools/property/tests/RecPred.hs | haskell | module RecPred where
property Univ = Gfp X . X
property P = [] \/ (Univ : P)
| |
b872f73a4685e9d1acccbbd589cebf2ebc2911daf7ca095987486f8ff944f49e | nd/sicp | 5.20.scm |
free
|
V
Index 0 1 2 3 4 5
+----+----+----+----+----+----+--
the-cars | | n1 | p1 | p1 | | |
+----+----+----+----+----+----+--
the-cdrs | | n2 | p3 | e0 | | |
+----+----+----+----+----+----+--
| null | https://raw.githubusercontent.com/nd/sicp/d8587a0403d95af7c7bcf59b812f98c4f8550afd/ch05/5.20.scm | scheme |
free
|
V
Index 0 1 2 3 4 5
+----+----+----+----+----+----+--
the-cars | | n1 | p1 | p1 | | |
+----+----+----+----+----+----+--
the-cdrs | | n2 | p3 | e0 | | |
+----+----+----+----+----+----+--
| |
01ee31647d52c9c36afb08a70a20310fcdd8118185dab78aa3fa94c9fbc6a400 | heraldry/heraldicon | geometry_test.cljs | (ns spec.heraldry.ordinary.geometry-test
(:require
[cljs.test :refer-macros [are deftest]]
[spec.heraldicon.test-util :as tu]
[spec.heraldry.specs]))
(deftest valid-geometry
(are [form] (tu/valid? :heraldry.ordinary/geometry form)
{}
{:size-mode (tu/example :heraldry.ordinary.geometry/size-mode)}
{:size 5}
{:stretch 1.2}
{:width 12}
{:height 10}
{:thickness 20}
{:eccentricity 1.4}))
(deftest invalid-geometry
(are [form] (tu/invalid? :heraldry.ordinary/geometry form)
{:size-mode :wrong}
{:size :wrong}
{:stretch :wrong}
{:width :wrong}
{:height :wrong}
{:thickness :wrong}
{:eccentricity :wrong}))
| null | https://raw.githubusercontent.com/heraldry/heraldicon/19c9d10485bbc48e98ddee30092a246cccc986d2/test/spec/heraldry/ordinary/geometry_test.cljs | clojure | (ns spec.heraldry.ordinary.geometry-test
(:require
[cljs.test :refer-macros [are deftest]]
[spec.heraldicon.test-util :as tu]
[spec.heraldry.specs]))
(deftest valid-geometry
(are [form] (tu/valid? :heraldry.ordinary/geometry form)
{}
{:size-mode (tu/example :heraldry.ordinary.geometry/size-mode)}
{:size 5}
{:stretch 1.2}
{:width 12}
{:height 10}
{:thickness 20}
{:eccentricity 1.4}))
(deftest invalid-geometry
(are [form] (tu/invalid? :heraldry.ordinary/geometry form)
{:size-mode :wrong}
{:size :wrong}
{:stretch :wrong}
{:width :wrong}
{:height :wrong}
{:thickness :wrong}
{:eccentricity :wrong}))
| |
846088b7077a75e59087abfe61bd6eda86f2ddc34b8dbec3d69ebe16dd1d1341 | nextjournal/viewers | devdocs.cljs | (ns nextjournal.devdocs
"Views for devdocs:
* a collection view
* a document view
The registry -- holding document and navigation structure -- is a nested collection (a map) of
* `:devdocs` a sequence of clerk docs
* `:collections` a sequence of sub-collections."
(:require [clojure.string :as str]
[nextjournal.ui.components.icon :as icon]
[nextjournal.ui.components.navbar :as navbar]
[nextjournal.ui.components.localstorage :as ls]
[lambdaisland.deja-fu :as deja-fu]
[nextjournal.clerk.render :as render]
[reagent.core :as reagent]
[reitit.frontend.easy :as rfe]))
(goog-define contentsTitle "contents")
(goog-define logoImage "-logo-white.svg")
(defonce registry (reagent/atom []))
;; TODO: maybe compile into reitit router
(defn find-coll [reg path] (some #(and (str/starts-with? path (:path %)) %) (:items reg)))
(defn find-doc [{:keys [items]} path] (some #(and (= path (:path %)) %) items))
(defn lookup [registry path]
(or (find-doc registry path)
(loop [r registry]
(when-some [{:as coll :keys [items]} (find-coll r path)]
(or (find-doc coll path)
(when items (recur coll)))))))
#_(lookup @registry "README.md")
#_(lookup @registry "docs/reference.md")
#_(lookup @registry "docs/clerk")
#_(lookup @registry "docs/clerk/clerk.clj")
(defn scroll-to-fragment [el-id]
(when-let [el (js/document.getElementById el-id)]
(.scrollIntoView el)))
(declare collection-inner-view)
(defn item-view [{:as item :keys [title edn-doc path last-modified items]}]
[:div
(cond
edn-doc ;; doc
[:div.mb-2
[:a.hover:underline.font-bold
{:href (when edn-doc (rfe/href :devdocs/show {:path path})) :title path}
title]
(when last-modified
[:p.text-xs.text-gray-500.mt-1
(-> last-modified
deja-fu/local-date-time
(deja-fu/format "MMM dd yyyy, HH:mm"))])]
(seq items) ;; collection
[collection-inner-view item])])
(defn collection-inner-view [{:keys [title items level]}]
[:div
{:class (when-not title "pt-8")}
(when title
[:h3 {:style {:margin-top "2rem" :margin-bottom "1rem"}} title])
(into [:div]
(map (fn [item] [item-view item]))
items)])
(defn collection-view [collection]
[:div.overflow-y-auto.bg-white.dark:bg-gray-900.flex-auto.pb-12.font-sans
[:div.w-full.max-w-prose.px-8.mx-auto
[:h1.pt-8 "Devdocs"]
[collection-inner-view collection]]])
(defn devdoc-view [{:as doc :keys [edn-doc fragment]}]
[:div.overflow-y-auto.bg-white.dark:bg-gray-900.flex-auto.relative.font-sans
(cond-> {:style {:padding-top 45 :padding-bottom 70}}
fragment (assoc :ref #(scroll-to-fragment fragment)))
[:div.absolute.left-7.md:right-6.md:left-auto.top-0.p-3
[:div.text-gray-400.text-xs.font-mono.float-right (:path doc)]]
[render/inspect-presented (try
(render/read-string edn-doc)
(catch :default e
(js/console.error :clerk.sci-viewer/read-error e)
"Parse error..."))]])
(defn navbar-items [items]
(mapv (fn [{:as item :keys [items path]}]
(assoc item :expanded? true
:path (rfe/href :devdocs/show {:path path})
:items (navbar-items items))) items))
(def local-storage-key "devdocs-navbar")
(defn navbar-state [{:as _registry :keys [items] :navbar/keys [theme]}]
{:items (navbar-items items)
:theme (merge {:slide-over "bg-slate-100 font-sans border-r"} theme)
:width 220
:mobile-width 300
:local-storage-key local-storage-key
:open? (ls/get-item local-storage-key)})
(defn view [{:as data :keys [path] }]
(reagent/with-let [!state (reagent/atom (navbar-state @registry))]
[:div.flex.h-screen
[navbar/toggle-button !state
[:<>
[icon/menu {:size 20}]
[:span.uppercase.tracking-wider.ml-1.font-bold
{:class "text-[12px]"} "Nav"]]
{:class "z-10 fixed right-2 top-2 md:right-auto md:left-3 md:top-3 text-slate-400 font-sans text-xs hover:underline cursor-pointer flex items-center bg-white dark:bg-gray-900 py-1 px-3 md:p-0 rounded-full border md:border-0 border-slate-200 shadow md:shadow-none"}]
[navbar/panel !state [navbar/navbar !state]]
(if (or (nil? path) (contains? #{"" "/"} path))
[collection-view @registry]
(let [{:as node :keys [edn-doc]} (lookup @registry path)]
(when edn-doc ^{:key path} [devdoc-view node])))]))
(defn devdoc-commands
"For use with the commands/command-bar API"
([] (devdoc-commands @registry))
([{:keys [items]}]
(letfn [(item->command [{:keys [title path items]}]
(cond-> {:title title}
(not items) (assoc :dispatch [:router/push [:devdocs/show {:path path}]])
items (assoc :subcommands (mapv item->command items))))]
{:subcommands (-> [{:title "Index" :dispatch [:router/push [:devdocs/show {:path ""}]]}]
(into (map item->command) items))})))
(defn view-data
"Get the view and and path-params data from a reitit match. Pass this to the
view functions above."
[match]
(let [{:keys [data path-params]} match]
(merge data path-params)))
| null | https://raw.githubusercontent.com/nextjournal/viewers/35e4c1465b257032c54f629a7fc775cff64f8b8b/modules/devdocs/src/nextjournal/devdocs.cljs | clojure | TODO: maybe compile into reitit router
doc
collection | (ns nextjournal.devdocs
"Views for devdocs:
* a collection view
* a document view
The registry -- holding document and navigation structure -- is a nested collection (a map) of
* `:devdocs` a sequence of clerk docs
* `:collections` a sequence of sub-collections."
(:require [clojure.string :as str]
[nextjournal.ui.components.icon :as icon]
[nextjournal.ui.components.navbar :as navbar]
[nextjournal.ui.components.localstorage :as ls]
[lambdaisland.deja-fu :as deja-fu]
[nextjournal.clerk.render :as render]
[reagent.core :as reagent]
[reitit.frontend.easy :as rfe]))
(goog-define contentsTitle "contents")
(goog-define logoImage "-logo-white.svg")
(defonce registry (reagent/atom []))
(defn find-coll [reg path] (some #(and (str/starts-with? path (:path %)) %) (:items reg)))
(defn find-doc [{:keys [items]} path] (some #(and (= path (:path %)) %) items))
(defn lookup [registry path]
(or (find-doc registry path)
(loop [r registry]
(when-some [{:as coll :keys [items]} (find-coll r path)]
(or (find-doc coll path)
(when items (recur coll)))))))
#_(lookup @registry "README.md")
#_(lookup @registry "docs/reference.md")
#_(lookup @registry "docs/clerk")
#_(lookup @registry "docs/clerk/clerk.clj")
(defn scroll-to-fragment [el-id]
(when-let [el (js/document.getElementById el-id)]
(.scrollIntoView el)))
(declare collection-inner-view)
(defn item-view [{:as item :keys [title edn-doc path last-modified items]}]
[:div
(cond
[:div.mb-2
[:a.hover:underline.font-bold
{:href (when edn-doc (rfe/href :devdocs/show {:path path})) :title path}
title]
(when last-modified
[:p.text-xs.text-gray-500.mt-1
(-> last-modified
deja-fu/local-date-time
(deja-fu/format "MMM dd yyyy, HH:mm"))])]
[collection-inner-view item])])
(defn collection-inner-view [{:keys [title items level]}]
[:div
{:class (when-not title "pt-8")}
(when title
[:h3 {:style {:margin-top "2rem" :margin-bottom "1rem"}} title])
(into [:div]
(map (fn [item] [item-view item]))
items)])
(defn collection-view [collection]
[:div.overflow-y-auto.bg-white.dark:bg-gray-900.flex-auto.pb-12.font-sans
[:div.w-full.max-w-prose.px-8.mx-auto
[:h1.pt-8 "Devdocs"]
[collection-inner-view collection]]])
(defn devdoc-view [{:as doc :keys [edn-doc fragment]}]
[:div.overflow-y-auto.bg-white.dark:bg-gray-900.flex-auto.relative.font-sans
(cond-> {:style {:padding-top 45 :padding-bottom 70}}
fragment (assoc :ref #(scroll-to-fragment fragment)))
[:div.absolute.left-7.md:right-6.md:left-auto.top-0.p-3
[:div.text-gray-400.text-xs.font-mono.float-right (:path doc)]]
[render/inspect-presented (try
(render/read-string edn-doc)
(catch :default e
(js/console.error :clerk.sci-viewer/read-error e)
"Parse error..."))]])
(defn navbar-items [items]
(mapv (fn [{:as item :keys [items path]}]
(assoc item :expanded? true
:path (rfe/href :devdocs/show {:path path})
:items (navbar-items items))) items))
(def local-storage-key "devdocs-navbar")
(defn navbar-state [{:as _registry :keys [items] :navbar/keys [theme]}]
{:items (navbar-items items)
:theme (merge {:slide-over "bg-slate-100 font-sans border-r"} theme)
:width 220
:mobile-width 300
:local-storage-key local-storage-key
:open? (ls/get-item local-storage-key)})
(defn view [{:as data :keys [path] }]
(reagent/with-let [!state (reagent/atom (navbar-state @registry))]
[:div.flex.h-screen
[navbar/toggle-button !state
[:<>
[icon/menu {:size 20}]
[:span.uppercase.tracking-wider.ml-1.font-bold
{:class "text-[12px]"} "Nav"]]
{:class "z-10 fixed right-2 top-2 md:right-auto md:left-3 md:top-3 text-slate-400 font-sans text-xs hover:underline cursor-pointer flex items-center bg-white dark:bg-gray-900 py-1 px-3 md:p-0 rounded-full border md:border-0 border-slate-200 shadow md:shadow-none"}]
[navbar/panel !state [navbar/navbar !state]]
(if (or (nil? path) (contains? #{"" "/"} path))
[collection-view @registry]
(let [{:as node :keys [edn-doc]} (lookup @registry path)]
(when edn-doc ^{:key path} [devdoc-view node])))]))
(defn devdoc-commands
"For use with the commands/command-bar API"
([] (devdoc-commands @registry))
([{:keys [items]}]
(letfn [(item->command [{:keys [title path items]}]
(cond-> {:title title}
(not items) (assoc :dispatch [:router/push [:devdocs/show {:path path}]])
items (assoc :subcommands (mapv item->command items))))]
{:subcommands (-> [{:title "Index" :dispatch [:router/push [:devdocs/show {:path ""}]]}]
(into (map item->command) items))})))
(defn view-data
"Get the view and and path-params data from a reitit match. Pass this to the
view functions above."
[match]
(let [{:keys [data path-params]} match]
(merge data path-params)))
|
c139c8e3f65b077537d246faba5f27ceaf633af2ddd6946a1e6e530a7afc7b17 | MagnusS/okra | cat.ml |
* Copyright ( c ) 2021 - 22 < >
* Copyright ( c ) 2021 < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2021-22 Magnus Skjegstad <>
* Copyright (c) 2021 Thomas Gazagnaire <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
type t = {
show_time : bool;
show_time_calc : bool;
show_engineers : bool;
ignore_sections : string list;
include_sections : string list;
include_teams : string list;
include_categories : string list;
include_reports : string list;
filter : Okra.Report.filter;
files : string list;
in_place : bool;
output : string option;
okr_db : string option;
append_to : string option;
}
open Cmdliner
let show_time_term =
let info =
Arg.info [ "show-time" ] ~doc:"Include engineering time in output"
in
Arg.value (Arg.opt Arg.bool true info)
let show_time_calc_term =
let info =
Arg.info [ "show-time-calc" ]
~doc:
"Include intermediate time calculations in output, showing each time \
entry found with a sum at the end. This is useful for debugging when \
aggregating reports for multiple weeks."
in
Arg.value (Arg.opt Arg.bool false info)
let show_engineers_term =
let info =
Arg.info [ "show-engineers" ] ~doc:"Include a list of engineers per KR"
in
Arg.value (Arg.opt Arg.bool true info)
let engineer_term =
let info =
Arg.info [ "engineer"; "e" ]
~doc:
"Aggregate engineer reports. This is an alias for \
--include-sections=\"last week\", --ignore-sections=\"\""
in
Arg.value (Arg.flag info)
let team_term =
let info =
Arg.info [ "team"; "t" ]
~doc:
"Aggregate team reports. This is an alias for --include-sections=\"\", \
--ignore-sections=\"OKR updates\""
in
Arg.value (Arg.flag info)
let okr_db_term =
let info =
Arg.info [ "okr-db" ]
~doc:
"Replace KR titles, objectives and projects with information from a \
CSV. Requires header with columns id,title,objective,project."
in
Arg.value (Arg.opt (Arg.some Arg.file) None info)
let append_to =
let info =
Arg.info [ "append-to" ]
~doc:
"Take the reports passed as positional arguments and merge them into \
the already-generated, aggregate report."
in
Arg.value (Arg.opt (Arg.some Arg.file) None info)
let read_file f =
let ic = open_in f in
let s = really_input_string ic (in_channel_length ic) in
close_in ic;
s
let run conf =
let okr_db =
match conf.okr_db with
| None -> None
| Some f -> Some (Okra.Masterdb.load_csv f)
in
let md =
match conf.files with
| [] -> Omd.of_channel stdin
| fs ->
let s = String.concat "\n" (List.map read_file fs) in
Omd.of_string s
in
let oc =
match conf.output with
| Some f -> open_out f
| None -> (
if not conf.in_place then stdout
else
match conf.files with
| [] -> Fmt.invalid_arg "[-i] needs at list an input file."
| [ f ] -> open_out f
| _ -> Fmt.invalid_arg "[-i] needs at most a file.")
in
let existing_report =
match conf.append_to with
| None -> None
| Some file ->
let content = read_file file in
let exisiting =
Okra.Report.of_markdown ?okr_db (Omd.of_string content)
in
Some exisiting
in
let okrs =
try
Okra.Report.of_markdown ?existing_report
~ignore_sections:conf.ignore_sections
~include_sections:conf.include_sections ?okr_db md
with e ->
Logs.err (fun l ->
l
"An error ocurred while parsing the input file(s). Run `lint` for \
more information.\n\n\
%s\n"
(Printexc.to_string e));
exit 1
in
let filters =
match okr_db with
| None -> conf.filter
| Some okr_db ->
let additional_krs =
Okra.Masterdb.find_krs_for_teams okr_db conf.include_teams
@ Okra.Masterdb.find_krs_for_categories okr_db conf.include_categories
@ Okra.Masterdb.find_krs_for_reports okr_db conf.include_reports
in
let kr_ids =
List.map
(fun f ->
Okra.Report.Filter.kr_of_string (f : Okra.Masterdb.elt_t).id)
additional_krs
in
let extra_filter = Okra.Report.Filter.v ?include_krs:(Some kr_ids) () in
Okra.Report.Filter.union conf.filter extra_filter
in
let okrs = Okra.Report.filter filters okrs in
let pp =
Okra.Report.pp ~show_time:conf.show_time ~show_time_calc:conf.show_time_calc
~show_engineers:conf.show_engineers
in
Okra.Printer.to_channel oc pp okrs
let conf_term =
let open Let_syntax_cmdliner in
let+ show_time = show_time_term
and+ show_time_calc = show_time_calc_term
and+ show_engineers = show_engineers_term
and+ okr_db = okr_db_term
and+ append_to = append_to
and+ filter = Common.filter
and+ ignore_sections = Common.ignore_sections
and+ include_sections = Common.include_sections
and+ include_categories = Common.include_categories
and+ include_teams = Common.include_teams
and+ include_reports = Common.include_reports
and+ files = Common.files
and+ output = Common.output
and+ in_place = Common.in_place
and+ conf = Common.conf
and+ () = Common.setup () in
let okr_db =
match (okr_db, Conf.okr_db conf) with Some x, _ -> Some x | None, x -> x
in
{
show_time;
show_time_calc;
show_engineers;
ignore_sections;
include_sections;
include_categories;
include_teams;
include_reports;
filter;
okr_db;
files;
output;
in_place;
append_to;
}
let term =
let open Let_syntax_cmdliner in
let+ conf = conf_term and+ team = team_term and+ engineer = engineer_term in
let conf =
if engineer then
{ conf with ignore_sections = []; include_sections = [ "Last week" ] }
else if team then
{ conf with ignore_sections = [ "OKR Updates" ]; include_sections = [] }
else conf
in
run conf
let cmd =
let info =
Cmd.info "cat" ~doc:"parse and concatenate reports"
~man:
[
`S Manpage.s_description;
`P
"Parses one or more OKR reports and outputs a report aggregated \
per KR. See below for options for modifying the output format.";
]
in
Cmd.v info term
| null | https://raw.githubusercontent.com/MagnusS/okra/13f473baae1e8490887bde156f7bb238ef7c645e/bin/cat.ml | ocaml |
* Copyright ( c ) 2021 - 22 < >
* Copyright ( c ) 2021 < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2021-22 Magnus Skjegstad <>
* Copyright (c) 2021 Thomas Gazagnaire <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
type t = {
show_time : bool;
show_time_calc : bool;
show_engineers : bool;
ignore_sections : string list;
include_sections : string list;
include_teams : string list;
include_categories : string list;
include_reports : string list;
filter : Okra.Report.filter;
files : string list;
in_place : bool;
output : string option;
okr_db : string option;
append_to : string option;
}
open Cmdliner
let show_time_term =
let info =
Arg.info [ "show-time" ] ~doc:"Include engineering time in output"
in
Arg.value (Arg.opt Arg.bool true info)
let show_time_calc_term =
let info =
Arg.info [ "show-time-calc" ]
~doc:
"Include intermediate time calculations in output, showing each time \
entry found with a sum at the end. This is useful for debugging when \
aggregating reports for multiple weeks."
in
Arg.value (Arg.opt Arg.bool false info)
let show_engineers_term =
let info =
Arg.info [ "show-engineers" ] ~doc:"Include a list of engineers per KR"
in
Arg.value (Arg.opt Arg.bool true info)
let engineer_term =
let info =
Arg.info [ "engineer"; "e" ]
~doc:
"Aggregate engineer reports. This is an alias for \
--include-sections=\"last week\", --ignore-sections=\"\""
in
Arg.value (Arg.flag info)
let team_term =
let info =
Arg.info [ "team"; "t" ]
~doc:
"Aggregate team reports. This is an alias for --include-sections=\"\", \
--ignore-sections=\"OKR updates\""
in
Arg.value (Arg.flag info)
let okr_db_term =
let info =
Arg.info [ "okr-db" ]
~doc:
"Replace KR titles, objectives and projects with information from a \
CSV. Requires header with columns id,title,objective,project."
in
Arg.value (Arg.opt (Arg.some Arg.file) None info)
let append_to =
let info =
Arg.info [ "append-to" ]
~doc:
"Take the reports passed as positional arguments and merge them into \
the already-generated, aggregate report."
in
Arg.value (Arg.opt (Arg.some Arg.file) None info)
let read_file f =
let ic = open_in f in
let s = really_input_string ic (in_channel_length ic) in
close_in ic;
s
let run conf =
let okr_db =
match conf.okr_db with
| None -> None
| Some f -> Some (Okra.Masterdb.load_csv f)
in
let md =
match conf.files with
| [] -> Omd.of_channel stdin
| fs ->
let s = String.concat "\n" (List.map read_file fs) in
Omd.of_string s
in
let oc =
match conf.output with
| Some f -> open_out f
| None -> (
if not conf.in_place then stdout
else
match conf.files with
| [] -> Fmt.invalid_arg "[-i] needs at list an input file."
| [ f ] -> open_out f
| _ -> Fmt.invalid_arg "[-i] needs at most a file.")
in
let existing_report =
match conf.append_to with
| None -> None
| Some file ->
let content = read_file file in
let exisiting =
Okra.Report.of_markdown ?okr_db (Omd.of_string content)
in
Some exisiting
in
let okrs =
try
Okra.Report.of_markdown ?existing_report
~ignore_sections:conf.ignore_sections
~include_sections:conf.include_sections ?okr_db md
with e ->
Logs.err (fun l ->
l
"An error ocurred while parsing the input file(s). Run `lint` for \
more information.\n\n\
%s\n"
(Printexc.to_string e));
exit 1
in
let filters =
match okr_db with
| None -> conf.filter
| Some okr_db ->
let additional_krs =
Okra.Masterdb.find_krs_for_teams okr_db conf.include_teams
@ Okra.Masterdb.find_krs_for_categories okr_db conf.include_categories
@ Okra.Masterdb.find_krs_for_reports okr_db conf.include_reports
in
let kr_ids =
List.map
(fun f ->
Okra.Report.Filter.kr_of_string (f : Okra.Masterdb.elt_t).id)
additional_krs
in
let extra_filter = Okra.Report.Filter.v ?include_krs:(Some kr_ids) () in
Okra.Report.Filter.union conf.filter extra_filter
in
let okrs = Okra.Report.filter filters okrs in
let pp =
Okra.Report.pp ~show_time:conf.show_time ~show_time_calc:conf.show_time_calc
~show_engineers:conf.show_engineers
in
Okra.Printer.to_channel oc pp okrs
let conf_term =
let open Let_syntax_cmdliner in
let+ show_time = show_time_term
and+ show_time_calc = show_time_calc_term
and+ show_engineers = show_engineers_term
and+ okr_db = okr_db_term
and+ append_to = append_to
and+ filter = Common.filter
and+ ignore_sections = Common.ignore_sections
and+ include_sections = Common.include_sections
and+ include_categories = Common.include_categories
and+ include_teams = Common.include_teams
and+ include_reports = Common.include_reports
and+ files = Common.files
and+ output = Common.output
and+ in_place = Common.in_place
and+ conf = Common.conf
and+ () = Common.setup () in
let okr_db =
match (okr_db, Conf.okr_db conf) with Some x, _ -> Some x | None, x -> x
in
{
show_time;
show_time_calc;
show_engineers;
ignore_sections;
include_sections;
include_categories;
include_teams;
include_reports;
filter;
okr_db;
files;
output;
in_place;
append_to;
}
let term =
let open Let_syntax_cmdliner in
let+ conf = conf_term and+ team = team_term and+ engineer = engineer_term in
let conf =
if engineer then
{ conf with ignore_sections = []; include_sections = [ "Last week" ] }
else if team then
{ conf with ignore_sections = [ "OKR Updates" ]; include_sections = [] }
else conf
in
run conf
let cmd =
let info =
Cmd.info "cat" ~doc:"parse and concatenate reports"
~man:
[
`S Manpage.s_description;
`P
"Parses one or more OKR reports and outputs a report aggregated \
per KR. See below for options for modifying the output format.";
]
in
Cmd.v info term
| |
e5850d683eeb217057feab8b989618e6c87126a60f8d8171eda9ba0b3d8f0db1 | DeepSec-prover/deepsec | statistic.ml | (**************************************************************************)
(* *)
DeepSec
(* *)
, project PESTO ,
, project PESTO ,
, project PESTO ,
(* *)
Copyright ( C ) INRIA 2017 - 2020
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU General Public License version 3.0 as described in the
(* file LICENSE *)
(* *)
(**************************************************************************)
(*************
Statistic
**************)
let initial_time = (Unix.times ()).Unix.tms_utime
type stat =
{
mutable recorded: bool;
mutable time : float;
mutable call : int;
mutable time_last_restarted : float;
name : string;
}
let current_recording = ref []
let record_tail =
if Config.record_time
then
(fun ref_t f_cont f_next ->
ref_t.recorded <- true;
let t0 = (Unix.times ()).Unix.tms_utime in
(* We stop the current recording *)
begin match !current_recording with
| [] -> ()
| ref_t'::_ -> ref_t'.time <- ref_t'.time +. t0 -. ref_t'.time_last_restarted
end;
(* We add the new recording time *)
ref_t.time_last_restarted <- t0;
ref_t.call <- ref_t.call + 1;
current_recording := ref_t::!current_recording;
f_cont (fun () ->
(* We stop the clock *)
let t1 = (Unix.times ()).Unix.tms_utime in
ref_t.time <- ref_t.time +. t1 -. ref_t.time_last_restarted;
begin match !current_recording with
| _::((ref_t'::_) as q) ->
ref_t'.time_last_restarted <- t1;
current_recording := q
| _::q -> current_recording := q
| _ -> Config.internal_error "[statistic.ml >> record_time] There should be at least one recorder."
end;
f_next ()
)
)
else (fun _ f_cont f_next -> f_cont f_next)
let record_notail =
if Config.record_time
then
(fun ref_t f_cont ->
ref_t.recorded <- true;
let t0 = (Unix.times ()).Unix.tms_utime in
(* We stop the current recording *)
begin match !current_recording with
| [] -> ()
| ref_t'::_ -> ref_t'.time <- ref_t'.time +. t0 -. ref_t'.time_last_restarted
end;
(* We add the new recording time *)
ref_t.time_last_restarted <- t0;
ref_t.call <- ref_t.call + 1;
current_recording := ref_t::!current_recording;
let res = f_cont () in
(* We stop the clock *)
let t1 = (Unix.times ()).Unix.tms_utime in
ref_t.time <- ref_t.time +. t1 -. ref_t.time_last_restarted;
begin match !current_recording with
| _::((ref_t'::_) as q) ->
ref_t'.time_last_restarted <- t1;
current_recording := q
| _::q -> current_recording := q
| _ -> Config.internal_error "[statistic.ml >> record_time] There should be at least one recorder."
end;
res
)
else (fun _ f_cont -> f_cont ())
(******* The function recorded ******)
let recorder_list = ref []
let create name =
let r = { name = name; time = 0.; call = 0; recorded = false; time_last_restarted = 0. } in
recorder_list := r :: ! recorder_list;
r
let reset =
if Config.record_time
then
(fun () ->
List.iter (fun r -> r.time <- 0.; r.call <- 0; r.recorded <- false; r.time_last_restarted <- 0. ) !recorder_list;
current_recording := []
)
else (fun _ -> ())
let time_sat = create "Sat"
let time_non_deducible_term = create "Non Deducible Term"
let time_sat_disequation = create "Sat Disequation"
let time_split_data_constructor = create "Split Data Constructor"
let time_normalisation_deduction_consequence = create "Normalisation Deduction Consequence"
let time_rewrite = create "Rewrite"
let time_equality_constructor = create "Equality_constructor"
let time_next_transition = create "Next Transition"
let time_prepare = create "Prepare"
let time_other = create "Other"
let display_statistic () =
Display.display_list (fun r ->
Printf.sprintf "%s: %fs (%d calls)" r.name r.time r.call
) ", " !recorder_list
| null | https://raw.githubusercontent.com/DeepSec-prover/deepsec/8ddc45ec79de5ec49810302ea7da32d3dc9f46e4/Source/core_library/statistic.ml | ocaml | ************************************************************************
All rights reserved. This file is distributed under the terms of
file LICENSE
************************************************************************
************
Statistic
*************
We stop the current recording
We add the new recording time
We stop the clock
We stop the current recording
We add the new recording time
We stop the clock
****** The function recorded ***** | DeepSec
, project PESTO ,
, project PESTO ,
, project PESTO ,
Copyright ( C ) INRIA 2017 - 2020
the GNU General Public License version 3.0 as described in the
let initial_time = (Unix.times ()).Unix.tms_utime
type stat =
{
mutable recorded: bool;
mutable time : float;
mutable call : int;
mutable time_last_restarted : float;
name : string;
}
let current_recording = ref []
let record_tail =
if Config.record_time
then
(fun ref_t f_cont f_next ->
ref_t.recorded <- true;
let t0 = (Unix.times ()).Unix.tms_utime in
begin match !current_recording with
| [] -> ()
| ref_t'::_ -> ref_t'.time <- ref_t'.time +. t0 -. ref_t'.time_last_restarted
end;
ref_t.time_last_restarted <- t0;
ref_t.call <- ref_t.call + 1;
current_recording := ref_t::!current_recording;
f_cont (fun () ->
let t1 = (Unix.times ()).Unix.tms_utime in
ref_t.time <- ref_t.time +. t1 -. ref_t.time_last_restarted;
begin match !current_recording with
| _::((ref_t'::_) as q) ->
ref_t'.time_last_restarted <- t1;
current_recording := q
| _::q -> current_recording := q
| _ -> Config.internal_error "[statistic.ml >> record_time] There should be at least one recorder."
end;
f_next ()
)
)
else (fun _ f_cont f_next -> f_cont f_next)
let record_notail =
if Config.record_time
then
(fun ref_t f_cont ->
ref_t.recorded <- true;
let t0 = (Unix.times ()).Unix.tms_utime in
begin match !current_recording with
| [] -> ()
| ref_t'::_ -> ref_t'.time <- ref_t'.time +. t0 -. ref_t'.time_last_restarted
end;
ref_t.time_last_restarted <- t0;
ref_t.call <- ref_t.call + 1;
current_recording := ref_t::!current_recording;
let res = f_cont () in
let t1 = (Unix.times ()).Unix.tms_utime in
ref_t.time <- ref_t.time +. t1 -. ref_t.time_last_restarted;
begin match !current_recording with
| _::((ref_t'::_) as q) ->
ref_t'.time_last_restarted <- t1;
current_recording := q
| _::q -> current_recording := q
| _ -> Config.internal_error "[statistic.ml >> record_time] There should be at least one recorder."
end;
res
)
else (fun _ f_cont -> f_cont ())
let recorder_list = ref []
let create name =
let r = { name = name; time = 0.; call = 0; recorded = false; time_last_restarted = 0. } in
recorder_list := r :: ! recorder_list;
r
let reset =
if Config.record_time
then
(fun () ->
List.iter (fun r -> r.time <- 0.; r.call <- 0; r.recorded <- false; r.time_last_restarted <- 0. ) !recorder_list;
current_recording := []
)
else (fun _ -> ())
let time_sat = create "Sat"
let time_non_deducible_term = create "Non Deducible Term"
let time_sat_disequation = create "Sat Disequation"
let time_split_data_constructor = create "Split Data Constructor"
let time_normalisation_deduction_consequence = create "Normalisation Deduction Consequence"
let time_rewrite = create "Rewrite"
let time_equality_constructor = create "Equality_constructor"
let time_next_transition = create "Next Transition"
let time_prepare = create "Prepare"
let time_other = create "Other"
let display_statistic () =
Display.display_list (fun r ->
Printf.sprintf "%s: %fs (%d calls)" r.name r.time r.call
) ", " !recorder_list
|
5e87af0af336ef9842279cd53d20970158c46442f650063d55e6c40b8d56b53b | dnaeon/cl-migratum | 20220327224455-lisp_code_migration.down.lisp | i d : 20220327224455
;; direction: DOWN
;; description: lisp_code_migration
(:system :cl-migratum.test :package :cl-migratum.test.20220327224455 :handler :down)
| null | https://raw.githubusercontent.com/dnaeon/cl-migratum/b28031405ca5a43bee85af5da6ef761ceb951d0d/t/migrations/20220327224455-lisp_code_migration.down.lisp | lisp | direction: DOWN
description: lisp_code_migration | i d : 20220327224455
(:system :cl-migratum.test :package :cl-migratum.test.20220327224455 :handler :down)
|
30108d093b145021cca0270ad878f261ed8c501c5dea8e23b580405bed8de727 | jyh/metaprl | shell_tex.ml |
* Imperative interface to the TeX output file .
*
* ----------------------------------------------------------------
*
* Copyright ( C ) 2000 , Caltech
*
* This program is free software ; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation ; either version 2
* of the License , or ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU General Public License for more details .
*
* You should have received a copy of the GNU General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 675 Mass Ave , Cambridge , , USA .
*
* Author :
*
* Imperative interface to the TeX output file.
*
* ----------------------------------------------------------------
*
* Copyright (C) 2000 Jason Hickey, Caltech
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Author: Jason Hickey
*
*)
(*
* TeX prologue.
*)
let tex_prologue = "% -*- Mode: fundamental -*-
\\documentclass{report}
%
% Ludica-Bright fonts
%
%\\usepackage{lucidbry}
%\\usepackage[ansinew]{texnansi}
%\\usepackage[LY1]{fontenc}
%
% Otherwise, you need to include amssymb to get the math chars.
%
\\usepackage{amssymb}
%
% Hyperlinks
%
\\usepackage[dvipdfm]{hyperref}
%
% Definitions.
%
\\input{metaprl}
\\widepage
\\makeindex
\\begin{document}
\\sloppy
"
let tex_epilogue = "
\\end{document}
"
(*
* The output file is an out_channel option.
*)
let output = ref None
(*
* Open an output file.
* Return the output if already defined.
*)
let open_file () =
match !output with
Some out ->
out
| None ->
let out = open_out "output.tex" in
output_string out tex_prologue;
out
(*
* Close the output file.
*)
let close_file out =
match !output with
Some out ->
flush out
| None ->
output_string out tex_epilogue;
close_out out
(*
* Set the output file.
*)
let set_file name =
let _ =
match !output with
Some out ->
close_out out;
output := None
| None ->
()
in
let name =
if Filename.check_suffix name ".tex" then
Filename.chop_suffix name ".tex"
else
name
in
let outer_name = name ^ ".tex" in
let body_name = name ^ "-body.tex" in
let out = open_out outer_name in
let _ =
Printf.fprintf out "%s\n\\input{%s}\n%s" tex_prologue (Filename.basename body_name) tex_epilogue;
close_out out
in
let out = open_out body_name in
output_string out "% -*- Mode: fundamental -*-\n";
flush out;
output := Some out;
close_file out
(*
* -*-
* Local Variables:
* Caml-master: "compile"
* End:
* -*-
*)
| null | https://raw.githubusercontent.com/jyh/metaprl/51ba0bbbf409ecb7f96f5abbeb91902fdec47a19/support/shell/shell_tex.ml | ocaml |
* TeX prologue.
* The output file is an out_channel option.
* Open an output file.
* Return the output if already defined.
* Close the output file.
* Set the output file.
* -*-
* Local Variables:
* Caml-master: "compile"
* End:
* -*-
|
* Imperative interface to the TeX output file .
*
* ----------------------------------------------------------------
*
* Copyright ( C ) 2000 , Caltech
*
* This program is free software ; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation ; either version 2
* of the License , or ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU General Public License for more details .
*
* You should have received a copy of the GNU General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 675 Mass Ave , Cambridge , , USA .
*
* Author :
*
* Imperative interface to the TeX output file.
*
* ----------------------------------------------------------------
*
* Copyright (C) 2000 Jason Hickey, Caltech
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Author: Jason Hickey
*
*)
let tex_prologue = "% -*- Mode: fundamental -*-
\\documentclass{report}
%
% Ludica-Bright fonts
%
%\\usepackage{lucidbry}
%\\usepackage[ansinew]{texnansi}
%\\usepackage[LY1]{fontenc}
%
% Otherwise, you need to include amssymb to get the math chars.
%
\\usepackage{amssymb}
%
% Hyperlinks
%
\\usepackage[dvipdfm]{hyperref}
%
% Definitions.
%
\\input{metaprl}
\\widepage
\\makeindex
\\begin{document}
\\sloppy
"
let tex_epilogue = "
\\end{document}
"
let output = ref None
let open_file () =
match !output with
Some out ->
out
| None ->
let out = open_out "output.tex" in
output_string out tex_prologue;
out
let close_file out =
match !output with
Some out ->
flush out
| None ->
output_string out tex_epilogue;
close_out out
let set_file name =
let _ =
match !output with
Some out ->
close_out out;
output := None
| None ->
()
in
let name =
if Filename.check_suffix name ".tex" then
Filename.chop_suffix name ".tex"
else
name
in
let outer_name = name ^ ".tex" in
let body_name = name ^ "-body.tex" in
let out = open_out outer_name in
let _ =
Printf.fprintf out "%s\n\\input{%s}\n%s" tex_prologue (Filename.basename body_name) tex_epilogue;
close_out out
in
let out = open_out body_name in
output_string out "% -*- Mode: fundamental -*-\n";
flush out;
output := Some out;
close_file out
|
9ca9ef8f6e27606dde0f10da63b0c46244e3adb0b2a83984323ce789e1ebcd27 | skanev/playground | 04.scm | EOPL exercise B.04
;
; Extend the language and interpreter of the preceding exercise to include
; variables. This new interpreter will require an environment parameter.
(define scanner-spec
'((white-sp (whitespace) skip)
(identifier (letter (arbno (or letter digit))) symbol)
(additive-op ((or "+" "-")) symbol)
(multiplicative-op ((or "*" "/")) symbol)
(number (digit (arbno digit)) number)))
(define grammar
'((expression
(term (arbno additive-op term))
op)
(term
(factor (arbno multiplicative-op factor))
op)
(factor
(number)
number)
(factor
(identifier)
ref)
(factor
("(" expression ")")
factor)))
(define-datatype ast ast?
(op
(first-operand ast?)
(operators (list-of symbol?))
(rest-operands (list-of ast?)))
(factor
(value ast?))
(ref
(name symbol?))
(number
(value integer?)))
(define scan&parse
(sllgen:make-string-parser scanner-spec grammar))
(define (eval* tree env)
(cases ast tree
(op (first ops rest)
(apply-ops (eval* first env)
ops
(map (curryr eval* env) rest)))
(number (val)
val)
(ref (var)
(lookup var env))
(factor (expr)
(eval* expr env))))
(define (apply-ops first ops rest)
(if (null? ops)
first
(apply-ops ((eval (car ops)) first (car rest))
(cdr ops)
(cdr rest))))
(define (lookup var env)
(cond ((null? env)
(eopl:error 'lookup "Variable not found: ~s" var))
((eqv? var (caar env))
(cadar env))
(else
(lookup var (cdr env)))))
(define (value-of code env)
(eval* (scan&parse code) env))
| null | https://raw.githubusercontent.com/skanev/playground/d88e53a7f277b35041c2f709771a0b96f993b310/scheme/eopl/B/04.scm | scheme |
Extend the language and interpreter of the preceding exercise to include
variables. This new interpreter will require an environment parameter. | EOPL exercise B.04
(define scanner-spec
'((white-sp (whitespace) skip)
(identifier (letter (arbno (or letter digit))) symbol)
(additive-op ((or "+" "-")) symbol)
(multiplicative-op ((or "*" "/")) symbol)
(number (digit (arbno digit)) number)))
(define grammar
'((expression
(term (arbno additive-op term))
op)
(term
(factor (arbno multiplicative-op factor))
op)
(factor
(number)
number)
(factor
(identifier)
ref)
(factor
("(" expression ")")
factor)))
(define-datatype ast ast?
(op
(first-operand ast?)
(operators (list-of symbol?))
(rest-operands (list-of ast?)))
(factor
(value ast?))
(ref
(name symbol?))
(number
(value integer?)))
(define scan&parse
(sllgen:make-string-parser scanner-spec grammar))
(define (eval* tree env)
(cases ast tree
(op (first ops rest)
(apply-ops (eval* first env)
ops
(map (curryr eval* env) rest)))
(number (val)
val)
(ref (var)
(lookup var env))
(factor (expr)
(eval* expr env))))
(define (apply-ops first ops rest)
(if (null? ops)
first
(apply-ops ((eval (car ops)) first (car rest))
(cdr ops)
(cdr rest))))
(define (lookup var env)
(cond ((null? env)
(eopl:error 'lookup "Variable not found: ~s" var))
((eqv? var (caar env))
(cadar env))
(else
(lookup var (cdr env)))))
(define (value-of code env)
(eval* (scan&parse code) env))
|
59f938d641ee63bca1a310c45e46588725a0073bbb07804d19b38c70a5bb1a7c | clojure/algo.generic | test_functor.clj | ;; Test routines for clojure.algo.generic.collection
Copyright ( c ) , 2011 . 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 clojure.algo.generic.test-functor
(:use [clojure.test :only (deftest is are run-tests)])
(:require [clojure.algo.generic.functor :as gf])
(:require [clojure.algo.generic.collection :as gc]))
Test implementations for CLojure 's built - in collections
(deftest builtin-collections
(are [a b] (= a b)
(gf/fmap inc (list 1 2 3)) (list 2 3 4)
(gf/fmap inc [1 2 3]) [2 3 4]
(gf/fmap inc {:A 1 :B 2 :C 3}) {:A 2 :B 3 :C 4}
(gf/fmap inc #{1 2 3}) #{2 3 4}
(gf/fmap inc (lazy-seq [1 2 3])) (list 2 3 4)
(gf/fmap inc (seq [1 2 3])) (list 2 3 4)
(gf/fmap inc (range 3)) (list 1 2 3)
(gf/fmap inc nil) nil))
; Test implementation for functions
(deftest functions
(let [f (fn [x] (+ x x))
x [-1 0 1 2]]
(is (= (map (gf/fmap - f) x)
(map (comp - f) x)))))
; Futures and delays
(deftest future-test
(is (= 2 @(gf/fmap inc (future 1)))))
(deftest delay-test
(is (= 2 @(gf/fmap inc (delay 1)))))
; Define a multiset class. The representation is a map from values to counts.
(defrecord multiset [map])
(defn mset
[& elements]
(gc/into (new multiset {}) elements))
; Implement the collection multimethods.
(defmethod gc/conj multiset
([ms x]
(let [msmap (:map ms)]
(new multiset (assoc msmap x (inc (get msmap x 0))))))
([ms x & xs]
(reduce gc/conj (gc/conj ms x) xs)))
(defmethod gc/empty multiset
[ms]
(new multiset {}))
(defmethod gc/seq multiset
[ms]
(apply concat (map (fn [[x n]] (repeat n x)) (:map ms))))
; Implement fmap
(defmethod gf/fmap multiset
[f m]
(gc/into (gc/empty m) (map f (gc/seq m))))
Multiset tests
(deftest multiset-tests
(are [a b] (= a b)
(gf/fmap inc (mset 1 2 3)) (mset 2 3 4)))
| null | https://raw.githubusercontent.com/clojure/algo.generic/48f3894155abbc14835213281d01355af683b47a/src/test/clojure/clojure/algo/generic/test_functor.clj | clojure | Test routines for clojure.algo.generic.collection
Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this
distribution. By using this software in any fashion, you are
agreeing to be bound by the terms of this license. You must not
remove this notice, or any other, from this software.
Test implementation for functions
Futures and delays
Define a multiset class. The representation is a map from values to counts.
Implement the collection multimethods.
Implement fmap |
Copyright ( c ) , 2011 . All rights reserved . The use
and distribution terms for this software are covered by the Eclipse
(ns clojure.algo.generic.test-functor
(:use [clojure.test :only (deftest is are run-tests)])
(:require [clojure.algo.generic.functor :as gf])
(:require [clojure.algo.generic.collection :as gc]))
Test implementations for CLojure 's built - in collections
(deftest builtin-collections
(are [a b] (= a b)
(gf/fmap inc (list 1 2 3)) (list 2 3 4)
(gf/fmap inc [1 2 3]) [2 3 4]
(gf/fmap inc {:A 1 :B 2 :C 3}) {:A 2 :B 3 :C 4}
(gf/fmap inc #{1 2 3}) #{2 3 4}
(gf/fmap inc (lazy-seq [1 2 3])) (list 2 3 4)
(gf/fmap inc (seq [1 2 3])) (list 2 3 4)
(gf/fmap inc (range 3)) (list 1 2 3)
(gf/fmap inc nil) nil))
(deftest functions
(let [f (fn [x] (+ x x))
x [-1 0 1 2]]
(is (= (map (gf/fmap - f) x)
(map (comp - f) x)))))
(deftest future-test
(is (= 2 @(gf/fmap inc (future 1)))))
(deftest delay-test
(is (= 2 @(gf/fmap inc (delay 1)))))
(defrecord multiset [map])
(defn mset
[& elements]
(gc/into (new multiset {}) elements))
(defmethod gc/conj multiset
([ms x]
(let [msmap (:map ms)]
(new multiset (assoc msmap x (inc (get msmap x 0))))))
([ms x & xs]
(reduce gc/conj (gc/conj ms x) xs)))
(defmethod gc/empty multiset
[ms]
(new multiset {}))
(defmethod gc/seq multiset
[ms]
(apply concat (map (fn [[x n]] (repeat n x)) (:map ms))))
(defmethod gf/fmap multiset
[f m]
(gc/into (gc/empty m) (map f (gc/seq m))))
Multiset tests
(deftest multiset-tests
(are [a b] (= a b)
(gf/fmap inc (mset 1 2 3)) (mset 2 3 4)))
|
6309a66c963f8b4db66309981e47a367bbd8107e17f7eef6c9478c10b6cb9607 | sadiqj/ocaml-esp32 | genprintval.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
and , projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(* To print values *)
open Misc
open Format
open Longident
open Path
open Types
open Outcometree
module type OBJ =
sig
type t
val repr : 'a -> t
val obj : t -> 'a
val is_block : t -> bool
val tag : t -> int
val size : t -> int
val field : t -> int -> t
val double_array_tag : int
val double_field : t -> int -> float
end
module type EVALPATH =
sig
type valu
val eval_path: Env.t -> Path.t -> valu
exception Error
val same_value: valu -> valu -> bool
end
type ('a, 'b) gen_printer =
| Zero of 'b
| Succ of ('a -> ('a, 'b) gen_printer)
module type S =
sig
type t
val install_printer :
Path.t -> Types.type_expr -> (formatter -> t -> unit) -> unit
val install_generic_printer :
Path.t -> Path.t ->
(int -> (int -> t -> Outcometree.out_value,
t -> Outcometree.out_value) gen_printer) ->
unit
val install_generic_printer' :
Path.t -> Path.t ->
(formatter -> t -> unit,
formatter -> t -> unit) gen_printer ->
unit
val remove_printer : Path.t -> unit
val outval_of_untyped_exception : t -> Outcometree.out_value
val outval_of_value :
int -> int ->
(int -> t -> Types.type_expr -> Outcometree.out_value option) ->
Env.t -> t -> type_expr -> Outcometree.out_value
end
module Make(O : OBJ)(EVP : EVALPATH with type valu = O.t) = struct
type t = O.t
module ObjTbl = Hashtbl.Make(struct
type t = O.t
let equal = (==)
let hash x =
try
Hashtbl.hash x
with _exn -> 0
end)
(* Given an exception value, we cannot recover its type,
hence we cannot print its arguments in general.
Here, we do a feeble attempt to print
integer, string and float arguments... *)
let outval_of_untyped_exception_args obj start_offset =
if O.size obj > start_offset then begin
let list = ref [] in
for i = start_offset to O.size obj - 1 do
let arg = O.field obj i in
if not (O.is_block arg) then
list := Oval_int (O.obj arg : int) :: !list
(* Note: this could be a char or a constant constructor... *)
else if O.tag arg = Obj.string_tag then
list :=
Oval_string ((O.obj arg : string), max_int, Ostr_string) :: !list
else if O.tag arg = Obj.double_tag then
list := Oval_float (O.obj arg : float) :: !list
else
list := Oval_constr (Oide_ident "_", []) :: !list
done;
List.rev !list
end
else []
let outval_of_untyped_exception bucket =
if O.tag bucket <> 0 then
Oval_constr (Oide_ident (O.obj (O.field bucket 0) : string), [])
else
let name = (O.obj(O.field(O.field bucket 0) 0) : string) in
let args =
if (name = "Match_failure"
|| name = "Assert_failure"
|| name = "Undefined_recursive_module")
&& O.size bucket = 2
&& O.tag(O.field bucket 1) = 0
then outval_of_untyped_exception_args (O.field bucket 1) 0
else outval_of_untyped_exception_args bucket 1 in
Oval_constr (Oide_ident name, args)
(* The user-defined printers. Also used for some builtin types. *)
type printer =
| Simple of Types.type_expr * (O.t -> Outcometree.out_value)
| Generic of Path.t * (int -> (int -> O.t -> Outcometree.out_value,
O.t -> Outcometree.out_value) gen_printer)
let printers = ref ([
( Pident(Ident.create "print_int"),
Simple (Predef.type_int,
(fun x -> Oval_int (O.obj x : int))) );
( Pident(Ident.create "print_float"),
Simple (Predef.type_float,
(fun x -> Oval_float (O.obj x : float))) );
( Pident(Ident.create "print_char"),
Simple (Predef.type_char,
(fun x -> Oval_char (O.obj x : char))) );
( Pident(Ident.create "print_int32"),
Simple (Predef.type_int32,
(fun x -> Oval_int32 (O.obj x : int32))) );
( Pident(Ident.create "print_nativeint"),
Simple (Predef.type_nativeint,
(fun x -> Oval_nativeint (O.obj x : nativeint))) );
( Pident(Ident.create "print_int64"),
Simple (Predef.type_int64,
(fun x -> Oval_int64 (O.obj x : int64)) ))
] : (Path.t * printer) list)
let exn_printer ppf path exn =
fprintf ppf "<printer %a raised an exception: %s>" Printtyp.path path (Printexc.to_string exn)
let out_exn path exn =
Oval_printer (fun ppf -> exn_printer ppf path exn)
let install_printer path ty fn =
let print_val ppf obj =
try fn ppf obj with exn -> exn_printer ppf path exn in
let printer obj = Oval_printer (fun ppf -> print_val ppf obj) in
printers := (path, Simple (ty, printer)) :: !printers
let install_generic_printer function_path constr_path fn =
printers := (function_path, Generic (constr_path, fn)) :: !printers
let install_generic_printer' function_path ty_path fn =
let rec build gp depth =
match gp with
| Zero fn ->
let out_printer obj =
let printer ppf =
try fn ppf obj with exn -> exn_printer ppf function_path exn in
Oval_printer printer in
Zero out_printer
| Succ fn ->
let print_val fn_arg =
let print_arg ppf o =
!Oprint.out_value ppf (fn_arg (depth+1) o) in
build (fn print_arg) depth in
Succ print_val in
printers := (function_path, Generic (ty_path, build fn)) :: !printers
let remove_printer path =
let rec remove = function
| [] -> raise Not_found
| ((p, _) as printer) :: rem ->
if Path.same p path then rem else printer :: remove rem in
printers := remove !printers
(* Print a constructor or label, giving it the same prefix as the type
it comes from. Attempt to omit the prefix if the type comes from
a module that has been opened. *)
let tree_of_qualified lookup_fun env ty_path name =
match ty_path with
| Pident _ ->
Oide_ident name
| Pdot(p, _s, _pos) ->
if try
match (lookup_fun (Lident name) env).desc with
| Tconstr(ty_path', _, _) -> Path.same ty_path ty_path'
| _ -> false
with Not_found -> false
then Oide_ident name
else Oide_dot (Printtyp.tree_of_path p, name)
| Papply _ ->
Printtyp.tree_of_path ty_path
let tree_of_constr =
tree_of_qualified
(fun lid env -> (Env.lookup_constructor lid env).cstr_res)
and tree_of_label =
tree_of_qualified (fun lid env -> (Env.lookup_label lid env).lbl_res)
(* An abstract type *)
let abstract_type =
Ctype.newty (Tconstr (Pident (Ident.create "abstract"), [], ref Mnil))
(* The main printing function *)
let outval_of_value max_steps max_depth check_depth env obj ty =
let printer_steps = ref max_steps in
let nested_values = ObjTbl.create 8 in
let nest_gen err f depth obj ty =
let repr = obj in
if not (O.is_block repr) then
f depth obj ty
else
if ObjTbl.mem nested_values repr then
err
else begin
ObjTbl.add nested_values repr ();
let ret = f depth obj ty in
ObjTbl.remove nested_values repr;
ret
end
in
let nest f = nest_gen (Oval_stuff "<cycle>") f in
let rec tree_of_val depth obj ty =
decr printer_steps;
if !printer_steps < 0 || depth < 0 then Oval_ellipsis
else begin
try
find_printer depth env ty obj
with Not_found ->
match (Ctype.repr ty).desc with
| Tvar _ | Tunivar _ ->
Oval_stuff "<poly>"
| Tarrow _ ->
Oval_stuff "<fun>"
| Ttuple(ty_list) ->
Oval_tuple (tree_of_val_list 0 depth obj ty_list)
| Tconstr(path, [ty_arg], _)
when Path.same path Predef.path_list ->
if O.is_block obj then
match check_depth depth obj ty with
Some x -> x
| None ->
let rec tree_of_conses tree_list depth obj ty_arg =
if !printer_steps < 0 || depth < 0 then
Oval_ellipsis :: tree_list
else if O.is_block obj then
let tree =
nest tree_of_val (depth - 1) (O.field obj 0) ty_arg
in
let next_obj = O.field obj 1 in
nest_gen (Oval_stuff "<cycle>" :: tree :: tree_list)
(tree_of_conses (tree :: tree_list))
depth next_obj ty_arg
else tree_list
in
Oval_list (List.rev (tree_of_conses [] depth obj ty_arg))
else
Oval_list []
| Tconstr(path, [ty_arg], _)
when Path.same path Predef.path_array ->
let length = O.size obj in
if length > 0 then
match check_depth depth obj ty with
Some x -> x
| None ->
let rec tree_of_items tree_list i =
if !printer_steps < 0 || depth < 0 then
Oval_ellipsis :: tree_list
else if i < length then
let tree =
nest tree_of_val (depth - 1) (O.field obj i) ty_arg
in
tree_of_items (tree :: tree_list) (i + 1)
else tree_list
in
Oval_array (List.rev (tree_of_items [] 0))
else
Oval_array []
| Tconstr(path, [], _)
when Path.same path Predef.path_string ->
Oval_string ((O.obj obj : string), !printer_steps, Ostr_string)
| Tconstr (path, [], _)
when Path.same path Predef.path_bytes ->
let s = Bytes.to_string (O.obj obj : bytes) in
Oval_string (s, !printer_steps, Ostr_bytes)
| Tconstr (path, [ty_arg], _)
when Path.same path Predef.path_lazy_t ->
let obj_tag = O.tag obj in
Lazy values are represented in three possible ways :
1 . a lazy thunk that is not yet forced has tag
Obj.lazy_tag
2 . a lazy thunk that has just been forced has tag
Obj.forward_tag ; its first field is the forced
result , which we can print
3 . when the GC moves a forced trunk with forward_tag ,
or when a thunk is directly created from a value ,
we get a third representation where the value is
directly exposed , without the Obj.forward_tag
( if its own tag is not ambiguous , that is neither
lazy_tag nor forward_tag )
Note that using Lazy.is_val and Lazy.force would be
unsafe , because they use the Obj . * functions rather
than the O. * functions of the functor argument , and
would thus crash if called from the toplevel
( debugger / printval instantiates . Make with
an Obj module talking over a socket ) .
1. a lazy thunk that is not yet forced has tag
Obj.lazy_tag
2. a lazy thunk that has just been forced has tag
Obj.forward_tag; its first field is the forced
result, which we can print
3. when the GC moves a forced trunk with forward_tag,
or when a thunk is directly created from a value,
we get a third representation where the value is
directly exposed, without the Obj.forward_tag
(if its own tag is not ambiguous, that is neither
lazy_tag nor forward_tag)
Note that using Lazy.is_val and Lazy.force would be
unsafe, because they use the Obj.* functions rather
than the O.* functions of the functor argument, and
would thus crash if called from the toplevel
(debugger/printval instantiates Genprintval.Make with
an Obj module talking over a socket).
*)
if obj_tag = Obj.lazy_tag then Oval_stuff "<lazy>"
else begin
let forced_obj =
if obj_tag = Obj.forward_tag then O.field obj 0 else obj
in
calling oneself recursively on forced_obj risks
having a false positive for cycle detection ;
indeed , in case ( 3 ) above , the value is stored
as - is instead of being wrapped in a forward
pointer . It means that , for ( lazy " foo " ) , we have
forced_obj = = obj
and it is easy to wrongly print ( lazy < cycle > ) in such
a case ( PR#6669 ) .
Unfortunately , there is a corner - case that * is *
a real cycle : using -rectypes one can define
let rec x = lazy x
which creates a Forward_tagged block that points to
itself . For this reason , we still " nest "
( detect head cycles ) on forward tags .
having a false positive for cycle detection;
indeed, in case (3) above, the value is stored
as-is instead of being wrapped in a forward
pointer. It means that, for (lazy "foo"), we have
forced_obj == obj
and it is easy to wrongly print (lazy <cycle>) in such
a case (PR#6669).
Unfortunately, there is a corner-case that *is*
a real cycle: using -rectypes one can define
let rec x = lazy x
which creates a Forward_tagged block that points to
itself. For this reason, we still "nest"
(detect head cycles) on forward tags.
*)
let v =
if obj_tag = Obj.forward_tag
then nest tree_of_val depth forced_obj ty_arg
else tree_of_val depth forced_obj ty_arg
in
Oval_constr (Oide_ident "lazy", [v])
end
| Tconstr(path, ty_list, _) -> begin
try
let decl = Env.find_type path env in
match decl with
| {type_kind = Type_abstract; type_manifest = None} ->
Oval_stuff "<abstr>"
| {type_kind = Type_abstract; type_manifest = Some body} ->
tree_of_val depth obj
(try Ctype.apply env decl.type_params body ty_list with
Ctype.Cannot_apply -> abstract_type)
| {type_kind = Type_variant constr_list; type_unboxed} ->
let unbx = type_unboxed.unboxed in
let tag =
if unbx then Cstr_unboxed
else if O.is_block obj
then Cstr_block(O.tag obj)
else Cstr_constant(O.obj obj) in
let {cd_id;cd_args;cd_res} =
Datarepr.find_constr_by_tag tag constr_list in
let type_params =
match cd_res with
Some t ->
begin match (Ctype.repr t).desc with
Tconstr (_,params,_) ->
params
| _ -> assert false end
| None -> decl.type_params
in
begin
match cd_args with
| Cstr_tuple l ->
let ty_args =
List.map
(function ty ->
try Ctype.apply env type_params ty ty_list with
Ctype.Cannot_apply -> abstract_type)
l
in
tree_of_constr_with_args (tree_of_constr env path)
(Ident.name cd_id) false 0 depth obj
ty_args unbx
| Cstr_record lbls ->
let r =
tree_of_record_fields depth
env path type_params ty_list
lbls 0 obj unbx
in
Oval_constr(tree_of_constr env path
(Ident.name cd_id),
[ r ])
end
| {type_kind = Type_record(lbl_list, rep)} ->
begin match check_depth depth obj ty with
Some x -> x
| None ->
let pos =
match rep with
| Record_extension -> 1
| _ -> 0
in
let unbx =
match rep with Record_unboxed _ -> true | _ -> false
in
tree_of_record_fields depth
env path decl.type_params ty_list
lbl_list pos obj unbx
end
| {type_kind = Type_open} ->
tree_of_extension path depth obj
with
Not_found -> (* raised by Env.find_type *)
Oval_stuff "<abstr>"
| Datarepr.Constr_not_found -> (* raised by find_constr_by_tag *)
Oval_stuff "<unknown constructor>"
end
| Tvariant row ->
let row = Btype.row_repr row in
if O.is_block obj then
let tag : int = O.obj (O.field obj 0) in
let rec find = function
| (l, f) :: fields ->
if Btype.hash_variant l = tag then
match Btype.row_field_repr f with
| Rpresent(Some ty) | Reither(_,[ty],_,_) ->
let args =
nest tree_of_val (depth - 1) (O.field obj 1) ty
in
Oval_variant (l, Some args)
| _ -> find fields
else find fields
| [] -> Oval_stuff "<variant>" in
find row.row_fields
else
let tag : int = O.obj obj in
let rec find = function
| (l, _) :: fields ->
if Btype.hash_variant l = tag then
Oval_variant (l, None)
else find fields
| [] -> Oval_stuff "<variant>" in
find row.row_fields
| Tobject (_, _) ->
Oval_stuff "<obj>"
| Tsubst ty ->
tree_of_val (depth - 1) obj ty
| Tfield(_, _, _, _) | Tnil | Tlink _ ->
fatal_error "Printval.outval_of_value"
| Tpoly (ty, _) ->
tree_of_val (depth - 1) obj ty
| Tpackage _ ->
Oval_stuff "<module>"
end
and tree_of_record_fields depth env path type_params ty_list
lbl_list pos obj unboxed =
let rec tree_of_fields pos = function
| [] -> []
| {ld_id; ld_type} :: remainder ->
let ty_arg =
try
Ctype.apply env type_params ld_type
ty_list
with
Ctype.Cannot_apply -> abstract_type in
let name = Ident.name ld_id in
PR#5722 : print full module path only
for first record field
for first record field *)
let lid =
if pos = 0 then tree_of_label env path name
else Oide_ident name
and v =
if unboxed then
tree_of_val (depth - 1) obj ty_arg
else begin
let fld =
if O.tag obj = O.double_array_tag then
O.repr (O.double_field obj pos)
else
O.field obj pos
in
nest tree_of_val (depth - 1) fld ty_arg
end
in
(lid, v) :: tree_of_fields (pos + 1) remainder
in
Oval_record (tree_of_fields pos lbl_list)
and tree_of_val_list start depth obj ty_list =
let rec tree_list i = function
| [] -> []
| ty :: ty_list ->
let tree = nest tree_of_val (depth - 1) (O.field obj i) ty in
tree :: tree_list (i + 1) ty_list in
tree_list start ty_list
and tree_of_constr_with_args
tree_of_cstr cstr_name inlined start depth obj ty_args unboxed =
let lid = tree_of_cstr cstr_name in
let args =
if inlined || unboxed then
match ty_args with
| [ty] -> [ tree_of_val (depth - 1) obj ty ]
| _ -> assert false
else
tree_of_val_list start depth obj ty_args
in
Oval_constr (lid, args)
and tree_of_extension type_path depth bucket =
let slot =
if O.tag bucket <> 0 then bucket
else O.field bucket 0
in
let name = (O.obj(O.field slot 0) : string) in
let lid = Longident.parse name in
try
(* Attempt to recover the constructor description for the exn
from its name *)
let cstr = Env.lookup_constructor lid env in
let path =
match cstr.cstr_tag with
Cstr_extension(p, _) -> p
| _ -> raise Not_found
in
(* Make sure this is the right exception and not an homonym,
by evaluating the exception found and comparing with the
identifier contained in the exception bucket *)
if not (EVP.same_value slot (EVP.eval_path env path))
then raise Not_found;
tree_of_constr_with_args
(fun x -> Oide_ident x) name (cstr.cstr_inlined <> None)
1 depth bucket
cstr.cstr_args false
with Not_found | EVP.Error ->
match check_depth depth bucket ty with
Some x -> x
| None when Path.same type_path Predef.path_exn->
outval_of_untyped_exception bucket
| None ->
Oval_stuff "<extension>"
and find_printer depth env ty =
let rec find = function
| [] -> raise Not_found
| (_name, Simple (sch, printer)) :: remainder ->
if Ctype.moregeneral env false sch ty
then printer
else find remainder
| (_name, Generic (path, fn)) :: remainder ->
begin match (Ctype.expand_head env ty).desc with
| Tconstr (p, args, _) when Path.same p path ->
begin try apply_generic_printer path (fn depth) args
with exn -> (fun _obj -> out_exn path exn) end
| _ -> find remainder end in
find !printers
and apply_generic_printer path printer args =
match (printer, args) with
| (Zero fn, []) -> (fun (obj : O.t)-> try fn obj with exn -> out_exn path exn)
| (Succ fn, arg :: args) ->
let printer = fn (fun depth obj -> tree_of_val depth obj arg) in
apply_generic_printer path printer args
| _ ->
(fun _obj ->
let printer ppf =
fprintf ppf "<internal error: incorrect arity for '%a'>"
Printtyp.path path in
Oval_printer printer)
in nest tree_of_val max_depth obj ty
end
| null | https://raw.githubusercontent.com/sadiqj/ocaml-esp32/33aad4ca2becb9701eb90d779c1b1183aefeb578/toplevel/genprintval.ml | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
To print values
Given an exception value, we cannot recover its type,
hence we cannot print its arguments in general.
Here, we do a feeble attempt to print
integer, string and float arguments...
Note: this could be a char or a constant constructor...
The user-defined printers. Also used for some builtin types.
Print a constructor or label, giving it the same prefix as the type
it comes from. Attempt to omit the prefix if the type comes from
a module that has been opened.
An abstract type
The main printing function
raised by Env.find_type
raised by find_constr_by_tag
Attempt to recover the constructor description for the exn
from its name
Make sure this is the right exception and not an homonym,
by evaluating the exception found and comparing with the
identifier contained in the exception bucket | and , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Misc
open Format
open Longident
open Path
open Types
open Outcometree
module type OBJ =
sig
type t
val repr : 'a -> t
val obj : t -> 'a
val is_block : t -> bool
val tag : t -> int
val size : t -> int
val field : t -> int -> t
val double_array_tag : int
val double_field : t -> int -> float
end
module type EVALPATH =
sig
type valu
val eval_path: Env.t -> Path.t -> valu
exception Error
val same_value: valu -> valu -> bool
end
type ('a, 'b) gen_printer =
| Zero of 'b
| Succ of ('a -> ('a, 'b) gen_printer)
module type S =
sig
type t
val install_printer :
Path.t -> Types.type_expr -> (formatter -> t -> unit) -> unit
val install_generic_printer :
Path.t -> Path.t ->
(int -> (int -> t -> Outcometree.out_value,
t -> Outcometree.out_value) gen_printer) ->
unit
val install_generic_printer' :
Path.t -> Path.t ->
(formatter -> t -> unit,
formatter -> t -> unit) gen_printer ->
unit
val remove_printer : Path.t -> unit
val outval_of_untyped_exception : t -> Outcometree.out_value
val outval_of_value :
int -> int ->
(int -> t -> Types.type_expr -> Outcometree.out_value option) ->
Env.t -> t -> type_expr -> Outcometree.out_value
end
module Make(O : OBJ)(EVP : EVALPATH with type valu = O.t) = struct
type t = O.t
module ObjTbl = Hashtbl.Make(struct
type t = O.t
let equal = (==)
let hash x =
try
Hashtbl.hash x
with _exn -> 0
end)
let outval_of_untyped_exception_args obj start_offset =
if O.size obj > start_offset then begin
let list = ref [] in
for i = start_offset to O.size obj - 1 do
let arg = O.field obj i in
if not (O.is_block arg) then
list := Oval_int (O.obj arg : int) :: !list
else if O.tag arg = Obj.string_tag then
list :=
Oval_string ((O.obj arg : string), max_int, Ostr_string) :: !list
else if O.tag arg = Obj.double_tag then
list := Oval_float (O.obj arg : float) :: !list
else
list := Oval_constr (Oide_ident "_", []) :: !list
done;
List.rev !list
end
else []
let outval_of_untyped_exception bucket =
if O.tag bucket <> 0 then
Oval_constr (Oide_ident (O.obj (O.field bucket 0) : string), [])
else
let name = (O.obj(O.field(O.field bucket 0) 0) : string) in
let args =
if (name = "Match_failure"
|| name = "Assert_failure"
|| name = "Undefined_recursive_module")
&& O.size bucket = 2
&& O.tag(O.field bucket 1) = 0
then outval_of_untyped_exception_args (O.field bucket 1) 0
else outval_of_untyped_exception_args bucket 1 in
Oval_constr (Oide_ident name, args)
type printer =
| Simple of Types.type_expr * (O.t -> Outcometree.out_value)
| Generic of Path.t * (int -> (int -> O.t -> Outcometree.out_value,
O.t -> Outcometree.out_value) gen_printer)
let printers = ref ([
( Pident(Ident.create "print_int"),
Simple (Predef.type_int,
(fun x -> Oval_int (O.obj x : int))) );
( Pident(Ident.create "print_float"),
Simple (Predef.type_float,
(fun x -> Oval_float (O.obj x : float))) );
( Pident(Ident.create "print_char"),
Simple (Predef.type_char,
(fun x -> Oval_char (O.obj x : char))) );
( Pident(Ident.create "print_int32"),
Simple (Predef.type_int32,
(fun x -> Oval_int32 (O.obj x : int32))) );
( Pident(Ident.create "print_nativeint"),
Simple (Predef.type_nativeint,
(fun x -> Oval_nativeint (O.obj x : nativeint))) );
( Pident(Ident.create "print_int64"),
Simple (Predef.type_int64,
(fun x -> Oval_int64 (O.obj x : int64)) ))
] : (Path.t * printer) list)
let exn_printer ppf path exn =
fprintf ppf "<printer %a raised an exception: %s>" Printtyp.path path (Printexc.to_string exn)
let out_exn path exn =
Oval_printer (fun ppf -> exn_printer ppf path exn)
let install_printer path ty fn =
let print_val ppf obj =
try fn ppf obj with exn -> exn_printer ppf path exn in
let printer obj = Oval_printer (fun ppf -> print_val ppf obj) in
printers := (path, Simple (ty, printer)) :: !printers
let install_generic_printer function_path constr_path fn =
printers := (function_path, Generic (constr_path, fn)) :: !printers
let install_generic_printer' function_path ty_path fn =
let rec build gp depth =
match gp with
| Zero fn ->
let out_printer obj =
let printer ppf =
try fn ppf obj with exn -> exn_printer ppf function_path exn in
Oval_printer printer in
Zero out_printer
| Succ fn ->
let print_val fn_arg =
let print_arg ppf o =
!Oprint.out_value ppf (fn_arg (depth+1) o) in
build (fn print_arg) depth in
Succ print_val in
printers := (function_path, Generic (ty_path, build fn)) :: !printers
let remove_printer path =
let rec remove = function
| [] -> raise Not_found
| ((p, _) as printer) :: rem ->
if Path.same p path then rem else printer :: remove rem in
printers := remove !printers
let tree_of_qualified lookup_fun env ty_path name =
match ty_path with
| Pident _ ->
Oide_ident name
| Pdot(p, _s, _pos) ->
if try
match (lookup_fun (Lident name) env).desc with
| Tconstr(ty_path', _, _) -> Path.same ty_path ty_path'
| _ -> false
with Not_found -> false
then Oide_ident name
else Oide_dot (Printtyp.tree_of_path p, name)
| Papply _ ->
Printtyp.tree_of_path ty_path
let tree_of_constr =
tree_of_qualified
(fun lid env -> (Env.lookup_constructor lid env).cstr_res)
and tree_of_label =
tree_of_qualified (fun lid env -> (Env.lookup_label lid env).lbl_res)
let abstract_type =
Ctype.newty (Tconstr (Pident (Ident.create "abstract"), [], ref Mnil))
let outval_of_value max_steps max_depth check_depth env obj ty =
let printer_steps = ref max_steps in
let nested_values = ObjTbl.create 8 in
let nest_gen err f depth obj ty =
let repr = obj in
if not (O.is_block repr) then
f depth obj ty
else
if ObjTbl.mem nested_values repr then
err
else begin
ObjTbl.add nested_values repr ();
let ret = f depth obj ty in
ObjTbl.remove nested_values repr;
ret
end
in
let nest f = nest_gen (Oval_stuff "<cycle>") f in
let rec tree_of_val depth obj ty =
decr printer_steps;
if !printer_steps < 0 || depth < 0 then Oval_ellipsis
else begin
try
find_printer depth env ty obj
with Not_found ->
match (Ctype.repr ty).desc with
| Tvar _ | Tunivar _ ->
Oval_stuff "<poly>"
| Tarrow _ ->
Oval_stuff "<fun>"
| Ttuple(ty_list) ->
Oval_tuple (tree_of_val_list 0 depth obj ty_list)
| Tconstr(path, [ty_arg], _)
when Path.same path Predef.path_list ->
if O.is_block obj then
match check_depth depth obj ty with
Some x -> x
| None ->
let rec tree_of_conses tree_list depth obj ty_arg =
if !printer_steps < 0 || depth < 0 then
Oval_ellipsis :: tree_list
else if O.is_block obj then
let tree =
nest tree_of_val (depth - 1) (O.field obj 0) ty_arg
in
let next_obj = O.field obj 1 in
nest_gen (Oval_stuff "<cycle>" :: tree :: tree_list)
(tree_of_conses (tree :: tree_list))
depth next_obj ty_arg
else tree_list
in
Oval_list (List.rev (tree_of_conses [] depth obj ty_arg))
else
Oval_list []
| Tconstr(path, [ty_arg], _)
when Path.same path Predef.path_array ->
let length = O.size obj in
if length > 0 then
match check_depth depth obj ty with
Some x -> x
| None ->
let rec tree_of_items tree_list i =
if !printer_steps < 0 || depth < 0 then
Oval_ellipsis :: tree_list
else if i < length then
let tree =
nest tree_of_val (depth - 1) (O.field obj i) ty_arg
in
tree_of_items (tree :: tree_list) (i + 1)
else tree_list
in
Oval_array (List.rev (tree_of_items [] 0))
else
Oval_array []
| Tconstr(path, [], _)
when Path.same path Predef.path_string ->
Oval_string ((O.obj obj : string), !printer_steps, Ostr_string)
| Tconstr (path, [], _)
when Path.same path Predef.path_bytes ->
let s = Bytes.to_string (O.obj obj : bytes) in
Oval_string (s, !printer_steps, Ostr_bytes)
| Tconstr (path, [ty_arg], _)
when Path.same path Predef.path_lazy_t ->
let obj_tag = O.tag obj in
Lazy values are represented in three possible ways :
1 . a lazy thunk that is not yet forced has tag
Obj.lazy_tag
2 . a lazy thunk that has just been forced has tag
Obj.forward_tag ; its first field is the forced
result , which we can print
3 . when the GC moves a forced trunk with forward_tag ,
or when a thunk is directly created from a value ,
we get a third representation where the value is
directly exposed , without the Obj.forward_tag
( if its own tag is not ambiguous , that is neither
lazy_tag nor forward_tag )
Note that using Lazy.is_val and Lazy.force would be
unsafe , because they use the Obj . * functions rather
than the O. * functions of the functor argument , and
would thus crash if called from the toplevel
( debugger / printval instantiates . Make with
an Obj module talking over a socket ) .
1. a lazy thunk that is not yet forced has tag
Obj.lazy_tag
2. a lazy thunk that has just been forced has tag
Obj.forward_tag; its first field is the forced
result, which we can print
3. when the GC moves a forced trunk with forward_tag,
or when a thunk is directly created from a value,
we get a third representation where the value is
directly exposed, without the Obj.forward_tag
(if its own tag is not ambiguous, that is neither
lazy_tag nor forward_tag)
Note that using Lazy.is_val and Lazy.force would be
unsafe, because they use the Obj.* functions rather
than the O.* functions of the functor argument, and
would thus crash if called from the toplevel
(debugger/printval instantiates Genprintval.Make with
an Obj module talking over a socket).
*)
if obj_tag = Obj.lazy_tag then Oval_stuff "<lazy>"
else begin
let forced_obj =
if obj_tag = Obj.forward_tag then O.field obj 0 else obj
in
calling oneself recursively on forced_obj risks
having a false positive for cycle detection ;
indeed , in case ( 3 ) above , the value is stored
as - is instead of being wrapped in a forward
pointer . It means that , for ( lazy " foo " ) , we have
forced_obj = = obj
and it is easy to wrongly print ( lazy < cycle > ) in such
a case ( PR#6669 ) .
Unfortunately , there is a corner - case that * is *
a real cycle : using -rectypes one can define
let rec x = lazy x
which creates a Forward_tagged block that points to
itself . For this reason , we still " nest "
( detect head cycles ) on forward tags .
having a false positive for cycle detection;
indeed, in case (3) above, the value is stored
as-is instead of being wrapped in a forward
pointer. It means that, for (lazy "foo"), we have
forced_obj == obj
and it is easy to wrongly print (lazy <cycle>) in such
a case (PR#6669).
Unfortunately, there is a corner-case that *is*
a real cycle: using -rectypes one can define
let rec x = lazy x
which creates a Forward_tagged block that points to
itself. For this reason, we still "nest"
(detect head cycles) on forward tags.
*)
let v =
if obj_tag = Obj.forward_tag
then nest tree_of_val depth forced_obj ty_arg
else tree_of_val depth forced_obj ty_arg
in
Oval_constr (Oide_ident "lazy", [v])
end
| Tconstr(path, ty_list, _) -> begin
try
let decl = Env.find_type path env in
match decl with
| {type_kind = Type_abstract; type_manifest = None} ->
Oval_stuff "<abstr>"
| {type_kind = Type_abstract; type_manifest = Some body} ->
tree_of_val depth obj
(try Ctype.apply env decl.type_params body ty_list with
Ctype.Cannot_apply -> abstract_type)
| {type_kind = Type_variant constr_list; type_unboxed} ->
let unbx = type_unboxed.unboxed in
let tag =
if unbx then Cstr_unboxed
else if O.is_block obj
then Cstr_block(O.tag obj)
else Cstr_constant(O.obj obj) in
let {cd_id;cd_args;cd_res} =
Datarepr.find_constr_by_tag tag constr_list in
let type_params =
match cd_res with
Some t ->
begin match (Ctype.repr t).desc with
Tconstr (_,params,_) ->
params
| _ -> assert false end
| None -> decl.type_params
in
begin
match cd_args with
| Cstr_tuple l ->
let ty_args =
List.map
(function ty ->
try Ctype.apply env type_params ty ty_list with
Ctype.Cannot_apply -> abstract_type)
l
in
tree_of_constr_with_args (tree_of_constr env path)
(Ident.name cd_id) false 0 depth obj
ty_args unbx
| Cstr_record lbls ->
let r =
tree_of_record_fields depth
env path type_params ty_list
lbls 0 obj unbx
in
Oval_constr(tree_of_constr env path
(Ident.name cd_id),
[ r ])
end
| {type_kind = Type_record(lbl_list, rep)} ->
begin match check_depth depth obj ty with
Some x -> x
| None ->
let pos =
match rep with
| Record_extension -> 1
| _ -> 0
in
let unbx =
match rep with Record_unboxed _ -> true | _ -> false
in
tree_of_record_fields depth
env path decl.type_params ty_list
lbl_list pos obj unbx
end
| {type_kind = Type_open} ->
tree_of_extension path depth obj
with
Oval_stuff "<abstr>"
Oval_stuff "<unknown constructor>"
end
| Tvariant row ->
let row = Btype.row_repr row in
if O.is_block obj then
let tag : int = O.obj (O.field obj 0) in
let rec find = function
| (l, f) :: fields ->
if Btype.hash_variant l = tag then
match Btype.row_field_repr f with
| Rpresent(Some ty) | Reither(_,[ty],_,_) ->
let args =
nest tree_of_val (depth - 1) (O.field obj 1) ty
in
Oval_variant (l, Some args)
| _ -> find fields
else find fields
| [] -> Oval_stuff "<variant>" in
find row.row_fields
else
let tag : int = O.obj obj in
let rec find = function
| (l, _) :: fields ->
if Btype.hash_variant l = tag then
Oval_variant (l, None)
else find fields
| [] -> Oval_stuff "<variant>" in
find row.row_fields
| Tobject (_, _) ->
Oval_stuff "<obj>"
| Tsubst ty ->
tree_of_val (depth - 1) obj ty
| Tfield(_, _, _, _) | Tnil | Tlink _ ->
fatal_error "Printval.outval_of_value"
| Tpoly (ty, _) ->
tree_of_val (depth - 1) obj ty
| Tpackage _ ->
Oval_stuff "<module>"
end
and tree_of_record_fields depth env path type_params ty_list
lbl_list pos obj unboxed =
let rec tree_of_fields pos = function
| [] -> []
| {ld_id; ld_type} :: remainder ->
let ty_arg =
try
Ctype.apply env type_params ld_type
ty_list
with
Ctype.Cannot_apply -> abstract_type in
let name = Ident.name ld_id in
PR#5722 : print full module path only
for first record field
for first record field *)
let lid =
if pos = 0 then tree_of_label env path name
else Oide_ident name
and v =
if unboxed then
tree_of_val (depth - 1) obj ty_arg
else begin
let fld =
if O.tag obj = O.double_array_tag then
O.repr (O.double_field obj pos)
else
O.field obj pos
in
nest tree_of_val (depth - 1) fld ty_arg
end
in
(lid, v) :: tree_of_fields (pos + 1) remainder
in
Oval_record (tree_of_fields pos lbl_list)
and tree_of_val_list start depth obj ty_list =
let rec tree_list i = function
| [] -> []
| ty :: ty_list ->
let tree = nest tree_of_val (depth - 1) (O.field obj i) ty in
tree :: tree_list (i + 1) ty_list in
tree_list start ty_list
and tree_of_constr_with_args
tree_of_cstr cstr_name inlined start depth obj ty_args unboxed =
let lid = tree_of_cstr cstr_name in
let args =
if inlined || unboxed then
match ty_args with
| [ty] -> [ tree_of_val (depth - 1) obj ty ]
| _ -> assert false
else
tree_of_val_list start depth obj ty_args
in
Oval_constr (lid, args)
and tree_of_extension type_path depth bucket =
let slot =
if O.tag bucket <> 0 then bucket
else O.field bucket 0
in
let name = (O.obj(O.field slot 0) : string) in
let lid = Longident.parse name in
try
let cstr = Env.lookup_constructor lid env in
let path =
match cstr.cstr_tag with
Cstr_extension(p, _) -> p
| _ -> raise Not_found
in
if not (EVP.same_value slot (EVP.eval_path env path))
then raise Not_found;
tree_of_constr_with_args
(fun x -> Oide_ident x) name (cstr.cstr_inlined <> None)
1 depth bucket
cstr.cstr_args false
with Not_found | EVP.Error ->
match check_depth depth bucket ty with
Some x -> x
| None when Path.same type_path Predef.path_exn->
outval_of_untyped_exception bucket
| None ->
Oval_stuff "<extension>"
and find_printer depth env ty =
let rec find = function
| [] -> raise Not_found
| (_name, Simple (sch, printer)) :: remainder ->
if Ctype.moregeneral env false sch ty
then printer
else find remainder
| (_name, Generic (path, fn)) :: remainder ->
begin match (Ctype.expand_head env ty).desc with
| Tconstr (p, args, _) when Path.same p path ->
begin try apply_generic_printer path (fn depth) args
with exn -> (fun _obj -> out_exn path exn) end
| _ -> find remainder end in
find !printers
and apply_generic_printer path printer args =
match (printer, args) with
| (Zero fn, []) -> (fun (obj : O.t)-> try fn obj with exn -> out_exn path exn)
| (Succ fn, arg :: args) ->
let printer = fn (fun depth obj -> tree_of_val depth obj arg) in
apply_generic_printer path printer args
| _ ->
(fun _obj ->
let printer ppf =
fprintf ppf "<internal error: incorrect arity for '%a'>"
Printtyp.path path in
Oval_printer printer)
in nest tree_of_val max_depth obj ty
end
|
7beeea134875735a973367b51ccd41e4c9f6e3c4bbf4e04aaf1efacb7201cd96 | bobatkey/CS316-18 | Lec07.hs | module Lec07 where
import Test.QuickCheck
import Data.Foldable
LECTURE 07 : QUICKCHECK
1 . Individual testing
list_append_test1 :: Bool
list_append_test1 = [1,2,3] ++ [] == [1,2,3]
list_append_test2 :: Bool
list_append_test2 = [1,2,3,4] ++ [] == [1,2,3,4]
list_append_tests :: [Bool]
list_append_tests = [ list_append_test1
, list_append_test2
]
2 . Property based testing
list_append_prop1 :: [Int] -> Bool
list_append_prop1 xs = xs ++ [] == xs
list_append_prop2 :: [Int] -> Bool
list_append_prop2 xs = [] ++ xs == xs
list_append_prop3 :: [Int] -> [Int] -> [Int] -> Bool
list_append_prop3 xs ys zs = (xs ++ ys) ++ zs == xs ++ (ys ++ zs)
-- Monoids
monoid_prop1 :: (Eq m, Monoid m) => m -> Bool
monoid_prop1 x = x `mappend` mempty == x
monoid_prop2 :: (Eq m, Monoid m) => m -> Bool
monoid_prop2 x = mempty `mappend` x == x
monoid_prop3 :: (Eq m, Monoid m) => m -> m -> m -> Bool
monoid_prop3 x y z = (x `mappend` y) `mappend` z == x `mappend` (y `mappend` z)
data RGBA = MkRGBA { redChannel : : Double
, greenChannel : : Double
, : : Double
, alphaChannel : : Double
}
deriving ( Show , Eq )
instance Arbitrary RGBA where
arbitrary = MkRGBA < $ > arbitrary < * > arbitrary < * > arbitrary < * > arbitrary
instance where
mempty =
MkRGBA 0 0 0 0
mappend ( MkRGBA r1 g1 b1 0 ) ( MkRGBA r2 g2 b2 0 ) = mappend ( MkRGBA r1 g1 b1 a1 ) ( MkRGBA r2 g2 b2 a2 ) = MkRGBA r g b a
where
a = a1 + a2 - a1*a2
r = ( a1*r1 + ( 1 - a1)*a2*r2 ) / a
g = ( a1*g1 + ( 1 - a1)*a2*g2 ) / a
b = ( a1*b1 + ( 1 - a1)*a2*b2 ) / a
colour_prop1 = monoid_prop1 : : RGBA - > Bool
data RGBA = MkRGBA { redChannel :: Double
, greenChannel :: Double
, blueChannel :: Double
, alphaChannel :: Double
}
deriving (Show, Eq)
instance Arbitrary RGBA where
arbitrary = MkRGBA <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary
instance Monoid RGBA where
mempty =
MkRGBA 0 0 0 0
mappend (MkRGBA r1 g1 b1 0) (MkRGBA r2 g2 b2 0) = mempty
mappend (MkRGBA r1 g1 b1 a1) (MkRGBA r2 g2 b2 a2) = MkRGBA r g b a
where
a = a1 + a2 - a1*a2
r = (a1*r1 + (1-a1)*a2*r2) / a
g = (a1*g1 + (1-a1)*a2*g2) / a
b = (a1*b1 + (1-a1)*a2*b2) / a
colour_prop1 = monoid_prop1 :: RGBA -> Bool
-}
data Trit = True3 | False3 | Unknown deriving (Eq, Show)
tritAnd :: Trit -> Trit -> Trit
tritAnd False3 _ = False3
tritAnd _ False3 = False3
tritAnd Unknown _ = Unknown
tritAnd _ Unknown = Unknown
tritAnd True3 True3 = True3
instance Arbitrary Trit where
arbitrary = oneof [ pure True3, pure False3, pure Unknown ]
instance Monoid Trit where
mempty = True3
mappend = tritAnd
3 . Reference implementation testing
insert :: Ord a => a -> [a] -> [a]
insert x [] = [x]
insert x (y:ys)
| x <= y = x : y : ys
| otherwise = y : insert x ys
isort :: Ord a => [a] -> [a]
isort [] = []
isort (x:xs) = insert x (isort xs)
isSorted :: Ord a => [a] -> Bool
isSorted [] = True
isSorted [x] = True
isSorted (x:y:ys) = x <= y && isSorted (y:ys)
insert_preserves_sortedness :: Double -> [Double] -> Bool
insert_preserves_sortedness x xs =
isSorted (insert x (makeSorted 0 xs))
makeSorted :: Double -> [Double] -> [Double]
makeSorted i [] = []
makeSorted i (x:xs) = y : makeSorted y xs
where y = i + abs x
module Lec08 where
import Test . QuickCheck
{ - LECTURE 08 : QUICKCHECK
module Lec08 where
import Test.QuickCheck
{- LECTURE 08: QUICKCHECK -}
{- PART I : WRITING INDIVIDUAL TEST CASES -}
-- artisanal testing, one at a time
append_test_1 :: Bool
append_test_1 =
[1,2,3] ++ [4,5,6] == [1,2,3,4,5,6]
append_test_2 :: Bool
append_test_2 =
[4,5,6] ++ [1,2,3] == [4,5,6,1,2,3]
append_test_3 :: Bool
append_test_3 =
[] ++ [1,2,3] == [1,2,3]
append_test_4 :: Bool
append_test_4 =
[1,2,3] ++ [] == [1,2,3]
append_tests :: Bool
append_tests =
and [ append_test_1
, append_test_2
, append_test_3
, append_test_4
]
insert :: Ord a => a -> [a] -> [a]
insert x [] = [x]
insert x (y:ys)
| x <= y = x : y : ys
| otherwise = y : insert x ys
insert_test_1 :: Bool
insert_test_1 =
insert 3 [1,2,4,5] == [1,2,3,4,5]
{- PART II : PROPERTY BASED TESTING WITH QUICKCHECK -}
-- /~nr/cs257/archive/john-hughes/quick.pdf
-- Why not test with lots of examples, not just one?
append_left_nil_prop :: [Int] -> Bool
append_left_nil_prop xs =
[] ++ xs == xs
append_right_nil_prop :: [Int] -> Bool
append_right_nil_prop xs =
xs ++ [] == xs
append_faulty_prop :: [Int] -> Bool
append_faulty_prop xs =
xs ++ [0] == xs
-- (x + y) + z = x + (y + z)
append_assoc :: [Int] -> [Int] -> [Int] -> Bool
append_assoc xs ys zs =
(xs ++ ys) ++ zs == xs ++ (ys ++ zs)
reverse_reverse_prop :: [Int] -> Bool
reverse_reverse_prop xs =
reverse (reverse xs) == xs
reverse_does_nothing :: [Int] -> Bool
reverse_does_nothing xs =
reverse xs == xs
reverse_append :: [Int] -> [Int] -> Bool
reverse_append xs ys =
reverse (xs ++ ys) == reverse ys ++ reverse xs
slow_reverse :: [a] -> [a]
slow_reverse [] = []
slow_reverse (x:xs) = slow_reverse xs ++ [x]
reverse_eq_slow_reverse :: [Int] -> Bool
reverse_eq_slow_reverse xs =
reverse xs == slow_reverse xs
----------------------------------------------------------------------
isSorted :: Ord a => [a] -> Bool
isSorted [] = True
isSorted [x] = True
isSorted (x:y:ys) = x <= y && isSorted (y:ys)
insert_preserves_sortedness :: Int -> [Int] -> Bool
insert_preserves_sortedness x xs =
isSorted (insert x (makeSorted 0 xs))
makeSorted :: Int -> [Int] -> [Int]
makeSorted i [] = []
makeSorted i (x:xs) = y : makeSorted y xs
where y = i + abs x
makeSorted_prop :: [Int] -> Bool
makeSorted_prop xs =
isSorted (makeSorted 0 xs)
----------------------------------------------------------------------
data Tree a
= TLeaf
| TNode (Tree a) a (Tree a)
deriving (Show, Eq)
instance Arbitrary a => Arbitrary (Tree a) where
arbitrary = genTree 3
genTree :: Arbitrary a => Int -> Gen (Tree a)
genTree 0 = return TLeaf
genTree n = frequency [ (3, do l <- genTree (n-1)
x <- arbitrary
r <- genTree (n-1)
return (TNode l x r))
, (1, return TLeaf)
]
-}
| null | https://raw.githubusercontent.com/bobatkey/CS316-18/282dc3c876527c14acfed7bd38f24c9ff048627a/lectures/Lec07.hs | haskell | Monoids
LECTURE 08: QUICKCHECK
PART I : WRITING INDIVIDUAL TEST CASES
artisanal testing, one at a time
PART II : PROPERTY BASED TESTING WITH QUICKCHECK
/~nr/cs257/archive/john-hughes/quick.pdf
Why not test with lots of examples, not just one?
(x + y) + z = x + (y + z)
--------------------------------------------------------------------
-------------------------------------------------------------------- | module Lec07 where
import Test.QuickCheck
import Data.Foldable
LECTURE 07 : QUICKCHECK
1 . Individual testing
list_append_test1 :: Bool
list_append_test1 = [1,2,3] ++ [] == [1,2,3]
list_append_test2 :: Bool
list_append_test2 = [1,2,3,4] ++ [] == [1,2,3,4]
list_append_tests :: [Bool]
list_append_tests = [ list_append_test1
, list_append_test2
]
2 . Property based testing
list_append_prop1 :: [Int] -> Bool
list_append_prop1 xs = xs ++ [] == xs
list_append_prop2 :: [Int] -> Bool
list_append_prop2 xs = [] ++ xs == xs
list_append_prop3 :: [Int] -> [Int] -> [Int] -> Bool
list_append_prop3 xs ys zs = (xs ++ ys) ++ zs == xs ++ (ys ++ zs)
monoid_prop1 :: (Eq m, Monoid m) => m -> Bool
monoid_prop1 x = x `mappend` mempty == x
monoid_prop2 :: (Eq m, Monoid m) => m -> Bool
monoid_prop2 x = mempty `mappend` x == x
monoid_prop3 :: (Eq m, Monoid m) => m -> m -> m -> Bool
monoid_prop3 x y z = (x `mappend` y) `mappend` z == x `mappend` (y `mappend` z)
data RGBA = MkRGBA { redChannel : : Double
, greenChannel : : Double
, : : Double
, alphaChannel : : Double
}
deriving ( Show , Eq )
instance Arbitrary RGBA where
arbitrary = MkRGBA < $ > arbitrary < * > arbitrary < * > arbitrary < * > arbitrary
instance where
mempty =
MkRGBA 0 0 0 0
mappend ( MkRGBA r1 g1 b1 0 ) ( MkRGBA r2 g2 b2 0 ) = mappend ( MkRGBA r1 g1 b1 a1 ) ( MkRGBA r2 g2 b2 a2 ) = MkRGBA r g b a
where
a = a1 + a2 - a1*a2
r = ( a1*r1 + ( 1 - a1)*a2*r2 ) / a
g = ( a1*g1 + ( 1 - a1)*a2*g2 ) / a
b = ( a1*b1 + ( 1 - a1)*a2*b2 ) / a
colour_prop1 = monoid_prop1 : : RGBA - > Bool
data RGBA = MkRGBA { redChannel :: Double
, greenChannel :: Double
, blueChannel :: Double
, alphaChannel :: Double
}
deriving (Show, Eq)
instance Arbitrary RGBA where
arbitrary = MkRGBA <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary
instance Monoid RGBA where
mempty =
MkRGBA 0 0 0 0
mappend (MkRGBA r1 g1 b1 0) (MkRGBA r2 g2 b2 0) = mempty
mappend (MkRGBA r1 g1 b1 a1) (MkRGBA r2 g2 b2 a2) = MkRGBA r g b a
where
a = a1 + a2 - a1*a2
r = (a1*r1 + (1-a1)*a2*r2) / a
g = (a1*g1 + (1-a1)*a2*g2) / a
b = (a1*b1 + (1-a1)*a2*b2) / a
colour_prop1 = monoid_prop1 :: RGBA -> Bool
-}
data Trit = True3 | False3 | Unknown deriving (Eq, Show)
tritAnd :: Trit -> Trit -> Trit
tritAnd False3 _ = False3
tritAnd _ False3 = False3
tritAnd Unknown _ = Unknown
tritAnd _ Unknown = Unknown
tritAnd True3 True3 = True3
instance Arbitrary Trit where
arbitrary = oneof [ pure True3, pure False3, pure Unknown ]
instance Monoid Trit where
mempty = True3
mappend = tritAnd
3 . Reference implementation testing
insert :: Ord a => a -> [a] -> [a]
insert x [] = [x]
insert x (y:ys)
| x <= y = x : y : ys
| otherwise = y : insert x ys
isort :: Ord a => [a] -> [a]
isort [] = []
isort (x:xs) = insert x (isort xs)
isSorted :: Ord a => [a] -> Bool
isSorted [] = True
isSorted [x] = True
isSorted (x:y:ys) = x <= y && isSorted (y:ys)
insert_preserves_sortedness :: Double -> [Double] -> Bool
insert_preserves_sortedness x xs =
isSorted (insert x (makeSorted 0 xs))
makeSorted :: Double -> [Double] -> [Double]
makeSorted i [] = []
makeSorted i (x:xs) = y : makeSorted y xs
where y = i + abs x
module Lec08 where
import Test . QuickCheck
{ - LECTURE 08 : QUICKCHECK
module Lec08 where
import Test.QuickCheck
append_test_1 :: Bool
append_test_1 =
[1,2,3] ++ [4,5,6] == [1,2,3,4,5,6]
append_test_2 :: Bool
append_test_2 =
[4,5,6] ++ [1,2,3] == [4,5,6,1,2,3]
append_test_3 :: Bool
append_test_3 =
[] ++ [1,2,3] == [1,2,3]
append_test_4 :: Bool
append_test_4 =
[1,2,3] ++ [] == [1,2,3]
append_tests :: Bool
append_tests =
and [ append_test_1
, append_test_2
, append_test_3
, append_test_4
]
insert :: Ord a => a -> [a] -> [a]
insert x [] = [x]
insert x (y:ys)
| x <= y = x : y : ys
| otherwise = y : insert x ys
insert_test_1 :: Bool
insert_test_1 =
insert 3 [1,2,4,5] == [1,2,3,4,5]
append_left_nil_prop :: [Int] -> Bool
append_left_nil_prop xs =
[] ++ xs == xs
append_right_nil_prop :: [Int] -> Bool
append_right_nil_prop xs =
xs ++ [] == xs
append_faulty_prop :: [Int] -> Bool
append_faulty_prop xs =
xs ++ [0] == xs
append_assoc :: [Int] -> [Int] -> [Int] -> Bool
append_assoc xs ys zs =
(xs ++ ys) ++ zs == xs ++ (ys ++ zs)
reverse_reverse_prop :: [Int] -> Bool
reverse_reverse_prop xs =
reverse (reverse xs) == xs
reverse_does_nothing :: [Int] -> Bool
reverse_does_nothing xs =
reverse xs == xs
reverse_append :: [Int] -> [Int] -> Bool
reverse_append xs ys =
reverse (xs ++ ys) == reverse ys ++ reverse xs
slow_reverse :: [a] -> [a]
slow_reverse [] = []
slow_reverse (x:xs) = slow_reverse xs ++ [x]
reverse_eq_slow_reverse :: [Int] -> Bool
reverse_eq_slow_reverse xs =
reverse xs == slow_reverse xs
isSorted :: Ord a => [a] -> Bool
isSorted [] = True
isSorted [x] = True
isSorted (x:y:ys) = x <= y && isSorted (y:ys)
insert_preserves_sortedness :: Int -> [Int] -> Bool
insert_preserves_sortedness x xs =
isSorted (insert x (makeSorted 0 xs))
makeSorted :: Int -> [Int] -> [Int]
makeSorted i [] = []
makeSorted i (x:xs) = y : makeSorted y xs
where y = i + abs x
makeSorted_prop :: [Int] -> Bool
makeSorted_prop xs =
isSorted (makeSorted 0 xs)
data Tree a
= TLeaf
| TNode (Tree a) a (Tree a)
deriving (Show, Eq)
instance Arbitrary a => Arbitrary (Tree a) where
arbitrary = genTree 3
genTree :: Arbitrary a => Int -> Gen (Tree a)
genTree 0 = return TLeaf
genTree n = frequency [ (3, do l <- genTree (n-1)
x <- arbitrary
r <- genTree (n-1)
return (TNode l x r))
, (1, return TLeaf)
]
-}
|
a6dc148897da0a5bc9172864e6fef578bcd922f3293a7fa5e5dc4858a6196873 | soarlab/FPTaylor | more_num.mli | (* ========================================================================== *)
: A Tool for Rigorous Estimation of Round - off Errors
(* *)
Author : , University of Utah
(* *)
This file is distributed under the terms of the MIT license
(* ========================================================================== *)
(* -------------------------------------------------------------------------- *)
(* Functions for rational and floating-point numbers *)
(* -------------------------------------------------------------------------- *)
val numerator : Num.num -> Big_int.big_int
val denominator : Num.num -> Big_int.big_int
val num_of_float_string : string -> Num.num
val num_of_float : float -> Num.num
val log_big_int_floor : int -> Big_int.big_int -> int
val string_of_float_lo : int -> float -> string
val string_of_float_hi : int -> float -> string
val is_power_of_two : Num.num -> bool
val is_nan : float -> bool
val is_infinity : float -> bool
val next_float : float -> float
val prev_float : float -> float
val log2_num : Num.num -> int
val float_of_num_lo : Num.num -> float
val float_of_num_hi : Num.num -> float
val interval_of_num : Num.num -> Interval.interval
val interval_of_string : string -> Interval.interval
val check_interval : Interval.interval -> string | null | https://raw.githubusercontent.com/soarlab/FPTaylor/efbbc83970fe3c9f4cb33fafbbe1050dd18749cd/more_num.mli | ocaml | ==========================================================================
==========================================================================
--------------------------------------------------------------------------
Functions for rational and floating-point numbers
-------------------------------------------------------------------------- | : A Tool for Rigorous Estimation of Round - off Errors
Author : , University of Utah
This file is distributed under the terms of the MIT license
val numerator : Num.num -> Big_int.big_int
val denominator : Num.num -> Big_int.big_int
val num_of_float_string : string -> Num.num
val num_of_float : float -> Num.num
val log_big_int_floor : int -> Big_int.big_int -> int
val string_of_float_lo : int -> float -> string
val string_of_float_hi : int -> float -> string
val is_power_of_two : Num.num -> bool
val is_nan : float -> bool
val is_infinity : float -> bool
val next_float : float -> float
val prev_float : float -> float
val log2_num : Num.num -> int
val float_of_num_lo : Num.num -> float
val float_of_num_hi : Num.num -> float
val interval_of_num : Num.num -> Interval.interval
val interval_of_string : string -> Interval.interval
val check_interval : Interval.interval -> string |
f6fa958479bfa3f55b212f719e5f4cdded806791e1abd30dbdbf5b8628db2f07 | mfikes/fifth-postulate | ns476.cljs | (ns fifth-postulate.ns476)
(defn solve-for01 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for02 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for03 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for04 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for05 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for06 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for07 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for08 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for09 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for10 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for11 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for12 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for13 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for14 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for15 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for16 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for17 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for18 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for19 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
| null | https://raw.githubusercontent.com/mfikes/fifth-postulate/22cfd5f8c2b4a2dead1c15a96295bfeb4dba235e/src/fifth_postulate/ns476.cljs | clojure | (ns fifth-postulate.ns476)
(defn solve-for01 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for02 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for03 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for04 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for05 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for06 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for07 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for08 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for09 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for10 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for11 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for12 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for13 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for14 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for15 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for16 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for17 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for18 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for19 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
| |
786040b8ebe2f55d934ebf3bfb78a9ff11b91ef535fcc6f7717539b7a5aeb2f1 | mbenke/zpf2013 | CsvParse.hs | module MyParsec2a.CsvParse where
import MyParsec2a.Prim
import MyParsec2a.Combinators
A CSV file contains 0 or more lines , each of which is terminated
by the end - of - line character ( eol ) .
by the end-of-line character (eol). -}
csvFile :: Parser [[String]]
csvFile = manyTill line eof
Each line contains 1 or more cells , separated by a comma
line :: Parser [String]
line = cells `endBy` eol
cells = cellContent `sepBy` char ','
-- Each cell contains 0 or more characters, which must not be a comma or
EOL
cellContent :: Parser String
cellContent =
many (noneOf ",\n")
-- The end of line character is \n
eol :: Parser Char
eol = char '\n' | null | https://raw.githubusercontent.com/mbenke/zpf2013/85f32747e17f07a74e1c3cb064b1d6acaca3f2f0/Code/Parse1/MyParsec2a/CsvParse.hs | haskell | Each cell contains 0 or more characters, which must not be a comma or
The end of line character is \n | module MyParsec2a.CsvParse where
import MyParsec2a.Prim
import MyParsec2a.Combinators
A CSV file contains 0 or more lines , each of which is terminated
by the end - of - line character ( eol ) .
by the end-of-line character (eol). -}
csvFile :: Parser [[String]]
csvFile = manyTill line eof
Each line contains 1 or more cells , separated by a comma
line :: Parser [String]
line = cells `endBy` eol
cells = cellContent `sepBy` char ','
EOL
cellContent :: Parser String
cellContent =
many (noneOf ",\n")
eol :: Parser Char
eol = char '\n' |
cd9583a0b2eaf68ee3f29e31d2c2dfb3f30c022ca7276767030b61658e9d42c7 | maximedenes/native-coq | decl_interp.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
open Tacinterp
open Decl_expr
open Mod_subst
val intern_proof_instr : glob_sign -> raw_proof_instr -> glob_proof_instr
val interp_proof_instr : Decl_mode.pm_info ->
Evd.evar_map -> Environ.env -> glob_proof_instr -> proof_instr
| null | https://raw.githubusercontent.com/maximedenes/native-coq/3623a4d9fe95c165f02f7119c0e6564a83a9f4c9/plugins/decl_mode/decl_interp.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
********************************************************************** | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Tacinterp
open Decl_expr
open Mod_subst
val intern_proof_instr : glob_sign -> raw_proof_instr -> glob_proof_instr
val interp_proof_instr : Decl_mode.pm_info ->
Evd.evar_map -> Environ.env -> glob_proof_instr -> proof_instr
|
a6fdf692ae02d3a5524b908deea3728775822360bff0208adb3329a596987b51 | Drup/LILiS | bench_vonkoch.ml | open Benchmark
open Lilis
open Bench_common
let lsystems = [
4, "Von_koch" ;
5, "Von_koch" ;
6, "Von_koch" ;
7, "Von_koch" ;
8, "Von_koch" ;
9, "Von_koch" ;
]
let _ =
execute "bank_lsystem" lsystems all_optims [sequence]
| null | https://raw.githubusercontent.com/Drup/LILiS/df63fbc3ee77b3378ae1ef27715828c3ad892475/test/bench_vonkoch.ml | ocaml | open Benchmark
open Lilis
open Bench_common
let lsystems = [
4, "Von_koch" ;
5, "Von_koch" ;
6, "Von_koch" ;
7, "Von_koch" ;
8, "Von_koch" ;
9, "Von_koch" ;
]
let _ =
execute "bank_lsystem" lsystems all_optims [sequence]
| |
9ae699542c0337aff5a370daa7442b2f0465b011be0c5b55abdcf3483ed56139 | nuprl/gradual-typing-performance | region-typed.rkt | #lang typed/racket
(require "typed-base.rkt"
(prefix-in mred: typed/racket/gui))
(provide region-x region-y region-w region-h set-region-hilite?!
region-paint-callback region-label region-button? region-hilite?
region-callback region-decided-start? region-can-select?
set-region-decided-start?! set-region-can-select?!
region-interactive-callback make-region set-region-callback!)
(require/typed "region.rkt"
[make-region (->* (Real Real Real Real (Option String))
((Option (-> (Listof (Instance Card%)) Any)))
Region)]
[set-region-callback! (-> Region (Option (-> (Listof (Instance Card%)) Any)) Void)]
[region-x (Region -> Real)]
[region-y (Region -> Real)]
[region-w (Region -> Nonnegative-Real)]
[region-h (Region -> Nonnegative-Real)]
[set-region-hilite?! (Region Boolean -> Void)]
[region-paint-callback (Region -> (Option ((Instance mred:DC<%>) Real Real Real Real -> Any)))]
[region-label (Region -> (Option (U String (Instance mred:Bitmap%))))] ; No idea if this is correct or not?
[region-button? (Region -> Boolean)]
[region-hilite? (Region -> Boolean)]
[region-callback (Region -> (Option (case-> (-> Any) ((Listof (Instance Card%)) -> Any))))]
[region-decided-start? (Region -> Boolean)]
[region-can-select? (Region -> Boolean)]
[set-region-decided-start?! (Region Boolean -> Void)]
[set-region-can-select?! (Region Boolean -> Void)]
[region-interactive-callback (Region -> (Option (Boolean (Listof (Instance mred:Snip%)) -> Any)))])
| null | https://raw.githubusercontent.com/nuprl/gradual-typing-performance/35442b3221299a9cadba6810573007736b0d65d4/pre-benchmark/ecoop/benchmarks/gofish/both/region-typed.rkt | racket | No idea if this is correct or not? | #lang typed/racket
(require "typed-base.rkt"
(prefix-in mred: typed/racket/gui))
(provide region-x region-y region-w region-h set-region-hilite?!
region-paint-callback region-label region-button? region-hilite?
region-callback region-decided-start? region-can-select?
set-region-decided-start?! set-region-can-select?!
region-interactive-callback make-region set-region-callback!)
(require/typed "region.rkt"
[make-region (->* (Real Real Real Real (Option String))
((Option (-> (Listof (Instance Card%)) Any)))
Region)]
[set-region-callback! (-> Region (Option (-> (Listof (Instance Card%)) Any)) Void)]
[region-x (Region -> Real)]
[region-y (Region -> Real)]
[region-w (Region -> Nonnegative-Real)]
[region-h (Region -> Nonnegative-Real)]
[set-region-hilite?! (Region Boolean -> Void)]
[region-paint-callback (Region -> (Option ((Instance mred:DC<%>) Real Real Real Real -> Any)))]
[region-button? (Region -> Boolean)]
[region-hilite? (Region -> Boolean)]
[region-callback (Region -> (Option (case-> (-> Any) ((Listof (Instance Card%)) -> Any))))]
[region-decided-start? (Region -> Boolean)]
[region-can-select? (Region -> Boolean)]
[set-region-decided-start?! (Region Boolean -> Void)]
[set-region-can-select?! (Region Boolean -> Void)]
[region-interactive-callback (Region -> (Option (Boolean (Listof (Instance mred:Snip%)) -> Any)))])
|
fe036a7c68212880a85afa34f187e2df6dffe3156445808cdf9542aad59c4775 | expipiplus1/vulkan | VK_KHR_depth_stencil_resolve.hs | {-# language CPP #-}
-- | = Name
--
-- VK_KHR_depth_stencil_resolve - device extension
--
-- == VK_KHR_depth_stencil_resolve
--
-- [__Name String__]
-- @VK_KHR_depth_stencil_resolve@
--
-- [__Extension Type__]
-- Device extension
--
-- [__Registered Extension Number__]
200
--
-- [__Revision__]
1
--
-- [__Extension and Version Dependencies__]
--
- Requires support for Vulkan 1.0
--
-- - Requires @VK_KHR_create_renderpass2@ to be enabled for any
-- device-level functionality
--
-- [__Deprecation state__]
--
-- - /Promoted/ to
-- <-extensions/html/vkspec.html#versions-1.2-promotions Vulkan 1.2>
--
-- [__Contact__]
--
- Jan -
< -Docs/issues/new?body=[VK_KHR_depth_stencil_resolve ] @janharald%0A*Here describe the issue or question you have about the extension * >
--
-- == Other Extension Metadata
--
-- [__Last Modified Date__]
2018 - 04 - 09
--
-- [__Interactions and External Dependencies__]
--
- Promoted to Vulkan 1.2 Core
--
-- [__Contributors__]
--
- Jan - , Arm
--
- , Samsung Electronics
--
- Soowan Park , Samsung Electronics
--
- , NVIDIA
--
- , AMD
--
-- == Description
--
-- This extension adds support for automatically resolving multisampled
depth\/stencil attachments in a subpass in a similar manner as for color
-- attachments.
--
Multisampled color attachments can be resolved at the end of a subpass
-- by specifying @pResolveAttachments@ entries corresponding to the
-- @pColorAttachments@ array entries. This does not allow for a way to map
the resolve attachments to the depth\/stencil attachment . The
' Vulkan . Core10.CommandBufferBuilding.cmdResolveImage ' command does not
allow for depth\/stencil images . While there are other ways to resolve
the depth\/stencil attachment , they can give sub - optimal performance .
-- Extending the
' Vulkan . Core12.Promoted_From_VK_KHR_create_renderpass2.SubpassDescription2 '
-- in this extension allows an application to add a
@pDepthStencilResolveAttachment@ , that is similar to the color
@pResolveAttachments@ , that the @pDepthStencilAttachment@ can be
-- resolved into.
--
-- Depth and stencil samples are resolved to a single value based on the
-- resolve mode. The set of possible resolve modes is defined in the
' Vulkan . . . ' enum . The
' Vulkan . . ResolveModeFlagBits . RESOLVE_MODE_SAMPLE_ZERO_BIT '
-- mode is the only mode that is required of all implementations (that
support the extension or support Vulkan 1.2 or higher ) . Some
-- implementations may also support averaging (the same as color sample
-- resolve) or taking the minimum or maximum sample, which may be more
suitable for depth\/stencil resolve .
--
= = Promotion to Vulkan 1.2
--
All functionality in this extension is included in core Vulkan 1.2 , with
the suffix omitted . The original type , enum and command names are
-- still available as aliases of the core functionality.
--
-- == New Structures
--
-- - Extending
' Vulkan . ' :
--
-- - 'PhysicalDeviceDepthStencilResolvePropertiesKHR'
--
-- - Extending
' Vulkan . Core12.Promoted_From_VK_KHR_create_renderpass2.SubpassDescription2 ' :
--
-- - 'SubpassDescriptionDepthStencilResolveKHR'
--
-- == New Enums
--
-- - 'ResolveModeFlagBitsKHR'
--
-- == New Bitmasks
--
- ' ResolveModeFlagsKHR '
--
-- == New Enum Constants
--
-- - 'KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME'
--
- ' KHR_DEPTH_STENCIL_RESOLVE_SPEC_VERSION '
--
-- - Extending
' Vulkan . . . ' :
--
-- - 'RESOLVE_MODE_AVERAGE_BIT_KHR'
--
-- - 'RESOLVE_MODE_MAX_BIT_KHR'
--
-- - 'RESOLVE_MODE_MIN_BIT_KHR'
--
- ' RESOLVE_MODE_NONE_KHR '
--
-- - 'RESOLVE_MODE_SAMPLE_ZERO_BIT_KHR'
--
- Extending ' Vulkan . Core10.Enums . StructureType . StructureType ' :
--
- ' '
--
-- - 'STRUCTURE_TYPE_SUBPASS_DESCRIPTION_DEPTH_STENCIL_RESOLVE_KHR'
--
-- == Version History
--
- Revision 1 , 2018 - 04 - 09 ( Jan - )
--
-- - Initial revision
--
-- == See Also
--
-- 'PhysicalDeviceDepthStencilResolvePropertiesKHR',
' ResolveModeFlagBitsKHR ' , ' ResolveModeFlagsKHR ' ,
-- 'SubpassDescriptionDepthStencilResolveKHR'
--
-- == Document Notes
--
-- For more information, see the
-- <-extensions/html/vkspec.html#VK_KHR_depth_stencil_resolve Vulkan Specification>
--
-- This page is a generated document. Fixes and changes should be made to
-- the generator scripts, not directly.
module Vulkan.Extensions.VK_KHR_depth_stencil_resolve ( pattern STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_STENCIL_RESOLVE_PROPERTIES_KHR
, pattern STRUCTURE_TYPE_SUBPASS_DESCRIPTION_DEPTH_STENCIL_RESOLVE_KHR
, pattern RESOLVE_MODE_NONE_KHR
, pattern RESOLVE_MODE_SAMPLE_ZERO_BIT_KHR
, pattern RESOLVE_MODE_AVERAGE_BIT_KHR
, pattern RESOLVE_MODE_MIN_BIT_KHR
, pattern RESOLVE_MODE_MAX_BIT_KHR
, ResolveModeFlagsKHR
, ResolveModeFlagBitsKHR
, PhysicalDeviceDepthStencilResolvePropertiesKHR
, SubpassDescriptionDepthStencilResolveKHR
, KHR_DEPTH_STENCIL_RESOLVE_SPEC_VERSION
, pattern KHR_DEPTH_STENCIL_RESOLVE_SPEC_VERSION
, KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME
, pattern KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME
) where
import Data.String (IsString)
import Vulkan.Core12.Promoted_From_VK_KHR_depth_stencil_resolve (PhysicalDeviceDepthStencilResolveProperties)
import Vulkan.Core12.Enums.ResolveModeFlagBits (ResolveModeFlagBits)
import Vulkan.Core12.Enums.ResolveModeFlagBits (ResolveModeFlags)
import Vulkan.Core12.Promoted_From_VK_KHR_depth_stencil_resolve (SubpassDescriptionDepthStencilResolve)
import Vulkan.Core12.Enums.ResolveModeFlagBits (ResolveModeFlags)
import Vulkan.Core12.Enums.ResolveModeFlagBits (ResolveModeFlagBits(RESOLVE_MODE_AVERAGE_BIT))
import Vulkan.Core12.Enums.ResolveModeFlagBits (ResolveModeFlags)
import Vulkan.Core12.Enums.ResolveModeFlagBits (ResolveModeFlagBits(RESOLVE_MODE_MAX_BIT))
import Vulkan.Core12.Enums.ResolveModeFlagBits (ResolveModeFlags)
import Vulkan.Core12.Enums.ResolveModeFlagBits (ResolveModeFlagBits(RESOLVE_MODE_MIN_BIT))
import Vulkan.Core12.Enums.ResolveModeFlagBits (ResolveModeFlags)
import Vulkan.Core12.Enums.ResolveModeFlagBits (ResolveModeFlagBits(RESOLVE_MODE_NONE))
import Vulkan.Core12.Enums.ResolveModeFlagBits (ResolveModeFlags)
import Vulkan.Core12.Enums.ResolveModeFlagBits (ResolveModeFlagBits(RESOLVE_MODE_SAMPLE_ZERO_BIT))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_STENCIL_RESOLVE_PROPERTIES))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_SUBPASS_DESCRIPTION_DEPTH_STENCIL_RESOLVE))
No documentation found for TopLevel " VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_STENCIL_RESOLVE_PROPERTIES_KHR "
pattern STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_STENCIL_RESOLVE_PROPERTIES_KHR = STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_STENCIL_RESOLVE_PROPERTIES
No documentation found for TopLevel " VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_DEPTH_STENCIL_RESOLVE_KHR "
pattern STRUCTURE_TYPE_SUBPASS_DESCRIPTION_DEPTH_STENCIL_RESOLVE_KHR = STRUCTURE_TYPE_SUBPASS_DESCRIPTION_DEPTH_STENCIL_RESOLVE
No documentation found for TopLevel " VK_RESOLVE_MODE_NONE_KHR "
pattern RESOLVE_MODE_NONE_KHR = RESOLVE_MODE_NONE
No documentation found for TopLevel " VK_RESOLVE_MODE_SAMPLE_ZERO_BIT_KHR "
pattern RESOLVE_MODE_SAMPLE_ZERO_BIT_KHR = RESOLVE_MODE_SAMPLE_ZERO_BIT
No documentation found for TopLevel " VK_RESOLVE_MODE_AVERAGE_BIT_KHR "
pattern RESOLVE_MODE_AVERAGE_BIT_KHR = RESOLVE_MODE_AVERAGE_BIT
No documentation found for TopLevel " VK_RESOLVE_MODE_MIN_BIT_KHR "
pattern RESOLVE_MODE_MIN_BIT_KHR = RESOLVE_MODE_MIN_BIT
No documentation found for TopLevel " VK_RESOLVE_MODE_MAX_BIT_KHR "
pattern RESOLVE_MODE_MAX_BIT_KHR = RESOLVE_MODE_MAX_BIT
No documentation found for TopLevel " VkResolveModeFlagsKHR "
type ResolveModeFlagsKHR = ResolveModeFlags
No documentation found for TopLevel " VkResolveModeFlagBitsKHR "
type ResolveModeFlagBitsKHR = ResolveModeFlagBits
No documentation found for TopLevel " VkPhysicalDeviceDepthStencilResolvePropertiesKHR "
type PhysicalDeviceDepthStencilResolvePropertiesKHR = PhysicalDeviceDepthStencilResolveProperties
No documentation found for TopLevel " VkSubpassDescriptionDepthStencilResolveKHR "
type SubpassDescriptionDepthStencilResolveKHR = SubpassDescriptionDepthStencilResolve
type KHR_DEPTH_STENCIL_RESOLVE_SPEC_VERSION = 1
No documentation found for TopLevel " VK_KHR_DEPTH_STENCIL_RESOLVE_SPEC_VERSION "
pattern KHR_DEPTH_STENCIL_RESOLVE_SPEC_VERSION :: forall a . Integral a => a
pattern KHR_DEPTH_STENCIL_RESOLVE_SPEC_VERSION = 1
type KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME = "VK_KHR_depth_stencil_resolve"
No documentation found for TopLevel " VK_KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME "
pattern KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a
pattern KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME = "VK_KHR_depth_stencil_resolve"
| null | https://raw.githubusercontent.com/expipiplus1/vulkan/b1e33d1031779b4740c279c68879d05aee371659/src/Vulkan/Extensions/VK_KHR_depth_stencil_resolve.hs | haskell | # language CPP #
| = Name
VK_KHR_depth_stencil_resolve - device extension
== VK_KHR_depth_stencil_resolve
[__Name String__]
@VK_KHR_depth_stencil_resolve@
[__Extension Type__]
Device extension
[__Registered Extension Number__]
[__Revision__]
[__Extension and Version Dependencies__]
- Requires @VK_KHR_create_renderpass2@ to be enabled for any
device-level functionality
[__Deprecation state__]
- /Promoted/ to
<-extensions/html/vkspec.html#versions-1.2-promotions Vulkan 1.2>
[__Contact__]
== Other Extension Metadata
[__Last Modified Date__]
[__Interactions and External Dependencies__]
[__Contributors__]
== Description
This extension adds support for automatically resolving multisampled
attachments.
by specifying @pResolveAttachments@ entries corresponding to the
@pColorAttachments@ array entries. This does not allow for a way to map
Extending the
in this extension allows an application to add a
resolved into.
Depth and stencil samples are resolved to a single value based on the
resolve mode. The set of possible resolve modes is defined in the
mode is the only mode that is required of all implementations (that
implementations may also support averaging (the same as color sample
resolve) or taking the minimum or maximum sample, which may be more
still available as aliases of the core functionality.
== New Structures
- Extending
- 'PhysicalDeviceDepthStencilResolvePropertiesKHR'
- Extending
- 'SubpassDescriptionDepthStencilResolveKHR'
== New Enums
- 'ResolveModeFlagBitsKHR'
== New Bitmasks
== New Enum Constants
- 'KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME'
- Extending
- 'RESOLVE_MODE_AVERAGE_BIT_KHR'
- 'RESOLVE_MODE_MAX_BIT_KHR'
- 'RESOLVE_MODE_MIN_BIT_KHR'
- 'RESOLVE_MODE_SAMPLE_ZERO_BIT_KHR'
- 'STRUCTURE_TYPE_SUBPASS_DESCRIPTION_DEPTH_STENCIL_RESOLVE_KHR'
== Version History
- Initial revision
== See Also
'PhysicalDeviceDepthStencilResolvePropertiesKHR',
'SubpassDescriptionDepthStencilResolveKHR'
== Document Notes
For more information, see the
<-extensions/html/vkspec.html#VK_KHR_depth_stencil_resolve Vulkan Specification>
This page is a generated document. Fixes and changes should be made to
the generator scripts, not directly. | 200
1
- Requires support for Vulkan 1.0
- Jan -
< -Docs/issues/new?body=[VK_KHR_depth_stencil_resolve ] @janharald%0A*Here describe the issue or question you have about the extension * >
2018 - 04 - 09
- Promoted to Vulkan 1.2 Core
- Jan - , Arm
- , Samsung Electronics
- Soowan Park , Samsung Electronics
- , NVIDIA
- , AMD
depth\/stencil attachments in a subpass in a similar manner as for color
Multisampled color attachments can be resolved at the end of a subpass
the resolve attachments to the depth\/stencil attachment . The
' Vulkan . Core10.CommandBufferBuilding.cmdResolveImage ' command does not
allow for depth\/stencil images . While there are other ways to resolve
the depth\/stencil attachment , they can give sub - optimal performance .
' Vulkan . Core12.Promoted_From_VK_KHR_create_renderpass2.SubpassDescription2 '
@pDepthStencilResolveAttachment@ , that is similar to the color
@pResolveAttachments@ , that the @pDepthStencilAttachment@ can be
' Vulkan . . . ' enum . The
' Vulkan . . ResolveModeFlagBits . RESOLVE_MODE_SAMPLE_ZERO_BIT '
support the extension or support Vulkan 1.2 or higher ) . Some
suitable for depth\/stencil resolve .
= = Promotion to Vulkan 1.2
All functionality in this extension is included in core Vulkan 1.2 , with
the suffix omitted . The original type , enum and command names are
' Vulkan . ' :
' Vulkan . Core12.Promoted_From_VK_KHR_create_renderpass2.SubpassDescription2 ' :
- ' ResolveModeFlagsKHR '
- ' KHR_DEPTH_STENCIL_RESOLVE_SPEC_VERSION '
' Vulkan . . . ' :
- ' RESOLVE_MODE_NONE_KHR '
- Extending ' Vulkan . Core10.Enums . StructureType . StructureType ' :
- ' '
- Revision 1 , 2018 - 04 - 09 ( Jan - )
' ResolveModeFlagBitsKHR ' , ' ResolveModeFlagsKHR ' ,
module Vulkan.Extensions.VK_KHR_depth_stencil_resolve ( pattern STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_STENCIL_RESOLVE_PROPERTIES_KHR
, pattern STRUCTURE_TYPE_SUBPASS_DESCRIPTION_DEPTH_STENCIL_RESOLVE_KHR
, pattern RESOLVE_MODE_NONE_KHR
, pattern RESOLVE_MODE_SAMPLE_ZERO_BIT_KHR
, pattern RESOLVE_MODE_AVERAGE_BIT_KHR
, pattern RESOLVE_MODE_MIN_BIT_KHR
, pattern RESOLVE_MODE_MAX_BIT_KHR
, ResolveModeFlagsKHR
, ResolveModeFlagBitsKHR
, PhysicalDeviceDepthStencilResolvePropertiesKHR
, SubpassDescriptionDepthStencilResolveKHR
, KHR_DEPTH_STENCIL_RESOLVE_SPEC_VERSION
, pattern KHR_DEPTH_STENCIL_RESOLVE_SPEC_VERSION
, KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME
, pattern KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME
) where
import Data.String (IsString)
import Vulkan.Core12.Promoted_From_VK_KHR_depth_stencil_resolve (PhysicalDeviceDepthStencilResolveProperties)
import Vulkan.Core12.Enums.ResolveModeFlagBits (ResolveModeFlagBits)
import Vulkan.Core12.Enums.ResolveModeFlagBits (ResolveModeFlags)
import Vulkan.Core12.Promoted_From_VK_KHR_depth_stencil_resolve (SubpassDescriptionDepthStencilResolve)
import Vulkan.Core12.Enums.ResolveModeFlagBits (ResolveModeFlags)
import Vulkan.Core12.Enums.ResolveModeFlagBits (ResolveModeFlagBits(RESOLVE_MODE_AVERAGE_BIT))
import Vulkan.Core12.Enums.ResolveModeFlagBits (ResolveModeFlags)
import Vulkan.Core12.Enums.ResolveModeFlagBits (ResolveModeFlagBits(RESOLVE_MODE_MAX_BIT))
import Vulkan.Core12.Enums.ResolveModeFlagBits (ResolveModeFlags)
import Vulkan.Core12.Enums.ResolveModeFlagBits (ResolveModeFlagBits(RESOLVE_MODE_MIN_BIT))
import Vulkan.Core12.Enums.ResolveModeFlagBits (ResolveModeFlags)
import Vulkan.Core12.Enums.ResolveModeFlagBits (ResolveModeFlagBits(RESOLVE_MODE_NONE))
import Vulkan.Core12.Enums.ResolveModeFlagBits (ResolveModeFlags)
import Vulkan.Core12.Enums.ResolveModeFlagBits (ResolveModeFlagBits(RESOLVE_MODE_SAMPLE_ZERO_BIT))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_STENCIL_RESOLVE_PROPERTIES))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_SUBPASS_DESCRIPTION_DEPTH_STENCIL_RESOLVE))
No documentation found for TopLevel " VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_STENCIL_RESOLVE_PROPERTIES_KHR "
pattern STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_STENCIL_RESOLVE_PROPERTIES_KHR = STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_STENCIL_RESOLVE_PROPERTIES
No documentation found for TopLevel " VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_DEPTH_STENCIL_RESOLVE_KHR "
pattern STRUCTURE_TYPE_SUBPASS_DESCRIPTION_DEPTH_STENCIL_RESOLVE_KHR = STRUCTURE_TYPE_SUBPASS_DESCRIPTION_DEPTH_STENCIL_RESOLVE
No documentation found for TopLevel " VK_RESOLVE_MODE_NONE_KHR "
pattern RESOLVE_MODE_NONE_KHR = RESOLVE_MODE_NONE
No documentation found for TopLevel " VK_RESOLVE_MODE_SAMPLE_ZERO_BIT_KHR "
pattern RESOLVE_MODE_SAMPLE_ZERO_BIT_KHR = RESOLVE_MODE_SAMPLE_ZERO_BIT
No documentation found for TopLevel " VK_RESOLVE_MODE_AVERAGE_BIT_KHR "
pattern RESOLVE_MODE_AVERAGE_BIT_KHR = RESOLVE_MODE_AVERAGE_BIT
No documentation found for TopLevel " VK_RESOLVE_MODE_MIN_BIT_KHR "
pattern RESOLVE_MODE_MIN_BIT_KHR = RESOLVE_MODE_MIN_BIT
No documentation found for TopLevel " VK_RESOLVE_MODE_MAX_BIT_KHR "
pattern RESOLVE_MODE_MAX_BIT_KHR = RESOLVE_MODE_MAX_BIT
No documentation found for TopLevel " VkResolveModeFlagsKHR "
type ResolveModeFlagsKHR = ResolveModeFlags
No documentation found for TopLevel " VkResolveModeFlagBitsKHR "
type ResolveModeFlagBitsKHR = ResolveModeFlagBits
No documentation found for TopLevel " VkPhysicalDeviceDepthStencilResolvePropertiesKHR "
type PhysicalDeviceDepthStencilResolvePropertiesKHR = PhysicalDeviceDepthStencilResolveProperties
No documentation found for TopLevel " VkSubpassDescriptionDepthStencilResolveKHR "
type SubpassDescriptionDepthStencilResolveKHR = SubpassDescriptionDepthStencilResolve
type KHR_DEPTH_STENCIL_RESOLVE_SPEC_VERSION = 1
No documentation found for TopLevel " VK_KHR_DEPTH_STENCIL_RESOLVE_SPEC_VERSION "
pattern KHR_DEPTH_STENCIL_RESOLVE_SPEC_VERSION :: forall a . Integral a => a
pattern KHR_DEPTH_STENCIL_RESOLVE_SPEC_VERSION = 1
type KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME = "VK_KHR_depth_stencil_resolve"
No documentation found for TopLevel " VK_KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME "
pattern KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a
pattern KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME = "VK_KHR_depth_stencil_resolve"
|
0d675f0befe1c9798c5fcda1f0064e454e317e7ca7493da42e4095c9a1ea8b8c | jochu/swank-clojure | sockets.clj | Requires clojure 1.1 ( currently in alpha )
(ns swank.test-swank.util.net.sockets
(:import (java.net ServerSocket Socket InetSocketAddress))
(:use clojure.test
swank.util.net.sockets))
(deftest making-server
(are [x] (with-open [socket x]
(instance? ServerSocket x))
(make-server-socket)
(make-server-socket {:backlog 10})
(make-server-socket {:host "localhost"})))
;; Testing of connection (ought to do object mocks) | null | https://raw.githubusercontent.com/jochu/swank-clojure/b08daf866488b449a44ba8df6e5ae17a3515ef57/test/swank/test_swank/util/net/sockets.clj | clojure | Testing of connection (ought to do object mocks) | Requires clojure 1.1 ( currently in alpha )
(ns swank.test-swank.util.net.sockets
(:import (java.net ServerSocket Socket InetSocketAddress))
(:use clojure.test
swank.util.net.sockets))
(deftest making-server
(are [x] (with-open [socket x]
(instance? ServerSocket x))
(make-server-socket)
(make-server-socket {:backlog 10})
(make-server-socket {:host "localhost"})))
|
165cec2e4229a3945cc978ef6a38000c8fbcab98c33448b60de55ad97e847de4 | nvim-treesitter/nvim-treesitter | locals.scm | ; HEEx tags, components, and slots are references
[
(component_name)
(slot_name)
(tag_name)
] @reference
; Create a new scope within each HEEx tag, component, and slot
[
(component)
(slot)
(tag)
] @scope
| null | https://raw.githubusercontent.com/nvim-treesitter/nvim-treesitter/083aee08735fd5dcd02ef72d831b054244db73a4/queries/heex/locals.scm | scheme | HEEx tags, components, and slots are references
Create a new scope within each HEEx tag, component, and slot | [
(component_name)
(slot_name)
(tag_name)
] @reference
[
(component)
(slot)
(tag)
] @scope
|
e0dd0e3d2f04f5c8f42875d2f70d84c35791863b3e83e7eeb671c16eaa96aadf | janestreet/lwt-async | lwt_term.mli | Lightweight thread library for
* Module Lwt_term
* Copyright ( C ) 2009
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation , with linking exceptions ;
* either version 2.1 of the License , or ( at your option ) any later
* version . See COPYING file for details .
*
* This program is distributed in the hope that it will be useful , but
* WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
* Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA
* 02111 - 1307 , USA .
*
* Module Lwt_term
* Copyright (C) 2009 Jérémie Dimino
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, with linking exceptions;
* either version 2.1 of the License, or (at your option) any later
* version. See COPYING file for details.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*)
(** Terminal control *)
(** This modules allow you to write interactive programs using the
terminal. *)
val with_raw_mode : (unit -> 'a Lwt.t) -> 'a Lwt.t
(** [with_raw_mode f] executes [f] while the terminal is in ``raw
mode''. Raw mode means that character are returned as the user
type them (otherwise only complete line are returned to the
program).
If the terminal is already in raw mode, it just calls [f]. *)
val raw_mode : unit -> bool
(** Returns wether the terminal is currently in raw mode *)
val enter_drawing_mode : unit -> unit Lwt.t
(** Put the terminal into drawing mode *)
val leave_drawing_mode : unit -> unit Lwt.t
(** Restore the state of the terminal *)
val show_cursor : unit -> unit Lwt.t
* [ ( ) ] makes the cursor visible
val hide_cursor : unit -> unit Lwt.t
(** [hide_cursor ()] makes the cursor invisible *)
val clear_screen : unit -> unit Lwt.t
(** [clear_screen ()] clears the entire screen *)
val clear_line : unit -> unit Lwt.t
(** [clear_line ()] clears the current line *)
val goto_beginning_of_line : int -> unit Lwt.t
* [ goto_beginning_of_line n ] put the cursor at the beginning of
the [ n]th previous line .
- [ goto_beginning_of_line 0 ] goes to the beginning of the current line
- [ goto_beginning_of_line 1 ] goes to the beginning of the previous line
- ...
the [n]th previous line.
- [goto_beginning_of_line 0] goes to the beginning of the current line
- [goto_beginning_of_line 1] goes to the beginning of the previous line
- ...
*)
* { 6 Terminal informations }
(** Terminal sizes: *)
type size = {
lines : int;
columns : int;
}
val size : size React.signal
(** Size of the terminal. *)
val columns : int React.signal
(** Number of columns of the terminal *)
val lines : int React.signal
(** Number of lines of the terminal *)
* { 6 Keys }
val parse_key_raw : Text.t Lwt_stream.t -> Text.t Lwt.t
(** [parse_key_raw st] recognize escape sequence in a stream of
unicode character.
It returns either:
- either single characters, like ["a"], ["é"], ...
- either escape sequences
*)
(** Type of ``decoded'' keys.
This list is not exhaustive, but at least it should works on all
terminals: *)
type key =
| Key of Text.t
(** A unicode character or an uninterpreted sequence *)
| Key_up
| Key_down
| Key_left
| Key_right
| Key_f of int
| Key_next_page
| Key_previous_page
| Key_home
| Key_end
| Key_insert
| Key_delete
| Key_control of char
(** A control key *)
val string_of_key : key -> string
(** [string_of_key key] string representation of a key *)
val control_mapping : (int * char) list
* Mapping from control key codes to character codes .
Here is the list of control keys :
{ [
+ ------+-------+------+------+------+-------+------------------------------------------------+
| Char | Oct | Dec | Name | Hex | Key | Comment |
+ ------+-------+------+------+------+-------+------------------------------------------------+
| ' @ ' | 0o00 | 0 | NUL | 0x00 | ^@ \0 | Null byte |
| ' a ' | 0o01 | 1 | SOH | 0x01 | ^A | Start of heading |
| ' b ' | 0o02 | 2 | STX | 0x02 | ^B | Start of text |
| ' c ' | 0o03 | 3 | ETX | 0x03 | ^C | End of text |
| 'd ' | 0o04 | 4 | EOT | 0x04 | ^D | End of transmission |
| ' e ' | 0o05 | 5 | ENQ | 0x05 | ^E | Enquiry |
| ' f ' | 0o06 | 6 | ACK | 0x06 | ^F | Acknowledge |
| ' g ' | 0o07 | 7 | BEL | 0x07 | ^G | Ring terminal bell |
| ' h ' | 0o10 | 8 | BS | 0x08 | Backspace |
| ' i ' | 0o11 | 9 | HT | 0x09 | ^I \t | Horizontal tab |
| ' j ' | 0o12 | 10 | LF | 0x0a | ^J \n | Line feed |
| ' k ' | 0o13 | 11 | VT | 0x0b | ^K | Vertical tab |
| ' l ' | 0o14 | 12 | FF | 0x0c | ^L \f | Form feed |
| ' m ' | 0o15 | 13 | CR | 0x0d | ^M \r | Carriage return |
| ' n ' | 0o16 | 14 | SO | 0x0e | ^N | Shift out |
| ' o ' | 0o17 | 15 | SI | 0x0f | ^O | Shift in |
| ' p ' | 0o20 | 16 | DLE | 0x10 | ^P | Data link escape |
| ' q ' | 0o21 | 17 | DC1 | 0x11 | ^Q | Device control 1 ( ) |
| ' r ' | 0o22 | 18 | DC2 | 0x12 | ^R | Device control 2 |
| 's ' | 0o23 | 19 | DC3 | 0x13 | ^S | Device control 3 ( XOFF ) |
| ' t ' | 0o24 | 20 | DC4 | 0x14 | ^T | Device control 4 |
| ' u ' | 0o25 | 21 | NAK | 0x15 | ^U | Negative acknowledge |
| ' v ' | 0o26 | 22 | SYN | 0x16 | ^V | Synchronous idle |
| ' w ' | 0o27 | 23 ETB | 0x17 | ^W | End of transmission block |
| ' x ' | 0o30 | 24 | CAN | 0x18 | ^X | Cancel |
| ' y ' | 0o31 | 25 | EM | 0x19 | ^Y | End of medium |
| ' z ' | 0o32 | 26 | SUB | 0x1a | ^Z | Substitute character |
| ' [ ' | 0o33 | 27 | ESC | 0x1b | ^ [ | Escape |
| ' \ ' | 0o34 | 28 | FS | 0x1c | ^\ | File separator , Information separator four |
| ' ] ' | 0o35 | 29 | GS | 0x1d | ^ ] | Group separator , Information separator three |
| ' ^ ' | 0o36 | 30 | RS | 0x1e | ^^ | Record separator , Information separator two |
| ' _ ' | 0o37 | 31 | US | 0x1f | ^ _ | Unit separator , Information separator one |
| ' ? ' | 0o177 | 127 | DEL | 0x7f | ^ ? | Delete |
+ ------+-------+------+------+------+-------+------------------------------------------------+
] }
Here is the list of control keys:
{[
+------+-------+------+------+------+-------+------------------------------------------------+
| Char | Oct | Dec | Name | Hex | Key | Comment |
+------+-------+------+------+------+-------+------------------------------------------------+
| '@' | 0o00 | 0 | NUL | 0x00 | ^@ \0 | Null byte |
| 'a' | 0o01 | 1 | SOH | 0x01 | ^A | Start of heading |
| 'b' | 0o02 | 2 | STX | 0x02 | ^B | Start of text |
| 'c' | 0o03 | 3 | ETX | 0x03 | ^C | End of text |
| 'd' | 0o04 | 4 | EOT | 0x04 | ^D | End of transmission |
| 'e' | 0o05 | 5 | ENQ | 0x05 | ^E | Enquiry |
| 'f' | 0o06 | 6 | ACK | 0x06 | ^F | Acknowledge |
| 'g' | 0o07 | 7 | BEL | 0x07 | ^G | Ring terminal bell |
| 'h' | 0o10 | 8 | BS | 0x08 | ^H \b | Backspace |
| 'i' | 0o11 | 9 | HT | 0x09 | ^I \t | Horizontal tab |
| 'j' | 0o12 | 10 | LF | 0x0a | ^J \n | Line feed |
| 'k' | 0o13 | 11 | VT | 0x0b | ^K | Vertical tab |
| 'l' | 0o14 | 12 | FF | 0x0c | ^L \f | Form feed |
| 'm' | 0o15 | 13 | CR | 0x0d | ^M \r | Carriage return |
| 'n' | 0o16 | 14 | SO | 0x0e | ^N | Shift out |
| 'o' | 0o17 | 15 | SI | 0x0f | ^O | Shift in |
| 'p' | 0o20 | 16 | DLE | 0x10 | ^P | Data link escape |
| 'q' | 0o21 | 17 | DC1 | 0x11 | ^Q | Device control 1 (XON) |
| 'r' | 0o22 | 18 | DC2 | 0x12 | ^R | Device control 2 |
| 's' | 0o23 | 19 | DC3 | 0x13 | ^S | Device control 3 (XOFF) |
| 't' | 0o24 | 20 | DC4 | 0x14 | ^T | Device control 4 |
| 'u' | 0o25 | 21 | NAK | 0x15 | ^U | Negative acknowledge |
| 'v' | 0o26 | 22 | SYN | 0x16 | ^V | Synchronous idle |
| 'w' | 0o27 | 23 | ETB | 0x17 | ^W | End of transmission block |
| 'x' | 0o30 | 24 | CAN | 0x18 | ^X | Cancel |
| 'y' | 0o31 | 25 | EM | 0x19 | ^Y | End of medium |
| 'z' | 0o32 | 26 | SUB | 0x1a | ^Z | Substitute character |
| '[' | 0o33 | 27 | ESC | 0x1b | ^[ | Escape |
| '\' | 0o34 | 28 | FS | 0x1c | ^\ | File separator, Information separator four |
| ']' | 0o35 | 29 | GS | 0x1d | ^] | Group separator, Information separator three |
| '^' | 0o36 | 30 | RS | 0x1e | ^^ | Record separator, Information separator two |
| '_' | 0o37 | 31 | US | 0x1f | ^_ | Unit separator, Information separator one |
| '?' | 0o177 | 127 | DEL | 0x7f | ^? | Delete |
+------+-------+------+------+------+-------+------------------------------------------------+
]}
*)
val key_enter : key
* [ key_enter = Key_control ' j ' ]
val key_escape : key
* [ key_escape = Key_control ' \ [ ' ]
val key_tab : key
* [ key_escape = Key_control ' i ' ]
val key_backspace : key
* [ key_backspace = Key_control ' ? ' ]
val sequence_mapping : (Text.t * key) list
(** Mapping from sequence to keys *)
val decode_key : Text.t -> key
(** Decode a key. *)
val standard_input : Text.t Lwt_stream.t
(** The input stream used by {!read_key} *)
val read_key : unit -> key Lwt.t
* Get and decode a key from { ! }
* { 6 Styles }
type color = int
* Type of a color . Most modern terminals support either 88 or
256 colors .
256 colors. *)
val set_color : color -> int * int * int -> unit Lwt.t
* [ set_color num ( red , green , blue ) ] sets the three components of
the color number [ num ]
the color number [num] *)
* { 8 Standard colors }
val default : color
val black : color
val red : color
val green : color
val yellow : color
val blue : color
val magenta : color
val cyan : color
val white : color
* { 8 Light colors }
(** Note: these colors are not supposed to works on all terminals, but
in practice it works with all modern ones. By the way, using
standard colors + bold mode will give the same result as using a
light color. *)
val lblack : color
val lred : color
val lgreen : color
val lyellow : color
val lblue : color
val lmagenta : color
val lcyan : color
val lwhite : color
* { 8 Text with styles }
(** Elmement of a styled-text *)
type styled_text_instruction =
| Text of Text.t
(** Some text *)
| Reset
(** Resets all styles to default *)
| Bold
| Underlined
| Blink
| Inverse
| Hidden
| Foreground of color
| Background of color
type styled_text = styled_text_instruction list
(** A styled text is a list of instructions *)
val textf : ('a, unit, string, styled_text_instruction) format4 -> 'a
(** [textf fmt] formats a texts with [fmt] and returns [Text txt] *)
val text : Text.t -> styled_text_instruction
val reset : styled_text_instruction
val bold : styled_text_instruction
val underlined : styled_text_instruction
val blink : styled_text_instruction
val inverse : styled_text_instruction
val hidden : styled_text_instruction
val fg : color -> styled_text_instruction
(** [fg col = Foreground col] *)
val bg : color -> styled_text_instruction
(** [bg col = Background col] *)
val strip_styles : styled_text -> Text.t
(** Drop all styles *)
val styled_length : styled_text -> int
* Returns the length ( in unicode character ) of the given styled
text . The following equality holds for all styled - texts :
[ styled_length st = Text.length ( strip_styles st ) ]
text. The following equality holds for all styled-texts:
[styled_length st = Text.length (strip_styles st)]
*)
val write_styled : Lwt_text.output_channel -> styled_text -> unit Lwt.t
(** [write_styled oc st] writes [st] on [oc] using escape
sequences. *)
val printc : styled_text -> unit Lwt.t
* [ printc st ] prints the given styled text on standard output . If
stdout is not a tty , then styles are stripped .
The text is encoded to the system encoding before being
output .
stdout is not a tty, then styles are stripped.
The text is encoded to the system encoding before being
output. *)
val eprintc : styled_text -> unit Lwt.t
(** Same as [printc] but prints on stderr. *)
val printlc : styled_text -> unit Lwt.t
(** [printlc st] prints [st], then reset styles and prints a
newline *)
val eprintlc : styled_text -> unit Lwt.t
(** Same as [printlc] but prints on stderr *)
* { 6 Rendering }
(** Character styles *)
type style = {
bold : bool;
underlined : bool;
blink : bool;
inverse : bool;
hidden : bool;
foreground : color;
background : color;
}
(** A character on the screen: *)
type point = {
char : Text.t;
(** The character. *)
style : style;
(** The character style *)
}
val blank : point
(** A space with default color and styles *)
val render : point array array -> unit Lwt.t
(** Render an offscreen array to the terminal. *)
val render_update : point array array -> point array array -> unit Lwt.t
(** [render_update displayed to_display] does the same as [render
to_display] but assumes that [displayed] contains the current
displayed text. This reduces the amount of text sent to the
terminal. *)
(** {6 Drawing} *)
(** Off-screen zones *)
module Zone : sig
type t = {
points : point array array;
(** The off-screen matrix *)
x : int;
y : int;
(** Absolute coordinates of the top-left corner of the zone *)
width : int;
height : int;
(** Dimmensions of the zone *)
}
val points : t -> point array array
val x : t -> int
val y : t -> int
val width : t -> int
val height : t -> int
val make : width : int -> height : int -> t
(** Make a new zone where all points are initialized to
{!blank} *)
val sub : zone : t -> x : int -> y : int -> width : int -> height : int -> t
* [ sub ~zone ~x ~y ~width ~height ] creates a sub - zone of
[ zone ] . [ x ] and [ y ] are relatives to the zone top left corner .
@raise Invalid_argument if the sub zone is not included in
[ zone ]
[zone]. [x] and [y] are relatives to the zone top left corner.
@raise Invalid_argument if the sub zone is not included in
[zone]*)
val inner : t -> t
(** [inner zone] returns the inner part of [zone] *)
end
(** Drawing helpers *)
module Draw : sig
(** Note: except for {!get}, all function ignore points that are
outside the zone *)
val get : zone : Zone.t -> x : int -> y : int -> point
(** [get ~zone ~x ~y] returns the point at relative position [x]
and [y].
@raise Invalid_argument if the coordinates are outside the
zone *)
val set : zone : Zone.t -> x : int -> y : int -> point : point -> unit
(** [set ~zone ~x ~y ~popint] sets point at relative position [x]
and [y]. *)
val map : zone : Zone.t -> x : int -> y : int -> (point -> point) -> unit
(** [map ~zone ~x ~y f] replace the point at coordinates [(x, y)]
by the result of [f] applied on it. *)
val text : zone : Zone.t -> x : int -> y : int -> text : Text.t -> unit
(** Draw the given text at the given positon *)
val textf : Zone.t -> int -> int -> ('a, unit, string, unit) format4 -> 'a
(** Same as {!text} but uses a format string *)
val textc : zone : Zone.t -> x : int -> y : int -> text : styled_text -> unit
(** Same as {!text} but takes a text with styles *)
end
| null | https://raw.githubusercontent.com/janestreet/lwt-async/c738e6202c1c7409e079e513c7bdf469f7f9984c/src/text/lwt_term.mli | ocaml | * Terminal control
* This modules allow you to write interactive programs using the
terminal.
* [with_raw_mode f] executes [f] while the terminal is in ``raw
mode''. Raw mode means that character are returned as the user
type them (otherwise only complete line are returned to the
program).
If the terminal is already in raw mode, it just calls [f].
* Returns wether the terminal is currently in raw mode
* Put the terminal into drawing mode
* Restore the state of the terminal
* [hide_cursor ()] makes the cursor invisible
* [clear_screen ()] clears the entire screen
* [clear_line ()] clears the current line
* Terminal sizes:
* Size of the terminal.
* Number of columns of the terminal
* Number of lines of the terminal
* [parse_key_raw st] recognize escape sequence in a stream of
unicode character.
It returns either:
- either single characters, like ["a"], ["é"], ...
- either escape sequences
* Type of ``decoded'' keys.
This list is not exhaustive, but at least it should works on all
terminals:
* A unicode character or an uninterpreted sequence
* A control key
* [string_of_key key] string representation of a key
* Mapping from sequence to keys
* Decode a key.
* The input stream used by {!read_key}
* Note: these colors are not supposed to works on all terminals, but
in practice it works with all modern ones. By the way, using
standard colors + bold mode will give the same result as using a
light color.
* Elmement of a styled-text
* Some text
* Resets all styles to default
* A styled text is a list of instructions
* [textf fmt] formats a texts with [fmt] and returns [Text txt]
* [fg col = Foreground col]
* [bg col = Background col]
* Drop all styles
* [write_styled oc st] writes [st] on [oc] using escape
sequences.
* Same as [printc] but prints on stderr.
* [printlc st] prints [st], then reset styles and prints a
newline
* Same as [printlc] but prints on stderr
* Character styles
* A character on the screen:
* The character.
* The character style
* A space with default color and styles
* Render an offscreen array to the terminal.
* [render_update displayed to_display] does the same as [render
to_display] but assumes that [displayed] contains the current
displayed text. This reduces the amount of text sent to the
terminal.
* {6 Drawing}
* Off-screen zones
* The off-screen matrix
* Absolute coordinates of the top-left corner of the zone
* Dimmensions of the zone
* Make a new zone where all points are initialized to
{!blank}
* [inner zone] returns the inner part of [zone]
* Drawing helpers
* Note: except for {!get}, all function ignore points that are
outside the zone
* [get ~zone ~x ~y] returns the point at relative position [x]
and [y].
@raise Invalid_argument if the coordinates are outside the
zone
* [set ~zone ~x ~y ~popint] sets point at relative position [x]
and [y].
* [map ~zone ~x ~y f] replace the point at coordinates [(x, y)]
by the result of [f] applied on it.
* Draw the given text at the given positon
* Same as {!text} but uses a format string
* Same as {!text} but takes a text with styles | Lightweight thread library for
* Module Lwt_term
* Copyright ( C ) 2009
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation , with linking exceptions ;
* either version 2.1 of the License , or ( at your option ) any later
* version . See COPYING file for details .
*
* This program is distributed in the hope that it will be useful , but
* WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
* Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA
* 02111 - 1307 , USA .
*
* Module Lwt_term
* Copyright (C) 2009 Jérémie Dimino
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, with linking exceptions;
* either version 2.1 of the License, or (at your option) any later
* version. See COPYING file for details.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*)
val with_raw_mode : (unit -> 'a Lwt.t) -> 'a Lwt.t
val raw_mode : unit -> bool
val enter_drawing_mode : unit -> unit Lwt.t
val leave_drawing_mode : unit -> unit Lwt.t
val show_cursor : unit -> unit Lwt.t
* [ ( ) ] makes the cursor visible
val hide_cursor : unit -> unit Lwt.t
val clear_screen : unit -> unit Lwt.t
val clear_line : unit -> unit Lwt.t
val goto_beginning_of_line : int -> unit Lwt.t
* [ goto_beginning_of_line n ] put the cursor at the beginning of
the [ n]th previous line .
- [ goto_beginning_of_line 0 ] goes to the beginning of the current line
- [ goto_beginning_of_line 1 ] goes to the beginning of the previous line
- ...
the [n]th previous line.
- [goto_beginning_of_line 0] goes to the beginning of the current line
- [goto_beginning_of_line 1] goes to the beginning of the previous line
- ...
*)
* { 6 Terminal informations }
type size = {
lines : int;
columns : int;
}
val size : size React.signal
val columns : int React.signal
val lines : int React.signal
* { 6 Keys }
val parse_key_raw : Text.t Lwt_stream.t -> Text.t Lwt.t
type key =
| Key of Text.t
| Key_up
| Key_down
| Key_left
| Key_right
| Key_f of int
| Key_next_page
| Key_previous_page
| Key_home
| Key_end
| Key_insert
| Key_delete
| Key_control of char
val string_of_key : key -> string
val control_mapping : (int * char) list
* Mapping from control key codes to character codes .
Here is the list of control keys :
{ [
+ ------+-------+------+------+------+-------+------------------------------------------------+
| Char | Oct | Dec | Name | Hex | Key | Comment |
+ ------+-------+------+------+------+-------+------------------------------------------------+
| ' @ ' | 0o00 | 0 | NUL | 0x00 | ^@ \0 | Null byte |
| ' a ' | 0o01 | 1 | SOH | 0x01 | ^A | Start of heading |
| ' b ' | 0o02 | 2 | STX | 0x02 | ^B | Start of text |
| ' c ' | 0o03 | 3 | ETX | 0x03 | ^C | End of text |
| 'd ' | 0o04 | 4 | EOT | 0x04 | ^D | End of transmission |
| ' e ' | 0o05 | 5 | ENQ | 0x05 | ^E | Enquiry |
| ' f ' | 0o06 | 6 | ACK | 0x06 | ^F | Acknowledge |
| ' g ' | 0o07 | 7 | BEL | 0x07 | ^G | Ring terminal bell |
| ' h ' | 0o10 | 8 | BS | 0x08 | Backspace |
| ' i ' | 0o11 | 9 | HT | 0x09 | ^I \t | Horizontal tab |
| ' j ' | 0o12 | 10 | LF | 0x0a | ^J \n | Line feed |
| ' k ' | 0o13 | 11 | VT | 0x0b | ^K | Vertical tab |
| ' l ' | 0o14 | 12 | FF | 0x0c | ^L \f | Form feed |
| ' m ' | 0o15 | 13 | CR | 0x0d | ^M \r | Carriage return |
| ' n ' | 0o16 | 14 | SO | 0x0e | ^N | Shift out |
| ' o ' | 0o17 | 15 | SI | 0x0f | ^O | Shift in |
| ' p ' | 0o20 | 16 | DLE | 0x10 | ^P | Data link escape |
| ' q ' | 0o21 | 17 | DC1 | 0x11 | ^Q | Device control 1 ( ) |
| ' r ' | 0o22 | 18 | DC2 | 0x12 | ^R | Device control 2 |
| 's ' | 0o23 | 19 | DC3 | 0x13 | ^S | Device control 3 ( XOFF ) |
| ' t ' | 0o24 | 20 | DC4 | 0x14 | ^T | Device control 4 |
| ' u ' | 0o25 | 21 | NAK | 0x15 | ^U | Negative acknowledge |
| ' v ' | 0o26 | 22 | SYN | 0x16 | ^V | Synchronous idle |
| ' w ' | 0o27 | 23 ETB | 0x17 | ^W | End of transmission block |
| ' x ' | 0o30 | 24 | CAN | 0x18 | ^X | Cancel |
| ' y ' | 0o31 | 25 | EM | 0x19 | ^Y | End of medium |
| ' z ' | 0o32 | 26 | SUB | 0x1a | ^Z | Substitute character |
| ' [ ' | 0o33 | 27 | ESC | 0x1b | ^ [ | Escape |
| ' \ ' | 0o34 | 28 | FS | 0x1c | ^\ | File separator , Information separator four |
| ' ] ' | 0o35 | 29 | GS | 0x1d | ^ ] | Group separator , Information separator three |
| ' ^ ' | 0o36 | 30 | RS | 0x1e | ^^ | Record separator , Information separator two |
| ' _ ' | 0o37 | 31 | US | 0x1f | ^ _ | Unit separator , Information separator one |
| ' ? ' | 0o177 | 127 | DEL | 0x7f | ^ ? | Delete |
+ ------+-------+------+------+------+-------+------------------------------------------------+
] }
Here is the list of control keys:
{[
+------+-------+------+------+------+-------+------------------------------------------------+
| Char | Oct | Dec | Name | Hex | Key | Comment |
+------+-------+------+------+------+-------+------------------------------------------------+
| '@' | 0o00 | 0 | NUL | 0x00 | ^@ \0 | Null byte |
| 'a' | 0o01 | 1 | SOH | 0x01 | ^A | Start of heading |
| 'b' | 0o02 | 2 | STX | 0x02 | ^B | Start of text |
| 'c' | 0o03 | 3 | ETX | 0x03 | ^C | End of text |
| 'd' | 0o04 | 4 | EOT | 0x04 | ^D | End of transmission |
| 'e' | 0o05 | 5 | ENQ | 0x05 | ^E | Enquiry |
| 'f' | 0o06 | 6 | ACK | 0x06 | ^F | Acknowledge |
| 'g' | 0o07 | 7 | BEL | 0x07 | ^G | Ring terminal bell |
| 'h' | 0o10 | 8 | BS | 0x08 | ^H \b | Backspace |
| 'i' | 0o11 | 9 | HT | 0x09 | ^I \t | Horizontal tab |
| 'j' | 0o12 | 10 | LF | 0x0a | ^J \n | Line feed |
| 'k' | 0o13 | 11 | VT | 0x0b | ^K | Vertical tab |
| 'l' | 0o14 | 12 | FF | 0x0c | ^L \f | Form feed |
| 'm' | 0o15 | 13 | CR | 0x0d | ^M \r | Carriage return |
| 'n' | 0o16 | 14 | SO | 0x0e | ^N | Shift out |
| 'o' | 0o17 | 15 | SI | 0x0f | ^O | Shift in |
| 'p' | 0o20 | 16 | DLE | 0x10 | ^P | Data link escape |
| 'q' | 0o21 | 17 | DC1 | 0x11 | ^Q | Device control 1 (XON) |
| 'r' | 0o22 | 18 | DC2 | 0x12 | ^R | Device control 2 |
| 's' | 0o23 | 19 | DC3 | 0x13 | ^S | Device control 3 (XOFF) |
| 't' | 0o24 | 20 | DC4 | 0x14 | ^T | Device control 4 |
| 'u' | 0o25 | 21 | NAK | 0x15 | ^U | Negative acknowledge |
| 'v' | 0o26 | 22 | SYN | 0x16 | ^V | Synchronous idle |
| 'w' | 0o27 | 23 | ETB | 0x17 | ^W | End of transmission block |
| 'x' | 0o30 | 24 | CAN | 0x18 | ^X | Cancel |
| 'y' | 0o31 | 25 | EM | 0x19 | ^Y | End of medium |
| 'z' | 0o32 | 26 | SUB | 0x1a | ^Z | Substitute character |
| '[' | 0o33 | 27 | ESC | 0x1b | ^[ | Escape |
| '\' | 0o34 | 28 | FS | 0x1c | ^\ | File separator, Information separator four |
| ']' | 0o35 | 29 | GS | 0x1d | ^] | Group separator, Information separator three |
| '^' | 0o36 | 30 | RS | 0x1e | ^^ | Record separator, Information separator two |
| '_' | 0o37 | 31 | US | 0x1f | ^_ | Unit separator, Information separator one |
| '?' | 0o177 | 127 | DEL | 0x7f | ^? | Delete |
+------+-------+------+------+------+-------+------------------------------------------------+
]}
*)
val key_enter : key
* [ key_enter = Key_control ' j ' ]
val key_escape : key
* [ key_escape = Key_control ' \ [ ' ]
val key_tab : key
* [ key_escape = Key_control ' i ' ]
val key_backspace : key
* [ key_backspace = Key_control ' ? ' ]
val sequence_mapping : (Text.t * key) list
val decode_key : Text.t -> key
val standard_input : Text.t Lwt_stream.t
val read_key : unit -> key Lwt.t
* Get and decode a key from { ! }
* { 6 Styles }
type color = int
* Type of a color . Most modern terminals support either 88 or
256 colors .
256 colors. *)
val set_color : color -> int * int * int -> unit Lwt.t
* [ set_color num ( red , green , blue ) ] sets the three components of
the color number [ num ]
the color number [num] *)
* { 8 Standard colors }
val default : color
val black : color
val red : color
val green : color
val yellow : color
val blue : color
val magenta : color
val cyan : color
val white : color
* { 8 Light colors }
val lblack : color
val lred : color
val lgreen : color
val lyellow : color
val lblue : color
val lmagenta : color
val lcyan : color
val lwhite : color
* { 8 Text with styles }
type styled_text_instruction =
| Text of Text.t
| Reset
| Bold
| Underlined
| Blink
| Inverse
| Hidden
| Foreground of color
| Background of color
type styled_text = styled_text_instruction list
val textf : ('a, unit, string, styled_text_instruction) format4 -> 'a
val text : Text.t -> styled_text_instruction
val reset : styled_text_instruction
val bold : styled_text_instruction
val underlined : styled_text_instruction
val blink : styled_text_instruction
val inverse : styled_text_instruction
val hidden : styled_text_instruction
val fg : color -> styled_text_instruction
val bg : color -> styled_text_instruction
val strip_styles : styled_text -> Text.t
val styled_length : styled_text -> int
* Returns the length ( in unicode character ) of the given styled
text . The following equality holds for all styled - texts :
[ styled_length st = Text.length ( strip_styles st ) ]
text. The following equality holds for all styled-texts:
[styled_length st = Text.length (strip_styles st)]
*)
val write_styled : Lwt_text.output_channel -> styled_text -> unit Lwt.t
val printc : styled_text -> unit Lwt.t
* [ printc st ] prints the given styled text on standard output . If
stdout is not a tty , then styles are stripped .
The text is encoded to the system encoding before being
output .
stdout is not a tty, then styles are stripped.
The text is encoded to the system encoding before being
output. *)
val eprintc : styled_text -> unit Lwt.t
val printlc : styled_text -> unit Lwt.t
val eprintlc : styled_text -> unit Lwt.t
* { 6 Rendering }
type style = {
bold : bool;
underlined : bool;
blink : bool;
inverse : bool;
hidden : bool;
foreground : color;
background : color;
}
type point = {
char : Text.t;
style : style;
}
val blank : point
val render : point array array -> unit Lwt.t
val render_update : point array array -> point array array -> unit Lwt.t
module Zone : sig
type t = {
points : point array array;
x : int;
y : int;
width : int;
height : int;
}
val points : t -> point array array
val x : t -> int
val y : t -> int
val width : t -> int
val height : t -> int
val make : width : int -> height : int -> t
val sub : zone : t -> x : int -> y : int -> width : int -> height : int -> t
* [ sub ~zone ~x ~y ~width ~height ] creates a sub - zone of
[ zone ] . [ x ] and [ y ] are relatives to the zone top left corner .
@raise Invalid_argument if the sub zone is not included in
[ zone ]
[zone]. [x] and [y] are relatives to the zone top left corner.
@raise Invalid_argument if the sub zone is not included in
[zone]*)
val inner : t -> t
end
module Draw : sig
val get : zone : Zone.t -> x : int -> y : int -> point
val set : zone : Zone.t -> x : int -> y : int -> point : point -> unit
val map : zone : Zone.t -> x : int -> y : int -> (point -> point) -> unit
val text : zone : Zone.t -> x : int -> y : int -> text : Text.t -> unit
val textf : Zone.t -> int -> int -> ('a, unit, string, unit) format4 -> 'a
val textc : zone : Zone.t -> x : int -> y : int -> text : styled_text -> unit
end
|
8e602e97579bf14fd5f9f150d36007e8f7e454c2b55d31cf1893890b8eece796 | roman/lc-2018-rock-solid-haskell-services | SNS.hs | # LANGUAGE FlexibleContexts #
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE NoImplicitPrelude #
module App.Component.AWS.SNS (buildTopics) where
import RIO
import qualified RIO.HashMap as HashMap
import Data.Aeson ((.:), (.:?))
import qualified Data.Aeson as JSON
import qualified Network.AWS as AWS
import qualified Network.AWS.SNS as AWS
import qualified System.Etc as Etc
import Control.Monad.Component (ComponentM, buildComponent_, buildComponent)
import App.Component.AWS.Env (buildEnv, fetchSnsService)
import Types
buildSnsRemoteTopic :: AWS.HasEnv env => env -> Text -> RemoteTopic
buildSnsRemoteTopic env topicArn = do
RemoteTopic { _publishMessage }
where
_publishMessage content =
void
$ AWS.runResourceT
$ AWS.runAWS env
$ AWS.send (AWS.publish content & set AWS.pTopicARN (Just topicArn))
data RemoteTopicEntry
= RemoteTopicEntry
{
topicName :: !Text
, topicArn :: !Text
}
instance JSON.FromJSON RemoteTopicEntry where
parseJSON = JSON.withObject "RemoteTopicEntry" $ \obj ->
RemoteTopicEntry <$> obj .: "name"
<*> obj .: "arn"
buildTopics
:: Etc.IConfig config
=> config
-> LogFunc
-> ComponentM (HashMap Text RemoteTopic)
buildTopics config logFn = do
env <- buildEnv config logFn (fetchSnsService config)
case Etc.getConfigValue ["aws", "sns", "topics"] config of
Left err -> do
runRIO logFn $ logWarn $ "No SNS topics found: " <> displayShow err
return $ HashMap.empty
Right topicArnList -> do
topicList <- forM topicArnList $ \(RemoteTopicEntry {topicName, topicArn}) -> do
runRIO logFn $ do
logDebug
$ "Registering topic " <> displayShow topicName
<> " with ARN " <> displayShow topicArn
remoteTopic <- buildComponent_ topicName $ return $ buildSnsRemoteTopic env topicArn
return (topicName, remoteTopic)
return $ HashMap.fromList topicList
| null | https://raw.githubusercontent.com/roman/lc-2018-rock-solid-haskell-services/c964beba5ddc50bb586e02b14d8d89128f17a53f/5-web-crawl/app/App/Component/AWS/SNS.hs | haskell | # LANGUAGE NamedFieldPuns #
# LANGUAGE OverloadedStrings # | # LANGUAGE FlexibleContexts #
# LANGUAGE NoImplicitPrelude #
module App.Component.AWS.SNS (buildTopics) where
import RIO
import qualified RIO.HashMap as HashMap
import Data.Aeson ((.:), (.:?))
import qualified Data.Aeson as JSON
import qualified Network.AWS as AWS
import qualified Network.AWS.SNS as AWS
import qualified System.Etc as Etc
import Control.Monad.Component (ComponentM, buildComponent_, buildComponent)
import App.Component.AWS.Env (buildEnv, fetchSnsService)
import Types
buildSnsRemoteTopic :: AWS.HasEnv env => env -> Text -> RemoteTopic
buildSnsRemoteTopic env topicArn = do
RemoteTopic { _publishMessage }
where
_publishMessage content =
void
$ AWS.runResourceT
$ AWS.runAWS env
$ AWS.send (AWS.publish content & set AWS.pTopicARN (Just topicArn))
data RemoteTopicEntry
= RemoteTopicEntry
{
topicName :: !Text
, topicArn :: !Text
}
instance JSON.FromJSON RemoteTopicEntry where
parseJSON = JSON.withObject "RemoteTopicEntry" $ \obj ->
RemoteTopicEntry <$> obj .: "name"
<*> obj .: "arn"
buildTopics
:: Etc.IConfig config
=> config
-> LogFunc
-> ComponentM (HashMap Text RemoteTopic)
buildTopics config logFn = do
env <- buildEnv config logFn (fetchSnsService config)
case Etc.getConfigValue ["aws", "sns", "topics"] config of
Left err -> do
runRIO logFn $ logWarn $ "No SNS topics found: " <> displayShow err
return $ HashMap.empty
Right topicArnList -> do
topicList <- forM topicArnList $ \(RemoteTopicEntry {topicName, topicArn}) -> do
runRIO logFn $ do
logDebug
$ "Registering topic " <> displayShow topicName
<> " with ARN " <> displayShow topicArn
remoteTopic <- buildComponent_ topicName $ return $ buildSnsRemoteTopic env topicArn
return (topicName, remoteTopic)
return $ HashMap.fromList topicList
|
72e497f77c4616d91da31b9c6906c9254a1ec95531877cf8924ca9cdbb348988 | lesguillemets/sicp-haskell | 1.33.hs | module OneThirtythree where
-- takeWhile seems to be a better explanation.
twAccumulate' :: (Ord a)
=> (t -> t -> t) -> t -> (a -> t) -> (a -> Bool) -> (a -> a) -> a -> t
Phew ! I think can come very handy here .
twAccumulate' combiner nullValue term cond next a
= let iter acc x =
if not (cond x) then acc
else iter (acc `combiner` term x) (next x)
in
iter nullValue a
-- the sum of the squares of the prime numbers in the interval a to
-- b (assuming that you have a prime? predicate already written)
sumSqPrim :: Int -> Int -> Int
sumSqPrim a b = twAccumulate' (+) 0 (\n -> if isPrime n then n*n else 0)
(<= b) succ a
| Test : fmmm . .. sum . map ( ^2 ) $ [ 2,3,5,7,11,13,17,19 ]
> > > sumSqPrim 2 20
1027
-- Or this? Is this what it's asking for?
-- This does not seem to be a "generalization"...
filteredAccmulate' :: (Ord a)
=> (t -> t -> t) -> t ->
(a -> t) -> a -> (a -> a) -> a -> (a -> Bool) -> t
filteredAccmulate' combiner nullValue term a next b cond
= let iter acc x y
| x > y = acc
| cond x = iter (acc `combiner` term x) (next x) y
| otherwise = iter acc (next x) y
in
iter nullValue a b
-- | the sum of the squares of the prime numbers in the interval a to
-- | b (assuming that you have a prime? predicate already written)
> > > sumSqPrim ' 2 20
1027
sumSqPrim' :: Int -> Int -> Int
sumSqPrim' a b = filteredAccmulate' (+) 0 (^2) a succ b isPrime
-- the product of all the positive integers less than n that are relatively
-- prime to n
| n = 10 : 1 * 3 * 7 * 9 = 189
> > > prodRPs 10
189
--
| n = 11 : 10 !
> > > prodRPs 11
3628800
prodRPs :: (Integral a) => a -> a
prodRPs n = filteredAccmulate' (*) 1 id 1 succ n ((== 1) . gcd n)
isPrime :: Int -> Bool
isPrime 1 = False
isPrime 2 = True
isPrime n
= all (\i -> n `mod` i /= 0) $ 2:[3,5..(floor.sqrt.fromIntegral) n]
| null | https://raw.githubusercontent.com/lesguillemets/sicp-haskell/df524a1e28c45fb16a56f539cad8babc881d0431/exercise/chap01/sect3/1.33.hs | haskell | takeWhile seems to be a better explanation.
the sum of the squares of the prime numbers in the interval a to
b (assuming that you have a prime? predicate already written)
Or this? Is this what it's asking for?
This does not seem to be a "generalization"...
| the sum of the squares of the prime numbers in the interval a to
| b (assuming that you have a prime? predicate already written)
the product of all the positive integers less than n that are relatively
prime to n
| module OneThirtythree where
twAccumulate' :: (Ord a)
=> (t -> t -> t) -> t -> (a -> t) -> (a -> Bool) -> (a -> a) -> a -> t
Phew ! I think can come very handy here .
twAccumulate' combiner nullValue term cond next a
= let iter acc x =
if not (cond x) then acc
else iter (acc `combiner` term x) (next x)
in
iter nullValue a
sumSqPrim :: Int -> Int -> Int
sumSqPrim a b = twAccumulate' (+) 0 (\n -> if isPrime n then n*n else 0)
(<= b) succ a
| Test : fmmm . .. sum . map ( ^2 ) $ [ 2,3,5,7,11,13,17,19 ]
> > > sumSqPrim 2 20
1027
filteredAccmulate' :: (Ord a)
=> (t -> t -> t) -> t ->
(a -> t) -> a -> (a -> a) -> a -> (a -> Bool) -> t
filteredAccmulate' combiner nullValue term a next b cond
= let iter acc x y
| x > y = acc
| cond x = iter (acc `combiner` term x) (next x) y
| otherwise = iter acc (next x) y
in
iter nullValue a b
> > > sumSqPrim ' 2 20
1027
sumSqPrim' :: Int -> Int -> Int
sumSqPrim' a b = filteredAccmulate' (+) 0 (^2) a succ b isPrime
| n = 10 : 1 * 3 * 7 * 9 = 189
> > > prodRPs 10
189
| n = 11 : 10 !
> > > prodRPs 11
3628800
prodRPs :: (Integral a) => a -> a
prodRPs n = filteredAccmulate' (*) 1 id 1 succ n ((== 1) . gcd n)
isPrime :: Int -> Bool
isPrime 1 = False
isPrime 2 = True
isPrime n
= all (\i -> n `mod` i /= 0) $ 2:[3,5..(floor.sqrt.fromIntegral) n]
|
bbafbeff6b705cc993052cf2460bb8bf1996cfae3e843d99459d74043eb33b26 | gigasquid/clj-drone | multi_drone_nav_goals.clj | (ns clj-drone.example.nav-goals
(:require [clj-drone.core :refer :all]
[clj-drone.navdata :refer :all]
[clj-drone.goals :refer :all]))
;Logging goes to logs/drone.log
(set-log-data [:seq-num :battery-percent :control-state :detect-camera-type
:targets-num :targets])
(def drone1-shakes (atom 0))
(def drone2-shakes (atom 0))
Drone 1
;;;Taking off
(def-belief-action ba-landed1
"I (Drone1) am landed"
(fn [{:keys [control-state]}] (= control-state :landed))
(fn [navdata] (mdrone :drone1 :take-off)))
(def-belief-action ba-taking-off1
"I (Drone1) am taking off"
(fn [{:keys [control-state]}] (= control-state :trans-takeoff))
(fn [navdata] (mdrone :drone1 :take-off)))
(def-goal g-take-off1
"I (Drone1) want to fly."
(fn [{:keys [control-state]}] (= control-state :hovering))
[ba-landed1 ba-taking-off1])
;; Look for other drone and wave
(def-belief-action ba-not-see-other-drone1
"I (Drone1) does not see the other drone"
(fn [{:keys [targets-num]}] (= targets-num 0))
(fn [navdata] (mdrone :drone1 :spin-right 0.1)))
(def-belief-action ba-see-the-other-drone1
"I (Drone1) see the other drone"
(fn [{:keys [targets-num]}] (= targets-num 1))
(fn [navdata] (do
(mdrone :drone1 :anim-double-phi-theta-mixed)
(Thread/sleep 5000)
(swap! drone1-shakes inc)
)))
(def-goal g-find-other-drone-and-wave1
"I (Drone1) want to find the other drone"
(fn [_] (and (>= @drone1-shakes 1) (>= @drone2-shakes 1)))
[ba-not-see-other-drone1 ba-see-the-other-drone1])
;;; Land
(def-belief-action ba-flying1
"I (Drone1) am flying"
(fn [{:keys [control-state]}] (or (= control-state :hovering) (= control-state :flying)))
(fn [navdata] (do
(mdrone :drone1 :land))))
(def-belief-action ba-landing1
"I (Drone1) am landing"
(fn [{:keys [control-state]}] (= control-state :trans-landing))
nil)
(def-goal g-land1
"I (Drone1) want to land"
(fn [{:keys [control-state]}] (= control-state :landed))
[ba-flying1 ba-landing1])
Drone 2
;;;Taking off
(def-belief-action ba-landed2
"I (Drone2) am landed"
(fn [{:keys [control-state]}] (= control-state :landed))
(fn [navdata] (mdrone :drone2 :take-off)))
(def-belief-action ba-taking-off2
"I (Drone2) am taking off"
(fn [{:keys [control-state]}] (= control-state :trans-takeoff))
(fn [navdata] (mdrone :drone2 :take-off)))
(def-goal g-take-off2
"I (Drone2) want to fly."
(fn [{:keys [control-state]}] (= control-state :hovering))
[ba-landed2 ba-taking-off2])
;; Look for other drone and wave
(def-belief-action ba-not-see-other-drone2
"I (Drone2) does not see the other drone"
(fn [{:keys [targets-num]}] (= targets-num 0))
(fn [navdata] (mdrone :drone2 :spin-left 0.1)))
(def-belief-action ba-see-the-other-drone2
"I (Drone2) see the other drone"
(fn [{:keys [targets-num]}] (= targets-num 1))
(fn [navdata] (do
(mdrone :drone2 :anim-double-phi-theta-mixed)
(Thread/sleep 5000)
(swap! drone2-shakes inc))))
(def-goal g-find-other-drone-and-wave2
"I (Drone2) want to find the other drone"
(fn [_] (and (>= @drone1-shakes 1) (>= @drone2-shakes 1)))
[ba-not-see-other-drone2 ba-see-the-other-drone2])
;;; Land
(def-belief-action ba-flying2
"I (Drone2) am flying"
(fn [{:keys [control-state]}] (or (= control-state :hovering) (= control-state :flying)))
(fn [navdata] (do
(mdrone :drone2 :land))))
(def-belief-action ba-landing2
"I (Drone2) am landing"
(fn [{:keys [control-state]}] (= control-state :trans-landing))
nil)
(def-goal g-land2
"I (Drone2) want to land"
(fn [{:keys [control-state]}] (= control-state :landed))
[ba-flying2 ba-landing2])
;; ;;; initialization to run
drone1 is neo green
drone2 is mine with blue
(do
(reset! drone1-shakes 0)
(reset! drone2-shakes 0)
(drone-initialize :drone1 "192.168.1.100" default-at-port)
(mdrone :drone1 :init-targeting)
(mdrone :drone1 :target-shell-h)
(mdrone :drone1 :target-color-blue)
(set-current-goal-list drones :drone1 [g-take-off1 g-find-other-drone-and-wave1 g-land1])
(mdrone-init-navdata :drone1)
(start-stream :drone1)
(drone-initialize :drone2 "192.168.1.200" default-at-port)
(mdrone :drone2 :init-targeting)
(mdrone :drone2 :target-shell-h)
(mdrone :drone2 :target-color-green)
(set-current-goal-list drones :drone2 [g-take-off2 g-find-other-drone-and-wave2 g-land2])
(mdrone-init-navdata :drone2)
(start-stream :drone2)
)
;; ;;If running in the repl end the nav-stream when done
(end-navstream)
| null | https://raw.githubusercontent.com/gigasquid/clj-drone/b85320a0ab5e4d8589aaf77a0bd57e8a46e2905b/examples/multi_drone_nav_goals.clj | clojure | Logging goes to logs/drone.log
Taking off
Look for other drone and wave
Land
Taking off
Look for other drone and wave
Land
;;; initialization to run
;;If running in the repl end the nav-stream when done | (ns clj-drone.example.nav-goals
(:require [clj-drone.core :refer :all]
[clj-drone.navdata :refer :all]
[clj-drone.goals :refer :all]))
(set-log-data [:seq-num :battery-percent :control-state :detect-camera-type
:targets-num :targets])
(def drone1-shakes (atom 0))
(def drone2-shakes (atom 0))
Drone 1
(def-belief-action ba-landed1
"I (Drone1) am landed"
(fn [{:keys [control-state]}] (= control-state :landed))
(fn [navdata] (mdrone :drone1 :take-off)))
(def-belief-action ba-taking-off1
"I (Drone1) am taking off"
(fn [{:keys [control-state]}] (= control-state :trans-takeoff))
(fn [navdata] (mdrone :drone1 :take-off)))
(def-goal g-take-off1
"I (Drone1) want to fly."
(fn [{:keys [control-state]}] (= control-state :hovering))
[ba-landed1 ba-taking-off1])
(def-belief-action ba-not-see-other-drone1
"I (Drone1) does not see the other drone"
(fn [{:keys [targets-num]}] (= targets-num 0))
(fn [navdata] (mdrone :drone1 :spin-right 0.1)))
(def-belief-action ba-see-the-other-drone1
"I (Drone1) see the other drone"
(fn [{:keys [targets-num]}] (= targets-num 1))
(fn [navdata] (do
(mdrone :drone1 :anim-double-phi-theta-mixed)
(Thread/sleep 5000)
(swap! drone1-shakes inc)
)))
(def-goal g-find-other-drone-and-wave1
"I (Drone1) want to find the other drone"
(fn [_] (and (>= @drone1-shakes 1) (>= @drone2-shakes 1)))
[ba-not-see-other-drone1 ba-see-the-other-drone1])
(def-belief-action ba-flying1
"I (Drone1) am flying"
(fn [{:keys [control-state]}] (or (= control-state :hovering) (= control-state :flying)))
(fn [navdata] (do
(mdrone :drone1 :land))))
(def-belief-action ba-landing1
"I (Drone1) am landing"
(fn [{:keys [control-state]}] (= control-state :trans-landing))
nil)
(def-goal g-land1
"I (Drone1) want to land"
(fn [{:keys [control-state]}] (= control-state :landed))
[ba-flying1 ba-landing1])
Drone 2
(def-belief-action ba-landed2
"I (Drone2) am landed"
(fn [{:keys [control-state]}] (= control-state :landed))
(fn [navdata] (mdrone :drone2 :take-off)))
(def-belief-action ba-taking-off2
"I (Drone2) am taking off"
(fn [{:keys [control-state]}] (= control-state :trans-takeoff))
(fn [navdata] (mdrone :drone2 :take-off)))
(def-goal g-take-off2
"I (Drone2) want to fly."
(fn [{:keys [control-state]}] (= control-state :hovering))
[ba-landed2 ba-taking-off2])
(def-belief-action ba-not-see-other-drone2
"I (Drone2) does not see the other drone"
(fn [{:keys [targets-num]}] (= targets-num 0))
(fn [navdata] (mdrone :drone2 :spin-left 0.1)))
(def-belief-action ba-see-the-other-drone2
"I (Drone2) see the other drone"
(fn [{:keys [targets-num]}] (= targets-num 1))
(fn [navdata] (do
(mdrone :drone2 :anim-double-phi-theta-mixed)
(Thread/sleep 5000)
(swap! drone2-shakes inc))))
(def-goal g-find-other-drone-and-wave2
"I (Drone2) want to find the other drone"
(fn [_] (and (>= @drone1-shakes 1) (>= @drone2-shakes 1)))
[ba-not-see-other-drone2 ba-see-the-other-drone2])
(def-belief-action ba-flying2
"I (Drone2) am flying"
(fn [{:keys [control-state]}] (or (= control-state :hovering) (= control-state :flying)))
(fn [navdata] (do
(mdrone :drone2 :land))))
(def-belief-action ba-landing2
"I (Drone2) am landing"
(fn [{:keys [control-state]}] (= control-state :trans-landing))
nil)
(def-goal g-land2
"I (Drone2) want to land"
(fn [{:keys [control-state]}] (= control-state :landed))
[ba-flying2 ba-landing2])
drone1 is neo green
drone2 is mine with blue
(do
(reset! drone1-shakes 0)
(reset! drone2-shakes 0)
(drone-initialize :drone1 "192.168.1.100" default-at-port)
(mdrone :drone1 :init-targeting)
(mdrone :drone1 :target-shell-h)
(mdrone :drone1 :target-color-blue)
(set-current-goal-list drones :drone1 [g-take-off1 g-find-other-drone-and-wave1 g-land1])
(mdrone-init-navdata :drone1)
(start-stream :drone1)
(drone-initialize :drone2 "192.168.1.200" default-at-port)
(mdrone :drone2 :init-targeting)
(mdrone :drone2 :target-shell-h)
(mdrone :drone2 :target-color-green)
(set-current-goal-list drones :drone2 [g-take-off2 g-find-other-drone-and-wave2 g-land2])
(mdrone-init-navdata :drone2)
(start-stream :drone2)
)
(end-navstream)
|
857e74544c4d0cd885a40713dfe85160d385cecb369fefbd830ead472b87da06 | gcross/LogicGrowsOnTrees | RequestQueue.hs | {-# LANGUAGE ConstraintKinds #-}
# LANGUAGE RecursiveDo #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE RecordWildCards #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeFamilies #
{-# LANGUAGE TypeSynonymInstances #-}
# LANGUAGE UndecidableInstances #
# LANGUAGE UnicodeSyntax #
| To understand the purpose of this module , it helps to know that there are
two main loops running in the supervisor . The first loop runs inside the
' ' and is usually taken over by the adapter , which handles
the communication between the supervisors and the workers . The second loop
( referred to as the /controller/ ) is intended for the user to be able to
submit requests such as a global progress update to the supervisor , or
possibly adapter - specific requests ( such as changing the number of workers ) .
With this in mind , the purpose of this module is to create infrastructure
for the second loop ( the controller ) to submit requests to the first loop .
It provides this functionality through a class so that specific adapters can
extend this to provide requests specific to that adapter ( such as changing
the number of workers ) .
two main loops running in the supervisor. The first loop runs inside the
'SupervisorMonad' and is usually taken over by the adapter, which handles
the communication between the supervisors and the workers. The second loop
(referred to as the /controller/) is intended for the user to be able to
submit requests such as a global progress update to the supervisor, or
possibly adapter-specific requests (such as changing the number of workers).
With this in mind, the purpose of this module is to create infrastructure
for the second loop (the controller) to submit requests to the first loop.
It provides this functionality through a class so that specific adapters can
extend this to provide requests specific to that adapter (such as changing
the number of workers).
-}
module LogicGrowsOnTrees.Parallel.Common.RequestQueue
(
-- * Type-classes
RequestQueueMonad(..)
-- * Types
, Request
, RequestQueue(..)
, RequestQueueReader
-- * Functions
-- ** Synchronized requests
, addWorkerCountListener
, getCurrentProgress
, getCurrentStatistics
, getNumberOfWorkers
, requestProgressUpdate
, syncAsync
-- ** Request queue management
, addProgressReceiver
, enqueueRequest
, enqueueRequestAndWait
, newRequestQueue
, tryDequeueRequest
-- ** Request processing
, processAllRequests
, receiveProgress
, requestQueueProgram
-- ** Controller threads
, forkControllerThread
, killControllerThreads
-- ** CPU time tracking
, CPUTimeTracker
, newCPUTimeTracker
, startCPUTimeTracker
, getCurrentCPUTime
-- ** Miscellaneous
, getQuantityAsync
) where
import Control.Applicative ((<$>),(<*>),liftA2)
import Control.Arrow ((&&&))
import Control.Concurrent (ThreadId,forkIO,killThread)
import Control.Concurrent.MVar (newEmptyMVar,putMVar,takeMVar)
import Control.Concurrent.STM (atomically)
import Control.Concurrent.STM.TChan (TChan,newTChanIO,readTChan,tryReadTChan,writeTChan)
import Control.Concurrent.STM.TVar (TVar,modifyTVar',newTVarIO,readTVar,writeTVar)
import Control.Exception (BlockedIndefinitelyOnMVar(..),catch,finally,mask)
import Control.Monad ((>=>),join,liftM,liftM3,unless,void)
import Control.Monad.IO.Class (MonadIO(..))
import Control.Monad.Trans.Reader (ReaderT(..),ask)
import Data.IORef (IORef,atomicModifyIORef,readIORef,newIORef)
import Data.List (delete)
import Data.Time.Clock (NominalDiffTime,UTCTime,diffUTCTime,getCurrentTime)
import qualified LogicGrowsOnTrees.Parallel.Common.Supervisor as Supervisor
import LogicGrowsOnTrees.Parallel.Common.Supervisor
(RunStatistics
,SupervisorFullConstraint
,SupervisorMonad
,SupervisorProgram(..)
)
import LogicGrowsOnTrees.Parallel.ExplorationMode
--------------------------------------------------------------------------------
--------------------------------- Type-classes ---------------------------------
--------------------------------------------------------------------------------
{-| This class provides the set of supervisor requests common to all adapters. -}
class (HasExplorationMode m, Functor m, MonadIO m) ⇒ RequestQueueMonad m where
{-| Abort the supervisor. -}
abort :: m ()
{-| Submits a function to be called whenever the number of workers changes;
the given function will be also called immediately with the current
number of workers.
-}
addWorkerCountListenerAsync :: (Int → IO ()) → IO () → m ()
{-| Fork a new thread running in this monad; all controller threads are automnatically killed when the run is finished. -}
fork :: m () → m ThreadId
{-| Request the current progress, invoking the given callback with the result; see 'getCurrentProgress' for the synchronous version. -}
getCurrentProgressAsync :: (ProgressFor (ExplorationModeFor m) → IO ()) → m ()
{-| Get the current run statistics. -}
getCurrentStatisticsAsync :: (RunStatistics → IO ()) → m ()
{-| Request the number of workers, invoking the given callback with the result; see 'getNumberOfWorkers' for the synchronous version. -}
getNumberOfWorkersAsync :: (Int → IO ()) → m ()
{-| Request that a global progress update be performed, invoking the given callback with the result; see 'requestProgressUpdate' for the synchronous version. -}
requestProgressUpdateAsync :: (ProgressFor (ExplorationModeFor m) → IO ()) → m ()
| Sets the size of the workload buffer ; for more information , see ' Supervisor.setWorkloadBufferSize ' ( which links to the " LogicGrowsOnTrees . Parallel . Common . Supervisor " module ) .
setWorkloadBufferSize :: Int → m ()
--------------------------------------------------------------------------------
------------------------------------- Types ------------------------------------
--------------------------------------------------------------------------------
{-| A supervisor request. -}
type Request exploration_mode worker_id m = SupervisorMonad exploration_mode worker_id m ()
{-| A basic supervisor request queue. -}
data RequestQueue exploration_mode worker_id m = RequestQueue
{ {-| the queue of requests to the supervisor -}
requests :: !(TChan (Request exploration_mode worker_id m))
{-| a list of callbacks to invoke when a global progress update has completed -}
, receivers :: !(IORef [ProgressFor exploration_mode → IO ()])
{-| a list of the controller threads -}
, controllerThreads :: !(IORef [ThreadId])
}
| A basic supervisor request queue monad , which has an implicit ' RequestQueue '
object that it uses to communicate with the supervisor loop .
object that it uses to communicate with the supervisor loop.
-}
type RequestQueueReader exploration_mode worker_id m = ReaderT (RequestQueue exploration_mode worker_id m) IO
instance HasExplorationMode (RequestQueueReader exploration_mode worker_id m) where
type ExplorationModeFor (RequestQueueReader exploration_mode worker_id m) = exploration_mode
instance (SupervisorFullConstraint worker_id m) ⇒ RequestQueueMonad (RequestQueueReader exploration_mode worker_id m) where
abort = ask >>= enqueueRequest Supervisor.abortSupervisor
addWorkerCountListenerAsync listener callback = ask >>= enqueueRequest (Supervisor.addWorkerCountListener listener >> liftIO callback)
fork m = ask >>= flip forkControllerThread' m
getCurrentProgressAsync = (ask >>=) . getQuantityAsync Supervisor.getCurrentProgress
getCurrentStatisticsAsync = (ask >>=) . getQuantityAsync Supervisor.getCurrentStatistics
getNumberOfWorkersAsync = (ask >>=) . getQuantityAsync Supervisor.getNumberOfWorkers
requestProgressUpdateAsync receiveUpdatedProgress =
ask
>>=
liftIO
.
liftA2 (>>)
(addProgressReceiver receiveUpdatedProgress)
(enqueueRequest Supervisor.performGlobalProgressUpdate)
setWorkloadBufferSize size = ask >>= enqueueRequest (Supervisor.setWorkloadBufferSize size)
--------------------------------------------------------------------------------
---------------------------------- Functions -----------------------------------
--------------------------------------------------------------------------------
------------------------------ Synchronized requests ------------------------------
{-| Like 'addWorkerCountListenerAsync', but blocks until the listener has been added. -}
addWorkerCountListener :: RequestQueueMonad m ⇒ (Int → IO ()) → m ()
addWorkerCountListener listener = syncAsync (\callback → addWorkerCountListenerAsync listener (callback ()))
{-| Like 'getCurrentProgressAsync', but blocks until the result is ready. -}
getCurrentProgress :: RequestQueueMonad m ⇒ m (ProgressFor (ExplorationModeFor m))
getCurrentProgress = syncAsync getCurrentProgressAsync
| Like ' getCurrentStatisticsAsync ' , but blocks until the result is ready .
getCurrentStatistics :: RequestQueueMonad m ⇒ m RunStatistics
getCurrentStatistics = syncAsync getCurrentStatisticsAsync
{-| Like 'getNumberOfWorkersAsync', but blocks until the result is ready. -}
getNumberOfWorkers :: RequestQueueMonad m ⇒ m Int
getNumberOfWorkers = syncAsync getNumberOfWorkersAsync
{-| Like 'requestProgressUpdateAsync', but blocks until the progress update has completed. -}
requestProgressUpdate :: RequestQueueMonad m ⇒ m (ProgressFor (ExplorationModeFor m))
requestProgressUpdate = syncAsync requestProgressUpdateAsync
| General utility function for converting an asynchronous request to a
synchronous request ; it uses an ' MVar ' to hold the result of the request and
blocks until the ' MVar ' has been filled .
synchronous request; it uses an 'MVar' to hold the result of the request and
blocks until the 'MVar' has been filled.
-}
syncAsync :: MonadIO m ⇒ ((α → IO ()) → m ()) → m α
syncAsync runCommandAsync = do
result_mvar ← liftIO newEmptyMVar
runCommandAsync (putMVar result_mvar)
liftIO $
takeMVar result_mvar
`catch`
(\BlockedIndefinitelyOnMVar → error $ "blocked forever while waiting for controller to respond to request")
---------------------------- Request queue management -----------------------------
| Adds a callback to the given ' RequestQueue ' that will be invoked when the current global progress update has completed .
addProgressReceiver ::
MonadIO m' ⇒
(ProgressFor exploration_mode → IO ()) →
RequestQueue exploration_mode worker_id m →
m' ()
addProgressReceiver receiver =
liftIO
.
flip atomicModifyIORef ((receiver:) &&& const ())
.
receivers
{-| Enqueues a supervisor request into the given queue. -}
enqueueRequest ::
MonadIO m' ⇒
Request exploration_mode worker_id m →
RequestQueue exploration_mode worker_id m →
m' ()
enqueueRequest request =
liftIO
.
atomically
.
flip writeTChan request
.
requests
{-| Like 'enqueueRequest', but does not return until the request has been run -}
enqueueRequestAndWait ::
(MonadIO m, MonadIO m') ⇒
Request exploration_mode worker_id m →
RequestQueue exploration_mode worker_id m →
m' ()
enqueueRequestAndWait request request_queue = do
signal ← liftIO newEmptyMVar
enqueueRequest (request >> liftIO (putMVar signal ())) request_queue
liftIO $ takeMVar signal
| Constructs a new ' RequestQueue ' .
newRequestQueue ::
MonadIO m' ⇒
m' (RequestQueue exploration_mode worker_id m)
newRequestQueue = liftIO $ liftM3 RequestQueue newTChanIO (newIORef []) (newIORef [])
{-| Attempt to pop a request from the 'RequestQueue'. -}
tryDequeueRequest ::
MonadIO m' ⇒
RequestQueue exploration_mode worker_id m →
m' (Maybe (Request exploration_mode worker_id m))
tryDequeueRequest =
liftIO
.
atomically
.
tryReadTChan
.
requests
------------------------------- Request processing --------------------------------
| Processes all of the requests in the given ' RequestQueue ' , and returns when
the queue has been emptied .
the queue has been emptied.
-}
processAllRequests ::
MonadIO m ⇒
RequestQueue exploration_mode worker_id m →
SupervisorMonad exploration_mode worker_id m ()
processAllRequests (RequestQueue requests _ _) = go
where
go =
(liftIO . atomically . tryReadTChan) requests
>>=
maybe (return ()) (>> go)
| Invokes all of the callbacks with the given progress and then clears the list of callbacks .
receiveProgress ::
MonadIO m' ⇒
RequestQueue exploration_mode worker_id m →
ProgressFor exploration_mode →
m' ()
receiveProgress queue progress =
liftIO
.
join
.
liftM (sequence_ . map ($ progress))
.
flip atomicModifyIORef (const [] &&& id)
.
receivers
$
queue
{-| Creates a supervisor program that loops forever processing requests from the given queue. -}
requestQueueProgram ::
MonadIO m ⇒
SupervisorMonad exploration_mode worker_id m () {-^ initialization code to run before the loop is started -} →
RequestQueue exploration_mode worker_id m {-^ the request queue -} →
SupervisorProgram exploration_mode worker_id m
requestQueueProgram initialize =
flip (BlockingProgram initialize) id
.
liftIO
.
atomically
.
readTChan
.
requests
------------------------------ Controller threads ------------------------------
{-| Forks a controller thread; it's 'ThreadId' is added the list in the request
queue. We deliberately do not return the 'ThreadId' from this function
because you must always call `killControllerThreads` to kill the controller
thread as this makes sure that all child threads also get killed.
-}
forkControllerThread ::
MonadIO m' ⇒
RequestQueue exploration_mode worker_id m {-^ the request queue -} →
RequestQueueReader exploration_mode worker_id m () {-^ the controller thread -} →
m' ()
forkControllerThread request_queue controller =
void $ forkControllerThread' request_queue controller
forkControllerThread' ::
MonadIO m' ⇒
RequestQueue exploration_mode worker_id m →
RequestQueueReader exploration_mode worker_id m () →
m' ThreadId
forkControllerThread' request_queue controller = liftIO $ do
start_signal ← newEmptyMVar
rec thread_id ← forkIO $ mask $ \(restore :: ∀ α. IO α → IO α)→
(restore $ takeMVar start_signal >> runReaderT controller request_queue)
`finally`
(atomicModifyIORef (controllerThreads request_queue) (delete thread_id &&& const ()))
atomicModifyIORef (controllerThreads request_queue) ((thread_id:) &&& const ())
NOTE : The following signal is needed because we do n't want the new
thread to start until after its thread i d has been added to the
list , as otherwise it could result in an orphan thread that wo n't
get garbage collected until the supervisor finishes due to a
peculiarity of the GHC runtime where it does n't garbage collect a
thread as long as a ThreadId referring to it exists .
thread to start until after its thread id has been added to the
list, as otherwise it could result in an orphan thread that won't
get garbage collected until the supervisor finishes due to a
peculiarity of the GHC runtime where it doesn't garbage collect a
thread as long as a ThreadId referring to it exists.
-}
putMVar start_signal ()
return thread_id
{-| Kill all the controller threads and their children. -}
killControllerThreads ::
MonadIO m' ⇒
RequestQueue exploration_mode worker_id m {-^ the request queue -} →
m' ()
killControllerThreads = liftIO . readIORef . controllerThreads >=> liftIO . mapM_ killThread
------------------------------ CPU time tracking -------------------------------
{-| A data structure that tracks the amount of CPU time that has been used. -}
data CPUTimeTracker = CPUTimeTracker
{ trackerStarted :: IORef Bool
, trackerLastTime :: TVar (Maybe (UTCTime,Int))
, trackerTotalTime :: TVar NominalDiffTime
}
| Creates a new CPU time tracker , which should be equal to the amount of total
time used so far if we are continuing a previous run and zero otherwise .
time used so far if we are continuing a previous run and zero otherwise.
-}
newCPUTimeTracker :: NominalDiffTime → IO CPUTimeTracker
newCPUTimeTracker initial_cpu_time =
CPUTimeTracker
<$> newIORef False
<*> newTVarIO Nothing
<*> newTVarIO initial_cpu_time
computeAdditionalTime :: UTCTime → (UTCTime, Int) → NominalDiffTime
computeAdditionalTime current_time (last_time,last_number_of_workers) =
(current_time `diffUTCTime` last_time) * fromIntegral last_number_of_workers
{-| Starts the CPU time tracker; it detects when it has already been started so
if you attempt to start it more than once then all subsequent attempts will
be ignored.
-}
startCPUTimeTracker :: RequestQueueMonad m ⇒ CPUTimeTracker → m ()
startCPUTimeTracker CPUTimeTracker{..} =
(liftIO $ atomicModifyIORef trackerStarted (const True &&& id))
>>=
flip unless (addWorkerCountListener $ \current_number_of_workers → do
current_time ← getCurrentTime
atomically $ do
readTVar trackerLastTime >>= maybe
(pure ())
(\last → modifyTVar' trackerTotalTime (+ computeAdditionalTime current_time last))
writeTVar trackerLastTime $ Just (current_time,current_number_of_workers)
)
{-| Gets the current CPI time. -}
getCurrentCPUTime :: CPUTimeTracker → IO NominalDiffTime
getCurrentCPUTime CPUTimeTracker{..} = do
current_time ← getCurrentTime
atomically $ do
old_total_time ← readTVar trackerTotalTime
maybe_last ← readTVar trackerLastTime
return $ old_total_time + maybe 0 (computeAdditionalTime current_time) maybe_last
-------------------------------- Miscellaneous ---------------------------------
{-| Submits a 'Request' to the supervisor and invokes the given callback with the
result when it is available. (This function is used by
'getCurrentProgressAsync' and 'getNumberOfWorkersAsync'.)
-}
getQuantityAsync ::
( MonadIO m'
, SupervisorFullConstraint worker_id m
) ⇒
SupervisorMonad exploration_mode worker_id m α →
(α → IO ()) →
RequestQueue exploration_mode worker_id m →
m' ()
getQuantityAsync getQuantity receiveQuantity =
enqueueRequest $ getQuantity >>= liftIO . receiveQuantity
| null | https://raw.githubusercontent.com/gcross/LogicGrowsOnTrees/4befa81eb7152d877a7c78338d21bed61b06db66/LogicGrowsOnTrees/sources/LogicGrowsOnTrees/Parallel/Common/RequestQueue.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE RankNTypes #
# LANGUAGE TypeSynonymInstances #
* Type-classes
* Types
* Functions
** Synchronized requests
** Request queue management
** Request processing
** Controller threads
** CPU time tracking
** Miscellaneous
------------------------------------------------------------------------------
------------------------------- Type-classes ---------------------------------
------------------------------------------------------------------------------
| This class provides the set of supervisor requests common to all adapters.
| Abort the supervisor.
| Submits a function to be called whenever the number of workers changes;
the given function will be also called immediately with the current
number of workers.
| Fork a new thread running in this monad; all controller threads are automnatically killed when the run is finished.
| Request the current progress, invoking the given callback with the result; see 'getCurrentProgress' for the synchronous version.
| Get the current run statistics.
| Request the number of workers, invoking the given callback with the result; see 'getNumberOfWorkers' for the synchronous version.
| Request that a global progress update be performed, invoking the given callback with the result; see 'requestProgressUpdate' for the synchronous version.
------------------------------------------------------------------------------
----------------------------------- Types ------------------------------------
------------------------------------------------------------------------------
| A supervisor request.
| A basic supervisor request queue.
| the queue of requests to the supervisor
| a list of callbacks to invoke when a global progress update has completed
| a list of the controller threads
------------------------------------------------------------------------------
-------------------------------- Functions -----------------------------------
------------------------------------------------------------------------------
---------------------------- Synchronized requests ------------------------------
| Like 'addWorkerCountListenerAsync', but blocks until the listener has been added.
| Like 'getCurrentProgressAsync', but blocks until the result is ready.
| Like 'getNumberOfWorkersAsync', but blocks until the result is ready.
| Like 'requestProgressUpdateAsync', but blocks until the progress update has completed.
-------------------------- Request queue management -----------------------------
| Enqueues a supervisor request into the given queue.
| Like 'enqueueRequest', but does not return until the request has been run
| Attempt to pop a request from the 'RequestQueue'.
----------------------------- Request processing --------------------------------
| Creates a supervisor program that loops forever processing requests from the given queue.
^ initialization code to run before the loop is started
^ the request queue
---------------------------- Controller threads ------------------------------
| Forks a controller thread; it's 'ThreadId' is added the list in the request
queue. We deliberately do not return the 'ThreadId' from this function
because you must always call `killControllerThreads` to kill the controller
thread as this makes sure that all child threads also get killed.
^ the request queue
^ the controller thread
| Kill all the controller threads and their children.
^ the request queue
---------------------------- CPU time tracking -------------------------------
| A data structure that tracks the amount of CPU time that has been used.
| Starts the CPU time tracker; it detects when it has already been started so
if you attempt to start it more than once then all subsequent attempts will
be ignored.
| Gets the current CPI time.
------------------------------ Miscellaneous ---------------------------------
| Submits a 'Request' to the supervisor and invokes the given callback with the
result when it is available. (This function is used by
'getCurrentProgressAsync' and 'getNumberOfWorkersAsync'.)
| # LANGUAGE RecursiveDo #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE RecordWildCards #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
# LANGUAGE UnicodeSyntax #
| To understand the purpose of this module , it helps to know that there are
two main loops running in the supervisor . The first loop runs inside the
' ' and is usually taken over by the adapter , which handles
the communication between the supervisors and the workers . The second loop
( referred to as the /controller/ ) is intended for the user to be able to
submit requests such as a global progress update to the supervisor , or
possibly adapter - specific requests ( such as changing the number of workers ) .
With this in mind , the purpose of this module is to create infrastructure
for the second loop ( the controller ) to submit requests to the first loop .
It provides this functionality through a class so that specific adapters can
extend this to provide requests specific to that adapter ( such as changing
the number of workers ) .
two main loops running in the supervisor. The first loop runs inside the
'SupervisorMonad' and is usually taken over by the adapter, which handles
the communication between the supervisors and the workers. The second loop
(referred to as the /controller/) is intended for the user to be able to
submit requests such as a global progress update to the supervisor, or
possibly adapter-specific requests (such as changing the number of workers).
With this in mind, the purpose of this module is to create infrastructure
for the second loop (the controller) to submit requests to the first loop.
It provides this functionality through a class so that specific adapters can
extend this to provide requests specific to that adapter (such as changing
the number of workers).
-}
module LogicGrowsOnTrees.Parallel.Common.RequestQueue
(
RequestQueueMonad(..)
, Request
, RequestQueue(..)
, RequestQueueReader
, addWorkerCountListener
, getCurrentProgress
, getCurrentStatistics
, getNumberOfWorkers
, requestProgressUpdate
, syncAsync
, addProgressReceiver
, enqueueRequest
, enqueueRequestAndWait
, newRequestQueue
, tryDequeueRequest
, processAllRequests
, receiveProgress
, requestQueueProgram
, forkControllerThread
, killControllerThreads
, CPUTimeTracker
, newCPUTimeTracker
, startCPUTimeTracker
, getCurrentCPUTime
, getQuantityAsync
) where
import Control.Applicative ((<$>),(<*>),liftA2)
import Control.Arrow ((&&&))
import Control.Concurrent (ThreadId,forkIO,killThread)
import Control.Concurrent.MVar (newEmptyMVar,putMVar,takeMVar)
import Control.Concurrent.STM (atomically)
import Control.Concurrent.STM.TChan (TChan,newTChanIO,readTChan,tryReadTChan,writeTChan)
import Control.Concurrent.STM.TVar (TVar,modifyTVar',newTVarIO,readTVar,writeTVar)
import Control.Exception (BlockedIndefinitelyOnMVar(..),catch,finally,mask)
import Control.Monad ((>=>),join,liftM,liftM3,unless,void)
import Control.Monad.IO.Class (MonadIO(..))
import Control.Monad.Trans.Reader (ReaderT(..),ask)
import Data.IORef (IORef,atomicModifyIORef,readIORef,newIORef)
import Data.List (delete)
import Data.Time.Clock (NominalDiffTime,UTCTime,diffUTCTime,getCurrentTime)
import qualified LogicGrowsOnTrees.Parallel.Common.Supervisor as Supervisor
import LogicGrowsOnTrees.Parallel.Common.Supervisor
(RunStatistics
,SupervisorFullConstraint
,SupervisorMonad
,SupervisorProgram(..)
)
import LogicGrowsOnTrees.Parallel.ExplorationMode
class (HasExplorationMode m, Functor m, MonadIO m) ⇒ RequestQueueMonad m where
abort :: m ()
addWorkerCountListenerAsync :: (Int → IO ()) → IO () → m ()
fork :: m () → m ThreadId
getCurrentProgressAsync :: (ProgressFor (ExplorationModeFor m) → IO ()) → m ()
getCurrentStatisticsAsync :: (RunStatistics → IO ()) → m ()
getNumberOfWorkersAsync :: (Int → IO ()) → m ()
requestProgressUpdateAsync :: (ProgressFor (ExplorationModeFor m) → IO ()) → m ()
| Sets the size of the workload buffer ; for more information , see ' Supervisor.setWorkloadBufferSize ' ( which links to the " LogicGrowsOnTrees . Parallel . Common . Supervisor " module ) .
setWorkloadBufferSize :: Int → m ()
type Request exploration_mode worker_id m = SupervisorMonad exploration_mode worker_id m ()
data RequestQueue exploration_mode worker_id m = RequestQueue
requests :: !(TChan (Request exploration_mode worker_id m))
, receivers :: !(IORef [ProgressFor exploration_mode → IO ()])
, controllerThreads :: !(IORef [ThreadId])
}
| A basic supervisor request queue monad , which has an implicit ' RequestQueue '
object that it uses to communicate with the supervisor loop .
object that it uses to communicate with the supervisor loop.
-}
type RequestQueueReader exploration_mode worker_id m = ReaderT (RequestQueue exploration_mode worker_id m) IO
instance HasExplorationMode (RequestQueueReader exploration_mode worker_id m) where
type ExplorationModeFor (RequestQueueReader exploration_mode worker_id m) = exploration_mode
instance (SupervisorFullConstraint worker_id m) ⇒ RequestQueueMonad (RequestQueueReader exploration_mode worker_id m) where
abort = ask >>= enqueueRequest Supervisor.abortSupervisor
addWorkerCountListenerAsync listener callback = ask >>= enqueueRequest (Supervisor.addWorkerCountListener listener >> liftIO callback)
fork m = ask >>= flip forkControllerThread' m
getCurrentProgressAsync = (ask >>=) . getQuantityAsync Supervisor.getCurrentProgress
getCurrentStatisticsAsync = (ask >>=) . getQuantityAsync Supervisor.getCurrentStatistics
getNumberOfWorkersAsync = (ask >>=) . getQuantityAsync Supervisor.getNumberOfWorkers
requestProgressUpdateAsync receiveUpdatedProgress =
ask
>>=
liftIO
.
liftA2 (>>)
(addProgressReceiver receiveUpdatedProgress)
(enqueueRequest Supervisor.performGlobalProgressUpdate)
setWorkloadBufferSize size = ask >>= enqueueRequest (Supervisor.setWorkloadBufferSize size)
addWorkerCountListener :: RequestQueueMonad m ⇒ (Int → IO ()) → m ()
addWorkerCountListener listener = syncAsync (\callback → addWorkerCountListenerAsync listener (callback ()))
getCurrentProgress :: RequestQueueMonad m ⇒ m (ProgressFor (ExplorationModeFor m))
getCurrentProgress = syncAsync getCurrentProgressAsync
| Like ' getCurrentStatisticsAsync ' , but blocks until the result is ready .
getCurrentStatistics :: RequestQueueMonad m ⇒ m RunStatistics
getCurrentStatistics = syncAsync getCurrentStatisticsAsync
getNumberOfWorkers :: RequestQueueMonad m ⇒ m Int
getNumberOfWorkers = syncAsync getNumberOfWorkersAsync
requestProgressUpdate :: RequestQueueMonad m ⇒ m (ProgressFor (ExplorationModeFor m))
requestProgressUpdate = syncAsync requestProgressUpdateAsync
| General utility function for converting an asynchronous request to a
synchronous request ; it uses an ' MVar ' to hold the result of the request and
blocks until the ' MVar ' has been filled .
synchronous request; it uses an 'MVar' to hold the result of the request and
blocks until the 'MVar' has been filled.
-}
syncAsync :: MonadIO m ⇒ ((α → IO ()) → m ()) → m α
syncAsync runCommandAsync = do
result_mvar ← liftIO newEmptyMVar
runCommandAsync (putMVar result_mvar)
liftIO $
takeMVar result_mvar
`catch`
(\BlockedIndefinitelyOnMVar → error $ "blocked forever while waiting for controller to respond to request")
| Adds a callback to the given ' RequestQueue ' that will be invoked when the current global progress update has completed .
addProgressReceiver ::
MonadIO m' ⇒
(ProgressFor exploration_mode → IO ()) →
RequestQueue exploration_mode worker_id m →
m' ()
addProgressReceiver receiver =
liftIO
.
flip atomicModifyIORef ((receiver:) &&& const ())
.
receivers
enqueueRequest ::
MonadIO m' ⇒
Request exploration_mode worker_id m →
RequestQueue exploration_mode worker_id m →
m' ()
enqueueRequest request =
liftIO
.
atomically
.
flip writeTChan request
.
requests
enqueueRequestAndWait ::
(MonadIO m, MonadIO m') ⇒
Request exploration_mode worker_id m →
RequestQueue exploration_mode worker_id m →
m' ()
enqueueRequestAndWait request request_queue = do
signal ← liftIO newEmptyMVar
enqueueRequest (request >> liftIO (putMVar signal ())) request_queue
liftIO $ takeMVar signal
| Constructs a new ' RequestQueue ' .
newRequestQueue ::
MonadIO m' ⇒
m' (RequestQueue exploration_mode worker_id m)
newRequestQueue = liftIO $ liftM3 RequestQueue newTChanIO (newIORef []) (newIORef [])
tryDequeueRequest ::
MonadIO m' ⇒
RequestQueue exploration_mode worker_id m →
m' (Maybe (Request exploration_mode worker_id m))
tryDequeueRequest =
liftIO
.
atomically
.
tryReadTChan
.
requests
| Processes all of the requests in the given ' RequestQueue ' , and returns when
the queue has been emptied .
the queue has been emptied.
-}
processAllRequests ::
MonadIO m ⇒
RequestQueue exploration_mode worker_id m →
SupervisorMonad exploration_mode worker_id m ()
processAllRequests (RequestQueue requests _ _) = go
where
go =
(liftIO . atomically . tryReadTChan) requests
>>=
maybe (return ()) (>> go)
| Invokes all of the callbacks with the given progress and then clears the list of callbacks .
receiveProgress ::
MonadIO m' ⇒
RequestQueue exploration_mode worker_id m →
ProgressFor exploration_mode →
m' ()
receiveProgress queue progress =
liftIO
.
join
.
liftM (sequence_ . map ($ progress))
.
flip atomicModifyIORef (const [] &&& id)
.
receivers
$
queue
requestQueueProgram ::
MonadIO m ⇒
SupervisorProgram exploration_mode worker_id m
requestQueueProgram initialize =
flip (BlockingProgram initialize) id
.
liftIO
.
atomically
.
readTChan
.
requests
forkControllerThread ::
MonadIO m' ⇒
m' ()
forkControllerThread request_queue controller =
void $ forkControllerThread' request_queue controller
forkControllerThread' ::
MonadIO m' ⇒
RequestQueue exploration_mode worker_id m →
RequestQueueReader exploration_mode worker_id m () →
m' ThreadId
forkControllerThread' request_queue controller = liftIO $ do
start_signal ← newEmptyMVar
rec thread_id ← forkIO $ mask $ \(restore :: ∀ α. IO α → IO α)→
(restore $ takeMVar start_signal >> runReaderT controller request_queue)
`finally`
(atomicModifyIORef (controllerThreads request_queue) (delete thread_id &&& const ()))
atomicModifyIORef (controllerThreads request_queue) ((thread_id:) &&& const ())
NOTE : The following signal is needed because we do n't want the new
thread to start until after its thread i d has been added to the
list , as otherwise it could result in an orphan thread that wo n't
get garbage collected until the supervisor finishes due to a
peculiarity of the GHC runtime where it does n't garbage collect a
thread as long as a ThreadId referring to it exists .
thread to start until after its thread id has been added to the
list, as otherwise it could result in an orphan thread that won't
get garbage collected until the supervisor finishes due to a
peculiarity of the GHC runtime where it doesn't garbage collect a
thread as long as a ThreadId referring to it exists.
-}
putMVar start_signal ()
return thread_id
killControllerThreads ::
MonadIO m' ⇒
m' ()
killControllerThreads = liftIO . readIORef . controllerThreads >=> liftIO . mapM_ killThread
data CPUTimeTracker = CPUTimeTracker
{ trackerStarted :: IORef Bool
, trackerLastTime :: TVar (Maybe (UTCTime,Int))
, trackerTotalTime :: TVar NominalDiffTime
}
| Creates a new CPU time tracker , which should be equal to the amount of total
time used so far if we are continuing a previous run and zero otherwise .
time used so far if we are continuing a previous run and zero otherwise.
-}
newCPUTimeTracker :: NominalDiffTime → IO CPUTimeTracker
newCPUTimeTracker initial_cpu_time =
CPUTimeTracker
<$> newIORef False
<*> newTVarIO Nothing
<*> newTVarIO initial_cpu_time
computeAdditionalTime :: UTCTime → (UTCTime, Int) → NominalDiffTime
computeAdditionalTime current_time (last_time,last_number_of_workers) =
(current_time `diffUTCTime` last_time) * fromIntegral last_number_of_workers
startCPUTimeTracker :: RequestQueueMonad m ⇒ CPUTimeTracker → m ()
startCPUTimeTracker CPUTimeTracker{..} =
(liftIO $ atomicModifyIORef trackerStarted (const True &&& id))
>>=
flip unless (addWorkerCountListener $ \current_number_of_workers → do
current_time ← getCurrentTime
atomically $ do
readTVar trackerLastTime >>= maybe
(pure ())
(\last → modifyTVar' trackerTotalTime (+ computeAdditionalTime current_time last))
writeTVar trackerLastTime $ Just (current_time,current_number_of_workers)
)
getCurrentCPUTime :: CPUTimeTracker → IO NominalDiffTime
getCurrentCPUTime CPUTimeTracker{..} = do
current_time ← getCurrentTime
atomically $ do
old_total_time ← readTVar trackerTotalTime
maybe_last ← readTVar trackerLastTime
return $ old_total_time + maybe 0 (computeAdditionalTime current_time) maybe_last
getQuantityAsync ::
( MonadIO m'
, SupervisorFullConstraint worker_id m
) ⇒
SupervisorMonad exploration_mode worker_id m α →
(α → IO ()) →
RequestQueue exploration_mode worker_id m →
m' ()
getQuantityAsync getQuantity receiveQuantity =
enqueueRequest $ getQuantity >>= liftIO . receiveQuantity
|
aad17178862850ebbac2293cde9c9744c1eb9deaad9bc2ffabe48494aca04428 | TristeFigure/shuriken | jenny.clj | (ns shuriken.jenny
"Jenny said
When she was just about five years old
You know why parents gonna be the death of us all
Two TV sets and two Cadillac cars
Well you know, it ain't gonna help me at all, not just a tiny bit
Then one fine mornin' she turns on a New York station
She doesn't believe what she hears at all
Ooh, she started dancin' to that fine fine music
You know her life is saved by rock 'n' roll, yeah rock 'n' roll
Despite all the computations
You could just dance
To that rock 'n' roll station
And baby it was alright (it was alright)
Hey it was alright (it was alright)
Hey here she comes now!
Jump! jump!
The Velvet Underground - Rock & Roll"
(:use shuriken.debug
clojure.pprint)
(:require [dance.core :refer [dance path-dance]]
[lexikon.core :refer [lexical-context]]
[shuriken.exception :refer [silence]]
[shuriken.sequential :refet [get-nth-in assoc-nth-in]]))
(defmulti transform
(fn [form _ctx]
(if (list? form)
(let [m (-> form first resolve meta)]
(symbol (-> m :ns .getName name)
(-> m :name name)))
(class form))))
(def stock-sym (gensym "stock-"))
(defmethod transform :default [form {:keys [path]}]
`(let [ret# ~form]
(assoc! ~stock-sym ~path {:form '~form
:result ret#
; :context (lexical-context)
})
ret#))
(defn transform-bindings [bindings ctx]
(mapv (fn [[k v]]
[k (transform v)])
(partition 2 bindings)))
(defmethod transform 'clojure.core/let [[f bindings & body] ctx]
(println "----------------------------------")
(pprint `(~f ~(transform-bindings bindings)
~@(map transform body)))
(println "----------------------------------")
`(~f ~bindings
~@body))
(defn passover [& code]
(let [new-code (dance code path-dance
; :debug true
; :debug-context true
:post (fn [form ctx]
(let [new-form (if (list? form)
(transform form ctx)
form)]
[new-form ctx])))]
`(let [~stock-sym (transient {})]
~@new-code
(pprint (persistent! ~stock-sym)))))
(defn inject-in-code [k code stock]
(->> stock
(sort-by #(-> % first count -))
(reduce (fn [new-code [path data]]
(assoc-nth-in path (get data k)))
code)))
(def inject-results (partial inject-in-code :result))
(def inject-results (partial inject-in-code :form))
(def code
'(let [a 1
b 0]
(println (+ a b))
(println (/ a b))
(println (- a b))))
(pprint (-> code passover eval))
| null | https://raw.githubusercontent.com/TristeFigure/shuriken/cd36dd2a4005c85260125d89d5a3f475d248e6e4/src/shuriken/jenny.clj | clojure | :context (lexical-context)
:debug true
:debug-context true | (ns shuriken.jenny
"Jenny said
When she was just about five years old
You know why parents gonna be the death of us all
Two TV sets and two Cadillac cars
Well you know, it ain't gonna help me at all, not just a tiny bit
Then one fine mornin' she turns on a New York station
She doesn't believe what she hears at all
Ooh, she started dancin' to that fine fine music
You know her life is saved by rock 'n' roll, yeah rock 'n' roll
Despite all the computations
You could just dance
To that rock 'n' roll station
And baby it was alright (it was alright)
Hey it was alright (it was alright)
Hey here she comes now!
Jump! jump!
The Velvet Underground - Rock & Roll"
(:use shuriken.debug
clojure.pprint)
(:require [dance.core :refer [dance path-dance]]
[lexikon.core :refer [lexical-context]]
[shuriken.exception :refer [silence]]
[shuriken.sequential :refet [get-nth-in assoc-nth-in]]))
(defmulti transform
(fn [form _ctx]
(if (list? form)
(let [m (-> form first resolve meta)]
(symbol (-> m :ns .getName name)
(-> m :name name)))
(class form))))
(def stock-sym (gensym "stock-"))
(defmethod transform :default [form {:keys [path]}]
`(let [ret# ~form]
(assoc! ~stock-sym ~path {:form '~form
:result ret#
})
ret#))
(defn transform-bindings [bindings ctx]
(mapv (fn [[k v]]
[k (transform v)])
(partition 2 bindings)))
(defmethod transform 'clojure.core/let [[f bindings & body] ctx]
(println "----------------------------------")
(pprint `(~f ~(transform-bindings bindings)
~@(map transform body)))
(println "----------------------------------")
`(~f ~bindings
~@body))
(defn passover [& code]
(let [new-code (dance code path-dance
:post (fn [form ctx]
(let [new-form (if (list? form)
(transform form ctx)
form)]
[new-form ctx])))]
`(let [~stock-sym (transient {})]
~@new-code
(pprint (persistent! ~stock-sym)))))
(defn inject-in-code [k code stock]
(->> stock
(sort-by #(-> % first count -))
(reduce (fn [new-code [path data]]
(assoc-nth-in path (get data k)))
code)))
(def inject-results (partial inject-in-code :result))
(def inject-results (partial inject-in-code :form))
(def code
'(let [a 1
b 0]
(println (+ a b))
(println (/ a b))
(println (- a b))))
(pprint (-> code passover eval))
|
78bd9b351510e2a70200ff8c867bd68e1d6fd62750a51ebacc0e279f6bf9e27f | planetfederal/signal | rest_test.clj | (ns signal.rest-test
(:require [signal.test-utils :as utils]
[clojure.test :refer :all]
[clojure.spec.gen.alpha :as spec-gen]
[clojure.spec.alpha :as spec]
[signal.specs.input :refer :all]
[clojure.data.json :as json]))
(use-fixtures :once utils/setup-fixtures)
(deftest input-rest-test
(testing "Input REST"
(let [sample-input (-> (spec/gen :signal.specs.input/input-http) spec-gen/sample first)
res-post (utils/request-post "/api/inputs" (json/write-str sample-input))
id (get-in res-post [:result :id])
new-input (assoc sample-input :id id)
query-input (:result (utils/request-get (str "/api/inputs/" id)))
query-after (utils/request-get (str "/api/inputs/" id))
res-delete (utils/request-delete (str "/api/inputs/" id))]
(is (some? (:result res-post)))
(is (= (:id new-input) (:id query-input)))
(is (= (:type new-input) (:type query-input)))
(is (= (:definition new-input) (:definition query-input)))
(is (= (:result res-delete) "success"))
(is (= (:result query-after) (:result res-post))))))
(deftest processor-rest-test
(testing "processor REST"
(let [sample-processor (-> (spec/gen :signal.specs.processor/processor-spec)
spec-gen/sample first)
res-post (utils/request-post "/api/processors" (json/write-str sample-processor))
id (get-in res-post [:result :id])
new-processor (assoc sample-processor :id id)
query-processor (:result (utils/request-get (str "/api/processors/" id)))
query-after (utils/request-get (str "/api/processors/" id))
res-delete (utils/request-delete (str "/api/processors/" id))]
(is (some? (:result res-post)))
(is (= (:id new-processor) (:id query-processor)))
(is (= (:type new-processor) (:type query-processor)))
(is (= (:definition new-processor) (:definition query-processor)))
(is (= (:result res-delete) "success"))
(is (= (:result query-after) (:result res-post) )))))
| null | https://raw.githubusercontent.com/planetfederal/signal/e3eae56c753f0a56614ba8522278057ab2358c96/test/signal/rest_test.clj | clojure | (ns signal.rest-test
(:require [signal.test-utils :as utils]
[clojure.test :refer :all]
[clojure.spec.gen.alpha :as spec-gen]
[clojure.spec.alpha :as spec]
[signal.specs.input :refer :all]
[clojure.data.json :as json]))
(use-fixtures :once utils/setup-fixtures)
(deftest input-rest-test
(testing "Input REST"
(let [sample-input (-> (spec/gen :signal.specs.input/input-http) spec-gen/sample first)
res-post (utils/request-post "/api/inputs" (json/write-str sample-input))
id (get-in res-post [:result :id])
new-input (assoc sample-input :id id)
query-input (:result (utils/request-get (str "/api/inputs/" id)))
query-after (utils/request-get (str "/api/inputs/" id))
res-delete (utils/request-delete (str "/api/inputs/" id))]
(is (some? (:result res-post)))
(is (= (:id new-input) (:id query-input)))
(is (= (:type new-input) (:type query-input)))
(is (= (:definition new-input) (:definition query-input)))
(is (= (:result res-delete) "success"))
(is (= (:result query-after) (:result res-post))))))
(deftest processor-rest-test
(testing "processor REST"
(let [sample-processor (-> (spec/gen :signal.specs.processor/processor-spec)
spec-gen/sample first)
res-post (utils/request-post "/api/processors" (json/write-str sample-processor))
id (get-in res-post [:result :id])
new-processor (assoc sample-processor :id id)
query-processor (:result (utils/request-get (str "/api/processors/" id)))
query-after (utils/request-get (str "/api/processors/" id))
res-delete (utils/request-delete (str "/api/processors/" id))]
(is (some? (:result res-post)))
(is (= (:id new-processor) (:id query-processor)))
(is (= (:type new-processor) (:type query-processor)))
(is (= (:definition new-processor) (:definition query-processor)))
(is (= (:result res-delete) "success"))
(is (= (:result query-after) (:result res-post) )))))
| |
ada55823b4eae53fd4b8631d405bb8497a2915524a317ea883a9b3ab24ab7e7e | footprintanalytics/footprint-web | mysql_test.clj | (ns metabase.driver.mysql-test
(:require [clojure.java.jdbc :as jdbc]
[clojure.string :as str]
[clojure.test :refer :all]
[honeysql.core :as hsql]
[java-time :as t]
[metabase.config :as config]
[metabase.db.metadata-queries :as metadata-queries]
[metabase.driver :as driver]
[metabase.driver.mysql :as mysql]
[metabase.driver.mysql.ddl :as mysql.ddl]
[metabase.driver.sql-jdbc.connection :as sql-jdbc.conn]
[metabase.driver.sql-jdbc.sync :as sql-jdbc.sync]
[metabase.driver.sql-jdbc.sync.describe-table :as sql-jdbc.describe-table]
[metabase.driver.sql.query-processor :as sql.qp]
[metabase.models.database :refer [Database]]
[metabase.models.field :refer [Field]]
[metabase.models.table :refer [Table]]
[metabase.query-processor :as qp]
used for one SSL with PEM connectivity test
[metabase.query-processor-test.string-extracts-test :as string-extracts-test]
[metabase.sync :as sync]
[metabase.sync.analyze.fingerprint :as fingerprint]
[metabase.test :as mt]
[metabase.test.data.interface :as tx]
[metabase.util :as u]
[metabase.util.date-2 :as u.date]
[metabase.util.honeysql-extensions :as hx]
[toucan.db :as db]
[toucan.hydrate :refer [hydrate]]
[toucan.util.test :as tt]))
(deftest all-zero-dates-test
(mt/test-driver :mysql
(testing (str "MySQL allows 0000-00-00 dates, but JDBC does not; make sure that MySQL is converting them to NULL "
"when returning them like we asked")
(let [spec (sql-jdbc.conn/connection-details->spec :mysql (tx/dbdef->connection-details :mysql :server nil))]
;; Create the DB
(doseq [sql ["DROP DATABASE IF EXISTS all_zero_dates;"
"CREATE DATABASE all_zero_dates;"]]
(jdbc/execute! spec [sql]))
Create Table & add data
(let [details (tx/dbdef->connection-details :mysql :db {:database-name "all_zero_dates"})
spec (-> (sql-jdbc.conn/connection-details->spec :mysql details)
;; allow inserting dates where value is '0000-00-00' -- this is disallowed by default on newer
;; versions of MySQL, but we still want to test that we can handle it correctly for older ones
(assoc :sessionVariables "sql_mode='ALLOW_INVALID_DATES'"))]
(doseq [sql ["CREATE TABLE `exciting-moments-in-history` (`id` integer, `moment` timestamp);"
"INSERT INTO `exciting-moments-in-history` (`id`, `moment`) VALUES (1, '0000-00-00');"]]
(jdbc/execute! spec [sql]))
;; create & sync MB DB
(tt/with-temp Database [database {:engine "mysql", :details details}]
(sync/sync-database! database)
(mt/with-db database
;; run the query
(is (= [[1 nil]]
(mt/rows
(mt/run-mbql-query exciting-moments-in-history)))))))))))
;; Test how TINYINT(1) columns are interpreted. By default, they should be interpreted as integers, but with the
;; correct additional options, we should be able to change that -- see
;;
(tx/defdataset tiny-int-ones
[["number-of-cans"
[{:field-name "thing", :base-type :type/Text}
{:field-name "number-of-cans", :base-type {:native "tinyint(1)"}, :effective-type :type/Integer}]
[["Six Pack" 6]
["Toucan" 2]
["Empty Vending Machine" 0]]]])
(defn- db->fields [db]
(let [table-ids (db/select-ids 'Table :db_id (u/the-id db))]
(set (map (partial into {}) (db/select [Field :name :base_type :semantic_type] :table_id [:in table-ids])))))
(deftest tiny-int-1-test
(mt/test-driver :mysql
(mt/dataset tiny-int-ones
;; trigger a full sync on this database so fields are categorized correctly
(sync/sync-database! (mt/db))
(testing "By default TINYINT(1) should be a boolean"
(is (= #{{:name "number-of-cans", :base_type :type/Boolean, :semantic_type :type/Category}
{:name "id", :base_type :type/Integer, :semantic_type :type/PK}
{:name "thing", :base_type :type/Text, :semantic_type :type/Category}}
(db->fields (mt/db)))))
(testing "if someone says specifies `tinyInt1isBit=false`, it should come back as a number instead"
(tt/with-temp Database [db {:engine "mysql"
:details (assoc (:details (mt/db))
:additional-options "tinyInt1isBit=false")}]
(sync/sync-database! db)
(is (= #{{:name "number-of-cans", :base_type :type/Integer, :semantic_type :type/Quantity}
{:name "id", :base_type :type/Integer, :semantic_type :type/PK}
{:name "thing", :base_type :type/Text, :semantic_type :type/Category}}
(db->fields db))))))))
(tx/defdataset year-db
[["years"
[{:field-name "year_column", :base-type {:native "YEAR"}, :effective-type :type/Date}]
[[2001] [2002] [1999]]]])
(deftest year-test
(mt/test-driver :mysql
(mt/dataset year-db
(testing "By default YEAR"
(is (= #{{:name "year_column", :base_type :type/Date, :semantic_type nil}
{:name "id", :base_type :type/Integer, :semantic_type :type/PK}}
(db->fields (mt/db)))))
(let [table (db/select-one Table :db_id (u/id (mt/db)))
fields (db/select Field :table_id (u/id table) :name "year_column")]
(testing "Can select from this table"
(is (= [[#t "2001-01-01"] [#t "2002-01-01"] [#t "1999-01-01"]]
(metadata-queries/table-rows-sample table fields (constantly conj)))))
(testing "We can fingerprint this table"
(is (= 1
(:updated-fingerprints (#'fingerprint/fingerprint-table! table fields)))))))))
(deftest db-default-timezone-test
(mt/test-driver :mysql
(let [timezone (fn [result-row]
(let [db (mt/db)]
(with-redefs [jdbc/query (let [orig jdbc/query]
(fn [spec sql-args & options]
(if (and (string? sql-args)
(str/includes? sql-args "GLOBAL.time_zone"))
[result-row]
(apply orig spec sql-args options))))]
(driver/db-default-timezone driver/*driver* db))))]
(testing "Should use global timezone by default"
(is (= "US/Pacific"
(timezone {:global_tz "US/Pacific", :system_tz "UTC"}))))
(testing "If global timezone is 'SYSTEM', should use system timezone"
(is (= "UTC"
(timezone {:global_tz "SYSTEM", :system_tz "UTC"}))))
(testing "Should fall back to returning `offset` if global/system aren't present"
(is (= "+00:00"
(timezone {:offset "00:00"}))))
(testing "If global timezone is invalid, should fall back to offset"
(is (= "-08:00"
(timezone {:global_tz "PDT", :system_tz "PDT", :offset "-08:00"}))))
(testing "Should add a `+` if needed to offset"
(is (= "+00:00"
(timezone {:global_tz "PDT", :system_tz "UTC", :offset "00:00"})))))
(testing "real timezone query doesn't fail"
(is (nil? (try
(driver/db-default-timezone driver/*driver* (mt/db))
nil
(catch Throwable e
e)))))))
(deftest timezone-date-formatting-test
(mt/test-driver :mysql
Most of our tests either deal in UTC ( offset 00:00 ) or America / Los_Angeles timezones ( -07:00/-08:00 ) . When dealing
;; with dates, we will often truncate the timestamp to a date. When we only test with negative timezone offsets, in
;; combination with this truncation, means we could have a bug and it's hidden by this negative-only offset. As an
example , if we have a datetime like 2018 - 08 - 17 00:00:00 - 08:00 , converting to UTC this becomes 2018 - 08 - 17
08:00:00 + 00:00 , which when truncated is still 2018 - 08 - 17 . That same scenario in Hong Kong is 2018 - 08 - 17
00:00:00 + 08:00 , which then becomes 2018 - 08 - 16 16:00:00 + 00:00 when converted to UTC , which will truncate to
2018 - 08 - 16 , instead of 2018 - 08 - 17
(mt/with-system-timezone-id "Asia/Hong_Kong"
(letfn [(run-query-with-report-timezone [report-timezone]
(mt/with-temporary-setting-values [report-timezone report-timezone]
(mt/first-row
(qp/process-query
{:database (mt/id)
:type :native
:settings {:report-timezone "UTC"}
:native {:query "SELECT cast({{date}} as date)"
:template-tags {:date {:name "date" :display_name "Date" :type "date"}}}
:parameters [{:type "date/single" :target ["variable" ["template-tag" "date"]] :value "2018-04-18"}]}))))]
(testing "date formatting when system-timezone == report-timezone"
(is (= ["2018-04-18T00:00:00+08:00"]
(run-query-with-report-timezone "Asia/Hong_Kong"))))
This tests a similar scenario , but one in which the JVM timezone is in Hong Kong , but the report timezone
is in Los Angeles . The Joda Time date parsing functions for the most part default to UTC . Our tests all run
;; with a UTC JVM timezone. This test catches a bug where we are incorrectly assuming a date is in UTC when
the JVM timezone is different .
;;
;; The original bug can be found here: . The MySQL driver code
was parsing the date using JodateTime 's date parser , which is in UTC . The MySQL driver code was assuming
;; that date was in the system timezone rather than UTC which caused an incorrect conversion and with the
;; trucation, let to it being off by a day
(testing "date formatting when system-timezone != report-timezone"
(is (= ["2018-04-18T00:00:00-07:00"]
(run-query-with-report-timezone "America/Los_Angeles"))))))))
(def ^:private sample-connection-details
{:db "my_db", :host "localhost", :port "3306", :user "cam", :password "bad-password"})
(def ^:private sample-jdbc-spec
{:password "bad-password"
:characterSetResults "UTF8"
:characterEncoding "UTF8"
:classname "org.mariadb.jdbc.Driver"
:subprotocol "mysql"
:zeroDateTimeBehavior "convertToNull"
:user "cam"
:subname "//localhost:3306/my_db"
:connectionAttributes (str "program_name:" config/mb-version-and-process-identifier)
:useCompression true
:useUnicode true})
(deftest connection-spec-test
(testing "Do `:ssl` connection details give us the connection spec we'd expect?"
(is (= (assoc sample-jdbc-spec :useSSL true :serverSslCert "sslCert")
(sql-jdbc.conn/connection-details->spec :mysql (assoc sample-connection-details :ssl true
:ssl-cert "sslCert")))))
(testing "what about non-SSL connections?"
(is (= (assoc sample-jdbc-spec :useSSL false)
(sql-jdbc.conn/connection-details->spec :mysql sample-connection-details))))
(testing "Connections that are `:ssl false` but with `useSSL` in the additional options should be treated as SSL (see #9629)"
(is (= (assoc sample-jdbc-spec :useSSL true
:subname "//localhost:3306/my_db?useSSL=true&trustServerCertificate=true")
(sql-jdbc.conn/connection-details->spec :mysql
(assoc sample-connection-details
:ssl false
:additional-options "useSSL=true&trustServerCertificate=true")))))
(testing "A program_name specified in additional-options is not overwritten by us"
(let [conn-attrs "connectionAttributes=program_name:my_custom_value"]
(is (= (-> sample-jdbc-spec
(assoc :subname (str "//localhost:3306/my_db?" conn-attrs), :useSSL false)
;; because program_name was in additional-options, we shouldn't use emit :connectionAttributes
(dissoc :connectionAttributes))
(sql-jdbc.conn/connection-details->spec
:mysql
(assoc sample-connection-details :additional-options conn-attrs)))))))
(deftest read-timediffs-test
(mt/test-driver :mysql
(testing "Make sure negative result of *diff() functions don't cause Exceptions (#10983)"
(doseq [{:keys [interval expected message]}
[{:interval "-1 HOUR"
:expected "-01:00:00"
:message "Negative durations should come back as Strings"}
{:interval "25 HOUR"
:expected "25:00:00"
:message "Durations outside the valid range of `LocalTime` should come back as Strings"}
{:interval "1 HOUR"
:expected #t "01:00:00"
:message "A `timediff()` result within the valid range should still come back as a `LocalTime`"}]]
(testing (str "\n" interval "\n" message)
(is (= [expected]
(mt/first-row
(qp/process-query
(assoc (mt/native-query
{:query (format "SELECT timediff(current_timestamp + INTERVAL %s, current_timestamp)" interval)})
disable the middleware that normally converts ` LocalTime ` to ` Strings ` so we can verify
;; our driver is actually doing the right thing
:middleware {:format-rows? false}))))))))))
(defn- table-fingerprint
[{:keys [fields name]}]
{:name name
:fields (map #(select-keys % [:name :base_type]) fields)})
(deftest system-versioned-tables-test
(mt/test-driver :mysql
(testing "system versioned tables appear during a sync"
(let [spec (sql-jdbc.conn/connection-details->spec :mysql (tx/dbdef->connection-details :mysql :server nil))]
;; Create the DB
(doseq [sql ["DROP DATABASE IF EXISTS versioned_tables;"
"CREATE DATABASE versioned_tables;"]]
(jdbc/execute! spec [sql]))
Create Table & add data
(let [details (tx/dbdef->connection-details :mysql :db {:database-name "versioned_tables"})
spec (sql-jdbc.conn/connection-details->spec :mysql details)
compat (try
(doseq [sql ["CREATE TABLE IF NOT EXISTS src1 (id INTEGER, t TEXT);"
"CREATE TABLE IF NOT EXISTS src2 (id INTEGER, t TEXT);"
"ALTER TABLE src2 ADD SYSTEM VERSIONING;"
"INSERT INTO src1 VALUES (1, '2020-03-01 12:20:35');"
"INSERT INTO src2 VALUES (1, '2020-03-01 12:20:35');"]]
(jdbc/execute! spec [sql]))
true
(catch java.sql.SQLSyntaxErrorException se
;; if an error is received with SYSTEM VERSIONING mentioned, the version
;; of mysql or mariadb being tested against does not support system versioning,
;; so do not continue
(if (re-matches #".*VERSIONING'.*" (.getMessage se))
false
(throw se))))]
(when compat
(tt/with-temp Database [database {:engine "mysql", :details details}]
(sync/sync-database! database)
(is (= [{:name "src1"
:fields [{:name "id"
:base_type :type/Integer}
{:name "t"
:base_type :type/Text}]}
{:name "src2"
:fields [{:name "id"
:base_type :type/Integer}
{:name "t"
:base_type :type/Text}]}]
(->> (hydrate (db/select Table :db_id (:id database) {:order-by [:name]}) :fields)
(map table-fingerprint)))))))))))
(deftest group-on-time-column-test
(mt/test-driver :mysql
(testing "can group on TIME columns (#12846)"
(mt/dataset attempted-murders
(let [now-date-str (u.date/format (t/local-date (t/zone-id "UTC")))
add-date-fn (fn [t] [(str now-date-str "T" t)])]
(testing "by minute"
(is (= (map add-date-fn ["00:14:00Z" "00:23:00Z" "00:35:00Z"])
(mt/rows
(mt/run-mbql-query attempts
{:breakout [!minute.time]
:order-by [[:asc !minute.time]]
:limit 3})))))
(testing "by hour"
(is (= (map add-date-fn ["23:00:00Z" "20:00:00Z" "19:00:00Z"])
(mt/rows
(mt/run-mbql-query attempts
{:breakout [!hour.time]
:order-by [[:desc !hour.time]]
:limit 3}))))))))))
(defn- pretty-sql [s]
(str/replace s #"`" ""))
(deftest do-not-cast-to-date-if-column-is-already-a-date-test
(testing "Don't wrap Field in date() if it's already a DATE (#11502)"
(mt/test-driver :mysql
(mt/dataset attempted-murders
(let [query (mt/mbql-query attempts
{:aggregation [[:count]]
:breakout [!day.date]})]
(is (= (str "SELECT attempts.date AS date, count(*) AS count "
"FROM attempts "
"GROUP BY attempts.date "
"ORDER BY attempts.date ASC")
(some-> (qp/compile query) :query pretty-sql))))))
(testing "trunc-with-format should not cast a field if it is already a DATETIME"
(is (= ["SELECT str_to_date(date_format(CAST(field AS datetime), '%Y'), '%Y')"]
(hsql/format {:select [(#'mysql/trunc-with-format "%Y" :field)]})))
(is (= ["SELECT str_to_date(date_format(field, '%Y'), '%Y')"]
(hsql/format {:select [(#'mysql/trunc-with-format
"%Y"
(hx/with-database-type-info :field "datetime"))]}))))))
(deftest mysql-connect-with-ssl-and-pem-cert-test
(mt/test-driver :mysql
(if (System/getenv "MB_MYSQL_SSL_TEST_SSL_CERT")
(testing "MySQL with SSL connectivity using PEM certificate"
(mt/with-env-keys-renamed-by #(str/replace-first % "mb-mysql-ssl-test" "mb-mysql-test")
(string-extracts-test/test-breakout)))
(println (u/format-color 'yellow
"Skipping %s because %s env var is not set"
"mysql-connect-with-ssl-and-pem-cert-test"
"MB_MYSQL_SSL_TEST_SSL_CERT")))))
;; MariaDB doesn't have support for explicit JSON columns, it does it in a more SQL Server-ish way
;; where LONGTEXT columns are the actual JSON columns and there's JSON functions that just work on them,
;; construed as text.
;; You could even have mixed JSON / non JSON columns...
Therefore , we ca n't just automatically get JSON columns in MariaDB . Therefore , no JSON support .
;; Therefore, no JSON tests.
(defn- version-query [db-id] {:type :native, :native {:query "SELECT VERSION();"}, :database db-id})
(defn- is-mariadb? [db-id] (str/includes?
(or (get-in (qp/process-userland-query (version-query db-id)) [:data :rows 0 0]) "")
"Maria"))
(deftest nested-field-column-test
(mt/test-driver :mysql
(mt/dataset json
(when (not (is-mariadb? (u/id (mt/db))))
(testing "Nested field column listing"
(is (= #{{:name "json_bit → 1234123412314",
:database-type "timestamp",
:base-type :type/DateTime,
:database-position 0,
:visibility-type :normal,
:nfc-path [:json_bit "1234123412314"]}
{:name "json_bit → boop",
:database-type "timestamp",
:base-type :type/DateTime,
:database-position 0,
:visibility-type :normal,
:nfc-path [:json_bit "boop"]}
{:name "json_bit → genres",
:database-type "text",
:base-type :type/Array,
:database-position 0,
:visibility-type :normal,
:nfc-path [:json_bit "genres"]}
{:name "json_bit → 1234",
:database-type "bigint",
:base-type :type/Integer,
:database-position 0,
:visibility-type :normal,
:nfc-path [:json_bit "1234"]}
{:name "json_bit → doop",
:database-type "text",
:base-type :type/Text,
:database-position 0,
:visibility-type :normal,
:nfc-path [:json_bit "doop"]}
{:name "json_bit → noop",
:database-type "timestamp",
:base-type :type/DateTime,
:database-position 0,
:visibility-type :normal,
:nfc-path [:json_bit "noop"]}
{:name "json_bit → zoop",
:database-type "timestamp",
:base-type :type/DateTime,
:database-position 0,
:visibility-type :normal,
:nfc-path [:json_bit "zoop"]}
{:name "json_bit → published",
:database-type "text",
:base-type :type/Text,
:database-position 0,
:visibility-type :normal,
:nfc-path [:json_bit "published"]}
{:name "json_bit → title",
:database-type "text",
:base-type :type/Text,
:database-position 0,
:visibility-type :normal,
:nfc-path [:json_bit "title"]}}
(sql-jdbc.sync/describe-nested-field-columns
:mysql
(mt/db)
{:name "json"}))))))))
(deftest big-nested-field-column-test
(mt/test-driver :mysql
(mt/dataset json
(when (not (is-mariadb? (u/id (mt/db))))
(testing "Nested field column listing, but big"
(is (= sql-jdbc.describe-table/max-nested-field-columns
(count (sql-jdbc.sync/describe-nested-field-columns
:mysql
(mt/db)
{:name "big_json"})))))))))
(deftest json-query-test
(let [boop-identifier (:form (hx/with-type-info (hx/identifier :field "boop" "bleh -> meh") {}))]
(testing "Transforming MBQL query with JSON in it to mysql query works"
(let [boop-field {:nfc_path [:bleh :meh] :database_type "bigint"}]
(is (= ["convert(json_extract(boop.bleh, ?), UNSIGNED)" "$.\"meh\""]
(hsql/format (#'sql.qp/json-query :mysql boop-identifier boop-field))))))
(testing "What if types are weird and we have lists"
(let [weird-field {:nfc_path [:bleh "meh" :foobar 1234] :database_type "bigint"}]
(is (= ["convert(json_extract(boop.bleh, ?), UNSIGNED)" "$.\"meh\".\"foobar\".\"1234\""]
(hsql/format (#'sql.qp/json-query :mysql boop-identifier weird-field))))))
(testing "Doesn't complain when field is boolean"
(let [boolean-boop-field {:database_type "boolean" :nfc_path [:bleh "boop" :foobar 1234]}]
(is (= ["json_extract(boop.bleh, ?)" "$.\"boop\".\"foobar\".\"1234\""]
(hsql/format (#'sql.qp/json-query :mysql boop-identifier boolean-boop-field))))))))
(deftest json-alias-test
(mt/test-driver :mysql
(when (not (is-mariadb? (u/id (mt/db))))
(testing "json breakouts and order bys have alias coercion"
(mt/dataset json
(let [table (db/select-one Table :db_id (u/id (mt/db)) :name "json")]
(sync/sync-table! table)
(let [field (db/select-one Field :table_id (u/id table) :name "json_bit → 1234")
compile-res (qp/compile
{:database (u/the-id (mt/db))
:type :query
:query {:source-table (u/the-id table)
:aggregation [[:count]]
:breakout [[:field (u/the-id field) nil]]}})]
(is (= (str "SELECT convert(json_extract(json.json_bit, ?), UNSIGNED) AS `json_bit → 1234`, "
"count(*) AS `count` FROM `json` GROUP BY convert(json_extract(json.json_bit, ?), UNSIGNED) "
"ORDER BY convert(json_extract(json.json_bit, ?), UNSIGNED) ASC")
(:query compile-res)))
(is (= '("$.\"1234\"" "$.\"1234\"" "$.\"1234\"") (:params compile-res))))))))))
(deftest complicated-json-identifier-test
(mt/test-driver :mysql
(when (not (is-mariadb? (u/id (mt/db))))
(testing "Deal with complicated identifier (#22967, but for mysql)"
(mt/dataset json
(let [database (mt/db)
table (db/select-one Table :db_id (u/id database) :name "json")]
(sync/sync-table! table)
(let [field (db/select-one Field :table_id (u/id table) :name "json_bit → 1234")]
(mt/with-everything-store
(let [field-clause [:field (u/the-id field) {:binning
{:strategy :num-bins,
:num-bins 100,
:min-value 0.75,
:max-value 54.0,
:bin-width 0.75}}]]
(is (= ["((floor(((convert(json_extract(json.json_bit, ?), UNSIGNED) - 0.75) / 0.75)) * 0.75) + 0.75)" "$.\"1234\""]
(hsql/format (sql.qp/->honeysql :mysql field-clause)))))))))))))
(tx/defdataset json-unwrap-bigint-and-boolean
"Used for testing mysql json value unwrapping"
[["bigint-and-bool-table"
[{:field-name "jsoncol" :base-type :type/JSON}]
[["{\"mybool\":true, \"myint\":1234567890123456789}"]
["{\"mybool\":false,\"myint\":12345678901234567890}"]
["{\"mybool\":true, \"myint\":123}"]]]])
(deftest json-unwrapping-bigint-and-boolean
(mt/test-driver :mysql
(when-not (is-mariadb? (mt/id))
(mt/dataset json-unwrap-bigint-and-boolean
(sync/sync-database! (mt/db))
(testing "Fields marked as :type/SerializedJSON are fingerprinted that way"
(is (= #{{:name "id", :base_type :type/Integer, :semantic_type :type/PK}
{:name "jsoncol", :base_type :type/SerializedJSON, :semantic_type :type/SerializedJSON}
{:name "jsoncol → myint", :base_type :type/Number, :semantic_type nil}
{:name "jsoncol → mybool", :base_type :type/Boolean, :semantic_type nil}}
(db->fields (mt/db)))))
(testing "Nested field columns are correct"
(is (= #{{:name "jsoncol → mybool", :database-type "boolean", :base-type :type/Boolean, :database-position 0, :visibility-type :normal, :nfc-path [:jsoncol "mybool"]}
{:name "jsoncol → myint", :database-type "double precision", :base-type :type/Number, :database-position 0, :visibility-type :normal, :nfc-path [:jsoncol "myint"]}}
(sql-jdbc.sync/describe-nested-field-columns
:mysql
(mt/db)
(db/select-one Table :db_id (mt/id) :name "bigint-and-bool-table")))))))))
(deftest can-shut-off-json-unwrapping
(mt/test-driver :mysql
;; in here we fiddle with the mysql db details
(let [db (db/select-one Database :id (mt/id))]
(try
(db/update! Database (mt/id) {:details (assoc (:details db) :json-unfolding true)})
(is (= true (driver/database-supports? :mysql :nested-field-columns (mt/db))))
(db/update! Database (mt/id) {:details (assoc (:details db) :json-unfolding false)})
(is (= false (driver/database-supports? :mysql :nested-field-columns (mt/db))))
(db/update! Database (mt/id) {:details (assoc (:details db) :json-unfolding nil)})
(is (= true (driver/database-supports? :mysql :nested-field-columns (mt/db))))
un fiddle with the mysql db details .
(finally (db/update! Database (mt/id) :details (:details db)))))))
(deftest ddl.execute-with-timeout-test
(mt/test-driver :mysql
(mt/dataset json
(let [db-spec (sql-jdbc.conn/db->pooled-connection-spec (mt/db))]
(is (thrown-with-msg?
Exception
#"Killed mysql process id [\d,]+ due to timeout."
(#'mysql.ddl/execute-with-timeout! db-spec db-spec 10 ["select sleep(5)"])))
(is (= true (#'mysql.ddl/execute-with-timeout! db-spec db-spec 5000 ["select sleep(0.1) as val"])))))))
| null | https://raw.githubusercontent.com/footprintanalytics/footprint-web/d3090d943dd9fcea493c236f79e7ef8a36ae17fc/test/metabase/driver/mysql_test.clj | clojure | Create the DB
allow inserting dates where value is '0000-00-00' -- this is disallowed by default on newer
versions of MySQL, but we still want to test that we can handle it correctly for older ones
create & sync MB DB
run the query
Test how TINYINT(1) columns are interpreted. By default, they should be interpreted as integers, but with the
correct additional options, we should be able to change that -- see
trigger a full sync on this database so fields are categorized correctly
with dates, we will often truncate the timestamp to a date. When we only test with negative timezone offsets, in
combination with this truncation, means we could have a bug and it's hidden by this negative-only offset. As an
with a UTC JVM timezone. This test catches a bug where we are incorrectly assuming a date is in UTC when
The original bug can be found here: . The MySQL driver code
that date was in the system timezone rather than UTC which caused an incorrect conversion and with the
trucation, let to it being off by a day
because program_name was in additional-options, we shouldn't use emit :connectionAttributes
our driver is actually doing the right thing
Create the DB
if an error is received with SYSTEM VERSIONING mentioned, the version
of mysql or mariadb being tested against does not support system versioning,
so do not continue
MariaDB doesn't have support for explicit JSON columns, it does it in a more SQL Server-ish way
where LONGTEXT columns are the actual JSON columns and there's JSON functions that just work on them,
construed as text.
You could even have mixed JSON / non JSON columns...
Therefore, no JSON tests.
in here we fiddle with the mysql db details | (ns metabase.driver.mysql-test
(:require [clojure.java.jdbc :as jdbc]
[clojure.string :as str]
[clojure.test :refer :all]
[honeysql.core :as hsql]
[java-time :as t]
[metabase.config :as config]
[metabase.db.metadata-queries :as metadata-queries]
[metabase.driver :as driver]
[metabase.driver.mysql :as mysql]
[metabase.driver.mysql.ddl :as mysql.ddl]
[metabase.driver.sql-jdbc.connection :as sql-jdbc.conn]
[metabase.driver.sql-jdbc.sync :as sql-jdbc.sync]
[metabase.driver.sql-jdbc.sync.describe-table :as sql-jdbc.describe-table]
[metabase.driver.sql.query-processor :as sql.qp]
[metabase.models.database :refer [Database]]
[metabase.models.field :refer [Field]]
[metabase.models.table :refer [Table]]
[metabase.query-processor :as qp]
used for one SSL with PEM connectivity test
[metabase.query-processor-test.string-extracts-test :as string-extracts-test]
[metabase.sync :as sync]
[metabase.sync.analyze.fingerprint :as fingerprint]
[metabase.test :as mt]
[metabase.test.data.interface :as tx]
[metabase.util :as u]
[metabase.util.date-2 :as u.date]
[metabase.util.honeysql-extensions :as hx]
[toucan.db :as db]
[toucan.hydrate :refer [hydrate]]
[toucan.util.test :as tt]))
(deftest all-zero-dates-test
(mt/test-driver :mysql
(testing (str "MySQL allows 0000-00-00 dates, but JDBC does not; make sure that MySQL is converting them to NULL "
"when returning them like we asked")
(let [spec (sql-jdbc.conn/connection-details->spec :mysql (tx/dbdef->connection-details :mysql :server nil))]
(doseq [sql ["DROP DATABASE IF EXISTS all_zero_dates;"
"CREATE DATABASE all_zero_dates;"]]
(jdbc/execute! spec [sql]))
Create Table & add data
(let [details (tx/dbdef->connection-details :mysql :db {:database-name "all_zero_dates"})
spec (-> (sql-jdbc.conn/connection-details->spec :mysql details)
(assoc :sessionVariables "sql_mode='ALLOW_INVALID_DATES'"))]
(doseq [sql ["CREATE TABLE `exciting-moments-in-history` (`id` integer, `moment` timestamp);"
"INSERT INTO `exciting-moments-in-history` (`id`, `moment`) VALUES (1, '0000-00-00');"]]
(jdbc/execute! spec [sql]))
(tt/with-temp Database [database {:engine "mysql", :details details}]
(sync/sync-database! database)
(mt/with-db database
(is (= [[1 nil]]
(mt/rows
(mt/run-mbql-query exciting-moments-in-history)))))))))))
(tx/defdataset tiny-int-ones
[["number-of-cans"
[{:field-name "thing", :base-type :type/Text}
{:field-name "number-of-cans", :base-type {:native "tinyint(1)"}, :effective-type :type/Integer}]
[["Six Pack" 6]
["Toucan" 2]
["Empty Vending Machine" 0]]]])
(defn- db->fields [db]
(let [table-ids (db/select-ids 'Table :db_id (u/the-id db))]
(set (map (partial into {}) (db/select [Field :name :base_type :semantic_type] :table_id [:in table-ids])))))
(deftest tiny-int-1-test
(mt/test-driver :mysql
(mt/dataset tiny-int-ones
(sync/sync-database! (mt/db))
(testing "By default TINYINT(1) should be a boolean"
(is (= #{{:name "number-of-cans", :base_type :type/Boolean, :semantic_type :type/Category}
{:name "id", :base_type :type/Integer, :semantic_type :type/PK}
{:name "thing", :base_type :type/Text, :semantic_type :type/Category}}
(db->fields (mt/db)))))
(testing "if someone says specifies `tinyInt1isBit=false`, it should come back as a number instead"
(tt/with-temp Database [db {:engine "mysql"
:details (assoc (:details (mt/db))
:additional-options "tinyInt1isBit=false")}]
(sync/sync-database! db)
(is (= #{{:name "number-of-cans", :base_type :type/Integer, :semantic_type :type/Quantity}
{:name "id", :base_type :type/Integer, :semantic_type :type/PK}
{:name "thing", :base_type :type/Text, :semantic_type :type/Category}}
(db->fields db))))))))
(tx/defdataset year-db
[["years"
[{:field-name "year_column", :base-type {:native "YEAR"}, :effective-type :type/Date}]
[[2001] [2002] [1999]]]])
(deftest year-test
(mt/test-driver :mysql
(mt/dataset year-db
(testing "By default YEAR"
(is (= #{{:name "year_column", :base_type :type/Date, :semantic_type nil}
{:name "id", :base_type :type/Integer, :semantic_type :type/PK}}
(db->fields (mt/db)))))
(let [table (db/select-one Table :db_id (u/id (mt/db)))
fields (db/select Field :table_id (u/id table) :name "year_column")]
(testing "Can select from this table"
(is (= [[#t "2001-01-01"] [#t "2002-01-01"] [#t "1999-01-01"]]
(metadata-queries/table-rows-sample table fields (constantly conj)))))
(testing "We can fingerprint this table"
(is (= 1
(:updated-fingerprints (#'fingerprint/fingerprint-table! table fields)))))))))
(deftest db-default-timezone-test
(mt/test-driver :mysql
(let [timezone (fn [result-row]
(let [db (mt/db)]
(with-redefs [jdbc/query (let [orig jdbc/query]
(fn [spec sql-args & options]
(if (and (string? sql-args)
(str/includes? sql-args "GLOBAL.time_zone"))
[result-row]
(apply orig spec sql-args options))))]
(driver/db-default-timezone driver/*driver* db))))]
(testing "Should use global timezone by default"
(is (= "US/Pacific"
(timezone {:global_tz "US/Pacific", :system_tz "UTC"}))))
(testing "If global timezone is 'SYSTEM', should use system timezone"
(is (= "UTC"
(timezone {:global_tz "SYSTEM", :system_tz "UTC"}))))
(testing "Should fall back to returning `offset` if global/system aren't present"
(is (= "+00:00"
(timezone {:offset "00:00"}))))
(testing "If global timezone is invalid, should fall back to offset"
(is (= "-08:00"
(timezone {:global_tz "PDT", :system_tz "PDT", :offset "-08:00"}))))
(testing "Should add a `+` if needed to offset"
(is (= "+00:00"
(timezone {:global_tz "PDT", :system_tz "UTC", :offset "00:00"})))))
(testing "real timezone query doesn't fail"
(is (nil? (try
(driver/db-default-timezone driver/*driver* (mt/db))
nil
(catch Throwable e
e)))))))
(deftest timezone-date-formatting-test
(mt/test-driver :mysql
Most of our tests either deal in UTC ( offset 00:00 ) or America / Los_Angeles timezones ( -07:00/-08:00 ) . When dealing
example , if we have a datetime like 2018 - 08 - 17 00:00:00 - 08:00 , converting to UTC this becomes 2018 - 08 - 17
08:00:00 + 00:00 , which when truncated is still 2018 - 08 - 17 . That same scenario in Hong Kong is 2018 - 08 - 17
00:00:00 + 08:00 , which then becomes 2018 - 08 - 16 16:00:00 + 00:00 when converted to UTC , which will truncate to
2018 - 08 - 16 , instead of 2018 - 08 - 17
(mt/with-system-timezone-id "Asia/Hong_Kong"
(letfn [(run-query-with-report-timezone [report-timezone]
(mt/with-temporary-setting-values [report-timezone report-timezone]
(mt/first-row
(qp/process-query
{:database (mt/id)
:type :native
:settings {:report-timezone "UTC"}
:native {:query "SELECT cast({{date}} as date)"
:template-tags {:date {:name "date" :display_name "Date" :type "date"}}}
:parameters [{:type "date/single" :target ["variable" ["template-tag" "date"]] :value "2018-04-18"}]}))))]
(testing "date formatting when system-timezone == report-timezone"
(is (= ["2018-04-18T00:00:00+08:00"]
(run-query-with-report-timezone "Asia/Hong_Kong"))))
This tests a similar scenario , but one in which the JVM timezone is in Hong Kong , but the report timezone
is in Los Angeles . The Joda Time date parsing functions for the most part default to UTC . Our tests all run
the JVM timezone is different .
was parsing the date using JodateTime 's date parser , which is in UTC . The MySQL driver code was assuming
(testing "date formatting when system-timezone != report-timezone"
(is (= ["2018-04-18T00:00:00-07:00"]
(run-query-with-report-timezone "America/Los_Angeles"))))))))
(def ^:private sample-connection-details
{:db "my_db", :host "localhost", :port "3306", :user "cam", :password "bad-password"})
(def ^:private sample-jdbc-spec
{:password "bad-password"
:characterSetResults "UTF8"
:characterEncoding "UTF8"
:classname "org.mariadb.jdbc.Driver"
:subprotocol "mysql"
:zeroDateTimeBehavior "convertToNull"
:user "cam"
:subname "//localhost:3306/my_db"
:connectionAttributes (str "program_name:" config/mb-version-and-process-identifier)
:useCompression true
:useUnicode true})
(deftest connection-spec-test
(testing "Do `:ssl` connection details give us the connection spec we'd expect?"
(is (= (assoc sample-jdbc-spec :useSSL true :serverSslCert "sslCert")
(sql-jdbc.conn/connection-details->spec :mysql (assoc sample-connection-details :ssl true
:ssl-cert "sslCert")))))
(testing "what about non-SSL connections?"
(is (= (assoc sample-jdbc-spec :useSSL false)
(sql-jdbc.conn/connection-details->spec :mysql sample-connection-details))))
(testing "Connections that are `:ssl false` but with `useSSL` in the additional options should be treated as SSL (see #9629)"
(is (= (assoc sample-jdbc-spec :useSSL true
:subname "//localhost:3306/my_db?useSSL=true&trustServerCertificate=true")
(sql-jdbc.conn/connection-details->spec :mysql
(assoc sample-connection-details
:ssl false
:additional-options "useSSL=true&trustServerCertificate=true")))))
(testing "A program_name specified in additional-options is not overwritten by us"
(let [conn-attrs "connectionAttributes=program_name:my_custom_value"]
(is (= (-> sample-jdbc-spec
(assoc :subname (str "//localhost:3306/my_db?" conn-attrs), :useSSL false)
(dissoc :connectionAttributes))
(sql-jdbc.conn/connection-details->spec
:mysql
(assoc sample-connection-details :additional-options conn-attrs)))))))
(deftest read-timediffs-test
(mt/test-driver :mysql
(testing "Make sure negative result of *diff() functions don't cause Exceptions (#10983)"
(doseq [{:keys [interval expected message]}
[{:interval "-1 HOUR"
:expected "-01:00:00"
:message "Negative durations should come back as Strings"}
{:interval "25 HOUR"
:expected "25:00:00"
:message "Durations outside the valid range of `LocalTime` should come back as Strings"}
{:interval "1 HOUR"
:expected #t "01:00:00"
:message "A `timediff()` result within the valid range should still come back as a `LocalTime`"}]]
(testing (str "\n" interval "\n" message)
(is (= [expected]
(mt/first-row
(qp/process-query
(assoc (mt/native-query
{:query (format "SELECT timediff(current_timestamp + INTERVAL %s, current_timestamp)" interval)})
disable the middleware that normally converts ` LocalTime ` to ` Strings ` so we can verify
:middleware {:format-rows? false}))))))))))
(defn- table-fingerprint
[{:keys [fields name]}]
{:name name
:fields (map #(select-keys % [:name :base_type]) fields)})
(deftest system-versioned-tables-test
(mt/test-driver :mysql
(testing "system versioned tables appear during a sync"
(let [spec (sql-jdbc.conn/connection-details->spec :mysql (tx/dbdef->connection-details :mysql :server nil))]
(doseq [sql ["DROP DATABASE IF EXISTS versioned_tables;"
"CREATE DATABASE versioned_tables;"]]
(jdbc/execute! spec [sql]))
Create Table & add data
(let [details (tx/dbdef->connection-details :mysql :db {:database-name "versioned_tables"})
spec (sql-jdbc.conn/connection-details->spec :mysql details)
compat (try
(doseq [sql ["CREATE TABLE IF NOT EXISTS src1 (id INTEGER, t TEXT);"
"CREATE TABLE IF NOT EXISTS src2 (id INTEGER, t TEXT);"
"ALTER TABLE src2 ADD SYSTEM VERSIONING;"
"INSERT INTO src1 VALUES (1, '2020-03-01 12:20:35');"
"INSERT INTO src2 VALUES (1, '2020-03-01 12:20:35');"]]
(jdbc/execute! spec [sql]))
true
(catch java.sql.SQLSyntaxErrorException se
(if (re-matches #".*VERSIONING'.*" (.getMessage se))
false
(throw se))))]
(when compat
(tt/with-temp Database [database {:engine "mysql", :details details}]
(sync/sync-database! database)
(is (= [{:name "src1"
:fields [{:name "id"
:base_type :type/Integer}
{:name "t"
:base_type :type/Text}]}
{:name "src2"
:fields [{:name "id"
:base_type :type/Integer}
{:name "t"
:base_type :type/Text}]}]
(->> (hydrate (db/select Table :db_id (:id database) {:order-by [:name]}) :fields)
(map table-fingerprint)))))))))))
(deftest group-on-time-column-test
(mt/test-driver :mysql
(testing "can group on TIME columns (#12846)"
(mt/dataset attempted-murders
(let [now-date-str (u.date/format (t/local-date (t/zone-id "UTC")))
add-date-fn (fn [t] [(str now-date-str "T" t)])]
(testing "by minute"
(is (= (map add-date-fn ["00:14:00Z" "00:23:00Z" "00:35:00Z"])
(mt/rows
(mt/run-mbql-query attempts
{:breakout [!minute.time]
:order-by [[:asc !minute.time]]
:limit 3})))))
(testing "by hour"
(is (= (map add-date-fn ["23:00:00Z" "20:00:00Z" "19:00:00Z"])
(mt/rows
(mt/run-mbql-query attempts
{:breakout [!hour.time]
:order-by [[:desc !hour.time]]
:limit 3}))))))))))
(defn- pretty-sql [s]
(str/replace s #"`" ""))
(deftest do-not-cast-to-date-if-column-is-already-a-date-test
(testing "Don't wrap Field in date() if it's already a DATE (#11502)"
(mt/test-driver :mysql
(mt/dataset attempted-murders
(let [query (mt/mbql-query attempts
{:aggregation [[:count]]
:breakout [!day.date]})]
(is (= (str "SELECT attempts.date AS date, count(*) AS count "
"FROM attempts "
"GROUP BY attempts.date "
"ORDER BY attempts.date ASC")
(some-> (qp/compile query) :query pretty-sql))))))
(testing "trunc-with-format should not cast a field if it is already a DATETIME"
(is (= ["SELECT str_to_date(date_format(CAST(field AS datetime), '%Y'), '%Y')"]
(hsql/format {:select [(#'mysql/trunc-with-format "%Y" :field)]})))
(is (= ["SELECT str_to_date(date_format(field, '%Y'), '%Y')"]
(hsql/format {:select [(#'mysql/trunc-with-format
"%Y"
(hx/with-database-type-info :field "datetime"))]}))))))
(deftest mysql-connect-with-ssl-and-pem-cert-test
(mt/test-driver :mysql
(if (System/getenv "MB_MYSQL_SSL_TEST_SSL_CERT")
(testing "MySQL with SSL connectivity using PEM certificate"
(mt/with-env-keys-renamed-by #(str/replace-first % "mb-mysql-ssl-test" "mb-mysql-test")
(string-extracts-test/test-breakout)))
(println (u/format-color 'yellow
"Skipping %s because %s env var is not set"
"mysql-connect-with-ssl-and-pem-cert-test"
"MB_MYSQL_SSL_TEST_SSL_CERT")))))
Therefore , we ca n't just automatically get JSON columns in MariaDB . Therefore , no JSON support .
(defn- version-query [db-id] {:type :native, :native {:query "SELECT VERSION();"}, :database db-id})
(defn- is-mariadb? [db-id] (str/includes?
(or (get-in (qp/process-userland-query (version-query db-id)) [:data :rows 0 0]) "")
"Maria"))
(deftest nested-field-column-test
(mt/test-driver :mysql
(mt/dataset json
(when (not (is-mariadb? (u/id (mt/db))))
(testing "Nested field column listing"
(is (= #{{:name "json_bit → 1234123412314",
:database-type "timestamp",
:base-type :type/DateTime,
:database-position 0,
:visibility-type :normal,
:nfc-path [:json_bit "1234123412314"]}
{:name "json_bit → boop",
:database-type "timestamp",
:base-type :type/DateTime,
:database-position 0,
:visibility-type :normal,
:nfc-path [:json_bit "boop"]}
{:name "json_bit → genres",
:database-type "text",
:base-type :type/Array,
:database-position 0,
:visibility-type :normal,
:nfc-path [:json_bit "genres"]}
{:name "json_bit → 1234",
:database-type "bigint",
:base-type :type/Integer,
:database-position 0,
:visibility-type :normal,
:nfc-path [:json_bit "1234"]}
{:name "json_bit → doop",
:database-type "text",
:base-type :type/Text,
:database-position 0,
:visibility-type :normal,
:nfc-path [:json_bit "doop"]}
{:name "json_bit → noop",
:database-type "timestamp",
:base-type :type/DateTime,
:database-position 0,
:visibility-type :normal,
:nfc-path [:json_bit "noop"]}
{:name "json_bit → zoop",
:database-type "timestamp",
:base-type :type/DateTime,
:database-position 0,
:visibility-type :normal,
:nfc-path [:json_bit "zoop"]}
{:name "json_bit → published",
:database-type "text",
:base-type :type/Text,
:database-position 0,
:visibility-type :normal,
:nfc-path [:json_bit "published"]}
{:name "json_bit → title",
:database-type "text",
:base-type :type/Text,
:database-position 0,
:visibility-type :normal,
:nfc-path [:json_bit "title"]}}
(sql-jdbc.sync/describe-nested-field-columns
:mysql
(mt/db)
{:name "json"}))))))))
(deftest big-nested-field-column-test
(mt/test-driver :mysql
(mt/dataset json
(when (not (is-mariadb? (u/id (mt/db))))
(testing "Nested field column listing, but big"
(is (= sql-jdbc.describe-table/max-nested-field-columns
(count (sql-jdbc.sync/describe-nested-field-columns
:mysql
(mt/db)
{:name "big_json"})))))))))
(deftest json-query-test
(let [boop-identifier (:form (hx/with-type-info (hx/identifier :field "boop" "bleh -> meh") {}))]
(testing "Transforming MBQL query with JSON in it to mysql query works"
(let [boop-field {:nfc_path [:bleh :meh] :database_type "bigint"}]
(is (= ["convert(json_extract(boop.bleh, ?), UNSIGNED)" "$.\"meh\""]
(hsql/format (#'sql.qp/json-query :mysql boop-identifier boop-field))))))
(testing "What if types are weird and we have lists"
(let [weird-field {:nfc_path [:bleh "meh" :foobar 1234] :database_type "bigint"}]
(is (= ["convert(json_extract(boop.bleh, ?), UNSIGNED)" "$.\"meh\".\"foobar\".\"1234\""]
(hsql/format (#'sql.qp/json-query :mysql boop-identifier weird-field))))))
(testing "Doesn't complain when field is boolean"
(let [boolean-boop-field {:database_type "boolean" :nfc_path [:bleh "boop" :foobar 1234]}]
(is (= ["json_extract(boop.bleh, ?)" "$.\"boop\".\"foobar\".\"1234\""]
(hsql/format (#'sql.qp/json-query :mysql boop-identifier boolean-boop-field))))))))
(deftest json-alias-test
(mt/test-driver :mysql
(when (not (is-mariadb? (u/id (mt/db))))
(testing "json breakouts and order bys have alias coercion"
(mt/dataset json
(let [table (db/select-one Table :db_id (u/id (mt/db)) :name "json")]
(sync/sync-table! table)
(let [field (db/select-one Field :table_id (u/id table) :name "json_bit → 1234")
compile-res (qp/compile
{:database (u/the-id (mt/db))
:type :query
:query {:source-table (u/the-id table)
:aggregation [[:count]]
:breakout [[:field (u/the-id field) nil]]}})]
(is (= (str "SELECT convert(json_extract(json.json_bit, ?), UNSIGNED) AS `json_bit → 1234`, "
"count(*) AS `count` FROM `json` GROUP BY convert(json_extract(json.json_bit, ?), UNSIGNED) "
"ORDER BY convert(json_extract(json.json_bit, ?), UNSIGNED) ASC")
(:query compile-res)))
(is (= '("$.\"1234\"" "$.\"1234\"" "$.\"1234\"") (:params compile-res))))))))))
(deftest complicated-json-identifier-test
(mt/test-driver :mysql
(when (not (is-mariadb? (u/id (mt/db))))
(testing "Deal with complicated identifier (#22967, but for mysql)"
(mt/dataset json
(let [database (mt/db)
table (db/select-one Table :db_id (u/id database) :name "json")]
(sync/sync-table! table)
(let [field (db/select-one Field :table_id (u/id table) :name "json_bit → 1234")]
(mt/with-everything-store
(let [field-clause [:field (u/the-id field) {:binning
{:strategy :num-bins,
:num-bins 100,
:min-value 0.75,
:max-value 54.0,
:bin-width 0.75}}]]
(is (= ["((floor(((convert(json_extract(json.json_bit, ?), UNSIGNED) - 0.75) / 0.75)) * 0.75) + 0.75)" "$.\"1234\""]
(hsql/format (sql.qp/->honeysql :mysql field-clause)))))))))))))
(tx/defdataset json-unwrap-bigint-and-boolean
"Used for testing mysql json value unwrapping"
[["bigint-and-bool-table"
[{:field-name "jsoncol" :base-type :type/JSON}]
[["{\"mybool\":true, \"myint\":1234567890123456789}"]
["{\"mybool\":false,\"myint\":12345678901234567890}"]
["{\"mybool\":true, \"myint\":123}"]]]])
(deftest json-unwrapping-bigint-and-boolean
(mt/test-driver :mysql
(when-not (is-mariadb? (mt/id))
(mt/dataset json-unwrap-bigint-and-boolean
(sync/sync-database! (mt/db))
(testing "Fields marked as :type/SerializedJSON are fingerprinted that way"
(is (= #{{:name "id", :base_type :type/Integer, :semantic_type :type/PK}
{:name "jsoncol", :base_type :type/SerializedJSON, :semantic_type :type/SerializedJSON}
{:name "jsoncol → myint", :base_type :type/Number, :semantic_type nil}
{:name "jsoncol → mybool", :base_type :type/Boolean, :semantic_type nil}}
(db->fields (mt/db)))))
(testing "Nested field columns are correct"
(is (= #{{:name "jsoncol → mybool", :database-type "boolean", :base-type :type/Boolean, :database-position 0, :visibility-type :normal, :nfc-path [:jsoncol "mybool"]}
{:name "jsoncol → myint", :database-type "double precision", :base-type :type/Number, :database-position 0, :visibility-type :normal, :nfc-path [:jsoncol "myint"]}}
(sql-jdbc.sync/describe-nested-field-columns
:mysql
(mt/db)
(db/select-one Table :db_id (mt/id) :name "bigint-and-bool-table")))))))))
(deftest can-shut-off-json-unwrapping
(mt/test-driver :mysql
(let [db (db/select-one Database :id (mt/id))]
(try
(db/update! Database (mt/id) {:details (assoc (:details db) :json-unfolding true)})
(is (= true (driver/database-supports? :mysql :nested-field-columns (mt/db))))
(db/update! Database (mt/id) {:details (assoc (:details db) :json-unfolding false)})
(is (= false (driver/database-supports? :mysql :nested-field-columns (mt/db))))
(db/update! Database (mt/id) {:details (assoc (:details db) :json-unfolding nil)})
(is (= true (driver/database-supports? :mysql :nested-field-columns (mt/db))))
un fiddle with the mysql db details .
(finally (db/update! Database (mt/id) :details (:details db)))))))
(deftest ddl.execute-with-timeout-test
(mt/test-driver :mysql
(mt/dataset json
(let [db-spec (sql-jdbc.conn/db->pooled-connection-spec (mt/db))]
(is (thrown-with-msg?
Exception
#"Killed mysql process id [\d,]+ due to timeout."
(#'mysql.ddl/execute-with-timeout! db-spec db-spec 10 ["select sleep(5)"])))
(is (= true (#'mysql.ddl/execute-with-timeout! db-spec db-spec 5000 ["select sleep(0.1) as val"])))))))
|
deb8b87007062c16f6f2df19bf3d403780a760a04e313775d21887b2fa2db385 | informatimago/lisp | c-sexp-loader.lisp | (eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COM.INFORMATIMAGO.LANGUAGES.LINC")
(defun linc-eval (form)
0)
(defun load-linc-file (input-file &key output-file
(verbose *compile-verbose*)
(print *compile-print*)
(external-format :default)
(if-does-not-exist :error))
(let ((*package* (com.informatimago.common-lisp.interactive.interactive:mkupack
:name "com.informatimago.languages.linc.c-"
:use '("COM.INFORMATIMAGO.LANGUAGES.LINC.C")))
(*readtable* (copy-readtable com.informatimago.languages.linc::*c-readtable*))
(*compile-verbose* verbose)
(*compile-print* print)
(warnings-p nil)
(failure-p nil))
(with-open-file (input input-file
:external-format external-format
:if-does-not-exist (when if-does-not-exist :error))
(handler-bind ((warning (lambda (condition)
(declare (ignore condition))
(incf warnings-p)
nil))
(style-warning (lambda (condition)
(declare (ignore condition))
nil))
(error (lambda (condition)
(format *error-output* "~&;; ~A~%" condition)
(invoke-restart (find-restart 'continue-translation condition)))))
(loop
:for form := (read input nil input)
:until (eql form input)
:do (when print
(format t "~&~S~%" form))
(let ((result (linc-eval form)))
(when verbose
(format t "~&-> ~S~%" result)))
:finally (return t))))))
;;;; THE END ;;;;
| null | https://raw.githubusercontent.com/informatimago/lisp/571af24c06ba466e01b4c9483f8bb7690bc46d03/languages/linc/c-sexp-loader.lisp | lisp | THE END ;;;; | (eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COM.INFORMATIMAGO.LANGUAGES.LINC")
(defun linc-eval (form)
0)
(defun load-linc-file (input-file &key output-file
(verbose *compile-verbose*)
(print *compile-print*)
(external-format :default)
(if-does-not-exist :error))
(let ((*package* (com.informatimago.common-lisp.interactive.interactive:mkupack
:name "com.informatimago.languages.linc.c-"
:use '("COM.INFORMATIMAGO.LANGUAGES.LINC.C")))
(*readtable* (copy-readtable com.informatimago.languages.linc::*c-readtable*))
(*compile-verbose* verbose)
(*compile-print* print)
(warnings-p nil)
(failure-p nil))
(with-open-file (input input-file
:external-format external-format
:if-does-not-exist (when if-does-not-exist :error))
(handler-bind ((warning (lambda (condition)
(declare (ignore condition))
(incf warnings-p)
nil))
(style-warning (lambda (condition)
(declare (ignore condition))
nil))
(error (lambda (condition)
(format *error-output* "~&;; ~A~%" condition)
(invoke-restart (find-restart 'continue-translation condition)))))
(loop
:for form := (read input nil input)
:until (eql form input)
:do (when print
(format t "~&~S~%" form))
(let ((result (linc-eval form)))
(when verbose
(format t "~&-> ~S~%" result)))
:finally (return t))))))
|
319fc1edad0cb73c68f340d13f3841bc260a681d4f7458253f303410c0df0a3c | returntocorp/semgrep | parsing_hacks_js.mli | val fix_tokens : Parser_js.token list -> Parser_js.token list
val fix_tokens_ASI : Parser_js.token list -> Parser_js.token list
| null | https://raw.githubusercontent.com/returntocorp/semgrep/00f1e67bbb80f00e29db3381288fc00398b6868a/languages/javascript/menhir/parsing_hacks_js.mli | ocaml | val fix_tokens : Parser_js.token list -> Parser_js.token list
val fix_tokens_ASI : Parser_js.token list -> Parser_js.token list
| |
a2549098daf804bd84b345f6e612e41072edb480ffb67efb30dd0434b5325be3 | re-xyr/cleff | Any.hs | -- |
Copyright : ( c ) 2021
-- License: BSD3
-- Maintainer:
-- Stability: unstable
Portability : non - portable ( GHC only )
module Data.Any (Any, pattern Any, fromAny) where
import GHC.Exts (Any)
import Unsafe.Coerce (unsafeCoerce)
-- | A pattern synonym for coercing values to and from t'Any'. This is not any less unsafe but prevents possible
-- misuses.
pattern Any :: forall a. a -> Any
pattern Any {fromAny} <- (unsafeCoerce -> fromAny)
where Any = unsafeCoerce
{-# COMPLETE Any #-}
| null | https://raw.githubusercontent.com/re-xyr/cleff/28c74f3c6dd473e6b773ba26b785980ee5607234/src/Data/Any.hs | haskell | |
License: BSD3
Maintainer:
Stability: unstable
| A pattern synonym for coercing values to and from t'Any'. This is not any less unsafe but prevents possible
misuses.
# COMPLETE Any # | Copyright : ( c ) 2021
Portability : non - portable ( GHC only )
module Data.Any (Any, pattern Any, fromAny) where
import GHC.Exts (Any)
import Unsafe.Coerce (unsafeCoerce)
pattern Any :: forall a. a -> Any
pattern Any {fromAny} <- (unsafeCoerce -> fromAny)
where Any = unsafeCoerce
|
ea984c8932c6429702ffeaba06e45f1d60867f4bf816bff78d89d58484637e6f | lpgauth/marina | marina_request.erl | -module(marina_request).
-include("marina_internal.hrl").
-compile(inline).
-compile({inline_size, 512}).
-export([
auth_response/3,
execute/4,
prepare/3,
query/4,
startup/1
]).
%% public
-spec auth_response(frame_flag(), binary(), binary()) -> iolist().
auth_response(FrameFlags, Username, Password) ->
Body = <<0, Username/binary, 0, Password/binary>>,
Body2 = encode_body(FrameFlags, [marina_types:encode_bytes(Body)]),
marina_frame:encode(#frame {
stream = ?DEFAULT_STREAM,
opcode = ?OP_AUTH_RESPONSE,
flags = FrameFlags,
body = Body2
}).
-spec execute(stream(), frame_flag(), statement_id(), query_opts()) -> iolist().
execute(Stream, FrameFlags, StatementId, QueryOpts) ->
ConsistencyLevel = marina_utils:query_opts(consistency_level, QueryOpts),
Flags = flags(QueryOpts),
Body2 = encode_body(FrameFlags, [
marina_types:encode_short_bytes(StatementId),
marina_types:encode_short(ConsistencyLevel),
Flags
]),
marina_frame:encode(#frame {
stream = Stream,
opcode = ?OP_EXECUTE,
flags = FrameFlags,
body = Body2
}).
-spec prepare(stream(), frame_flag(), query()) -> iolist().
prepare(Stream, FrameFlags, Query) ->
Body2 = encode_body(FrameFlags, [
marina_types:encode_long_string(Query)
]),
marina_frame:encode(#frame {
stream = Stream,
opcode = ?OP_PREPARE,
flags = FrameFlags,
body = Body2
}).
-spec query(stream(), frame_flag(), query(), query_opts()) ->
iolist().
query(Stream, FrameFlags, Query, QueryOpts) ->
ConsistencyLevel = maps:get(consistency_level, QueryOpts,
?DEFAULT_CONSISTENCY_LEVEL),
Flags = flags(QueryOpts),
Body2 = encode_body(FrameFlags, [
marina_types:encode_long_string(Query),
marina_types:encode_short(ConsistencyLevel),
Flags
]),
marina_frame:encode(#frame {
stream = Stream,
opcode = ?OP_QUERY,
flags = FrameFlags,
body = Body2
}).
-spec startup(frame_flag()) -> iolist().
startup(FrameFlags) ->
Body = case FrameFlags of
1 ->
[?CQL_VERSION, ?LZ4_COMPRESSION];
0 ->
[?CQL_VERSION]
end,
marina_frame:encode(#frame {
stream = ?DEFAULT_STREAM,
opcode = ?OP_STARTUP,
flags = FrameFlags,
body = [marina_types:encode_string_map(Body)]
}).
%% private
encode_body(0, Body) ->
Body;
encode_body(1, Body) ->
{ok, Body2} = marina_utils:pack(Body),
Body2.
flags(QueryOpts) ->
{Mask1, Values} = values_flag(QueryOpts),
Mask2 = skip_metadata(QueryOpts),
{Mask3, PageSize} = page_size_flag(QueryOpts),
{Mask4, PagingState} = paging_state(QueryOpts),
Flags = Mask1 + Mask2 + Mask3 + Mask4,
[Flags, Values, PageSize, PagingState].
page_size_flag(QueryOpts) ->
case marina_utils:query_opts(page_size, QueryOpts) of
undefined ->
{0, []};
PageSize ->
{4, marina_types:encode_int(PageSize)}
end.
paging_state(QueryOpts) ->
case marina_utils:query_opts(paging_state, QueryOpts) of
undefined ->
{0, []};
PagingState ->
{8, marina_types:encode_bytes(PagingState)}
end.
skip_metadata(QueryOpts) ->
case marina_utils:query_opts(skip_metadata, QueryOpts) of
false -> 0;
true -> 2
end.
values_flag(QueryOpts) ->
case marina_utils:query_opts(values, QueryOpts) of
undefined ->
{0, []};
Values ->
ValuesCount = length(Values),
EncodedValues = [marina_types:encode_bytes(Value) ||
Value <- Values],
Values2 = [marina_types:encode_short(ValuesCount),
EncodedValues],
{1, Values2}
end.
| null | https://raw.githubusercontent.com/lpgauth/marina/2d775c003f58d125bb38e7c953c30c36aebc72c6/src/marina_request.erl | erlang | public
private | -module(marina_request).
-include("marina_internal.hrl").
-compile(inline).
-compile({inline_size, 512}).
-export([
auth_response/3,
execute/4,
prepare/3,
query/4,
startup/1
]).
-spec auth_response(frame_flag(), binary(), binary()) -> iolist().
auth_response(FrameFlags, Username, Password) ->
Body = <<0, Username/binary, 0, Password/binary>>,
Body2 = encode_body(FrameFlags, [marina_types:encode_bytes(Body)]),
marina_frame:encode(#frame {
stream = ?DEFAULT_STREAM,
opcode = ?OP_AUTH_RESPONSE,
flags = FrameFlags,
body = Body2
}).
-spec execute(stream(), frame_flag(), statement_id(), query_opts()) -> iolist().
execute(Stream, FrameFlags, StatementId, QueryOpts) ->
ConsistencyLevel = marina_utils:query_opts(consistency_level, QueryOpts),
Flags = flags(QueryOpts),
Body2 = encode_body(FrameFlags, [
marina_types:encode_short_bytes(StatementId),
marina_types:encode_short(ConsistencyLevel),
Flags
]),
marina_frame:encode(#frame {
stream = Stream,
opcode = ?OP_EXECUTE,
flags = FrameFlags,
body = Body2
}).
-spec prepare(stream(), frame_flag(), query()) -> iolist().
prepare(Stream, FrameFlags, Query) ->
Body2 = encode_body(FrameFlags, [
marina_types:encode_long_string(Query)
]),
marina_frame:encode(#frame {
stream = Stream,
opcode = ?OP_PREPARE,
flags = FrameFlags,
body = Body2
}).
-spec query(stream(), frame_flag(), query(), query_opts()) ->
iolist().
query(Stream, FrameFlags, Query, QueryOpts) ->
ConsistencyLevel = maps:get(consistency_level, QueryOpts,
?DEFAULT_CONSISTENCY_LEVEL),
Flags = flags(QueryOpts),
Body2 = encode_body(FrameFlags, [
marina_types:encode_long_string(Query),
marina_types:encode_short(ConsistencyLevel),
Flags
]),
marina_frame:encode(#frame {
stream = Stream,
opcode = ?OP_QUERY,
flags = FrameFlags,
body = Body2
}).
-spec startup(frame_flag()) -> iolist().
startup(FrameFlags) ->
Body = case FrameFlags of
1 ->
[?CQL_VERSION, ?LZ4_COMPRESSION];
0 ->
[?CQL_VERSION]
end,
marina_frame:encode(#frame {
stream = ?DEFAULT_STREAM,
opcode = ?OP_STARTUP,
flags = FrameFlags,
body = [marina_types:encode_string_map(Body)]
}).
encode_body(0, Body) ->
Body;
encode_body(1, Body) ->
{ok, Body2} = marina_utils:pack(Body),
Body2.
flags(QueryOpts) ->
{Mask1, Values} = values_flag(QueryOpts),
Mask2 = skip_metadata(QueryOpts),
{Mask3, PageSize} = page_size_flag(QueryOpts),
{Mask4, PagingState} = paging_state(QueryOpts),
Flags = Mask1 + Mask2 + Mask3 + Mask4,
[Flags, Values, PageSize, PagingState].
page_size_flag(QueryOpts) ->
case marina_utils:query_opts(page_size, QueryOpts) of
undefined ->
{0, []};
PageSize ->
{4, marina_types:encode_int(PageSize)}
end.
paging_state(QueryOpts) ->
case marina_utils:query_opts(paging_state, QueryOpts) of
undefined ->
{0, []};
PagingState ->
{8, marina_types:encode_bytes(PagingState)}
end.
skip_metadata(QueryOpts) ->
case marina_utils:query_opts(skip_metadata, QueryOpts) of
false -> 0;
true -> 2
end.
values_flag(QueryOpts) ->
case marina_utils:query_opts(values, QueryOpts) of
undefined ->
{0, []};
Values ->
ValuesCount = length(Values),
EncodedValues = [marina_types:encode_bytes(Value) ||
Value <- Values],
Values2 = [marina_types:encode_short(ValuesCount),
EncodedValues],
{1, Values2}
end.
|
cfe37d206e7723746ca52fa9cb39ef88a0e4b46529b154dd19f4cf08408b9e5e | GaloisInc/HaNS | Fragments.hs | # LANGUAGE RecordWildCards #
# LANGUAGE PatternGuards #
module Hans.IP4.Fragments (
FragTable(),
newFragTable, cleanupFragTable,
processFragment,
) where
import Hans.Config
import qualified Hans.HashTable as HT
import Hans.IP4.Packet
import Hans.Lens (view)
import Hans.Monad
import Hans.Network.Types (NetworkProtocol)
import Hans.Threads (forkNamed)
import Hans.Time (toUSeconds)
import Control.Concurrent (ThreadId,threadDelay,killThread)
import Control.Monad (forever)
import qualified Data.ByteString as S
import Data.Time.Clock
(UTCTime,getCurrentTime,NominalDiffTime,addUTCTime)
| Keys are of the form @(src , dest , prot , ident)@.
type Key = (IP4,IP4,NetworkProtocol,IP4Ident)
type Table = HT.HashTable Key Buffer
-- XXX: there isn't any way to limit the size of the fragment table right now.
data FragTable = FragTable { ftEntries :: !Table
, ftDuration :: !NominalDiffTime
, ftPurgeThread :: !ThreadId
}
newFragTable :: Config -> IO FragTable
newFragTable Config { .. } =
do ftEntries <- HT.newHashTable 31
ftPurgeThread <- forkNamed "IP4 Fragment Purge Thread"
(purgeEntries cfgIP4FragTimeout ftEntries)
return FragTable { ftDuration = cfgIP4FragTimeout, .. }
cleanupFragTable :: FragTable -> IO ()
cleanupFragTable FragTable { .. } = killThread ftPurgeThread
-- | Handle an incoming fragment. If the fragment is buffered, but doesn't
-- complete the packet, the escape continuation is invoked.
processFragment :: FragTable -> IP4Header -> S.ByteString
-> Hans (IP4Header,S.ByteString)
processFragment FragTable { .. } hdr body
-- no fragments
| not (view ip4MoreFragments hdr) && view ip4FragmentOffset hdr == 0 =
return (hdr,body)
-- fragment
| otherwise =
do mb <- io $ do now <- getCurrentTime
let expire = addUTCTime ftDuration now
frag = mkFragment hdr body
key = mkKey hdr
HT.alter (updateBuffer expire hdr frag) key ftEntries
case mb of
-- abort packet processing here, as there's nothing left to do
Nothing -> escape
-- return the reassembled packet
Just (hdr',body') -> return (hdr',body')
# INLINE processFragment #
-- Table Purging ---------------------------------------------------------------
| Every second , purge the fragment table of entries that have expired .
purgeEntries :: NominalDiffTime -> Table -> IO ()
purgeEntries lifetime entries = forever $
do threadDelay halfLife
now <- getCurrentTime
HT.filterHashTable (\_ Buffer { .. } -> bufExpire < now) entries
where
halfLife = toUSeconds (lifetime / 2)
-- Fragment Operations ---------------------------------------------------------
INVARIANT : When new fragments are inserted into bufFragments , they are merged
-- together when possible. This makes it easier to check the state of the whole
-- buffer.
data Buffer = Buffer { bufExpire :: !UTCTime
, bufSize :: !(Maybe Int)
, bufHeader :: !(Maybe IP4Header)
, bufFragments :: ![Fragment]
}
data Fragment = Fragment { fragStart :: {-# UNPACK #-} !Int
, fragEnd :: {-# UNPACK #-} !Int
, fragPayload :: [S.ByteString]
} deriving (Show)
mkKey :: IP4Header -> Key
mkKey IP4Header { .. } = (ip4SourceAddr,ip4DestAddr,ip4Protocol,ip4Ident)
mkFragment :: IP4Header -> S.ByteString -> Fragment
mkFragment hdr body = Fragment { .. }
where
fragStart = fromIntegral (view ip4FragmentOffset hdr)
fragEnd = fragStart + S.length body
fragPayload = [body]
-- | Create a buffer, given an expiration time, initial fragment, and
-- 'IP4Header' of that initial fragment. The initial header is included for the
case where the initial fragment is also the first fragment in the sequence .
mkBuffer :: UTCTime -> IP4Header -> Fragment -> Buffer
mkBuffer bufExpire hdr frag =
addFragment hdr frag
Buffer { bufHeader = Nothing
, bufSize = Nothing
, bufFragments = []
, .. }
| For use with HT.alter . When the first element is ' Just ' , the second will
-- be 'Nothing', indicating that the entry in the table should be updated, and
there 's no result yet . When the first element is ' Nothing ' , the second will
-- be 'Just', indicating that the entry should be removed from the table, and
-- that this is the final buffer.
updateBuffer :: UTCTime -> IP4Header -> Fragment -> Maybe Buffer
-> (Maybe Buffer,Maybe (IP4Header,S.ByteString))
-- the entry already exists in the table, removing it if it's full
updateBuffer _ hdr frag (Just buf) =
let buf' = addFragment hdr frag buf
in case bufFull buf' of
Just res -> (Nothing, Just res)
Nothing -> (Just buf', Nothing)
-- create a new entry in the table
updateBuffer expire hdr frag Nothing =
let buf = mkBuffer expire hdr frag
in buf `seq` (Just buf, Nothing)
-- | When the buffer is full and all fragments are accounted for, reassemble it
-- into a new packet.
bufFull :: Buffer -> Maybe (IP4Header,S.ByteString)
bufFull Buffer { .. }
| Just size <- bufSize
, Just hdr <- bufHeader
, [Fragment { .. }] <- bufFragments
, fragEnd == size =
Just (hdr, S.concat fragPayload)
| otherwise =
Nothing
-- | Insert the fragment into the buffer.
addFragment :: IP4Header -> Fragment -> Buffer -> Buffer
addFragment hdr frag buf =
Buffer { bufExpire = bufExpire buf
, bufSize = size'
, bufHeader = case bufHeader buf of
Nothing | view ip4FragmentOffset hdr == 0 -> Just hdr
_ -> bufHeader buf
, bufFragments = insertFragment (bufFragments buf)
}
where
size' | view ip4MoreFragments hdr = bufSize buf
| otherwise = Just $! fragEnd frag
insertFragment frags@(f:fs)
| fragEnd frag == fragStart f = mergeFragment frag f : fs
| fragStart frag == fragEnd f = mergeFragment f frag : fs
| fragStart frag < fragStart f = frag : frags
| otherwise = f : insertFragment fs
insertFragment [] = [frag]
mergeFragment :: Fragment -> Fragment -> Fragment
mergeFragment a b =
Fragment { fragStart = fragStart a
, fragEnd = fragEnd b
, fragPayload = fragPayload a ++ fragPayload b
}
| null | https://raw.githubusercontent.com/GaloisInc/HaNS/2af19397dbb4f828192f896b223ed2b77dd9a055/src/Hans/IP4/Fragments.hs | haskell | XXX: there isn't any way to limit the size of the fragment table right now.
| Handle an incoming fragment. If the fragment is buffered, but doesn't
complete the packet, the escape continuation is invoked.
no fragments
fragment
abort packet processing here, as there's nothing left to do
return the reassembled packet
Table Purging ---------------------------------------------------------------
Fragment Operations ---------------------------------------------------------
together when possible. This makes it easier to check the state of the whole
buffer.
# UNPACK #
# UNPACK #
| Create a buffer, given an expiration time, initial fragment, and
'IP4Header' of that initial fragment. The initial header is included for the
be 'Nothing', indicating that the entry in the table should be updated, and
be 'Just', indicating that the entry should be removed from the table, and
that this is the final buffer.
the entry already exists in the table, removing it if it's full
create a new entry in the table
| When the buffer is full and all fragments are accounted for, reassemble it
into a new packet.
| Insert the fragment into the buffer. | # LANGUAGE RecordWildCards #
# LANGUAGE PatternGuards #
module Hans.IP4.Fragments (
FragTable(),
newFragTable, cleanupFragTable,
processFragment,
) where
import Hans.Config
import qualified Hans.HashTable as HT
import Hans.IP4.Packet
import Hans.Lens (view)
import Hans.Monad
import Hans.Network.Types (NetworkProtocol)
import Hans.Threads (forkNamed)
import Hans.Time (toUSeconds)
import Control.Concurrent (ThreadId,threadDelay,killThread)
import Control.Monad (forever)
import qualified Data.ByteString as S
import Data.Time.Clock
(UTCTime,getCurrentTime,NominalDiffTime,addUTCTime)
| Keys are of the form @(src , dest , prot , ident)@.
type Key = (IP4,IP4,NetworkProtocol,IP4Ident)
type Table = HT.HashTable Key Buffer
data FragTable = FragTable { ftEntries :: !Table
, ftDuration :: !NominalDiffTime
, ftPurgeThread :: !ThreadId
}
newFragTable :: Config -> IO FragTable
newFragTable Config { .. } =
do ftEntries <- HT.newHashTable 31
ftPurgeThread <- forkNamed "IP4 Fragment Purge Thread"
(purgeEntries cfgIP4FragTimeout ftEntries)
return FragTable { ftDuration = cfgIP4FragTimeout, .. }
cleanupFragTable :: FragTable -> IO ()
cleanupFragTable FragTable { .. } = killThread ftPurgeThread
processFragment :: FragTable -> IP4Header -> S.ByteString
-> Hans (IP4Header,S.ByteString)
processFragment FragTable { .. } hdr body
| not (view ip4MoreFragments hdr) && view ip4FragmentOffset hdr == 0 =
return (hdr,body)
| otherwise =
do mb <- io $ do now <- getCurrentTime
let expire = addUTCTime ftDuration now
frag = mkFragment hdr body
key = mkKey hdr
HT.alter (updateBuffer expire hdr frag) key ftEntries
case mb of
Nothing -> escape
Just (hdr',body') -> return (hdr',body')
# INLINE processFragment #
| Every second , purge the fragment table of entries that have expired .
purgeEntries :: NominalDiffTime -> Table -> IO ()
purgeEntries lifetime entries = forever $
do threadDelay halfLife
now <- getCurrentTime
HT.filterHashTable (\_ Buffer { .. } -> bufExpire < now) entries
where
halfLife = toUSeconds (lifetime / 2)
INVARIANT : When new fragments are inserted into bufFragments , they are merged
data Buffer = Buffer { bufExpire :: !UTCTime
, bufSize :: !(Maybe Int)
, bufHeader :: !(Maybe IP4Header)
, bufFragments :: ![Fragment]
}
, fragPayload :: [S.ByteString]
} deriving (Show)
mkKey :: IP4Header -> Key
mkKey IP4Header { .. } = (ip4SourceAddr,ip4DestAddr,ip4Protocol,ip4Ident)
mkFragment :: IP4Header -> S.ByteString -> Fragment
mkFragment hdr body = Fragment { .. }
where
fragStart = fromIntegral (view ip4FragmentOffset hdr)
fragEnd = fragStart + S.length body
fragPayload = [body]
case where the initial fragment is also the first fragment in the sequence .
mkBuffer :: UTCTime -> IP4Header -> Fragment -> Buffer
mkBuffer bufExpire hdr frag =
addFragment hdr frag
Buffer { bufHeader = Nothing
, bufSize = Nothing
, bufFragments = []
, .. }
| For use with HT.alter . When the first element is ' Just ' , the second will
there 's no result yet . When the first element is ' Nothing ' , the second will
updateBuffer :: UTCTime -> IP4Header -> Fragment -> Maybe Buffer
-> (Maybe Buffer,Maybe (IP4Header,S.ByteString))
updateBuffer _ hdr frag (Just buf) =
let buf' = addFragment hdr frag buf
in case bufFull buf' of
Just res -> (Nothing, Just res)
Nothing -> (Just buf', Nothing)
updateBuffer expire hdr frag Nothing =
let buf = mkBuffer expire hdr frag
in buf `seq` (Just buf, Nothing)
bufFull :: Buffer -> Maybe (IP4Header,S.ByteString)
bufFull Buffer { .. }
| Just size <- bufSize
, Just hdr <- bufHeader
, [Fragment { .. }] <- bufFragments
, fragEnd == size =
Just (hdr, S.concat fragPayload)
| otherwise =
Nothing
addFragment :: IP4Header -> Fragment -> Buffer -> Buffer
addFragment hdr frag buf =
Buffer { bufExpire = bufExpire buf
, bufSize = size'
, bufHeader = case bufHeader buf of
Nothing | view ip4FragmentOffset hdr == 0 -> Just hdr
_ -> bufHeader buf
, bufFragments = insertFragment (bufFragments buf)
}
where
size' | view ip4MoreFragments hdr = bufSize buf
| otherwise = Just $! fragEnd frag
insertFragment frags@(f:fs)
| fragEnd frag == fragStart f = mergeFragment frag f : fs
| fragStart frag == fragEnd f = mergeFragment f frag : fs
| fragStart frag < fragStart f = frag : frags
| otherwise = f : insertFragment fs
insertFragment [] = [frag]
mergeFragment :: Fragment -> Fragment -> Fragment
mergeFragment a b =
Fragment { fragStart = fragStart a
, fragEnd = fragEnd b
, fragPayload = fragPayload a ++ fragPayload b
}
|
c46d57aad16cd9db56c817df44453bbdae5918b2a7b89630de30a26b9ba78c09 | exoscale/clostack | config.clj | (ns clostack.config
"This namespace provides a few functions which try very hard
to find configuration for the library. See the `init` function
for a description of the logic."
(:require [clojure.string :as s]
[clojure.edn :as edn]
[exoscale.cloak :as cloak]))
(defn getenv
"Fetch variable from environment or system properties"
([prop]
(getenv prop nil))
([prop default]
(let [p (name prop)
e (-> p (s/replace "." "_") (s/upper-case))]
(or (System/getProperty p)
(System/getenv e)
default))))
(defn read-config
"Try to read configuration from a path. Expects EDN files"
[path]
(try
(edn/read-string (slurp path))
(catch Exception _)))
(defn config-path
"Find out where the configuration file lives"
[]
(or (getenv :clostack.config.file)
(format "%s/.clostack" (System/getenv "HOME"))))
(defn environment-config
"Try getting configuration from the environment."
[]
(let [names [:clostack.api.key :clostack.api.secret :clostack.endpoint :clostack.expiration]
keys [:api-key :api-secret :endpoint :expiration]
vars (mapv getenv names)]
(when-not (some nil? vars)
(reduce merge {} (partition 2 (interleave keys vars))))))
(defn keywordify
"Single-depth walk of a map, keywordizing keys."
[m]
(reduce merge {} (for [[k v] m] [(keyword k) v])))
(defn file-config
"Get a profile from a config."
[profile config]
(let [var-or-profile (get config profile)]
(when (keyword? var-or-profile)
(get config var-or-profile))))
(defn init
"Get configuration. First try the environment, if not found,
read from a file."
[]
(let [path (config-path)
config (keywordify (read-config path))
profile (keyword (getenv :clostack.profile "default"))]
(-> (keywordify
(or (environment-config)
(file-config profile config)
(throw (ex-info "Could not find configuration profile for clostack."
{:config-path path
:config config}))))
(update :api-secret cloak/mask))))
| null | https://raw.githubusercontent.com/exoscale/clostack/551865988fdb540cb3c6fb901ab84283a63dfdd6/src/clostack/config.clj | clojure | (ns clostack.config
"This namespace provides a few functions which try very hard
to find configuration for the library. See the `init` function
for a description of the logic."
(:require [clojure.string :as s]
[clojure.edn :as edn]
[exoscale.cloak :as cloak]))
(defn getenv
"Fetch variable from environment or system properties"
([prop]
(getenv prop nil))
([prop default]
(let [p (name prop)
e (-> p (s/replace "." "_") (s/upper-case))]
(or (System/getProperty p)
(System/getenv e)
default))))
(defn read-config
"Try to read configuration from a path. Expects EDN files"
[path]
(try
(edn/read-string (slurp path))
(catch Exception _)))
(defn config-path
"Find out where the configuration file lives"
[]
(or (getenv :clostack.config.file)
(format "%s/.clostack" (System/getenv "HOME"))))
(defn environment-config
"Try getting configuration from the environment."
[]
(let [names [:clostack.api.key :clostack.api.secret :clostack.endpoint :clostack.expiration]
keys [:api-key :api-secret :endpoint :expiration]
vars (mapv getenv names)]
(when-not (some nil? vars)
(reduce merge {} (partition 2 (interleave keys vars))))))
(defn keywordify
"Single-depth walk of a map, keywordizing keys."
[m]
(reduce merge {} (for [[k v] m] [(keyword k) v])))
(defn file-config
"Get a profile from a config."
[profile config]
(let [var-or-profile (get config profile)]
(when (keyword? var-or-profile)
(get config var-or-profile))))
(defn init
"Get configuration. First try the environment, if not found,
read from a file."
[]
(let [path (config-path)
config (keywordify (read-config path))
profile (keyword (getenv :clostack.profile "default"))]
(-> (keywordify
(or (environment-config)
(file-config profile config)
(throw (ex-info "Could not find configuration profile for clostack."
{:config-path path
:config config}))))
(update :api-secret cloak/mask))))
| |
b00156c48f0828350243d2a146bb38dc2e4dd806852e3589790b0b1d98c4b63c | jlongster/genetic-canvas | ffi#.scm |
(c-define-type u8 unsigned-char)
(c-define-type u8* (pointer u8))
| null | https://raw.githubusercontent.com/jlongster/genetic-canvas/2592e48ddbd168a819ca6ca330a6f8af6ffc37aa/lib/ffi/ffi%23.scm | scheme |
(c-define-type u8 unsigned-char)
(c-define-type u8* (pointer u8))
| |
249fe83c32ec66fae92e3a936ec2ba4d2be8417a35356eb89323dad5807e557e | alanz/ghc-exactprint | T9968.hs | # LANGUAGE DeriveAnyClass , MultiParamTypeClasses #
module T9968 where
class C a b
data X = X deriving (C Int)
| null | https://raw.githubusercontent.com/alanz/ghc-exactprint/b6b75027811fa4c336b34122a7a7b1a8df462563/tests/examples/ghc80/T9968.hs | haskell | # LANGUAGE DeriveAnyClass , MultiParamTypeClasses #
module T9968 where
class C a b
data X = X deriving (C Int)
| |
11da0394b38806b41e576e80703c6508416bfabd72ab720287e4d0557a9a4088 | sbelak/tide | dtw.clj | (ns tide.dtw
(:import com.fastdtw.dtw.FastDTW
(com.fastdtw.timeseries TimeSeriesBase TimeSeriesPoint TimeSeriesItem)
(com.fastdtw.util Distances DistanceFunction)))
(defn- ensure-seq
[x]
(if (sequential? x)
x
[x]))
(defn- build-timeseries
[ts]
(if (sequential? (first ts))
(.build (reduce (fn [builder [x y]]
(->> y
ensure-seq
double-array
TimeSeriesPoint.
(TimeSeriesItem. x)
(.add builder)))
(TimeSeriesBase/builder)
ts))
(build-timeseries (map-indexed vector ts))))
(defn dtw
([ts1 ts2]
(dtw {} ts1 ts2))
([opts ts1 ts2]
(let [{:keys [distance search-radius]
:or {distance Distances/EUCLIDEAN_DISTANCE
search-radius 1}} opts
distance (if (instance? DistanceFunction distance)
distance
(reify
DistanceFunction
(calcDistance [this a b]
(distance a b))))
tw (FastDTW/compare (build-timeseries ts1)
(build-timeseries ts2)
search-radius distance)
path (.getPath tw)]
{:path (for [i (range (.size path))]
(let [cell (.get path i)]
[(.getCol cell) (.getRow cell)]))
:distance (.getDistance tw)})))
| null | https://raw.githubusercontent.com/sbelak/tide/bedda6844a33e176836f11d2330a9d7d4a0f14df/src/tide/dtw.clj | clojure | (ns tide.dtw
(:import com.fastdtw.dtw.FastDTW
(com.fastdtw.timeseries TimeSeriesBase TimeSeriesPoint TimeSeriesItem)
(com.fastdtw.util Distances DistanceFunction)))
(defn- ensure-seq
[x]
(if (sequential? x)
x
[x]))
(defn- build-timeseries
[ts]
(if (sequential? (first ts))
(.build (reduce (fn [builder [x y]]
(->> y
ensure-seq
double-array
TimeSeriesPoint.
(TimeSeriesItem. x)
(.add builder)))
(TimeSeriesBase/builder)
ts))
(build-timeseries (map-indexed vector ts))))
(defn dtw
([ts1 ts2]
(dtw {} ts1 ts2))
([opts ts1 ts2]
(let [{:keys [distance search-radius]
:or {distance Distances/EUCLIDEAN_DISTANCE
search-radius 1}} opts
distance (if (instance? DistanceFunction distance)
distance
(reify
DistanceFunction
(calcDistance [this a b]
(distance a b))))
tw (FastDTW/compare (build-timeseries ts1)
(build-timeseries ts2)
search-radius distance)
path (.getPath tw)]
{:path (for [i (range (.size path))]
(let [cell (.get path i)]
[(.getCol cell) (.getRow cell)]))
:distance (.getDistance tw)})))
| |
b1ddb4fe92de7f5f4bc0e30b132f19f61e7bc14aa33d638f52bb3eb4cfcaed3d | maybevoid/casimir | Resource.hs | module Casimir.Test.Higher.Resource
( resourceTests
)
where
import qualified Casimir.Base as Base
import Test.Tasty hiding (withResource)
import Test.Tasty.HUnit
import Data.IORef
import Control.Exception
import Control.Monad.Trans.State.Strict (StateT, execStateT)
import Casimir.Base
import Casimir.Higher
import Casimir.Ops.Io
import Casimir.Ops.State
import Casimir.Ops.State.Lift
import Casimir.Ops.State.Transform
import Casimir.Computation
import Casimir.Higher.Ops.Resource
resourceTests :: TestTree
resourceTests = testGroup "ResourceEff Tests"
[ testResource1
, testResource2
]
type BracketResourceEff = ResourceEff BracketResource
bracketHandler
:: HigherOpsHandler NoEff BracketResourceEff IO
bracketHandler = baseOpsHandler ioBracketOps
ioHandler :: BaseOpsHandler NoEff IoEff IO
ioHandler = baseOpsHandler ioOps
stateTHandler
:: forall s eff
. (Effect eff)
=> BaseOpsHandler NoEff (StateEff s) (StateT s eff)
stateTHandler = baseOpsHandler stateTOps
pushRef :: forall a . IORef [a] -> a
-> Eff IoEff ()
pushRef ref x = do
xs <- liftIo $ readIORef ref
liftIo $ writeIORef ref $ xs <> [x]
pushIo :: forall a . IORef [a] -> a -> IO ()
pushIo = Base.withOps ioOps pushRef
pushState
:: forall a . a
-> Eff (StateEff [a]) ()
pushState x = do
xs <- get
put $ xs <> [x]
makeResource
:: String
-> String
-> IORef [String]
-> BracketResource String
makeResource name value ref = BracketResource alloc release
where
alloc = do
pushIo ref $ name <> ": alloc"
return value
release _ = do
pushIo ref $ name <> ": release"
return ()
comp1
:: IORef [String]
-> Eff (StateEff [String] ∪ IoEff ∪ BracketResourceEff) ()
comp1 ref = do
push "outer-comp: start"
res <- withResource resource1 $ \arg -> do
push $ "inner-comp with argument: " <> arg
return "inner-result"
push $ "result from inner-comp: " <> res
where
push :: String -> Eff (StateEff [String] ∪ IoEff) ()
push x = do
pushRef ref x
pushState x
resource1 :: BracketResource String
resource1 = makeResource "resource1" "foo" ref
pipeline1
:: forall comp
. (forall eff . (Effect eff)
=> BaseComputation
(StateEff [String] ∪ IoEff ∪ BracketResourceEff)
comp
eff)
-> HigherComputation NoEff comp (StateT [String] IO)
pipeline1 comp11 =
bindOpsHandler (toHigherComputation stateTHandler) $
liftComputation stateTHigherLift $
bindOpsHandler @(StateEff [String]) bracketHandler $
toHigherComputation $
bindOpsHandler @(StateEff [String] ∪ BracketResourceEff) ioHandler $
comp11
comp2
:: IORef [String]
-> HigherComputation NoEff (Return ()) (StateT [String] IO)
comp2 ref = pipeline1 $ genericReturn $ comp1 ref
testResource1 :: TestTree
testResource1 = testCase "Resource test 2" $ do
ref <- newIORef []
s1 <- execStateT (execComp $ comp2 ref) []
assertEqual "Happy path should update state correctly"
[ "outer-comp: start"
, "inner-comp with argument: foo"
, "result from inner-comp: inner-result"
]
s1
s2 <- readIORef ref
assertEqual "Happy path should update IORef correctly"
[ "outer-comp: start"
, "resource1: alloc"
, "inner-comp with argument: foo"
, "resource1: release"
, "result from inner-comp: inner-result"
]
s2
data DummyError = DummyError
deriving (Show, Eq)
instance Exception DummyError
comp3
:: IORef [String]
-> Eff (StateEff [String] ∪ IoEff ∪ BracketResourceEff) ()
comp3 ref = do
push "outer-comp: start"
res1 <- withResource resource1 $ \arg1 -> do
push $ "inner-comp-1 with argument: " <> arg1
res2 <- withResource resource2 $ \arg2 -> do
push $ "inner-comp-2 with argument: " <> arg2
liftIo $ throwIO DummyError
push $ "result from inner-comp-2: " <> res2
return "inner-result-1"
push $ "result from inner-comp: " <> res1
where
push :: String -> Eff (StateEff [String] ∪ IoEff) ()
push x = do
pushRef ref x
pushState x
resource1 :: BracketResource String
resource1 = makeResource "resource1" "foo" ref
resource2 :: BracketResource String
resource2 = makeResource "resource2" "bar" ref
comp4
:: IORef [String]
-> HigherComputation NoEff (Return ()) (StateT [String] IO)
comp4 ref = pipeline1 $ genericReturn $ comp3 ref
testResource2 :: TestTree
testResource2 = testCase "Resource test 2" $ do
ref <- newIORef []
res <- try $ execStateT (execComp $ comp4 ref) []
assertEqual "Computation should raise error"
(Left DummyError) res
s2 <- readIORef ref
assertEqual "IORef should still log all alloc release"
[ "outer-comp: start"
, "resource1: alloc"
, "inner-comp-1 with argument: foo"
, "resource2: alloc"
, "inner-comp-2 with argument: bar"
, "resource2: release"
, "resource1: release"
]
s2
| null | https://raw.githubusercontent.com/maybevoid/casimir/ebbfa403739d6f258e6ac6793549006a0e8bff42/casimir/src/test/Casimir/Test/Higher/Resource.hs | haskell | module Casimir.Test.Higher.Resource
( resourceTests
)
where
import qualified Casimir.Base as Base
import Test.Tasty hiding (withResource)
import Test.Tasty.HUnit
import Data.IORef
import Control.Exception
import Control.Monad.Trans.State.Strict (StateT, execStateT)
import Casimir.Base
import Casimir.Higher
import Casimir.Ops.Io
import Casimir.Ops.State
import Casimir.Ops.State.Lift
import Casimir.Ops.State.Transform
import Casimir.Computation
import Casimir.Higher.Ops.Resource
resourceTests :: TestTree
resourceTests = testGroup "ResourceEff Tests"
[ testResource1
, testResource2
]
type BracketResourceEff = ResourceEff BracketResource
bracketHandler
:: HigherOpsHandler NoEff BracketResourceEff IO
bracketHandler = baseOpsHandler ioBracketOps
ioHandler :: BaseOpsHandler NoEff IoEff IO
ioHandler = baseOpsHandler ioOps
stateTHandler
:: forall s eff
. (Effect eff)
=> BaseOpsHandler NoEff (StateEff s) (StateT s eff)
stateTHandler = baseOpsHandler stateTOps
pushRef :: forall a . IORef [a] -> a
-> Eff IoEff ()
pushRef ref x = do
xs <- liftIo $ readIORef ref
liftIo $ writeIORef ref $ xs <> [x]
pushIo :: forall a . IORef [a] -> a -> IO ()
pushIo = Base.withOps ioOps pushRef
pushState
:: forall a . a
-> Eff (StateEff [a]) ()
pushState x = do
xs <- get
put $ xs <> [x]
makeResource
:: String
-> String
-> IORef [String]
-> BracketResource String
makeResource name value ref = BracketResource alloc release
where
alloc = do
pushIo ref $ name <> ": alloc"
return value
release _ = do
pushIo ref $ name <> ": release"
return ()
comp1
:: IORef [String]
-> Eff (StateEff [String] ∪ IoEff ∪ BracketResourceEff) ()
comp1 ref = do
push "outer-comp: start"
res <- withResource resource1 $ \arg -> do
push $ "inner-comp with argument: " <> arg
return "inner-result"
push $ "result from inner-comp: " <> res
where
push :: String -> Eff (StateEff [String] ∪ IoEff) ()
push x = do
pushRef ref x
pushState x
resource1 :: BracketResource String
resource1 = makeResource "resource1" "foo" ref
pipeline1
:: forall comp
. (forall eff . (Effect eff)
=> BaseComputation
(StateEff [String] ∪ IoEff ∪ BracketResourceEff)
comp
eff)
-> HigherComputation NoEff comp (StateT [String] IO)
pipeline1 comp11 =
bindOpsHandler (toHigherComputation stateTHandler) $
liftComputation stateTHigherLift $
bindOpsHandler @(StateEff [String]) bracketHandler $
toHigherComputation $
bindOpsHandler @(StateEff [String] ∪ BracketResourceEff) ioHandler $
comp11
comp2
:: IORef [String]
-> HigherComputation NoEff (Return ()) (StateT [String] IO)
comp2 ref = pipeline1 $ genericReturn $ comp1 ref
testResource1 :: TestTree
testResource1 = testCase "Resource test 2" $ do
ref <- newIORef []
s1 <- execStateT (execComp $ comp2 ref) []
assertEqual "Happy path should update state correctly"
[ "outer-comp: start"
, "inner-comp with argument: foo"
, "result from inner-comp: inner-result"
]
s1
s2 <- readIORef ref
assertEqual "Happy path should update IORef correctly"
[ "outer-comp: start"
, "resource1: alloc"
, "inner-comp with argument: foo"
, "resource1: release"
, "result from inner-comp: inner-result"
]
s2
data DummyError = DummyError
deriving (Show, Eq)
instance Exception DummyError
comp3
:: IORef [String]
-> Eff (StateEff [String] ∪ IoEff ∪ BracketResourceEff) ()
comp3 ref = do
push "outer-comp: start"
res1 <- withResource resource1 $ \arg1 -> do
push $ "inner-comp-1 with argument: " <> arg1
res2 <- withResource resource2 $ \arg2 -> do
push $ "inner-comp-2 with argument: " <> arg2
liftIo $ throwIO DummyError
push $ "result from inner-comp-2: " <> res2
return "inner-result-1"
push $ "result from inner-comp: " <> res1
where
push :: String -> Eff (StateEff [String] ∪ IoEff) ()
push x = do
pushRef ref x
pushState x
resource1 :: BracketResource String
resource1 = makeResource "resource1" "foo" ref
resource2 :: BracketResource String
resource2 = makeResource "resource2" "bar" ref
comp4
:: IORef [String]
-> HigherComputation NoEff (Return ()) (StateT [String] IO)
comp4 ref = pipeline1 $ genericReturn $ comp3 ref
testResource2 :: TestTree
testResource2 = testCase "Resource test 2" $ do
ref <- newIORef []
res <- try $ execStateT (execComp $ comp4 ref) []
assertEqual "Computation should raise error"
(Left DummyError) res
s2 <- readIORef ref
assertEqual "IORef should still log all alloc release"
[ "outer-comp: start"
, "resource1: alloc"
, "inner-comp-1 with argument: foo"
, "resource2: alloc"
, "inner-comp-2 with argument: bar"
, "resource2: release"
, "resource1: release"
]
s2
| |
669c0f52f66e875a90dbed24675cfa1530012b1888426486cc2b5b2edaa7f0eb | scrintal/heroicons-reagent | phone_arrow_up_right.cljs | (ns com.scrintal.heroicons.outline.phone-arrow-up-right)
(defn render []
[:svg {:xmlns ""
:fill "none"
:viewBox "0 0 24 24"
:strokeWidth "1.5"
:stroke "currentColor"
:aria-hidden "true"}
[:path {:strokeLinecap "round"
:strokeLinejoin "round"
:d "M20.25 3.75v4.5m0-4.5h-4.5m4.5 0l-6 6m3 12c-8.284 0-15-6.716-15-15V4.5A2.25 2.25 0 014.5 2.25h1.372c.516 0 .966.351 1.091.852l1.106 4.423c.11.44-.054.902-.417 1.173l-1.293.97a1.062 1.062 0 00-.38 1.21 12.035 12.035 0 007.143 7.143c.441.162.928-.004 1.21-.38l.97-1.293a1.125 1.125 0 011.173-.417l4.423 1.106c.5.125.852.575.852 1.091V19.5a2.25 2.25 0 01-2.25 2.25h-2.25z"}]]) | null | https://raw.githubusercontent.com/scrintal/heroicons-reagent/572f51d2466697ec4d38813663ee2588960365b6/src/com/scrintal/heroicons/outline/phone_arrow_up_right.cljs | clojure | (ns com.scrintal.heroicons.outline.phone-arrow-up-right)
(defn render []
[:svg {:xmlns ""
:fill "none"
:viewBox "0 0 24 24"
:strokeWidth "1.5"
:stroke "currentColor"
:aria-hidden "true"}
[:path {:strokeLinecap "round"
:strokeLinejoin "round"
:d "M20.25 3.75v4.5m0-4.5h-4.5m4.5 0l-6 6m3 12c-8.284 0-15-6.716-15-15V4.5A2.25 2.25 0 014.5 2.25h1.372c.516 0 .966.351 1.091.852l1.106 4.423c.11.44-.054.902-.417 1.173l-1.293.97a1.062 1.062 0 00-.38 1.21 12.035 12.035 0 007.143 7.143c.441.162.928-.004 1.21-.38l.97-1.293a1.125 1.125 0 011.173-.417l4.423 1.106c.5.125.852.575.852 1.091V19.5a2.25 2.25 0 01-2.25 2.25h-2.25z"}]]) | |
c07550f47597ee8fa046faca21bdb6c62d7ed6907ea062f4e1677ae93dcace5d | hpdeifel/hledger-iadd | WrappedText.hs | | TODO Use the built - in wrapping feature in brick-0.20
module Brick.Widgets.WrappedText (wrappedText) where
import Brick
import Data.Text (Text)
import qualified Data.Text as T
import Lens.Micro
-- | Widget like 'txt', but wrap all lines to fit on the screen.
--
-- Doesn't do word wrap, just breaks the line whenever the maximum width is
-- exceeded.
wrappedText :: Text -> Widget n
wrappedText theText = Widget Fixed Fixed $ do
ctx <- getContext
let newText = wrapLines (ctx^.availWidthL) theText
render $ txt newText
-- | Wrap all lines in input to fit into maximum width.
--
-- Doesn't do word wrap, just breaks the line whenever the maximum width is
-- exceeded.
wrapLines :: Int -> Text -> Text
wrapLines width = T.unlines . concat . map wrap . T.lines
where
wrap = T.chunksOf width
| null | https://raw.githubusercontent.com/hpdeifel/hledger-iadd/782239929d411bce4714e65dd5c7bb97b2ba4e75/src/Brick/Widgets/WrappedText.hs | haskell | | Widget like 'txt', but wrap all lines to fit on the screen.
Doesn't do word wrap, just breaks the line whenever the maximum width is
exceeded.
| Wrap all lines in input to fit into maximum width.
Doesn't do word wrap, just breaks the line whenever the maximum width is
exceeded. | | TODO Use the built - in wrapping feature in brick-0.20
module Brick.Widgets.WrappedText (wrappedText) where
import Brick
import Data.Text (Text)
import qualified Data.Text as T
import Lens.Micro
wrappedText :: Text -> Widget n
wrappedText theText = Widget Fixed Fixed $ do
ctx <- getContext
let newText = wrapLines (ctx^.availWidthL) theText
render $ txt newText
wrapLines :: Int -> Text -> Text
wrapLines width = T.unlines . concat . map wrap . T.lines
where
wrap = T.chunksOf width
|
094b2040978a160cb87867d79d9fd9f7aa446870d913f8fa37749b5389d27da5 | GrammaticalFramework/gf-core | Structure.hs | module Structure where
data SentenceType = Q | Dir | Top
deriving (Show,Eq)
data NPType = Generic | Impers | Normal | Exist
deriving (Show,Eq)
data VPForm = Cop | Sup | VV | VA
| V | V2 | V2A | V2Pass
| Fut | FutKommer
| VS
deriving (Eq,Show)
data VForm a
= VInf | VPart | VSupin | VImp | VTense a
deriving (Show,Eq)
instance Functor VForm where
fmap f VInf = VInf
fmap f VPart = VPart
fmap f VSupin = VSupin
fmap f VImp = VImp
fmap f (VTense t) = VTense (f t)
| null | https://raw.githubusercontent.com/GrammaticalFramework/gf-core/9b4f2dd18b64b770aaebfa1885085e8e3447f119/treebanks/talbanken/Structure.hs | haskell | module Structure where
data SentenceType = Q | Dir | Top
deriving (Show,Eq)
data NPType = Generic | Impers | Normal | Exist
deriving (Show,Eq)
data VPForm = Cop | Sup | VV | VA
| V | V2 | V2A | V2Pass
| Fut | FutKommer
| VS
deriving (Eq,Show)
data VForm a
= VInf | VPart | VSupin | VImp | VTense a
deriving (Show,Eq)
instance Functor VForm where
fmap f VInf = VInf
fmap f VPart = VPart
fmap f VSupin = VSupin
fmap f VImp = VImp
fmap f (VTense t) = VTense (f t)
| |
f0dee2a41432a852e437438693dbe6153034271a89532b373d9ffcdb56a49f11 | kmi/ocml | rete-working-memory.lisp | -*- Mode : LISP ; Syntax : Common - lisp ; Base : 10 ; Package : ; -*-
(in-package "OCML")
;;;The functions in this file handle adding and removing new alpha patterns to the rete network.
;;;The top level entry points in the code for doing this are the following:
;;;MATCH-ALPHA-NODE-AGAINST-INSTANCE ---This is called in order to match
a generic instance spec pattern such as ( < class > < x > < attr1 > < y1> ............. > < yn > )
;;;to an instance of class <class>.
;;;MATCH-ALPHA-NODE-AGAINST-POSSIBLE-INSTANCE ---This is called after new slot values have
been asserted , say .... valuen of slot1 of inst1 , to try and match a rule antecedent ,
with the form ( < class > < instance - id > .... < value > .... ) to a
;;;;to a (possible) instance of class <class>.
;;;RUN-ALPHA-TEST --- This is called when a new relation instance (wm-pattern) has been asserted.
It first checks whether the wm - pattern satisfies the infra - element
;;;condition (alpha test). If this is the case, it propagates the pattern
;;;through the rete network.
;;;DUMMY-INPUT ---This is called when a rule has been compiled which hasn't got any
;;;positive antecedent. The function creates a dummy input, corresponding to a
an instantiation with no LHS
;;;REMOVE-WM-PATTERN-FROM-RETE ---Top level function called when a pattern needs to be
;;;removed from the rete network. It is the inverse of run-alpha-test
MAYBE - REMOVE - INSTANCE - SPEC - INPUTS ---This is called after a number of values of
the slot of an instance , say sloti , have been removed , to delete any associated alpha
;;;alpha-input, if any exists, from a node such as (<class> <id> .........<sloti> <value>...)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;MATCH-ALPHA-NODE-AGAINST-INSTANCE ---This takes care of performing the alpha node
;;;test on a generic instance spec pattern such as
( < class > < x > < attr1 > < y1> ............. > < yn > )
(defmethod match-alpha-node-against-instance ((node alpha-node)(inst basic-domain-class))
(with-slots (pattern successor beta-node-like?) node
(maybe-propagate-alpha-inputs pattern successor beta-node-like?
(match-spec-against-instance inst (car pattern) (cdr pattern) nil))))
(defun maybe-propagate-alpha-inputs (pattern successor beta-node-like? envs)
(let ((alpha-inputs (unless (eq envs :fail)
(loop for env in envs
collecting (generate-instance-pattern pattern env)))))
(when alpha-inputs
(propagate-alpha-inputs successor alpha-inputs beta-node-like?))))
(defun propagate-alpha-inputs (successor alpha-inputs beta-node-like?)
(if beta-node-like? ;Can only be beta-node-like? if it is positive
(new-beta-inputs successor
(mapcar #'list alpha-inputs))
(dolist (input alpha-inputs)
(new-alpha-input successor input))))
;;;MATCH-ALPHA-NODE-AGAINST-POSSIBLE-INSTANCE ---This is called after new slot values have
been asserted , say .... valuen of slot1 of inst1 , to try and match a rule antecedent ,
with the form ( < class > < instance - id > .... < value > .... )
(defmethod match-alpha-node-against-possible-instance ((node alpha-node) name slot values &optional remove?)
(with-slots (relation pattern successor beta-node-like?) node
First , check this is an instance of the class
(name relation)) ;associated with the node
(let ((env (match name (car pattern)))) ;Then, match name against instance id in instance spec
(unless (eq env :fail)
(if remove?
(maybe-remove-instance-spec-inputs node name slot values)
(maybe-propagate-alpha-inputs ;If we succeed match the rest of the slot spec
pattern successor beta-node-like? ;and - if successful - propagate alpha inputs
(match-slot-value-spec-against-alpha-node name (name relation) slot values (cdr pattern) env))))))))
;;; MATCH-SLOT-VALUE-SPEC-AGAINST-ALPHA-NODE ---This is used by
;;;match-alpha-node-against-possible-instance (which is called after new slot values have been
asserted , say .... valuen of slot1 of inst1 ) to try and match the slot specification
part - which has the format ( < value1> ........... slotn < valuen > ) - of an antecedent .
(defun match-slot-value-spec-against-alpha-node (name class-name slot values all-slots-spec env
&aux new-envs)
First , remove slot pair from pattern
(remove-slot-entry all-slots-spec slot)
(setf new-envs
(if modified-pattern
(match-spec-against-instance-slots ;Then, match instance to modified pattern
(find-current-instance name class-name)
modified-pattern
env)
'(nil)))
(unless (eq new-envs :fail) ;If we succeed
(loop with result
for value in values
for more-envs = (match* (list slot value) ;we try matching the new values as well
the-slot-spec
new-envs)
unless (eq more-envs :fail)
do
(setf result (nconc result more-envs))
finally
(return result)))))
(defun remove-slot-entry (slot-spec slot)
(let ((position (position slot slot-spec)))
(values
(append (subseq slot-spec 0 position)
(subseq slot-spec (+ 2 position)))
(subseq slot-spec position (+ 2 position)))))
(defun generate-instance-pattern (pattern env)
(instantiate pattern env))
;;;RUN-ALPHA-TEST --- This is called when a new wm-pattern has been asserted.
It first checks whether the wm - pattern satisfies the infra - element
;;;condition (alpha test). If this is the case, it propagates the pattern
;;;through the rete network.
(defmethod run-alpha-test ((node alpha-node)args)
(with-slots (test-fun successor beta-node-like?) node
(when (funcall test-fun args)
(if beta-node-like? ;Can only be beta-node-like? if it is positive
(new-beta-inputs successor (list (list args)))
(new-alpha-input successor args)))))
;;;DUMMY-INPUT ---This is called when a rule has been compiled which hasn't got any
;;;positive antecedent. The function creates a dummy input, corresponding to a
an instantiation with no LHS
(defmethod dummy-input ((node alpha-node))
(with-slots (successor) node
(new-beta-inputs successor
(list (make-dummy-support)))))
;;;NEW-ALPHA-INPUT ---This is called when a new alpha input (i.e. a new wm pattern
;;;which has passed the relevant alpha test) is passed on to a beta node. In this case
;;;we run the beta test to check which test cases (beta inputs + new alpha input)
;;;pass the beta test. The winners are then propagated down the rete network.
(defmethod new-alpha-input ((node beta-node) args)
(with-slots (alpha-inputs successor not-nodep beta-inputs) node
(push args alpha-inputs)
(Let* ((result (if not-nodep
(apply-negative-beta-filter ;;In this case we want to collect the losers
node beta-inputs (list args)t)
(apply-positive-beta-filter node beta-inputs (list args))))
(fun (if not-nodep #'remove-beta-inputs #'new-beta-inputs)))
(when result
(funcall fun successor result)))))
NEW - ALPHA - INPUT END - NODE --This handles the extreme case in which a rule
has no beta nodes . This means there is only one positive antecedent and
;;;no negative ones.
(defmethod new-alpha-input ((node end-node) args)
(new-beta-inputs node (list args)))
;;; Called when new winners have been propagated down the network, to
;;; filter them using the beta test.
(defmethod new-beta-inputs ((node beta-node) new-beta-inputs)
(with-slots (beta-inputs successor alpha-inputs not-nodep) node
(setf beta-inputs (append new-beta-inputs beta-inputs))
(let ((winners (funcall (if not-nodep
#'apply-negative-beta-filter
#'apply-positive-beta-filter)
node new-beta-inputs alpha-inputs)))
(when winners
(new-beta-inputs successor winners)))))
;;;NEW-BETA-INPUTS END-NODE
(defmethod new-beta-inputs ((node end-node) inputs)
(with-slots (beta-inputs rule) node
(setf beta-inputs (append inputs beta-inputs))
;;; (when *interpreter-running*
(unless *compiling-fc-rule*
(new-instantiations rule inputs))))
;;;APPLY-POSITIVE-BETA-FILTER
(defmethod apply-positive-beta-filter ((node beta-node)beta-inputs alpha-inputs)
(with-slots (test-fun) node
(loop with winners
for alpha-input in alpha-inputs
do
(setf alpha-input (list alpha-input))
(loop for beta-input in beta-inputs
for test-case = (append beta-input alpha-input)
do
;;;(pprint test-fun)
;;;;;(pprint test-case)
(when (funcall test-fun test-case)
(push test-case winners)))
finally
(return winners))))
;;;APPLY-NEGATIVE-BETA-FILTER ---This is called to perform the beta test on a
;;;negative beta node. It takes a set of beta inputs and a set of alpha inputs
;;;and returns all the beta inputs which have not been ruled out by any of the alpha inputs
(defmethod apply-negative-beta-filter ((node beta-node) beta-inputs alpha-inputs &optional return-losers?)
(with-slots (test-fun index) node
(loop with place-holder = (make-list index) ;;This is to get the test case of the right length
for beta-input in beta-inputs
with winners = beta-inputs
while winners
do
;;;(pprint test-fun)
(loop for alpha-input in alpha-inputs
for test-case = (append beta-input place-holder (list alpha-input))
do
;;(pprint test-case)
(when (funcall test-fun test-case)
(setf winners (remove beta-input winners :test #'equal)))
while winners)
finally
(return
(if return-losers?
(set-difference beta-inputs winners)
winners)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;REMOVE-WM-PATTERN-FROM-RETE ---Top level function called when a pattern needs to be
;;;removed from the rete network
(defmethod remove-wm-pattern-from-rete ((node alpha-node) args)
(with-slots (beta-node-like? successor position) node
(if beta-node-like?
(remove-beta-inputs-with-pattern successor args position) ;;;;(list (list args)))
(remove-alpha-input successor args position))))
MAYBE - REMOVE - INSTANCE - SPEC - INPUTS ---This is called after a number of values of
the slot of an instance , say sloti , have been removed , to delete any associated alpha
;;;alpha-input, if any exists, from a node such as (<class> <id> .........<sloti> <value>...)
(defmethod maybe-remove-instance-spec-inputs ((node alpha-node) name &optional slot values)
(with-slots (beta-node-like? successor position) node
(if beta-node-like?
(if values
(remove-beta-inputs-with-slot-values successor name slot values position)
(remove-beta-inputs-with-instance-name successor name position))
(if values
(remove-alpha-input-with-slot-values successor name slot values position)
(remove-alpha-input-with-instance-name successor name position)))))
;;;REMOVE-ALPHA-INPUT ---
(defmethod remove-alpha-input ((node beta-node) args position &aux temp)
(with-slots (alpha-inputs successor not-nodep ) node
(setf temp (remove args alpha-inputs :test #'equal))
(unless (equal temp alpha-inputs)
(setf alpha-inputs temp)
(if not-nodep
(maybe-resuscitate-beta-inputs node)
(remove-beta-inputs-with-pattern successor args position)))))
REMOVE - ALPHA - INPUT - WITH - SLOT - VALUES
(defmethod remove-alpha-input-with-slot-values ((node beta-node) name slot values position &aux temp)
(with-slots (alpha-inputs successor not-nodep ) node
(setf temp (remove-if #'(lambda (input)
(match-slot-values input name slot values))
alpha-inputs))
(unless (equal temp alpha-inputs)
(setf alpha-inputs temp)
(if not-nodep
(maybe-resuscitate-beta-inputs node)
(remove-beta-inputs-with-slot-values successor name slot values position)))))
(defmethod remove-alpha-input-with-instance-name ((node beta-node) name position &aux temp)
(with-slots (alpha-inputs successor not-nodep ) node
(setf temp (remove-if #'(lambda (input)
(equal (car input) name))
alpha-inputs))
(unless (equal temp alpha-inputs)
(setf alpha-inputs temp)
(if not-nodep
(maybe-resuscitate-beta-inputs node)
(remove-beta-inputs-with-instance-name successor name position)))))
MAYBE - RESUSCITATE - BETA - INPUTS ---This is called after a negative alpha input has been
;;;removed, to check whether any new winners can be generated.
(defmethod maybe-resuscitate-beta-inputs ((node beta-node))
(with-slots (beta-inputs alpha-inputs successor) node
(let ((new-winners (set-difference
(apply-negative-beta-filter ;This returns all the
node beta-inputs alpha-inputs) ;current winners
(beta-inputs successor)
:test #'equal)))
(when new-winners
(new-beta-inputs successor new-winners)))))
;;;REMOVE-BETA-INPUTS--
(defmethod remove-beta-inputs :before ((node beta-node)losers)
(with-slots (beta-inputs)node
(setf beta-inputs (set-difference beta-inputs losers :test #'equal))))
(defmethod remove-beta-inputs ((node beta-node)losers)
(with-slots (successor not-nodep) node
(if not-nodep
(remove-beta-inputs successor losers)
(remove-beta-inputs-with-partial-set successor losers))))
(defmethod remove-beta-inputs ((node end-node) losers)
(with-slots (rule) node
;; (when *interpreter-running*
(unless *compiling-fc-rule*
(remove-instantiations rule losers))))
;;;REMOVE-BETA-INPUTS-WITH-PATTERN ---This is called when a wm-element associated with a
;;;positive alpha node has been deleted
(defmethod remove-beta-inputs-with-pattern ((node beta-node) pattern position)
(with-slots (beta-inputs) node
(let ((to-be-removed (filter beta-inputs #'(lambda (x)
(equal (elt x position)pattern)))))
(when to-be-removed
(remove-beta-inputs node to-be-removed)))))
(defmethod remove-beta-inputs-with-slot-values ((node beta-node) name slot values position)
(with-slots (beta-inputs) node
(let ((to-be-removed (filter beta-inputs #'(lambda (x)
(match-slot-values (elt x position) name slot values)))))
(when to-be-removed
(remove-beta-inputs node to-be-removed)))))
(defmethod remove-beta-inputs-with-instance-name ((node beta-node) name position)
(with-slots (beta-inputs) node
(let ((to-be-removed (filter beta-inputs #'(lambda (x)
(equal (car (elt x position)) name)))))
(when to-be-removed
(remove-beta-inputs node to-be-removed)))))
(defun match-slot-values (instantiated-pattern name slot values &aux pos)
(and (equal (car instantiated-pattern)
name)
(setf pos (position slot instantiated-pattern))
(member (elt instantiated-pattern (1+ pos)) values :test #'equal)))
;;;REMOVE-BETA-INPUTS-WITH-PARTIAL-SET
(defmethod remove-beta-inputs-with-partial-set ((node beta-node) partial-support-sets)
(with-slots (beta-inputs) node
(let ((to-be-removed (filter beta-inputs #'(lambda (b)
(some #'(lambda (s)
(equal s (subseq b 0 (length s))))
partial-support-sets)))))
(when to-be-removed
(remove-beta-inputs node to-be-removed)))))
| null | https://raw.githubusercontent.com/kmi/ocml/90b0b173f588c580c26393c94f9970282c640f4d/src/rete-working-memory.lisp | lisp | Syntax : Common - lisp ; Base : 10 ; Package : ; -*-
The functions in this file handle adding and removing new alpha patterns to the rete network.
The top level entry points in the code for doing this are the following:
MATCH-ALPHA-NODE-AGAINST-INSTANCE ---This is called in order to match
to an instance of class <class>.
MATCH-ALPHA-NODE-AGAINST-POSSIBLE-INSTANCE ---This is called after new slot values have
to a (possible) instance of class <class>.
RUN-ALPHA-TEST --- This is called when a new relation instance (wm-pattern) has been asserted.
condition (alpha test). If this is the case, it propagates the pattern
through the rete network.
DUMMY-INPUT ---This is called when a rule has been compiled which hasn't got any
positive antecedent. The function creates a dummy input, corresponding to a
REMOVE-WM-PATTERN-FROM-RETE ---Top level function called when a pattern needs to be
removed from the rete network. It is the inverse of run-alpha-test
alpha-input, if any exists, from a node such as (<class> <id> .........<sloti> <value>...)
MATCH-ALPHA-NODE-AGAINST-INSTANCE ---This takes care of performing the alpha node
test on a generic instance spec pattern such as
Can only be beta-node-like? if it is positive
MATCH-ALPHA-NODE-AGAINST-POSSIBLE-INSTANCE ---This is called after new slot values have
associated with the node
Then, match name against instance id in instance spec
If we succeed match the rest of the slot spec
and - if successful - propagate alpha inputs
MATCH-SLOT-VALUE-SPEC-AGAINST-ALPHA-NODE ---This is used by
match-alpha-node-against-possible-instance (which is called after new slot values have been
Then, match instance to modified pattern
If we succeed
we try matching the new values as well
RUN-ALPHA-TEST --- This is called when a new wm-pattern has been asserted.
condition (alpha test). If this is the case, it propagates the pattern
through the rete network.
Can only be beta-node-like? if it is positive
DUMMY-INPUT ---This is called when a rule has been compiled which hasn't got any
positive antecedent. The function creates a dummy input, corresponding to a
NEW-ALPHA-INPUT ---This is called when a new alpha input (i.e. a new wm pattern
which has passed the relevant alpha test) is passed on to a beta node. In this case
we run the beta test to check which test cases (beta inputs + new alpha input)
pass the beta test. The winners are then propagated down the rete network.
In this case we want to collect the losers
no negative ones.
Called when new winners have been propagated down the network, to
filter them using the beta test.
NEW-BETA-INPUTS END-NODE
(when *interpreter-running*
APPLY-POSITIVE-BETA-FILTER
(pprint test-fun)
(pprint test-case)
APPLY-NEGATIVE-BETA-FILTER ---This is called to perform the beta test on a
negative beta node. It takes a set of beta inputs and a set of alpha inputs
and returns all the beta inputs which have not been ruled out by any of the alpha inputs
This is to get the test case of the right length
(pprint test-fun)
(pprint test-case)
REMOVE-WM-PATTERN-FROM-RETE ---Top level function called when a pattern needs to be
removed from the rete network
(list (list args)))
alpha-input, if any exists, from a node such as (<class> <id> .........<sloti> <value>...)
REMOVE-ALPHA-INPUT ---
removed, to check whether any new winners can be generated.
This returns all the
current winners
REMOVE-BETA-INPUTS--
(when *interpreter-running*
REMOVE-BETA-INPUTS-WITH-PATTERN ---This is called when a wm-element associated with a
positive alpha node has been deleted
REMOVE-BETA-INPUTS-WITH-PARTIAL-SET |
(in-package "OCML")
a generic instance spec pattern such as ( < class > < x > < attr1 > < y1> ............. > < yn > )
been asserted , say .... valuen of slot1 of inst1 , to try and match a rule antecedent ,
with the form ( < class > < instance - id > .... < value > .... ) to a
It first checks whether the wm - pattern satisfies the infra - element
an instantiation with no LHS
MAYBE - REMOVE - INSTANCE - SPEC - INPUTS ---This is called after a number of values of
the slot of an instance , say sloti , have been removed , to delete any associated alpha
( < class > < x > < attr1 > < y1> ............. > < yn > )
(defmethod match-alpha-node-against-instance ((node alpha-node)(inst basic-domain-class))
(with-slots (pattern successor beta-node-like?) node
(maybe-propagate-alpha-inputs pattern successor beta-node-like?
(match-spec-against-instance inst (car pattern) (cdr pattern) nil))))
(defun maybe-propagate-alpha-inputs (pattern successor beta-node-like? envs)
(let ((alpha-inputs (unless (eq envs :fail)
(loop for env in envs
collecting (generate-instance-pattern pattern env)))))
(when alpha-inputs
(propagate-alpha-inputs successor alpha-inputs beta-node-like?))))
(defun propagate-alpha-inputs (successor alpha-inputs beta-node-like?)
(new-beta-inputs successor
(mapcar #'list alpha-inputs))
(dolist (input alpha-inputs)
(new-alpha-input successor input))))
been asserted , say .... valuen of slot1 of inst1 , to try and match a rule antecedent ,
with the form ( < class > < instance - id > .... < value > .... )
(defmethod match-alpha-node-against-possible-instance ((node alpha-node) name slot values &optional remove?)
(with-slots (relation pattern successor beta-node-like?) node
First , check this is an instance of the class
(unless (eq env :fail)
(if remove?
(maybe-remove-instance-spec-inputs node name slot values)
(match-slot-value-spec-against-alpha-node name (name relation) slot values (cdr pattern) env))))))))
asserted , say .... valuen of slot1 of inst1 ) to try and match the slot specification
part - which has the format ( < value1> ........... slotn < valuen > ) - of an antecedent .
(defun match-slot-value-spec-against-alpha-node (name class-name slot values all-slots-spec env
&aux new-envs)
First , remove slot pair from pattern
(remove-slot-entry all-slots-spec slot)
(setf new-envs
(if modified-pattern
(find-current-instance name class-name)
modified-pattern
env)
'(nil)))
(loop with result
for value in values
the-slot-spec
new-envs)
unless (eq more-envs :fail)
do
(setf result (nconc result more-envs))
finally
(return result)))))
(defun remove-slot-entry (slot-spec slot)
(let ((position (position slot slot-spec)))
(values
(append (subseq slot-spec 0 position)
(subseq slot-spec (+ 2 position)))
(subseq slot-spec position (+ 2 position)))))
(defun generate-instance-pattern (pattern env)
(instantiate pattern env))
It first checks whether the wm - pattern satisfies the infra - element
(defmethod run-alpha-test ((node alpha-node)args)
(with-slots (test-fun successor beta-node-like?) node
(when (funcall test-fun args)
(new-beta-inputs successor (list (list args)))
(new-alpha-input successor args)))))
an instantiation with no LHS
(defmethod dummy-input ((node alpha-node))
(with-slots (successor) node
(new-beta-inputs successor
(list (make-dummy-support)))))
(defmethod new-alpha-input ((node beta-node) args)
(with-slots (alpha-inputs successor not-nodep beta-inputs) node
(push args alpha-inputs)
(Let* ((result (if not-nodep
node beta-inputs (list args)t)
(apply-positive-beta-filter node beta-inputs (list args))))
(fun (if not-nodep #'remove-beta-inputs #'new-beta-inputs)))
(when result
(funcall fun successor result)))))
NEW - ALPHA - INPUT END - NODE --This handles the extreme case in which a rule
has no beta nodes . This means there is only one positive antecedent and
(defmethod new-alpha-input ((node end-node) args)
(new-beta-inputs node (list args)))
(defmethod new-beta-inputs ((node beta-node) new-beta-inputs)
(with-slots (beta-inputs successor alpha-inputs not-nodep) node
(setf beta-inputs (append new-beta-inputs beta-inputs))
(let ((winners (funcall (if not-nodep
#'apply-negative-beta-filter
#'apply-positive-beta-filter)
node new-beta-inputs alpha-inputs)))
(when winners
(new-beta-inputs successor winners)))))
(defmethod new-beta-inputs ((node end-node) inputs)
(with-slots (beta-inputs rule) node
(setf beta-inputs (append inputs beta-inputs))
(unless *compiling-fc-rule*
(new-instantiations rule inputs))))
(defmethod apply-positive-beta-filter ((node beta-node)beta-inputs alpha-inputs)
(with-slots (test-fun) node
(loop with winners
for alpha-input in alpha-inputs
do
(setf alpha-input (list alpha-input))
(loop for beta-input in beta-inputs
for test-case = (append beta-input alpha-input)
do
(when (funcall test-fun test-case)
(push test-case winners)))
finally
(return winners))))
(defmethod apply-negative-beta-filter ((node beta-node) beta-inputs alpha-inputs &optional return-losers?)
(with-slots (test-fun index) node
for beta-input in beta-inputs
with winners = beta-inputs
while winners
do
(loop for alpha-input in alpha-inputs
for test-case = (append beta-input place-holder (list alpha-input))
do
(when (funcall test-fun test-case)
(setf winners (remove beta-input winners :test #'equal)))
while winners)
finally
(return
(if return-losers?
(set-difference beta-inputs winners)
winners)))))
(defmethod remove-wm-pattern-from-rete ((node alpha-node) args)
(with-slots (beta-node-like? successor position) node
(if beta-node-like?
(remove-alpha-input successor args position))))
MAYBE - REMOVE - INSTANCE - SPEC - INPUTS ---This is called after a number of values of
the slot of an instance , say sloti , have been removed , to delete any associated alpha
(defmethod maybe-remove-instance-spec-inputs ((node alpha-node) name &optional slot values)
(with-slots (beta-node-like? successor position) node
(if beta-node-like?
(if values
(remove-beta-inputs-with-slot-values successor name slot values position)
(remove-beta-inputs-with-instance-name successor name position))
(if values
(remove-alpha-input-with-slot-values successor name slot values position)
(remove-alpha-input-with-instance-name successor name position)))))
(defmethod remove-alpha-input ((node beta-node) args position &aux temp)
(with-slots (alpha-inputs successor not-nodep ) node
(setf temp (remove args alpha-inputs :test #'equal))
(unless (equal temp alpha-inputs)
(setf alpha-inputs temp)
(if not-nodep
(maybe-resuscitate-beta-inputs node)
(remove-beta-inputs-with-pattern successor args position)))))
REMOVE - ALPHA - INPUT - WITH - SLOT - VALUES
(defmethod remove-alpha-input-with-slot-values ((node beta-node) name slot values position &aux temp)
(with-slots (alpha-inputs successor not-nodep ) node
(setf temp (remove-if #'(lambda (input)
(match-slot-values input name slot values))
alpha-inputs))
(unless (equal temp alpha-inputs)
(setf alpha-inputs temp)
(if not-nodep
(maybe-resuscitate-beta-inputs node)
(remove-beta-inputs-with-slot-values successor name slot values position)))))
(defmethod remove-alpha-input-with-instance-name ((node beta-node) name position &aux temp)
(with-slots (alpha-inputs successor not-nodep ) node
(setf temp (remove-if #'(lambda (input)
(equal (car input) name))
alpha-inputs))
(unless (equal temp alpha-inputs)
(setf alpha-inputs temp)
(if not-nodep
(maybe-resuscitate-beta-inputs node)
(remove-beta-inputs-with-instance-name successor name position)))))
MAYBE - RESUSCITATE - BETA - INPUTS ---This is called after a negative alpha input has been
(defmethod maybe-resuscitate-beta-inputs ((node beta-node))
(with-slots (beta-inputs alpha-inputs successor) node
(let ((new-winners (set-difference
(beta-inputs successor)
:test #'equal)))
(when new-winners
(new-beta-inputs successor new-winners)))))
(defmethod remove-beta-inputs :before ((node beta-node)losers)
(with-slots (beta-inputs)node
(setf beta-inputs (set-difference beta-inputs losers :test #'equal))))
(defmethod remove-beta-inputs ((node beta-node)losers)
(with-slots (successor not-nodep) node
(if not-nodep
(remove-beta-inputs successor losers)
(remove-beta-inputs-with-partial-set successor losers))))
(defmethod remove-beta-inputs ((node end-node) losers)
(with-slots (rule) node
(unless *compiling-fc-rule*
(remove-instantiations rule losers))))
(defmethod remove-beta-inputs-with-pattern ((node beta-node) pattern position)
(with-slots (beta-inputs) node
(let ((to-be-removed (filter beta-inputs #'(lambda (x)
(equal (elt x position)pattern)))))
(when to-be-removed
(remove-beta-inputs node to-be-removed)))))
(defmethod remove-beta-inputs-with-slot-values ((node beta-node) name slot values position)
(with-slots (beta-inputs) node
(let ((to-be-removed (filter beta-inputs #'(lambda (x)
(match-slot-values (elt x position) name slot values)))))
(when to-be-removed
(remove-beta-inputs node to-be-removed)))))
(defmethod remove-beta-inputs-with-instance-name ((node beta-node) name position)
(with-slots (beta-inputs) node
(let ((to-be-removed (filter beta-inputs #'(lambda (x)
(equal (car (elt x position)) name)))))
(when to-be-removed
(remove-beta-inputs node to-be-removed)))))
(defun match-slot-values (instantiated-pattern name slot values &aux pos)
(and (equal (car instantiated-pattern)
name)
(setf pos (position slot instantiated-pattern))
(member (elt instantiated-pattern (1+ pos)) values :test #'equal)))
(defmethod remove-beta-inputs-with-partial-set ((node beta-node) partial-support-sets)
(with-slots (beta-inputs) node
(let ((to-be-removed (filter beta-inputs #'(lambda (b)
(some #'(lambda (s)
(equal s (subseq b 0 (length s))))
partial-support-sets)))))
(when to-be-removed
(remove-beta-inputs node to-be-removed)))))
|
670994e9be209db862186a072abec8b418c27d4276e9814accf11fd2df6c6e37 | rtoy/cmucl | boot-2011-04-01-cross.lisp | Add -unidata command line option to allow user to tell where
the unidata.bin file is .
;;
To build 2011 - 06 , you need to do a cross - compile . Use this as the
;; cross-compile bootstrap file.
#+x86
(load "target:tools/cross-scripts/cross-x86-x86.lisp")
#+sparc
(load "target:tools/cross-scripts/cross-sparc-sparc.lisp")
| null | https://raw.githubusercontent.com/rtoy/cmucl/9b1abca53598f03a5b39ded4185471a5b8777dea/src/bootfiles/20b/boot-2011-04-01-cross.lisp | lisp |
cross-compile bootstrap file. | Add -unidata command line option to allow user to tell where
the unidata.bin file is .
To build 2011 - 06 , you need to do a cross - compile . Use this as the
#+x86
(load "target:tools/cross-scripts/cross-x86-x86.lisp")
#+sparc
(load "target:tools/cross-scripts/cross-sparc-sparc.lisp")
|
c89152027e31b868899eda5baf0cf858bda714c94638bbdc5f9d99b8c5c5550e | jacobobryant/biff | rum.clj | (ns com.biffweb.impl.rum
(:require [clojure.java.io :as io]
[clojure.string :as str]
[com.biffweb.impl.util :as util]
[ring.middleware.anti-forgery :as anti-forgery]
[rum.core :as rum]))
(defn render [body]
{:status 200
:headers {"content-type" "text/html; charset=utf-8"}
:body (str "<!DOCTYPE html>\n" (rum/render-static-markup body))})
(defn unsafe [html]
{:dangerouslySetInnerHTML {:__html html}})
(def emdash [:span (unsafe "—")])
(def endash [:span (unsafe "–")])
(def nbsp [:span (unsafe " ")])
(defn g-fonts
[families]
[:link {:href (apply str ""
(for [f families]
(str "&family=" f)))
:rel "stylesheet"}])
(defn base-html
[{:base/keys [title
description
lang
image
icon
url
canonical
font-families
head]}
& contents]
[:html
{:lang lang
:style {:min-height "100%"
:height "auto"}}
[:head
[:title title]
[:meta {:name "description" :content description}]
[:meta {:content title :property "og:title"}]
[:meta {:content description :property "og:description"}]
(when image
[:<>
[:meta {:content image :property "og:image"}]
[:meta {:content "summary_large_image" :name "twitter:card"}]])
(when-some [url (or url canonical)]
[:meta {:content url :property "og:url"}])
(when-some [url (or canonical url)]
[:link {:ref "canonical" :href url}])
[:meta {:name "viewport" :content "width=device-width, initial-scale=1"}]
(when icon
[:link {:rel "icon"
:type "image/png"
:sizes "16x16"
:href icon}])
[:meta {:charset "utf-8"}]
(when (not-empty font-families)
[:<>
[:link {:href "", :rel "preconnect"}]
[:link {:crossorigin "crossorigin",
:href "",
:rel "preconnect"}]
(g-fonts font-families)])
(into [:<>] head)]
[:body
{:style {:position "absolute"
:width "100%"
:min-height "100%"
:display "flex"
:flex-direction "column"}}
contents]])
(defn form
[{:keys [hidden] :as opts} & body]
[:form (-> (merge {:method "post"} opts)
(dissoc :hidden)
(assoc-in [:style :margin-bottom] 0))
(for [[k v] (util/assoc-some hidden "__anti-forgery-token" anti-forgery/*anti-forgery-token*)]
[:input {:type "hidden"
:name k
:value v}])
body])
;; you could say that rum is one of our main exports
(defn export-rum
[pages dir]
(doseq [[path rum] pages
:let [full-path (cond-> (str dir path)
(str/ends-with? path "/") (str "index.html"))]]
(io/make-parents full-path)
(spit full-path (str "<!DOCTYPE html>\n" (rum/render-static-markup rum)))))
| null | https://raw.githubusercontent.com/jacobobryant/biff/b339095197679dd4c546971f5a053d312c42b231/src/com/biffweb/impl/rum.clj | clojure | you could say that rum is one of our main exports | (ns com.biffweb.impl.rum
(:require [clojure.java.io :as io]
[clojure.string :as str]
[com.biffweb.impl.util :as util]
[ring.middleware.anti-forgery :as anti-forgery]
[rum.core :as rum]))
(defn render [body]
{:status 200
:headers {"content-type" "text/html; charset=utf-8"}
:body (str "<!DOCTYPE html>\n" (rum/render-static-markup body))})
(defn unsafe [html]
{:dangerouslySetInnerHTML {:__html html}})
(def emdash [:span (unsafe "—")])
(def endash [:span (unsafe "–")])
(def nbsp [:span (unsafe " ")])
(defn g-fonts
[families]
[:link {:href (apply str ""
(for [f families]
(str "&family=" f)))
:rel "stylesheet"}])
(defn base-html
[{:base/keys [title
description
lang
image
icon
url
canonical
font-families
head]}
& contents]
[:html
{:lang lang
:style {:min-height "100%"
:height "auto"}}
[:head
[:title title]
[:meta {:name "description" :content description}]
[:meta {:content title :property "og:title"}]
[:meta {:content description :property "og:description"}]
(when image
[:<>
[:meta {:content image :property "og:image"}]
[:meta {:content "summary_large_image" :name "twitter:card"}]])
(when-some [url (or url canonical)]
[:meta {:content url :property "og:url"}])
(when-some [url (or canonical url)]
[:link {:ref "canonical" :href url}])
[:meta {:name "viewport" :content "width=device-width, initial-scale=1"}]
(when icon
[:link {:rel "icon"
:type "image/png"
:sizes "16x16"
:href icon}])
[:meta {:charset "utf-8"}]
(when (not-empty font-families)
[:<>
[:link {:href "", :rel "preconnect"}]
[:link {:crossorigin "crossorigin",
:href "",
:rel "preconnect"}]
(g-fonts font-families)])
(into [:<>] head)]
[:body
{:style {:position "absolute"
:width "100%"
:min-height "100%"
:display "flex"
:flex-direction "column"}}
contents]])
(defn form
[{:keys [hidden] :as opts} & body]
[:form (-> (merge {:method "post"} opts)
(dissoc :hidden)
(assoc-in [:style :margin-bottom] 0))
(for [[k v] (util/assoc-some hidden "__anti-forgery-token" anti-forgery/*anti-forgery-token*)]
[:input {:type "hidden"
:name k
:value v}])
body])
(defn export-rum
[pages dir]
(doseq [[path rum] pages
:let [full-path (cond-> (str dir path)
(str/ends-with? path "/") (str "index.html"))]]
(io/make-parents full-path)
(spit full-path (str "<!DOCTYPE html>\n" (rum/render-static-markup rum)))))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.